Access Violation - Pointers in C

Hello,

The second printf doesn't work. could you please explain?
Thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# include <stdio.h>


int main()
{
	int n[3][3] =
	{
		{2,4,3 },
		{6,8,5},
		{3,5,1 }
	};

	int** ptr;
	ptr = n;


	printf_s("\n%d", *(*(n + 2) + 1)); //5

	printf_s("\n%d", *(*(ptr + 2) + 1)); //5 and doesn't work! --- ptr and n have same address

	return 0;
}
Your pointer is the wrong type.
At the very least, you should have got a warning from your assignment.

The "array becomes a pointer" rule only applies to the left-most dimension of an array, not all of them.
So [N] gets you to *, [X][Y] goes to (*)[Y], not **.

1
2
	int (*ptr)[3];
	ptr = n;


And yes, you need the brackets in the declaration of your pointer.
int *ptr[3] is something different to int (*ptr)[3]
The essential questions are:
How much is +2?
What is there?

int* * ptr; The ptr is a pointer to pointer.
When you take value of ptr and add 2 to it, you add 2 * sizeof(int*) bytes to the value.

int n[3][3]
When you take value of n and add 2 to it, you add 2 * sizeof(int[3]) bytes to the value.
Last edited on
i'm not sure how you were getting 5 but when I do this is seems to work. I know c is slightly different. The weird thing is if i try to cut int* b out of the situation it gives me an error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
	int n[3][3] =
	{
		{2,4,3 },
		{6,8,5},
		{3,5,1 }
	};
	
	int* b = &n[0][0];
	int** ptr=&b;
	
	printf_s("\n%d", *(*n+2)+1); //5

	printf_s("\n%d", *(*ptr+2)+1); //5 and doesn't work! --- ptr and n have same address

	return 0;
}

//also this seems to be acceptable
int* b = (int*)n;
	int** ptr=&b;
Last edited on
https://comp.lang.cpp.moderated.narkive.com/EtKG7hO6/cannot-convert-int-to-int-in-assignment

(Related?) examples:
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
26
#include <cstdio>


int main()
{
    constexpr int Rows { 3 };
    constexpr int Cols { 4 };

    int n[Rows][Cols] {
          {  0,  1,  2,  3 }
        , {  4,  5,  6,  7 }
        , {  8,  9, 10, 11 }
    };

    int (* p1)[Cols] { n };
    int* p2 { &n[0][0] };
    int* tmp[Rows] { n[0], n[1], n[2] };
    int** p3 { tmp };

    std::printf( "n : %d\n", *(*(n  + 2) + 1) );
    std::printf( "p1: %d\n", *(*(p1 + 2) + 1) );
    std::printf( "p2: %d\n", *(p2 + 2 * Cols + 1) );
    std::printf( "p3: %d\n", *(*(p3 + 2) + 1) );

    return 0;
}


Output:
n : 9
p1: 9
p2: 9
p3: 9


Topic archived. No new replies allowed.