c - 在C中按值调用函数
问题描述
不知何故,我是 C 语言的新手,我在这里尝试在主函数中调用一个函数“func”,但它给了我编译错误。我试图在 Google 中搜索与这种情况类似的示例,但仍然出现错误。
#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.
}
边注
您尚未初始化Arg
或Arr
主要。我怀疑您可能指的是命令行参数。
int main(int Arg, char* Arr[])
推荐阅读
- javascript - 如何在firebase中以随机模式对帖子进行排序,而不重复?
- typescript - 如何在Type中使用两次key
- java - 如何使用 JOptionPane 类处理异常
- python - 为什么我的 jupyter 笔记本中不需要“%matplotlib inline”?
- python - Python Shell 在使用 PyQt5 的 while 循环后重新启动
- hyperledger-fabric - 来自 Hyperledger Fabric JAVA SDK 的多个组织的认可
- validation - Hapijs Joi 引用模式键以在其他模型或路由中重用
- swiftui - SwiftUI:用状态驱动 NavigationLink 表示是什么意思?
- android - Android相机预览图通过Intent打开相机后旋转180度
- android - ClearFocus 将焦点设置在 LinearLayout 中的第一个视图上