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.
test[i] = &i- you assign pointers to a variable that does not exist when you print the array. This is undefined behavior. Don't use pointers in this code.(void *)pointer and use this pointer outside of the for loop somewhere, thismainis used(int *)pointer for testing.int *nn = malloc(sizeof(int)); nn = i; test[i] = nn;but still not work. I don't know what's wrong.