Ilya.K.
Ilya.K.

Reputation: 321

About pointers and strange error

I'm doing pretty simple manipulations on pointers and I get an error. I have a function which gets a block, which is a continuous "block" in memory, which I want to fill in with the information below. block is malloced with size of (sizeof(int)+12+size). username's length is 9 bytes (with the '\0').

typedef const char* const UserName;

static void changeAllFields(void **block, UserName username, int size){
            *((int*)(*block)) = size;
            (*block) += sizeof(int);
            *((char*)(*block)) = NULL;
            (*block) += 2;
            strcpy(*block, username);
            (*block) += 9;
            *((char*)(*block)) = NULL;
            (*block) += size;
            *((char*)(*block)) = NULL;

The error I get:

assignment makes integer from pointer without a cast [-Wint-conversion]

which points to: *((char*)(*block)) = NULL;

What is wrong ?

Upvotes: 0

Views: 73

Answers (2)

interjay
interjay

Reputation: 110192

NULL is a pointer value, but you're writing it into *((char*)(*block)) which has type char. If you actually want to write a char with a value of zero, it should be:

*(char*)(*block) = 0;

Note also that arithmetic operations on a void* as you do in (*block) += 2; are illegal, although some compilers may support them as an extension.

Upvotes: 3

Haris
Haris

Reputation: 12272

Since block is a pointer to a pointer to void, when you dereference it twice while casting it to char*, it would need a char.


If you want that to point to a NUL char, do

*((char*)(*block)) = '\0';


If you want to make it point to a NULL pointer, dereference it only once, like

*block = NULL;

Upvotes: 2

Related Questions