i’m learning C, currently pointers.
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int f1(int **w){
for (int i=0;i<2;i++){
for (int j=0;j<10;j++){
w[i][j]=10;
printf("%d ",w[i][j]);
}
printf("\n");
}
printf("----\n");
}
int main () {
int **w = (int **) malloc(sizeof(int*)*2);
for (int i=0;i<2;i++)
w[i] = (int*)malloc(sizeof(int)*10);
for (int i=0;i<2;i++){
for (int j=0;j<10;j++){
w[i][j]=i*10 + j;
printf("%d ",w[i][j]);
}
printf("\n");
}
printf("---\n");
f1(w);
for (int i=0;i<2;i++){
for (int j=0;j<10;j++){
w[i][j]=i*10 + j;
printf("%d ",w[i][j]);
}
printf("\n");
}
return 0;
}
So, I have this code
and here is the output:
0 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19
---
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
----
0 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19
I’m wondering, WHY the array values (see last 2 rows) are different to 10?.
My guess, not sending the correct pointer, but, in that case, WHERE is stored the array with 10…10?, is it created magically??
thanks
Seems the program is doing exactly what you have programmed it to do.
The f1 function sets all values to 10
the other places set it to