简体   繁体   English

如何在C中的malloc分配的内存区域中存储指向偏移位置的指针?

[英]how can i store a pointer to offseted location on malloced memory area in C?

I'm trying to make a very simple Hashtable with libraries I got. 我试图用我得到的库制作一个非常简单的哈希表。 The row that I try to make contains either C-string or int as key. 我尝试创建的行包含C字符串或int作为键。 Value can be of 4 different types. 值可以是4种不同的类型。 If it's struct I try to store a pointer in malloced memory area. 如果是struct,我尝试将指针存储在已分配的内存区域中。 However in my world this does not follow the same logic as non-pointer fields and I get: 但是在我的世界中,这与非指针字段的逻辑不同,因此我得到:

error C2106: '=' : left operand must be l-value when I try to store pointer as value:

Here's the code 这是代码

static void MakeRow(UtiHashtable_t *Hashtable, void *Key, void *Value, void *Row)
{
    int     KeySize, ValueSize;

    KeySize = sizeof(char) * Hashtable->KeyStringLength;
    ValueSize = GetValueSize(Hashtable);
    Row = malloc(KeySize + ValueSize);

    if (Hashtable->KeyType ==  MY_HASHTABLE_TYPE_STRING)  
        MyStrcpy((char *)Row, (char *)Key, Hashtable->KeyStringLength); 
    else if (Hashtable->KeyType ==  MY_HASHTABLE_TYPE_INT)
        ((int *)Row)[0] =  *(int *)Key;
    else
        MyAssert(0);

    switch (Hashtable->ValueType)
    {
    case MY_HASHTABLE_TYPE_STRING:
        MyStrcpy((char *)Row + KeySize, (char *)Value, Hashtable->ValueStringLength); 
        break;
    case MY_HASHTABLE_TYPE_INT: 
        *(int *)((char *)Row + KeySize) =  *(int *)Value;
        break;
    case MY_HASHTABLE_TYPE_DOUBLE: 
        *(double *)((char *)Row + KeySize) =  *(double *)Value;
        break;
    case MY_HASHTABLE_TYPE_STRUCT: 
        (int *)((char *)Row + KeySize) = (int *)Value;
        break;
    default:
        MyAssert(0);
    }
}

I know this is really basic and will get few down votes but besides the answer I would like to have explanation why this taking * away does not make it pointer. 我知道这真的很基本,只会得到很少的反对票,但是除了答案之外,我还想解释一下为什么带走*并不能使它成为指针。

The compiler allows: 编译器允许:

(int *)Value = (int *)Key;

so why not: 所以为什么不呢?

(int *)((char *)Row + KeySize) = (int *)Value;

Thanks & BR -Matti 谢谢&BR-马蒂

Using casts on an lvalue is deprecated. 不建议在左值上使用强制类型转换。

Also, some systems don't allow int s or pointers to be placed in arbitrary memory locations due to alignment issues. 同样,由于对齐问题,某些系统不允许将int或指针放置在任意内存位置中。

What you should do is to memcpy the pointer value to where you want it. 你应该做的是memcpy指针值到您想要的位置。 And when you want to use the pointer you need to memcpy it back to a pointer variable. 当您要使用指针时,需要将其回memcpy到指针变量。

您取消了左侧的取消引用*,因此分配不再有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM