gpt4 book ai didi

c - 为什么这会返回段错误?

转载 作者:行者123 更新时间:2023-11-30 18:35:29 24 4
gpt4 key购买 nike

这是一个用 .txt 文件中的单词填充 char 指针数组的程序。为什么以下代码会返回段错误?感谢任何帮助

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}


int main()
{
#define SIZE 100
char *username[100];
char word[80];
int num_words = 0;
size_t p;
size_t NumberOfElements;

/* Read words into array */


while(1 == scanf("%s", word)) {
username[num_words] = emalloc((strlen(word) + 1) * sizeof(word[0]));
strcpy(username[num_words], word);
num_words++;
}


/* Print out array */
NumberOfElements = sizeof(username)/sizeof(username[0]);
printf("no. %lu\n", NumberOfElements);
for (p = 0; p < NumberOfElements; p++) {
printf("%s", username[p]);
}

return EXIT_SUCCESS;
}

错误-

Segmentation Fault (core dumped)

最佳答案

NumberOfElements = sizeof(username)/sizeof(username[0]);

将始终返回 100,如果您输入的字数少于 80 个字,则用户名中的其余元素将不会被分配内存,因此当您打印未分配的指针时,它将导致未定义的行为

当你打印 username[p] 时,你应该循环直到 num_words ,而不是循环直到 NumberOfElements

关于c - 为什么这会返回段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46599191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com