Reputation: 9708
I want to skip p from the start of {0,1,2,3}
, to {4,5,6,7}
etc. How do I do that?
#include <stdio.h>
int main() {
char td[6][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11},
{12, 13, 14, 15},
{16, 17, 18, 19},
{20, 21, 22, 23}
};
char* p = *td;
printf("Address of td: \t%p, value=%u\n", td, (int)**td);
printf("Address of p: \t%p, value=%u\n", p, (int)*p);
p++;
/* How do I skip to the start of {4,5,6,7} (ie to be pointing at 4) ? */
printf("Address of p: \t%p, value=%u\n", p, (int)*p);
return 0;
}
Upvotes: 1
Views: 776
Reputation: 147
td + 1 will also skip by 4 elements. Because td is pointing to first array consist of 4 elements.It is a pointer to a array
printf("Address of p: \t%p, value=%u\n", *(td+1), **(td+1));
example
char a[row][col];
for(i = 0 ; i < row*col ; i++)
printf("%c", *(*a+i) );
this will print the whole 2d array with just one loop.
Upvotes: 0
Reputation: 58271
You should first read this answer: Declaration-2
: Where I explained how char 2-D array stored in memory.
char*
p
points to td[0][0]
element in array that is 0
. If you wants to increment p
such that p
point to 4
that is td[1][0]
then increment p
by number of cols = 4 (array is row = 6 * col = 4).
p = p + 4;
Check this working code. I applied concept of row-major.
Upvotes: 1
Reputation: 5315
In order to skip to the next row, you need a pointer which points to the row containing four elements not a pointer to a single element.
So, the pointer would look like char (*p)[4] = td
now when you increment p by one it will be pointing to the next row ({4,5,6,7})
Also, your initialization of the character pointer is incorrect, it should be char *p = td
Upvotes: 0