Home > Net >  Pointers problems with C
Pointers problems with C

Time:12-22

I don't understand the difference in the t and p pointers. The t pointer gives the same output when printing t and *t only when using **t I get the value.

What's the difference between them?
The code is:

int main()
{
    int B [2][3] = {
      {2, 3, 6},
      {4, 5, 8}
    };
    int *p = B;
    int (*t)[3] = B;
    printf ("%d\n", p);
    printf ("%d\n", t);
    printf ("%d\n", *p);
    printf ("%d\n", *t);
    printf ("%d\n", **t);

    return 0;
}

Output is:

6422000
6422000
2
6422000
2

CodePudding user response:

Comments have addressed the importance of using the correct format specifiers, but here are a couple of other points to consider:

int *p is a single instance of a pointer to int, as such it can point to the location of a single int:

int *p = &B[0][0];//assigning address of p to the location of a single integer value

But int *p = B; because B is not a single int, should result in a warning. eg:

"warning: incompatible pointer types initializing 'int *' with an expression of type 'int [2][3]"

Also, the assignment:

int (*t)[3] = B;  

creates an array of 3 pointers to int, but serves to initialize only two of the three locations created because B is defined as having only two instances of 3 elements

int B [2][3] = {{2, 3, 6}, {4, 5, 8}};  

On my machine for example, the following address locations are assigned to t

t[0] == 0x0639FE94 //indicating location in memory of B[0]
t[1] == 0x0639FEA0 //indicating location in memory of B[1] 

It is unknown at this point what address t[2] is pointing at.

CodePudding user response:

Writing int *p = B; isn't a good idea but anyway, it puts the address of the very first element of B, 2 into p. So, p outputs the address(6422000) and *p outputs 2. All good till here.

What is t? It's a pointer to an array, B. What will happen when you print it, you'll get the address to B, which is always also the address of it's very first element, which happens to be 6422000. So, what will happen when you dereference t? You'll get and array, B in this case, which will then decay into a pointer and give you the memory address. And the memory address of B is 6422000. And **t will dereference the dereferenced array. The deference array is B, which will decay into the pointer, 6422000 in this case and that will be dereferenced again, giving 2.

Basically:

  • p: Address of the very first element of B, 2.
  • *p: Dereferenced p, in this case 2.
  • t: Address to B. Address of an array is also the address of it's very first element, equivalent to p.
  • *t: Dereferences into B, B will decay into it's very first element's pointer, equivalent to p.
  • **t: Dereferenced *t, which is 2.

Note: I know, the first element of B is {2, 3, 6}, not 2. I refer to 2 as "the very first element". That's inaccurate but for the purpose of explanation, I was forced to use the terminology.

  • Related