首页 > 解决方案 > C - 使用结构通过引用传递数组时遇到问题

问题描述

我正在尝试使用 struct 将 2D char* 数组、1D int 数组和整数传递给函数,但是我无法理解如何使用指针通过引用传递它们,而不仅仅是通过值传递它们。我需要所有变量都可以通过它们传入的函数进行编辑,并在整个程序中反映该值,而不仅仅是在函数范围内。本质上就像一个全局变量,但使用最初在函数中定义的结构从一个函数传递到另一个main函数。

我最初在开发过程中使用全局变量,因为它可以工作而且很容易,但是我在访问其中一个数组中的值时遇到了一些问题(当从某个函数访问时,它将返回空),而且我知道全局变量通常是一个坏主意。

我正在使用 GTK,据我所知,将多个参数传递给回调的唯一方法是使用结构,因此我需要通过结构传递它们,而不是直接将它们传递给函数。除非我错了?

我需要定义以下内容:

char* queuedHashes[100][101];
int queuedHashTypes[100] = {(int)NULL};
int hashCount = 0;

我一直无法理解实现这一点所需的指针和结构语法,而我尝试过的方法导致我遇到了 char* 数组类型not assignable,因此到目前为止还无法实现任何有效的东西。

任何帮助将不胜感激,谢谢。

标签: carrayspointersstructgtk

解决方案


要通过“引用”传递结构(我把它放在引号中,因为 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之后打印。


推荐阅读