Ambiguity in pointers

Hello,

Could you please explain this?

Dereference operator is used to access or manipulate data contained in memory location pointed to by a pointer. but in the below code when we use the dereference operator we get address instead of data contained in memory location .

I'm confused.

Thanks

Please See:

https://ibb.co/3zHCPHZ
What's a ?
Looks like a is an int*** (or is a 3D array).
So...
*a is an int** (value is an address)
**a is an int* (value is an address)
***a is a int (value is an int)

If you have int arr[10], then you need to dereference once to get an int.
If you have int arr[10][9][8], then you need to dereference all three layers to get an int.

int arr[10] is an array.
int arr[10][10] is an array of arrays.
int arr[10][10][10] is an array of arrays of arrays.
etc.
Last edited on
That code assumes that pointer and int are the same size. It won't work on a 64 bit OS. I'd look for another book.
dhayden, you're saying that because it's using %d and %u specifiers, right? It would be OK if it were %p?
Ganado, correct.
Thank you , @Ganado

With the below code, we can access value of 2-D array with one layer dereference.
I expect for access value of 2-D we should need two dereference **ptr instead *ptr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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", *(ptr + 4)); 

	return 0;
}
I don't know what your compiler is smoking, it must be on some very permissive mode.
 In function 'int main()':
14:6: error: cannot convert 'int [3][3]' to 'int*' in assignment
'int [3][3]' to 'int*'


Are you compiling as C or as C++???

For MS VS 2019, if you compile as C++ you get the error C2440 cannot convert from 'int [3][3]' to 'int *'. But if you compile as C, you get the warning C4047 'int *' differs in levels of indirection from 'int (*)[3]' - but the compilation succeeds!


True, I just assume a thread is C++ unless the OP specifically says it's C.
I guess C is more permissive here, but my guess is it's in the realm of "don't do that"/undefined behavior.

Edit: In this particular case, I assume assigning the array to an int* will now treat that int* as if it's pointing to a contiguous array of length 9, but I'm making a lot of assumptions in this post.
Last edited on
C is more of the 'well if you really want to, I guess you know what you're doing even I don't agree'. C++ is more 'don't be so stupid!'.
Last edited on
Topic archived. No new replies allowed.