嘿,我尝试通过int数组中的引用调用:
void function2(int stapel,int colour){
stapel[1]=stapel[0]
stapel[0]=colour;
}
void function1(int stapel){
int colour=2;
function2(stapel,colour);
}
int main(){
int *stapel;
stapel=malloc(sizeof(int)*2);
function1(stapel);
}
怎么了? :我想在我的主要功能中使用stapel。
答案 0 :(得分:4)
你的函数声明错误,你的函数正在接收指针。
您需要使用
void function2(int *stapel,int colour){...
void function1(int *stapel){...
而不只是int stape
。这是完整的代码:
void function2(int *stapel,int colour){
stapel[1]=stapel[0]
stapel[0]=colour;
}
void function1(int *stapel){
int colour=2;
function2(stapel, colour);
}
int main(){
int *stapel;
stapel=malloc(sizeof(int)*2);
function1(stapel);
free(stapel); // Also free the memory
}
正如评论中指出的那样,还记得在最后释放内存(这里没有实际的区别,因为程序将被终止,但总是一个好习惯)。
答案 1 :(得分:1)
在main
函数中,您将指向int
的指针作为参数传递,但函数不会将指针指向int
。更改函数以获取指针。在这方面,你得到的错误应该非常明显。
我们function2
中也存在订购问题,您使用未初始化的数据来初始化stapel[1]
。
答案 2 :(得分:0)
stape1
是指向int
的指针,您不能将其作为参数传递给需要整数值的函数。但是,从函数体中的使用来看,您似乎应该将函数声明更改为int*
而不是int
。
答案 3 :(得分:0)
检查这个
Edit this
function1(int *stapel)
and
function2(int *stapel,int colour)
答案 4 :(得分:0)
如果您希望在C中使用引用(或数组)传递指针,那么您只是在函数签名中说“{1}}”。
int stape1
然后你可以从主
传递指针void function1(int * stapel){
//...
}
之后不要忘记function1(stapel);
free
答案 5 :(得分:0)
我认为您可能必须在函数参数列表中使用int * stapel。我认为int stapel是在函数堆栈上推送的int类型的值。我认为int * stapel是指向堆栈上推送的地址的指针。最后,我似乎记得使用& stapel取消引用指针。对我来说已经很久了。我相信其中一位聪明的人会给你一个更好的答案;)
答案 6 :(得分:0)
#include<stdio.h>
#include<malloc.h>
void function2(int *stapel,int colour){
stapel[0]=colour;
stapel[1]=stapel[0];
}
void function1(int *stapel){
int colour=2;
function2(stapel,colour);
}
int main(){
int *stapel;
stapel=malloc(sizeof(int)*2);
function1(stapel);
printf("stapel[0]=%d stapel[1]=%d",stapel[0],stapel[1]);
return 0;
}
尝试此代码,它的工作正确....... 在你的程序中,你传递一个指针,但将其定义为整数
还有其他问题,我纠正了........
如果您有任何疑惑,可以问............