创建动态字符数组

Creating a dynamic char array

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

我试过使用 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]);
    }
}

我期望例如数组[0]到return字符串'alphabet'

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

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

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)