-1

Here's the code:

  char * pointer, ** ptr2;
  char ptr[5][100];

  strcpy(ptr[0],"fasfasf fasfas");
  strcpy(ptr[1],"sfasfa");

  ptr2=ptr;

When trying to read what's inside ptr2 it tells me that it cannot access that memory but i can access it through ptr. Any ideas on why is it failing? Thanks

Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92
  • 3
    A pointer to a pointer is not the same as an array of arrays. See e.g. [this old answer of mine](http://stackoverflow.com/questions/18440205/casting-void-to-2d-array-of-int-c/18440456#18440456) for a description of why. – Some programmer dude Nov 01 '16 at 15:37
  • Isn't your compiler warning you about the assignment `ptr2 = ptr`? – ad absurdum Nov 01 '16 at 15:45
  • It wasnt. I managed to work something around so that i can do what i wanted, thanks for the help guys – Roberto Sanchez Nov 01 '16 at 15:49

2 Answers2

0

As Some programmer dude says, an array of arrays is not the same as a pointer to a pointer.

Ask yourself this question, what does ptr[0] give you? Answer: an array of 100 chars.

So, ptr is acting like a pointer to an array of 100 chars, not, as you were trying, a pointer to a pointer to a char.

If we want to declare a pointer that will act like your ptr we declare it like this:

char (*ptr2)[100]

having done that you can then do

ptr2 = ptr;

like you were trying with no problems.

John Sharp
  • 801
  • 4
  • 5
0

The problem is in the line:

 ptr2=ptr;   // assignment from incompatible pointer type.

When working with multidimensional arrays I have observed that for passing the starting point of the array into a variable it is necessary to extract the address of the first item of the array.

char *ptr2;
char ptr[5][100];       // bi-dimensional
char another_ptr[100];  // uni-dimensional
ptr2 = ptr;             // COMPILER COMPLAINS
ptr2 = &ptr[0][0];      // array bi-dimensional - COMPILER DOES NOT COMPLAIN
ptr2 = another_ptr;     // COMPILER DOES NOT COMPLAIN