C中按值调用函数

标签 c arrays function pointers

我对 C 语言不熟悉,我试图在 main 函数中调用函数“func”,但它给了我编译错误。我试图在谷歌中搜索与这种情况类似的例子,但仍然出现错误。

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

struct str {
  int value;
  uint32_t ptr_next;
};

void func(int arg, char* arr[]);

int main() {
  int Arg;
  char* Arr[1];

  func(Arg, *Arr[1]);

  return 0;
}

void func(int arg, char* arr[]) {
  int list;

  struct str r;

  FILE* file = fopen(arr[1], "rb");

  do {
    list = fread(&r, sizeof(struct str), 1, file);

    if (list > 0)
      printf("%d ", r.value);

    fseek(file, r.ptr_next, 0);

  }

  while ((r.ptr_next != 0) && (list > 0));
}

问题是如何在C语言中按值调用函数?

最佳答案

C 只支持按值调用函数,C++ 中增加了按引用调用,并使用 & 符号。

传递给函数的值是内存中的一个位置,一个指针。如果您想向该函数传递该内存位置的数据副本,您需要为其创建一个副本。

// Assuming that Arg and Arr are initialized.
char* Arr2[];                     // Make a storage place for the char**.
Arr2 = malloc(Arg*sizeof(char*)); // Make the right number of char*s in it
for(int e=0; e<Arg; e++) {        // For each elem in the main array: 
  Arr2[e]=malloc(sizeof(char)*strlen(Arr[e])); // Make space for the chars,
  strcpy(Arr2[e],Arr[e]);                      // And copy them.
}
<小时/>

旁注

您尚未在 main 中初始化 ArgArr。我怀疑您可能指的是命令行参数。

int main(int Arg, char* Arr[])

关于C中按值调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59481144/

相关文章:

c - 等效表达式 memset 和 array

c - c中条件运算符内的递增运算符

从 C 中的 union 复制数据

c++ - 编译器提示 "Error: stray '\24 0' in program"

c - 试图理解 fgets()

c - 当我分配了足够的内存时,为什么会得到 "segmentation fault 11"?

ios - 索引(其中 :) method in swift is producing the wrong index

arrays - Scala 的多维数组再一次

javascript - 为什么 .parentNode 在 'undefined' 指针上返回 'this'?

r - 在 R 中的 split() 之后保持数据的原始顺序