Assigning memory to double pointer?

后端 未结 7 915
广开言路
广开言路 2020-12-04 16:18

I am having trouble understanding how to assign memory to a double pointer. I want to read an array of strings and store it.

    char **ptr;
    fp = fopen(\         


        
7条回答
  •  醉梦人生
    2020-12-04 16:39

     char **ptr;
        fp = fopen("file.txt","r");
        ptr = (char**)malloc(sizeof(char*)*50);
        for(int i=0; i<50; i++)
        {
           ptr[i] = (char*)malloc(sizeof(char)*50);
           fgets(ptr[i],50,fp);
        }
    
    fclose(fp);
    

    may be your typo mistake but your loop should be of 50 instead of 20 if you are looking for 50 x 50 matrix. Also after allocation of memory mentioned above you can access the buffer as ptr[i][j] i.e in the 2D format.

提交回复
热议问题