pointers

Hi!

If I write in c:

uint32_t* virtaddr;

Does it mean that the pointer indexing is in offset of 32 bits?
For example:
virtaddr[0] = 32 bit value
virtaddr[1] = next 32 bit value

Last edited on
Yes, the array subscripting operator, i.e. addr[n], gives you the n-th element of the array, starting at address addr.

The "offset", in bytes, between subsequent elements is determined by the type of the pointer. In your example, it is 4 bytes (32-Bit).

The same goes for pointer arithmetic:

1
2
3
4
5
6
7
8
const uint32_t values[] = { 1U, 2U, 3U };
const uint32_t *ptr = &values[0U];
	
printf("%u\n", *ptr);
ptr += 1U;
printf("%u\n", *ptr);
ptr += 1U;
printf("%u\n", *ptr);


Note how ptr += n moves the pointer by n elements, not necessarily by n bytes!

(The C compiler will refuse to do pointer arithmetic on void* pointers, because the element size is not known for such pointers)
Last edited on
Cool, thanks!

Is the definition of a pointer say something about how long is the pointer itself?
if I have:
uint32_t* virtaddr;

1. Can virtaddr be 0x1234567890 (5 bytes long)?

2. Does the compiler shows the pointer value in byte offset?
Last edited on
The pointer (memory address) itself always has the same size, regardless of it's underlying type.

However, the pointer size depends on the machine!

Typically, the size of a pointer is 32 bits (4 bytes) on the 32-Bit machine, and it is 64 bits (8 bytes) on the 64-Bit machine.

(machines with "segmented" memory are a bit more complicated, but I think we'll ignore them for now 😏)

Consider this code:
1
2
3
4
5
6
7
8
9
10
11
const uint32_t values32[] = { 1U, 2U, 3U };
const uint32_t* ptr32 = &values32[0U];

printf("uint32_t pointer size: %zu\n", sizeof(ptr32));
printf("uint32_t element size: %zu\n\n", sizeof(*ptr32));

const uint64_t values64[] = { 1U, 2U, 3U };
const uint64_t* ptr64 = &values64[0U];

printf("uint64_t pointer size: %zu\n", sizeof(ptr64));
printf("uint64_t element size: %zu\n\n", sizeof(*ptr64));

Output on the "x64" (64-Bit) machine:
uint32_t pointer size: 8
uint32_t element size: 4

uint64_t pointer size: 8
uint64_t element size: 8

Output on the "x86" (32-Bit) machine:
uint32_t pointer size: 4
uint32_t element size: 4

uint64_t pointer size: 4
uint64_t element size: 8


If you print a pointer, as in the following examples, you get the actual address, in bytes, not the element index:
1
2
3
printf("%p\n", my_pointer);     // <-- print address of 1st element
printf("%p\n", &my_pointer[0]); // <-- print address of 1st element (again)
printf("%p\n", &my_pointer[7]); // <-- print address of 8th element 

(Be aware the leading zero's may not be printed, but they still are there!)
Last edited on
Thank you 👌
I would point out that if you do any "pointer math" on your pointer the address currently being pointed to might not be the first address of your array as you might expect.

https://www.geeksforgeeks.org/pointer-arithmetics-in-c-with-examples/
Topic archived. No new replies allowed.