0

I want to use an array of pointers in a function and then visualize his values on the main function. I thought to use the array of pointer as a global variable but on the main function it doesn't show the same values of the void function. This is my first time asking a quest on stackoverflow so consider me as a beginner.

int *temp[65];

static void save_value(int t){
    int vet[64];
    int sum;
    int i;
    for(i=0;i<64;i++){
        vet[i]=0;
        temp[i]=0;
    }
    for(i=0; i<64; i++){
        sum = t ++;
        vet[i]=sum;
        temp[i]=&vet[i];
        printf("Temp for = %d\n", *temp[i]);
    }
    printf("\n");
}

int main(int argc, char** argv) {
    int i;
    int value;
    value=1;
    save_value(value);
    for(i=0; i<64; i++){
            printf("Temp = %d\n", *temp[i]);
    }
    return 0;
}

2 Answers 2

1

TL;DR The pointers in the global array of pointers point to invalid memory.

In the function save_value, pointers to the values in the array vet are assigned into the global array temp. The array vet is allocated on the stack and the values within it are only valid while save_value runs.

Therefore, a pointer value in temp in the closing printf statement cannot be relied upon to produce a valid value as the memory that was allocated to the array vet is no longer reserved for that purpose.

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

Comments

0

You are saving the address of stack variables to be used after returning from a function, this results in undefined behavior

you can fix it several ways - for example

static void save_value(int t) {
    static int vet[64]; <<<<===
    int sum;
    int i;
    for (i = 0; i < 64; i++) {
        vet[i] = 0;
        temp[i] = 0;
    }
    for (i = 0; i < 64; i++) {
        sum = t++;
        vet[i] = sum;
        temp[i] = &vet[i];
        printf("Temp for = %d\n", *temp[i]);
    }
    printf("\n");
}

or make vet a global too

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.