#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值。我的问题是编辑数组中的值,特别是分配新值和访问已经存在的值。在从文件中解析值后,我会分配值,但是当我试图在下面打印它们时,会出现分段错误。为什么我的代码在我的最后一个循环中保持分段错误,我是否必须在一个指针数组中打印出与我通常不同的值?谢谢!
发布于 2014-02-06 02:21:18
sizeof(table)不是3,它实际上是24,也就是3*8 (数组元素的数目*地址的大小)。由于尝试访问未分配的table[3] (以此类推),因此会出现分段错误。
https://stackoverflow.com/questions/21592578
复制相似问题