C actions and variables

2019-03-03 13:53发布

问题:

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!

回答1:

C is pass by value.

That means when copia_paraula() is being called Longitud receives a copy of what is stored in longparaula.

Inside copia_paraula() the code just modifies Longitud, that is the copy of longparaula. That's why Longitud does not changes its value.

To fix this pass down a "reference" to longparaula by passing its address, the pointer pointing to where longparaula is stored.

And then write the new value to where the pointer points:

void copia_paraula(char taula[15], int * pLongitud)
{
  int i = 0;
//  while ((c != ' ') & (c != '.')) // you do not want to perform a bit-wise "and"-operation
  while ((c != ' ') && (c != '.')) // but a logical, && is the logical "and"-operator
  {
       taula[i] = c;
       scanf("%c", &c); 
       i++;
  }

  *Longitud = i;
}

Call it like this:

char paraula[15];
int longparaula = 0;
copia_paraula(paraula, &longparaula);

Makeing sure the code does not write out of the char-array's bounds is left as an exercise.