2014-02-06 104 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