Can anyone explain me why i dont need -> int ***zd in the init function? Isn't this call by value and the intialization shouldnt stay when i want to print it? Or is a pointer automatically call by reference? I would love to understand how this exactly works, so if anyone can help me i would highly appreciate it!
#include <stdio.h>
#include <stdlib.h>
void initZD(int **zd, int width, int height){
for(int i = 0; i < width; i++){
for(int j = 0; j < height; j++){
zd[i][j] = rand() % 10;
}
}
return;
}
void printZD(int **zd, int breite, int hoehe){
for(int i = 0; i < breite; i++){
for(int j = 0; j < hoehe; j++){
printf("%d\t",zd[i][j]);
}
printf("\n");
}
}
int main(){
int **zd = NULL;
int width, heigth;
printf("Width: ");
scanf("%d", &width);
printf("Heigth: ");
scanf("%d", &heigth);
//zd = realloc(*zd, breite*sizeof(int));
//zd = calloc(breite, sizeof(int));
zd = malloc(width*sizeof(int));
for(int i = 0; i < width; i++){
//zd[i] = realloc(*zd, hoehe*sizeof(int));
//zd[i] = calloc(hoehe, sizeof(int));
zd[i] = malloc(heigth*sizeof(int));
}
initZD(zd, width, heigth);
printZD(zd, width, heigth);
free(zd);
for(int x = 0; x < width; x++){
free(zd[x]);
}
return 0;
}
initzDdoes not need the address ofzdbecause it does not changezd. It changes things that are pointed to viazd(specifically things that are pointed to by pointers thatzdpoints to).To change those things, it needs their addresses, and it has their addresses because they are pointed to by the pointers that
zdpoints to. (Generally, the pointers only point to the first of some number ofint, but the subscript operators inzd[i][j]do pointer arithmetic to calculate the addresses of following elements.)