C Pointers – Understanding 2D Arrays and Pointers

c++pointers

Hey All, I am a pointer newbie and in the following code, I am trying to store the values of a 2 D array in a structure and then print them. However, I get a compilation error at the line: fd->mychar[i] = newptr[i]; I get that while char * str is same as str[], char ** str isnt the same as str[][], but I cant find a solution to make the following work.

typedef struct mystruct{
  char mychar [20][20];
}mystruct_t;

void printvalues ( char ** newptr){
  int i;
  mystruct_t * fd;
  for (i=0;i<3;i++){
    fd->mychar[i] = newptr[i];
    printf("My value is %s and in struct %s\n", newptr[i], fd->mychar[i]);
  }
}
int main (int argc, char **argv){
 int i;
 char * abc[5] = {"123", "456", "789"};

 for (i=0;i<3;i++){
  printf("My value is %s\n", abc[i]);
 }
 printvalues(abc);
}

Best Answer

Most of the issue was your use of an unallocated structure. You used a pointer to mystruct_t but never allocated it. The following runs for me:

#include <stdio.h>

typedef struct mystruct
{
   char*  mychar [20];
} mystruct_t;

void printvalues( char** newptr )
{
   int i;
   // note: you used an unallocated pointer in your original code
   mystruct_t fd;
   for ( i = 0; i < 3; i++ )
   {
      fd.mychar[i] = newptr[i];
      printf( "My value is %s and in struct %s\n", newptr[i], fd.mychar[i] );
   }
}

int main( int argc, char **argv )
{
   int i;
   char * abc[5] = { "123", "456", "789" };

   for ( i = 0; i < 3; i++ )
   {
      printf( "My value is %s\n", abc[i] );
   }
   printvalues( abc );
}
Related Question