carrayspointersmultidimensional-arraynspointerarray

How to hand over values to a double-pointer and print the values out as if it would be an multidimensional array? (C)


I have following struct defined which I can not change:

typedef struct _content {
    int length;
    char **lines;    
} content_t;

I initialized it in the main function like that:

struct _content cont;
cont.length = 6;
cont.lines[cont.length-1][255];

I try to assign a value to a certain element of the multidimensional array and also to print the value out- which doesn't work:

cont.lines[1][1] = "A";
printf("\n\n%c", cont.lines[1][1]);

What am I doing wrong here? Many Thanks


Solution

  • int main(){
    
    content_t cont;
    cont.length = 6;
    cont.lines=malloc(sizeof(char*)*cont.length);
    
    for(int i=0;i<cont.length;i++) cont.lines[i]=malloc(255);
    
    printf("\n\n%c", cont.lines[1][1]);
    
    
    for(int i=0;i<cont.length;i++) free(cont.lines[i]);
    free(cont.lines);
    
    
    }
    

    that's the right way to do it