4

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;
}
1
  • 1
    Ask the authors of thar website Commented Sep 26 at 19:39

1 Answer 1

8

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;
}

Working pointer visualization

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.