创建一个动态字符数组

时间:2019-04-26 22:17:21

标签: c file char dynamic-arrays

我试图读取一个文件,并将单词存储到动态char数组中。现在,我遇到了分段错误(核心转储)错误。

我尝试使用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'

1 个答案:

答案 0 :(得分:0)

  

我遇到了分段错误(核心转储)错误。

警告您每次必须将 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)