Home > front end >  array of pointers as a global variable
array of pointers as a global variable

Time:06-15

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related