【问题标题】:Cannot pass struct to function by reference [duplicate]无法通过引用将结构传递给函数[重复]
【发布时间】:2019-05-21 11:54:16
【问题描述】:

我正在用 C 语言创建一个非常简单的字典结构,但我无法通过引用正确地将其传递给 dictAdd 函数。函数内部出现问题,结构值被破坏。请参阅下面的屏幕截图。当我进入第 18 行时一切都很好,但是当我进入第 19 行的函数时,结构字段将显示不适当的值。

第 18 行

第 19 行

字典.h

typedef struct DictionaryStruct
{
    int *arr;
    int arrLen;
} Dictionary;

Dictionary *dictCreate(int arrLen);
int dictAdd(Dictionary *dict, char *key, char *val);

字典.c

#include "Utils.h"
#include "Dictionary.h"

Dictionary *dictCreate(int arrLen)
{
    int *arr = createIntArray(arrLen);
    for (int i = 0; i < arrLen; ++i)
    {
        arr[i] = '\0';
    }

    Dictionary dict;
    dict.arr = arr;
    dict.arrLen = arrLen;
    return &dict;
}

int dictAdd(Dictionary *dict, char *key, char *val) {
    int hash = getHash(key, dict->arrLen);
    dict->arr[hash] = val;
}

Main.c

#include <stdio.h>
#include <stdlib.h>
#include "Utils.h"
#include "Dictionary.h"

int main() {
    Dictionary *dictPtr = dictCreate(5);
    dictAdd(dictPtr, "key1", "Hello");
    char *value1 = dictGet(dictPtr, "key1");
    printf("%s", value1);

    printf("Press any key to exit\n");
    getchar();
}

【问题讨论】:

    标签: c


    【解决方案1】:

    您正在返回一个指向本地的指针。在目标的生命周期结束后取消引用指针是未定义的行为

    您的dictCreate 也应该堆分配Dictionary 结构(除了堆分配int 数组)。

    【讨论】:

    • 非常感谢!我想我现在明白了。 struct 正在堆栈内存中分配
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多