This is another example of my neverending confusion related to memory and pointers in C

79 views Asked by At

I am a newbie in C, but I have already watched dozens of videos on YT about how to understand pointers... Unfortunately, it seems my stupid brain is not getting the point about pointers. Could anyone help me to understand why I am getting such values in the output?

The output is: 1-40 256-296 64-104

#include <stdio.h>
int main() {
    int arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int arr_size = sizeof(arr1) / sizeof(arr1[0]);
    int arr2[arr_size];
    int arr3[arr_size];
    int *ptr1 = arr1;
    int *ptr2 = arr2;
    int *ptr3 = arr3;
    printf("%u-%u %u-%u %u-%u\n", *ptr1, sizeof(arr1), *ptr2, *ptr2+sizeof(arr2), *ptr3, *ptr3+sizeof(arr3));
    return 0;
}

Thanks for help!

1

There are 1 answers

18
Vlad from Moscow On

The arrays arr2 and arr3 are not initialized. So their elements have indeterminate values. Outputting uninitialized elements invokes undefined behavior.

Also to output a value of the type size_t you need to use the conversion specifier zu instead of u in a call of printf.

So the only valid call of printf will look the following way

printf("%d-%zu\n", *ptr1, sizeof(arr1) );

This call outputs the value of the first element of the array arr1 by means of the pointer ptr1 that (value) is equal to 1 and the size of the array itself that can be equal to 40 provided that sizeof( int ) is equal to 4.