【发布时间】: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