2014-02-06 100 views
0
#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值。我的问题是关于编辑我的数组内的值,特别是分配新值并访问那里已有的值。从文件中解析出值后,我指定了我的值,但是当我尝试将其打印到下面时,出现了分段错误。为什么我的代码在我的最后一个循环中保持段错误,是否必须以不同于通常的方式打印出指针数组中的值?谢谢!指针和结构数组操作

回答

0

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

+0

假设一台64位机器,我需要添加一个地址的大小是8。 – Farzad

+0

嘿谢谢你的回复,所以如果我真的想malloc三个插槽中的数组我需要做的命令malloc(24)? – user1299379

+0

这就是问题,谢谢 – user1299379