I am trying to decrement a pointer while setting values to what the pointer is poiting to. When setting the values they show that they have been properly set, but when trying to retrieve them again it doesnt return the right values. Why is this, and how can I get it to work?
This is the code I tried:
int a = 0; int* sp = &a; int* start_sp = &a; for (int i = 0; i <= n; i++) { *sp = i; printf("%d, %d\n", *sp, sp); sp--; } sp = start_sp; printf("\n"); for (int i = 0; i <= n; i++) { printf("%d, %d\n", *sp, sp); sp--; } The output I get is:
0, 6291028 1, 6291024 2, 6291020 3, 6291016 4, 6291012 0, 6291028 1, 6291024 0, 6291020 6283584, 6291016 0, 6291012 Why is this happening?
a.how can I get it to work?By actually using memory you own.void *pointer is%p, and a cast is needed. Mismatching format specifier and argument type also leads to undefined behavior.mallocthe data will be stored on the heap, and the same with a normal array declaration, but that wouldn't really work since the array is of an unknown size. How would I do this then? @tkausl