嘿,我尝试从一个 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);
}
怎么了? :O 我现在想在我的主要功能中使用 stapel。
最佳答案
你有错误的函数声明,你的函数正在接收指针。
你需要使用
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
}
正如评论中所指出的,还记得在最后释放内存(这里没有实际区别,因为程序将终止,但始终是一个好习惯)。
关于使用 int 数组按引用调用。 2个功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21548579/