c - 在结构中分配和访问指向字符串的指针

标签 c pointers c99 struct memcpy

我试图将一个字符串存储在一个包含在结构中的数组中,并访问它,但我遇到了困难。该结构如下所示:

typedef struct {
    void **storage;
    int numStorage;
} Box;

Box 是这样初始化的:

    b->numStorage = 1000000; // Or set more intelligently
    Box *b = malloc(sizeof(Box));
    // Create an array of pointers
    b->storage = calloc(b->numStorage,sizeof(void *));

为了设置字符串,我使用了这个函数:

void SetString(Box *b, int offset, const char * key)
{
    // This may seem redundant but is necessary
    // I know I could do strcpy, but made the following alternate
    // this isn't the issue
    char * keyValue = malloc(strlen(key) + 1);
    memcpy(keyValue, key, strlen(key) + 1);

    // Assign keyValue to the offset pointer
    b->storage[offset*sizeof(void *)] = &keyValue;

    // Check if it works
    char ** ptr = b->storage[offset*sizeof(void *)];

    // It does
    printf("Hashcode %d, data contained %s\n", offset, *ptr);

}

问题出在我再次尝试以完全相同的偏移量检索它时:

// Return pointer to string
void *GetString(const Box *b, int offset, const char *key)

    char ** ptr = b->storage[offset*sizeof(void *)];
    if (ptr != NULL) {
        printf("Data should be %s\n", *ptr);
        return *ptr;
    } else {
     return NULL;
    }

返回的指针是乱码。有什么问题吗?

最佳答案

访问数组时不必指定实际的内存偏移量。只需给它索引,您就会得到正确的元素。

因此,在您的第三个代码块中:

b->storage[offset] = keyValue;

在你的第四个:

char *ptr = b->storage[offset];
if (ptr != NULL) {
    printf("Data should be %s\n", ptr);
    return ptr;
} else {
 return NULL;
}

还有,在第二段代码中,是否设置了b->numStorage

关于c - 在结构中分配和访问指向字符串的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772002/

相关文章:

c - 链表 append 实现在 C 中更新所有节点值

c - 获取客户端添加的 OpenSSL 自定义扩展

c - 获取函数名称作为符号(而不是字符串)- C 预处理器

c++ - 分配指针和使用 strcpy 之间的区别

C: 如果没有单独的功能,代码将无法工作。为什么?

c - 复制部分初始化的结构在 C 中定义良好吗?

c - 使用 C 验证文件中的登录凭据

c - 如何用C语言编写shift_elements函数?

C:寄存器地址还是内存地址?

c - 用 %p 打印空指针是未定义的行为?