Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to C and just learning about malloc and realloc and help from the community in understanding how to do this. I have a file with paragraphs that I need to read line by line and store the lines in array o strings while creating the arrays dynamically.

Inillially the MAX number of lines to store is 10 if this is not sufficient we use realloc to double the memory and print a message indicating that we reallocated memory. So far this is what I have and need help to finish

int main(int argc, char* argv[])
{
  char* p = malloc(10* sizeof(char));
  while(buffer, sizeof(buffer), stdin)
  {

  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
186 views
Welcome To Ask or Share your Answers For Others

1 Answer

while(buffer, ... does nothing, use fgets:

data.txt:

one
two
three

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

#define BUF_LEN 32

extern char *strdup(const char *);

int main(void)
{
    char **arr = NULL;
    char buf[BUF_LEN];
    size_t i, n = 0;
    FILE *f;

    f = fopen("data.txt", "r");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    while (fgets(buf, BUF_LEN, f)) {
        arr = realloc(arr, sizeof(*arr) * (n + 1));
        if (arr == NULL) {
            perror("realloc");
            exit(EXIT_FAILURE);
        }
        arr[n] = strdup(buf);
        if (arr[n++] == NULL) {
            perror("strdup");
            exit(EXIT_FAILURE);
        }
    }
    for (i = 0; i < n; i++) {
        printf("%s", arr[i]);
        free(arr[i]);
    }
    free(arr);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...