WolvenOmega WolvenOmega - 11 months ago 43
C Question

Allocating memory to a string in C

This is the relevant snip of my code:

size_t logsize;
char *log;
log_t *tmp;
tmp = headptr;
//some other stuff
while(tmp) {
logsize += (sizeof(log_t) + strleng(tmp->item.string) + 4);
*log = (char*)malloc(sizeof(logsize));

is a struct with
data_t item
, and
is a struct with
char *string

I'm trying to allocate memory to every
put together in one string, because I'm going to be passing that string outside of the function.

However, on the line where I'm allocating the memory, it says "assignment makes integer from pointer without a cast".

Any help clearing this up would be appreciated.

Jay Jay
Answer Source

log is declared as char *log, so dereferencing log i.e. *log makes it a char. The return from malloc is a pointer. So, when you assign it to *log, the compiler says you are trying to make an integer from a pointer which is correct.

But, based on your question and details in it, looks like there are other mistakes too. For Ex: you are trying to pass sizeof(logsize) which will yield only the size of the size_t. I guess you want a memory block equivalent to logsize and not sizeof(logsize).

You have also mentioned that you are having a char *string in your structure, in which you should be allocating memory for it seperately.

So, for now, looks like you will have to modify your statement as:

log = malloc(logsize);