arrayscpointersinteger

How to set int array pointer within for loop in c


The following code is trying to set the test array in the first for loop, but it can't be used in the second for loop.

int main()
{
    int *test[3];
        
    /** Try to set the array value one by one */
        
    for (int i = 0; i < 3; i++)
    {
        test[i] = &i;
    }
        
    /** Try to print the array value one by one */
    
    for (int i = 0; i < 3; i++)
    {
        int value = *test[i];
        printf("%d = %d\n", i, value);
    }
        
    return 0;
}

Here is the output:

0 = 3
1 = 3
2 = 3

What's wrong in my code and how to fix?


Solution

  • If you want to store some int values, you don't need pointers at all:

    #include <stdio.h>
    
    int main() {
        int test[3];
    
        /** Try to set the array value one by one */
        for (int i = 0; i < 3; i++) {
            test[i] = i;
        }
    
        /** Try to print the array value one by one */
        for (int i = 0; i < 3; i++) {
            int value = test[i];
            printf("%d = %d\n", i, value);
        }
    }
    

    Output:

    0 = 0
    1 = 1
    2 = 2
    

    Live demo 1


    If for some reason (which is not clear from your question) you need to store pointers, the pointers cannot point to i which is a local value in the for loop because they become dangling right after it, and so dereferrencing any of them invokes undefined-behavior.

    You can solve it by allocating new int objects (e.g. using malloc), but in this case you must remember to release them (with free) eventually to avoid a memory leak:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int * test[3];
    
        /** Try to set the array value one by one */
        for (int i = 0; i < 3; i++) {
            test[i] = malloc(sizeof(int));
            *test[i] = i;
        }
    
        /** Try to print the array value one by one */
        for (int i = 0; i < 3; i++) {
            int value = *test[i];
            printf("%d = %d\n", i, value);
        }
    
        /** free memory: */
        for (int i = 0; i < 3; i++) {
            free(test[i]);
        }
    }
    

    Live demo 2

    Note that I omitted error checking (e.g. malloc returns null upon failure) which should be added to the final code.

    Alternatively you can set the pointers to point to some elements outside the for loop - e.g. ones in a static array.