Im new with c language and im having difficult while trying to change an array on my main function using another function. Besides seeing the solution I’d also like to get a full explanation what is wrong with my code and what’s the explanation to your solution.
OK so I did too much tryouts and error experimentation but with no success to solve my problem. Eventually this is my current code:
#include <stdio.h>
#define MAX 20
typedef int Values[MAX];
int changeArr(Values *vals2)
{
*vals2[0] = 200;
*vals2[1] = 100;
printf("%d and ", *vals2[0]);
printf("%d\n", *vals2[1]);
return 0;
}
int main (int argc, char *argv[])
{
Values vals;
changeArr(&vals);
printf("%d and ", vals[0]);
printf("%d\n", vals[1]);
return 0;
}
Output is:
200 and 100
200 and 0
Instead of:
200 and 100
200 and 100
Version 1:
Instead of passing a pointer to the array, pass a pointer to the array’s first element.
Version 2:
use parentheses to compensate for the precedence.
The problem in your code is that
is
*(vals2[1]), so it dereferences a pointer one unit ofValuesafter the passed pointer. You have no accessible memory allocated there, so it’s undefined behaviour. In practice, it is the same as accessingfor an
But your
valsis only (equivalent to) anint arr[1][MAX];, so you are accessing out of bounds. But if nothing worse happens,*vals2[1] = 100;inchangeArrsetsvals[MAX]inmainto 100. It may overwrite something crucial, though.In
int changeArr(Values *vals2)you are passing a pointer to an array ofMAXints, resp the first such array in an array ofValues. Thenvals2[1]is the second array in that array ofValues(which doesn’t exist here), and*vals2[1] == vals2[1][0]the firstintin that second array. You want to modify elements of the first (and only) array in the pointed-to memory block, so you want to accessvals2[0][1], or equivalently(*vals2)[1].A picture:
in
changeArr, the pointervals2points to the arrayvals. Since it’s a pointer to anint[MAX],vals2+1points to anint[MAX]at an offset ofMAX*sizeof(int)bytes after the start ofvals(which is just behind the end ofvals).vals2[1], or equivalently*(vals2 + 1), is that array just aftervals(which doesn’t exist).You want to change
vals[1], which is located in the arrayvals2[0], at an offset of1*sizeof(int)bytes, so you needvals2[0][1]or equivalently(*vals2)[1].