下面的程序崩潰時,對於大n(n> 200)的分段,請您幫我解決。對於較大的值獲取分段錯誤
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
struct node {
char name[16];
char num[8];
};
int main() {
int n, i,j;
struct node *hash;
scanf("%d",&n);
hash = (struct node *) malloc(n * sizeof(struct node));
for (i=0; i<n ; i++) {
scanf("%s %s", (hash + (i *sizeof(struct node)))->name,
(hash + (i *sizeof(struct node)))->num);
}
for (i=0; i<n ; i++) {
printf("%s=%s\n",(hash + (i *sizeof(struct node)))->name,
(hash + (i *sizeof(struct node)))->num);
}
return (0);
}
輸入什麼字符串?任何大於15個字符或長度超過7位數字的名稱都會導致未定義的行爲,這可能會導致seg錯誤。 – StoryTeller
您想了解[pointer-arithmetic](http://stackoverflow.com/documentation/c/256/operators/2205/pointer-arithmetic#t=201701081538077668512)。這個'(hash +(i * sizeof(struct node)))...'應該是'(hash + i)...'或者只是'&hash [i] ...'。 – alk
另外,你的指針偏移很難閱讀(除了錯誤和超出你分配的內存)。讓編譯器處理'struct node'的大小,然後直接寫'hash [i]'。 – StoryTeller