gpt4 book ai didi

创建动态字符数组

转载 作者:行者123 更新时间:2023-11-30 16:18:32 26 4
gpt4 key购买 nike

我正在尝试读取文件并将单词存储到动态字符数组中。现在我收到了段错误(核心转储)错误。

我尝试使用 strdup() 和 strcpy() 仍然遇到相同的错误

char ** array;

int main(int argc, char * argv[]){
int size = 0;
int i;
FILE * file;
char * line;
size_t len;
ssize_t read;


file = fopen("wordsEn.txt", "r");
if(file == NULL){
printf("Error coudl not open wordsEn.txt\n");
return -1;
}

while((read = getline(&line, &len, file)) != -1){
size++;
}

array = (char **) malloc((sizeof(char *) * size));
rewind(file);

i = 0;
while((read = getline(&line, &len, file)) != -1){
//strcpy(array[i], line);
array[i] = strdup(line);
i++;
}

for(i = 0; i < size; i++){
printf("%s", array[i]);
}
}

我期望例如 array[0] 返回字符串“alphabet”

最佳答案

I am getting a Segmentation fault (core dumped) error.

警告每次必须将 line 重置为 NULL 并将 len 重置为 0 时,通过 getline 获取新分配的行,对于实例:

while(line = NULL, len = 0, (read = getline(&line, &len, file)) != -1){

请注意,您不必读取两次文件,您可以使用malloc然后realloc来增加(真正)动态数组的大小

<小时/>

提案:

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

int main()
{
char ** array = malloc(0);
size_t size = 0;
FILE * file;
char * line;
size_t len;
ssize_t read;

file = fopen("wordsEn.txt", "r");
if(file == NULL) {
printf("Error coudl not open wordsEn.txt\n");
return -1;
}

while (line = NULL, len = 0, (read = getline(&line, &len, file)) != -1){
array = realloc(array, (size+1) * sizeof(char *));
array[size++] = line;
}
free(line); /* do not forget to free it */
fclose(file);

for(size_t i = 0; i < size; i++){
printf("%s", array[i]);
}

/* free resources */
for(size_t i = 0; i < size; i++){
free(array[i]);
}
free(array);

return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall ar.c
pi@raspberrypi:/tmp $ cat wordsEn.txt
turlututu foo
bar
loop
pi@raspberrypi:/tmp $ ./a.out
turlututu foo
bar
loop
pi@raspberrypi:/tmp $

在 valgrind 下执行:

pi@raspberrypi:/tmp $ valgrind ./a.out
==13161== Memcheck, a memory error detector
==13161== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==13161== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==13161== Command: ./a.out
==13161==
turlututu foo
bar
loop
==13161==
==13161== HEAP SUMMARY:
==13161== in use at exit: 0 bytes in 0 blocks
==13161== total heap usage: 11 allocs, 11 frees, 5,976 bytes allocated
==13161==
==13161== All heap blocks were freed -- no leaks are possible
==13161==
==13161== For counts of detected and suppressed errors, rerun with: -v
==13161== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

关于创建动态字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55875518/

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