Why when I use:
char paraula[15];
int longparaula=0;
copia_paraula(paraula, longparaula);
It says that longparaula=0? paraula it's ok, and containd the values of the chars that I input, but longparaula always it's 0. If i don't initializate longparaula, it always equals an aleatory value. It will equals at the longitude of the array, isn't it? It's like the function can modify the valueo of "paraula", but can't modify the value of longparaula...
void copia_paraula(char taula[15], int Longitud){
int i=0;
while ((c!=' ') & (c!='.')){
taula[i]=c;
scanf("%c", &c);
i++;
}
Longitud=i;
}
Thanks in advance!
C is pass by value.
That means when
copia_paraula()
is being calledLongitud
receives a copy of what is stored inlongparaula
.Inside
copia_paraula()
the code just modifiesLongitud
, that is the copy oflongparaula
. That's whyLongitud
does not changes its value.To fix this pass down a "reference" to
longparaula
by passing its address, the pointer pointing to wherelongparaula
is stored.And then write the new value to where the pointer points:
Call it like this:
Makeing sure the code does not write out of the
char
-array's bounds is left as an exercise.