I’m new to C and I’m trying to understand how pointers work. In this piece of code, when I run it on Python Tutor (pythontutor.com) to see how the stack and heap work, I never see the pointer being created in either the stack or the heap. Yet, I am able to printf the values that the pointer points to. I don’t understand why the pointer isn’t visible in the memory visualization.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int length = 5;
int *numbers[length];
for (int i = 0; i < length; i++) {
numbers[i] = malloc(sizeof(int));
if (!numbers[i]) {
perror("malloc");
exit(1);
}
*numbers[i] = i * 10;
}
for (int i = 0; i < length; i++) {
printf("numbers[%d] = %d (address=%p)\n", i, *numbers[i], (void*)numbers[i]); // It works
}
return 0;
}
This is currently a limitation of Python Tutor. From C and C++ known limitations:
doesn’t show some arrays like VLAs
If you change to a fixed-size array it will show the pointers.
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 5
int main(void) {
int *numbers[LENGTH];
for (int i = 0; i < LENGTH; i++) {
numbers[i] = malloc(sizeof(int));
if (!numbers[i]) {
perror("malloc");
exit(1);
}
*numbers[i] = i * 10;
}
for (int i = 0; i < LENGTH; i++) {
printf("numbers[%d] = %d (address=%p)\n", i, *numbers[i], (void*)numbers[i]); // It works
}
return 0;
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With