简体   繁体   中英

How do I dynamically create an array of strings using scanf in C

So I have been searching through stack overflow for a little over an hour and I don't understand why this function is giving me a segmentation error. I want to create a string array, scan strings in through scanf, dynamically change the size of each string and return the string array. Can anyone help? Thank you.

char** readScores(int* count) {
    int c = 0;
    char** arr =(char**)malloc(100 * sizeof(char*));
    char* in;
    while(scanf("%s", in) != EOF) {
        arr[c] = (char*)malloc(strlen(in)+1);
        strcpy(arr[c], in);
    }
    *count = c;
    return arr;
}
char* in;
while(scanf("%s", in) != EOF) {

This tells the computer to read from standard input into the char buffer that in points to.

Which does not exist, because in is not initialised to anything (let alone a valid buffer).

I would not use scanf only fgets.

You need to allocate memory dor the arr and for every line referenced by elements of arr

char** readScores(size_t *count) {
    size_t lines = 0;
    char** arr = NULL, **tmp;
    char* in = malloc(MAXLINE), *result;
    size_t len;

    if(in)
    {
        do{
            result = fgets(in, MAXLINE, stdin);           
            if(result)
            {
                len = strlen(in);
                tmp = realloc(arr, sizeof(*tmp) * (lines + 1));
                if(tmp)
                {
                    arr = tmp;
                    len = strlen(in);
                    arr[lines] = malloc(len + (len == 0));
                    if(arr[lines])
                    {
                        if(len) memcpy(arr[lines], in, len - 1);
                        arr[lines++][len] = 0;
                    }
                    else
                    {
                        // error handling     
                    }
                }
                else
                {
                    // error handling 
                }
            }
        }while(result);
        free(in);
    }
    *count = lines;
    return arr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM