首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C语言中的指针和结构数组操作

C语言中的指针和结构数组操作
EN

Stack Overflow用户
提问于 2014-02-06 02:00:44
回答 1查看 761关注 0票数 0
代码语言:javascript
复制
 #define MAX_KEYS 65

struct Key {

        int id;
        char cryptkeys[MAX_KEYS];
};



int main(int argc, char ** argv) {
int MAX_LINE = 69;
struct Key *table[3];
struct Key *(*p)[] = &table;
//allocating space for the pointers in array
for(int i = 0; i < 4; i++) {
        table[i] = malloc(sizeof(struct Key));
}
//parsing the id and the keys
char id[3];
char key[65];  

for(int i = 0; i < size-1; i++) {
        struct Key *k = (struct Key*)malloc(sizeof(struct Key));
        string = a[i];
        strncpy(id, string, 3);
        id[3] = '\0';
        k->id = atoi(id);
        for(int j = 4; j < strlen(string); j++) {
                key[j-4] = string[j];
        }
        strcpy(k->cryptkeys, key);
        table[i] = k; 
        printf("%s", table[i]->cryptkeys); //this will print
}
for(int i = 0; i < sizeof(table) -1; i++) {
        printf("%d", table[i]->id); //seg fault here, what is the difference from above?
        printf(" ");
        printf("%s", table[i]->cryptkeys);

}
return 0;
}

大家好,我有一个关于在C中操作指针的问题。我已经声明了一个数组的指针,这些指针将被我创建的结构填充。每个结构都接受我从文件中读取的int和string值。我的问题是编辑数组中的值,特别是分配新值和访问已经存在的值。在从文件中解析值后,我会分配值,但是当我试图在下面打印它们时,会出现分段错误。为什么我的代码在我的最后一个循环中保持分段错误,我是否必须在一个指针数组中打印出与我通常不同的值?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-06 02:21:18

sizeof(table)不是3,它实际上是24,也就是3*8 (数组元素的数目*地址的大小)。由于尝试访问未分配的table[3] (以此类推),因此会出现分段错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21592578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档