Search code examples
cc89

C - Read and allocate an arbitrary array of strings


I'm getting mad at a really simple function to read an array of strings given in input. I also know how to read strings and put them into an array without writing a proper function (writing all thing in main() ). This is the example I'm using.

I think that the main obstacle is to use properly the 3-star pointer.

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

int read(char ***a, int *len){
    scanf("%d", len);

    if(*len <= 0) return 1;

    *a = malloc(*len * sizeof(char *));
    if(*a == NULL) return 1;

    for(int i=0; i<*len; i++){
        a[i] = malloc(101 * sizeof(char));
        scanf("%s", *a[i]);
    }
    return 0;
}

int main(){
    int len, i;
    char **A;
    // read an array of strings
    if( read(&A, &len)) return 1;

    // DO SOMETHING

    for(i=0; i<len; i++)
        printf("%s\n", A[i]);

    return 0;
}

Solution

  • You need to look out for two things: operator precedence and indirection level. Do enclose your variables in parenthesis if you don't know which operator has higher precedence than the other:

    #include <stdio.h>
    #include <stdlib.h>
    
    int read(char ***a, int *len)
    {
        scanf("%d", len);
    
        if (*len <= 0) return 1;
    
        *a = (char **)malloc(*len * sizeof(char *));
        if (*a == NULL) return 1;
    
        for (int i = 0; i<*len; i++) {
            (*a)[i] = (char *)malloc(101 * sizeof(char)); // note this line
            scanf("%s", (*a)[i]);
        }
        return 0;
    }
    
    int main()
    {
        int len, i;
        char **A;
        // read an array of strings
        if (read(&A, &len)) return 1;
    
        // DO SOMETHING
    
        for (i = 0; i<len; i++)
            printf("%s\n", A[i]);
    
        //system("PAUSE");
        return 0;
    }