Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c - How would I append a 2D array of char dynamically?

This code is raising segmentation fault, I'm not entirely where I did wrong. As soon as I input a string, it causes a segmentation fault. I was expecting it to append a new string in a new element of the char array.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char** append(char** b, size_t* size, char target[]);
int main(){
    size_t size = 1;
    char** b = malloc(sizeof(char)*size);
    while(1){
      char input[100] = "";
      scanf("%99s", input);
      if (strcmp(input, "end") == 0)
          break;
      b = append(b, &size, input);
    }
    for(int i = 0; i < size; i++)
        printf("%s ", b[i]);
    return 0;
}
char** append(char** arr, size_t* size, char target[]){
    *size += 1;
    size_t b = *size;
    char** new_arr = realloc(arr, b * sizeof(char));
    strcpy(new_arr[b - 1], target);
    return new_arr;
}
question from:https://stackoverflow.com/questions/65900525/how-would-i-append-a-2d-array-of-char-dynamically

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

1 Reply

0 votes
by (71.8m points)

Keeping your logic to have one last empty element. You want an array of char * so you need to allocate size * sizeof(char *)

You need memory for scanf and check the returned value Then you need to copy the scan string, using strdup for example

A list can be better for your case

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char** append(char** b, size_t* size, const char* target);
int main(){
    size_t size = 1;
    char** b = malloc(sizeof(char*)*size);
    while(1){
      char input[256];
      int res = scanf("%s", input);
      if (res == EOF || strcmp(input, "end") == 0)
          break;
      b = append(b, &size, input);
    }
    for(int i = 0; i < size; i++)
        printf("%s ", b[i]);
    printf("
");
    return 0;
}
char** append(char** arr, size_t* _size, const char* target){
    size_t size = *_size;
    arr[size - 1] = strdup(target);
    size++;
    char** new_arr = realloc(arr, size * sizeof(char *));
    *_size = size;
    return new_arr;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...