Reputation: 508
I know how can I use pointers in C with the 1-D array. like the following: but what if we have 2-D arrays? how can I address them by pointers? Thank you.
#include <stdio.h>
int main() {
int dar[4] = {1,2,3,4};
int *sar = NULL;
sar = dar;
for (int i = 0; i < 4; i++) {
printf("%d ", *(sar + i));
}
}
Upvotes: 2
Views: 98
Reputation: 148910
A 2-D array is... a 1-D array of 1-D arrays, and you can use the common pointer arithmetics on both.
That means that you can simply do:
#include <stdio.h>
int main() {
int dar[2][3] = {{1,2,3},
{4,5,6}};
for (int i = 0; i < 2; i++) {
int *bar = *(dar + i); // pointer to the row
for (int j = 0; j < 3; j++) {
printf("%d ",*(bar+j)); // access the values
}
printf("\n");
}
printf("\n");
}
It works, because in dar + i
, dar
decays to a pointer to its first row, so *(dar + 1)
(which is *by definition dar[i]
) represents the i-th row and in turn decays to a pointer to the first element of that row.
Disclaimer: this is just an addition to JJcopl's answer, but too rich to fit in a comment...
Upvotes: 0
Reputation: 182
This may also help.
#include <stdio.h>
int main()
{
int dar[2][3] = {1,2,3,
4,5,6};
int index=0;
for (int line = 0; line < 2; line++)
{
for (int col=0; col<3;col++)
{
printf("%d ", *(dar[0]+index));
index=index+1;
}
printf("\n");
}
return (0);
}
Upvotes: 1
Reputation: 508
Thanks to @Qubit I solved the problem. I post the answer for future reference.
#include <stdio.h>
int main() {
int dar[2][3] = {{1,2,3},
{4,5,6}};
int *sar = NULL;
int *bar = NULL;
sar = dar[0];
bar = dar[1];
for (int i = 0; i < 3; i++) {
printf("%d ", *(sar+i));
}
printf("\n");
for (int j = 0; j < 3; j++) {
printf("%d ",*(bar+j));
}
printf("\n");
}
Upvotes: 0