2

I have a file level variable called char *ptr, this pointer is pointing to a 2d char array that has X variable rows and Y variable columns.

I have created a simple print method to try and print every single char in this 2d array using the file level pointer *ptr

char *ptr;

someMethod() {
 ptr = *array; //point to the 2d char array
}


print() {
 for(int x = 0; x < rowMax; x++) {
  for(int y = 0; y < columnMax; y++) {
    printf("%c", *(*(ptr + x) + y); //error here
 }
 printf("\n");
}

But with this code I get a indirection requires pointer operand compile error, i'm wondering what i'm doing wrong here.

  • Similar question has some good explanations already: http://stackoverflow.com/questions/13554244/how-to-use-pointer-expressions-to-access-elements-of-a-two-dimensional-array-in – pete shanahan Oct 23 '16 at 23:26
  • `char *ptr` cannot point to a 2D array. It actually does not point to an array at all. But it **can** point to an element of a 1D array. If you want a 2D array, use one! No need for error-prone manual fiddling with indexes. – too honest for this site Oct 23 '16 at 23:26
  • I am creating different sized 2d arrays in my other method, so I cannot create a file level but instead only a pointer which points to different 2d arrays that are created. – user2946986 Oct 23 '16 at 23:30
  • Yes, but why is that a reason not to use a 2D array? (rhetorical question) – too honest for this site Oct 23 '16 at 23:58
  • There's nothing wrong with using one dimensional arrays as two dimensional. You simply need to keep track of the width of the array, as your indexing should be at `array[row*width + column]`. Note y is traditionally used for rows, and x is used for columns. – MarcD Oct 24 '16 at 01:26
  • This line `printf("%c", *(*(ptr + x) + y);` is pretty badly formed. ptr + x gives you a char*, then you dereference it and get a char, which you then add y to, and then you try to dereference that char, which can't possibly work. Use the syntax I showed you above. – MarcD Oct 24 '16 at 01:29
  • If you haven't already, always turn on your compiler warnings (e.g. `-Wall -Wextra`) That will detail any pointer assignment problems in your code. (you can add `-pedantic` to see virtually all compiler warnings) Do not consider your code reliable until it compiles without ***any*** warnings. – David C. Rankin Oct 24 '16 at 03:47

0 Answers0