简体   繁体   中英

allocate extra memory for a char but not for an int in an already allocated struct?

I got this error message: passing argument 1 of x makes integer from pointer without a cast. I have done exaclty the same way when passing an int and that worked perfectly. But when I did it with an char I got this error. Code:

struct x {
    char y;
}

struct x *make(char y)
{
    struct x *n = malloc(sizeof(struct x));
    n->y = y; 
    return n;
};

int main(void)
{
    make("y");
    return 0;
}

I fixed the error with changing char to an char * and use with use of strcpy. So it work perfectly. But I don't understand why I have to do that. I allocate memory for the whole struct with malloc(sizeof(struct x))? so why do I have to allocate extra memory for the char. That seems very strange. I maybe have missunderstand it? So why is this the case.

"y" 

is a string literal. That is a pointer to a null-terminated array of characters.

Your function receives a single character and so you would need to pass a character literal:

'y'

in order for your call to the function make to compile.


The change you describe in the final paragraph completely alters the structure. It changes the member from being a single character, allocated inline, to being a pointer to a null-terminated array of characters. And that latter variant would need separate allocation for the character array. That might be what you want to do, only you know. But you must understand the difference between a single character and a pointer to a null-terminated array of characters.

So, consider the version of the struct in the question:

struct x {
    char y;
}

You allocated a struct dynamically like this:

struct x *n = malloc(sizeof(struct x));

At this point you are done. All the members of the struct are allocated by this single call.

The alternate version of the struct that you discuss in the question looks like this:

struct x {
    char *y;
}

Again you would allocate the struct like this:

struct x *n = malloc(sizeof(struct x));

And again this allocates all the members of the struct. So the pointer n->y is allocated. But the missing step is that n->y has not been initialized . Typically that would involve a further call to malloc . A function to do that might look like this:

struct x *AllocStruct(const char *y)
{
    struct x *s = malloc(sizeof *s);
    s->y = malloc(strlen(y) + 1);
    strcpy(s->y, y);
    return s;
};

And then to free the struct you would do this:

void FreeStruct(const struct x *s)
{
    free(s->y);
    free(s);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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