Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a vector name as a pointer

Tags:

arrays

c

pointers

I know I can use a vector name as a pointer. For example, if I want to see the contents of an array using this technique, I can do it this way:

#include <stdio.h>

#define MAX 5

int main(void) {
    int *p;
    int a[MAX] = {1, 2, 3, 4, 5};

    for(p = a; p < a + MAX; p++)
        printf("%d -> (%p)\n", *p, p);

    printf("\n");

    return 0;
}

I want to do the same thing with a two-dimensional vector using the same technique (since a two-dimensional vector in C is processed as a single-dimensional vector), and I thought I'd do it like this:

#include <stdio.h>

#define MAX 5

int main(void) {
    int *p;
    int b[MAX][MAX] = {
        {1, 2, 3, 4, 5},
        {6, 7, 8, 9, 10},
        {11, 12, 13, 14, 15},
        {16, 17, 18, 19, 20},
        {21, 22, 23, 24, 25}
    };

    for(p = b; p < b + MAX * 2; p++)
        printf("%d -> (%p)\n", *p, p);

    printf("\n");

    return 0;
}

but it does not work. I could write:

for(p = &b[0][0]; p <= &b[MAX - 1][MAX - 1]; p++)
        printf("%d -> (%p)\n", *p, p);

but I'd like to understand why I can't use syntax like the one used for the one-dimensional vector.

like image 816
Roberto Rocco Avatar asked Apr 29 '26 21:04

Roberto Rocco


1 Answers

When you use the name of an array (there are no "vectors" in C), it "decays" into a pointer to the array's first element. That's simple and clear for simple (1D) arrays, but when you move to "2D" arrays, things are more complicated. First of all, the term "2D array" is ambiguous in C -- there are arrays of arrays and arrays of pointers, either of which can act like a 2D array, but they are very different.

In your case, you have an array of arrays, so you can do something like:

int b[MAX][MAX] = ...
int (*p1)[MAX];
int *p2;

for (p1 = b; p1 < b + MAX; p1++)
    for (p2 = *p1; p2 < *p1 + MAX; p2++)
        printf("%d -> (%p)\n", *p2, p2);

here, you use p1 to iterate over the outer array (so p1 is a pointer to an array), and then use p2 to iterate over each array.

If you really want to do it as a single loop, you can do

int *p;
for (p = *b; p < *(b + MAX); p++)
    printf("%d -> (%p)\n", *p, p);
like image 69
Chris Dodd Avatar answered May 02 '26 22:05

Chris Dodd