learner
learner

Reputation: 4818

cannot convert 'int [2][4]' to 'int**' in assignment

I am trying to do some stuff with pointers. I wrote the following code.

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int **p;

    int x[][4] = {{5,3,4,2},{5,3,4,2}} ;

    p = x;
    printf("%d\n", p);

    p++;
    printf("%d\n", p);
    return 0;
}

But I am getting errors. The error is at line :

p = x;

I think I am confused with pointers. Please help me with it.

Upvotes: 2

Views: 2697

Answers (2)

Josja
Josja

Reputation: 141

The mistake you made was the following: you knew you can handle arrays in a similar way as constant pointers, which also implies that pointers to pointers are similar to arrays of pointers, and which also implies that pointers to arrays are similar to arrays of arrays. However, arrays of pointers are different from arrays to arrays. "You only can play with the interpretation of the highest level of addressing."

This becomes more clear if you look at the size with which thing can be incremented (see below: 1. ~ 4. and 2. ~ 3. but not e.g. 1. ~ 2.).

From your question, the answer and reactions to the answer, I thought it would be appropriate to summarize all the weird syntax coming here together...

  1. int **p is a pointer to a pointer of integers,

    which would look like [address of int*] in memory.

    p++ will move p by an amount sizeof(int *), which is the size of an hexadecimal number representing the memory location of a pointer to an integer.

  2. int (*x)[4] is a pointer to an instance of int[4], i.e. a pointer to arrays of size 4 with integers.

    This would look like [address of int[4]] in memory.

    so x++ will move x by an amount of sizeof(&(int[4])), the amount of memory used to address an array of 4 integers

  3. int y[][4] is an array of arrays of 4 integers each, so basically y[1] will points to the location to which y++ would points if you would have declared instead 'int (*y)[4]'.

    [ However, you cannot move around with "arraypointers" because they are implicitly declared as constant (int [] ~ int * const). ]

    It will looks like [address of int[4]][address of int[4]][address of int[4]]... in your memory.

  4. int *z[4] is an array of pointers to integers

    so it will looks like [address of int*][address of int*][address of int][address of int] in memory. z[1] will give te value at the location z[0] + sizeof(int*).

Upvotes: 1

R Sahu
R Sahu

Reputation: 206607

x decays to type int (*)[4]. Hence use:

int (*p)[4];

Of course, change

printf("%d\n", p);

appropriately, such as:

printf("%d\n", p[0][0]);

Update

Given the declaration of x, you may use:

int (*p)[4] = x;

or

int* p[] = {x[0], x[1]};

But you may not use:

int** p = x;

Upvotes: 2

Related Questions