使用 int 数组按引用调用。 2个功能

标签 c pass-by-reference

嘿,我尝试从一个 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/

相关文章:

c - 为什么这个 C 程序输出一个负数?

C程序添加单个数字、大小写字母和其他字符

c++ - std::string 如何管理这个技巧?

c# - 从 C# 将数据传入和传出 DLL

C - 在运行时创建一个大小大于 10M 的数组

c - 无维度的全局整数数组

c - C语言中如何将int转换为字符串?

c# - 通过引用与值传递对象

php - 如何模拟一个变量通过引用传递给 PHPUnit 的函数?

c++ - 此代码对于重载比较运算符是否正确?