问题描述
为什么在我使用时:
char paraula [15];
int longparaula = 0;
copia_paraula(paraula,longparaula);
它说longparaula = 0? paraula没关系,并且包含我输入的字符的值,但longparaula总是为0.如果我没有初始化longparaula,它总是等于一个偶然的值。它将等于阵列的经度,不是吗?这就像函数可以修改paraula的值,但不能修改longparaula的值...
void copia_paraula(char taula [15],int Longitud){
int i = 0; ((c!='')&(c!='。')){
taula [i] = c;
scanf(%c,& c);
i ++;
}
Longitud = i;
}
感谢您!
C通过值传递。
这意味着当 copia_paraula()
被称为 Longitud
收到存储在 longparaula
中的内容的副本。
里面 copia_paraula()
代码只是修改 Longitud
,即 longparaula
。这就是为什么 Longitud
不会改变它的值。
为了解决这个问题, $ c> longparaula 通过传递其地址,指向指向 longparaula
的指针被存储。
然后将新值写入指针指向的位置:
pre $ void copia_paraula(char taula [15],int * pLongitud)
{
int i = 0;
// while((c!='')&(c!='。'))//你不想执行按位和操作
while( c!='')&&(c!='。'))//但是一个逻辑的&&是逻辑和 - 操作符
{
taula [i] = c;
scanf(%c,& c);
i ++;
}
* Longitud = i;
像这样调用它:
char paraula [15];
int longparaula = 0;
copia_paraula(paraula,& longparaula);
确保代码不会写出 char
- 数组的边界留作练习。
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 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.
这篇关于C动作和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!