【问题标题】:Assigning and accessing pointer to string within struct在结构中分配和访问指向字符串的指针
【发布时间】:2011-08-11 22:26:58
【问题描述】:

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

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;
    }

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

【问题讨论】:

    标签: c pointers c99 struct memcpy


    【解决方案1】:

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

    所以,在您的第三个代码块中:

    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 已经设置了吗?

    【讨论】:

      【解决方案2】:
      b->storage[offset*sizeof(void *)] = &keyValue;
      

      这会将局部变量keyValue 的地址存储在数组中。一旦函数完成,这个地址就失效了。我想你想要:

      b->storage[offset*sizeof(void *)] = keyValue;
      

      然后在检索时进行相应的更改。

      【讨论】:

        【解决方案3】:

        这不是吗:

        b->storage[offset*sizeof(void *)] = &keyValue
        

        设置 storage[offset*sizeof(void*)] 指向局部变量keyValue的地址?即函数返回后不再有效

        【讨论】:

          猜你喜欢
          • 2020-03-23
          • 2021-04-29
          • 2017-01-04
          • 2017-07-18
          • 1970-01-01
          • 1970-01-01
          • 2018-05-16
          • 1970-01-01
          相关资源
          最近更新 更多