c - C - 使用结构通过引用传递数组时遇到问题
问题描述
我正在尝试使用 struct 将 2D char* 数组、1D int 数组和整数传递给函数,但是我无法理解如何使用指针通过引用传递它们,而不仅仅是通过值传递它们。我需要所有变量都可以通过它们传入的函数进行编辑,并在整个程序中反映该值,而不仅仅是在函数范围内。本质上就像一个全局变量,但使用最初在函数中定义的结构从一个函数传递到另一个main
函数。
我最初在开发过程中使用全局变量,因为它可以工作而且很容易,但是我在访问其中一个数组中的值时遇到了一些问题(当从某个函数访问时,它将返回空),而且我知道全局变量通常是一个坏主意。
我正在使用 GTK,据我所知,将多个参数传递给回调的唯一方法是使用结构,因此我需要通过结构传递它们,而不是直接将它们传递给函数。除非我错了?
我需要定义以下内容:
char* queuedHashes[100][101];
int queuedHashTypes[100] = {(int)NULL};
int hashCount = 0;
我一直无法理解实现这一点所需的指针和结构语法,而我尝试过的方法导致我遇到了 char* 数组类型not assignable
,因此到目前为止还无法实现任何有效的东西。
任何帮助将不胜感激,谢谢。
解决方案
要通过“引用”传递结构(我把它放在引号中,因为 C 没有“引用”),您只需传递一个指向该结构的指针。结构的内容在结构指针指向的内存中。
所以如果你有这样的结构
struct myStruct
{
char* queuedHashes[100][101];
int queuedHashTypes[100];
int hashCount;
};
然后你可以有一个像
void myFunction(struct myStruct *theStructure)
{
theStructure->queuedHashTypes[0] = 1;
}
并使用如下结构和函数:
int main(void)
{
struct myStruct aStructure; // Define a structure object
aStructure.queuedHashTypes[0] = 0;
printf("Before calling the function queuedHashTypes[0] is %d\n",
aStructure.queuedHashTypes[0]);
myFunction(&aStructure); // Pass a pointer to the structure
printf("The function initialized queuedHashTypes[0] to %d\n",
aStructure.queuedHashTypes[0]);
}
上面的程序应该在函数queuedHashTypes[0]
调用0
之前和调用1
之后打印。
推荐阅读
- nginx - Nginx 日志写入标准输出导致管道损坏
- android - 将 ckpt-20 转换为 h5 或 pb
- django - /admin/quiz/client/2/change/ 处的 KeyError
- erlang - 牛仔休息中的自定义身体
- firebase - Firebase 深层链接 - 自定义网站图标
- laravel - 如何将 spatie / laravel-multitenancy 与单个数据库一起使用?
- javascript - 使用赛普拉斯中的索引访问 p 下拉项目
- dialogflow-cx - 在 dialogflow CX 电话网关中使用特定环境时面临 STT 问题
- magento - 如何将一个对象映射到 magento2 数据模型数组?
- node.js - 如何运行 MERN 应用程序