Search code examples
carraysstringpointersfree

Doublepointer with Strings in C / Pointers to Array with malloc


Can Someone explain to me why the first pointer (stringarray[0]) is missing in my output and how to solve it. also I'd like to know how I can free my memory of all malloc pointers.

int main(int argc, char **argv) {

[...]

char ** stringarray;
if (( stringarray = (char **)malloc(counter*sizeof(char)))== NULL){exit(0);}

int k = 0;
for (i = 0; i < len; i =i+1){
    if((strcmp(countries, districts[i]) == 0) && ( argvIntPeoplelimit <= people[i])) {
        if (( stringarray[k] = (char * ) malloc(100*sizeof(char)))== NULL){exit(0);}

        snprintf(stringarray[k],100,"The Country %s has %d people.",countries[i],people[i]);
        printf("%d %d %s %s %d\n",i,k,stringarray[k], countires[i],people[i] ); //here stringarray[k] k==0 has a value
        k=k+1;
    }  
}
write_file(stringarray,counter);
for (int f = 0; f < k; ++f)
{
    // if i call stringarray[0] nothing shows up


    //ERROR can't free(stringarray);

}
    return 0;
}

I don't know how to build up the structure pointers with strings that allows me to the handle the data over to " char *result[]" of write_file function.

void write_file(char *result[], int len);

Any help, tips, hints are great appreciated! Thank you!


Solution

  • I believe this is the correct way for allocating memory for an array of strings:

    // number of pointers/strings; don't have to cast the result of malloc
    char** stringArray = malloc(sizeof(char*) * 2);
    
    // allocate however many chars for each pointer
    for(i = 0; i < 2; ++i)
        stringArray[i] = malloc(sizeof(char) * 10);
    
    strcpy(stringArray[0], "Hello");
    strcpy(stringArray[1], "world!");
    
    printf("%s %s\n", stringArray[0], stringArray[1]);
    

    And for freeing the above, you'd do this:

    for(i = 0; i < 2; ++i)
        free(stringArray[i]);
    
    free(stringArray);