为什么我从scanf循环中遇到分段错误?

为什么我从scanf循环中遇到分段错误?

问题描述:

注释掉scanf循环后,分段错误错误消失.为什么该循环会给我带来细分错误?

The segmentation fault error disappears after commenting out the scanf loop. Why is that loop giving me a segmentation fault?

char** nameArray =  malloc(numNames * sizeof(char *)); 

for(i =0; i< 10; i++) { 
  nameArray[i] = malloc(25 * sizeof(char));
}

for (i = 0; i< numNames; i++) { 
  scanf("%s", &nameArray[i]);
}

for (i =0; i<numNames; i++) { 
  free(nameArray[i]);
}

首先,您需要进行更改

for(i =0; i< 10; i++) { 

for(i =0; i< numNames; i++) { 

,因为您需要创建足够的条目.

as you need to create enough entries.

还需要更改此行

scanf("%s", &nameArray[i]);

scanf("%s", nameArray[i]);

因为nameArray[i]是必需的字符指针.

as nameArray[i] is a character pointer as required.

也最好使用

scanf("%24s", nameArray[i]);

,因为这将防止缓冲区溢出.检查scant的返回值也是一个好主意

as this would prevent buffer overrun. Also it would be a good idea to check the return value of scant