C - 使用结构通过引用传递数组时遇到问题
C - Trouble passing arrays by reference using structs
我正在尝试使用结构将 2D char* 数组、1D int 数组和整数传递给函数,但是我无法思考如何使用指针通过引用传递它们,而是而不仅仅是价值。我需要所有变量都可以通过传递给它们的函数进行编辑,并在整个程序中反映出该值,而不仅仅是在函数范围内。本质上像一个全局变量,但使用结构从一个函数传递到另一个函数,最初在 main
函数中定义。
我最初在开发过程中使用全局变量,因为它很有效而且很简单,但是我 运行 在访问其中一个数组中的值时遇到了一些问题(当从某个函数访问时它会 return 空),而且我知道全局变量通常不是一个好主意。
我正在使用 GTK,据我所知,将多个参数传递到回调中的唯一方法是使用结构,因此我需要通过结构传递它们,而不是直接将它们传递到功能。除非我错了?
我需要定义以下内容:
char* queuedHashes[100][101];
int queuedHashTypes[100] = {(int)NULL};
int hashCount = 0;
我一直无法理解实现此目的所需的指针和结构语法,我尝试过的方法导致我 运行 进入 char* 数组类型 not assignable
,所以到目前为止还无法实施任何有效的方法。
非常感谢任何帮助,谢谢。
要通过 "reference" 传递一个结构(我把它放在引号中是因为 C 没有 "references"),您只需传递一个指向该结构的指针。结构的内容在结构指针指向的内存中。
所以如果你有这样的结构
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
。
我正在尝试使用结构将 2D char* 数组、1D int 数组和整数传递给函数,但是我无法思考如何使用指针通过引用传递它们,而是而不仅仅是价值。我需要所有变量都可以通过传递给它们的函数进行编辑,并在整个程序中反映出该值,而不仅仅是在函数范围内。本质上像一个全局变量,但使用结构从一个函数传递到另一个函数,最初在 main
函数中定义。
我最初在开发过程中使用全局变量,因为它很有效而且很简单,但是我 运行 在访问其中一个数组中的值时遇到了一些问题(当从某个函数访问时它会 return 空),而且我知道全局变量通常不是一个好主意。
我正在使用 GTK,据我所知,将多个参数传递到回调中的唯一方法是使用结构,因此我需要通过结构传递它们,而不是直接将它们传递到功能。除非我错了?
我需要定义以下内容:
char* queuedHashes[100][101];
int queuedHashTypes[100] = {(int)NULL};
int hashCount = 0;
我一直无法理解实现此目的所需的指针和结构语法,我尝试过的方法导致我 运行 进入 char* 数组类型 not assignable
,所以到目前为止还无法实施任何有效的方法。
非常感谢任何帮助,谢谢。
要通过 "reference" 传递一个结构(我把它放在引号中是因为 C 没有 "references"),您只需传递一个指向该结构的指针。结构的内容在结构指针指向的内存中。
所以如果你有这样的结构
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
。