Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing allocating the size of an array

Tags:

c

sizeof

gcc 4.4.3 c89

I am wondering why I can't allocate the size of the array when initializing an array of pointers to char.

I get the following error:

variable-sized object may not be initialized

This works ok. However, the sizeof of will return 4 bytes as a char * is 4 bytes in size. Which is no good, as its not the actual size that I want.

void inc_array(const char * const src, size_t size)
{
    /* Array of pointers */
    char *dest[sizeof(src)] = {0};
}

However, this is what I want to do is pass the actual size and use that to initialize the length of the array.

void inc_array(const char * const src, size_t size)
{
    /* Array of pointers */
    char *dest[size] = {0};
}

What is the difference when sizeof of returns a size_t and I am passing a size_t?

Many thanks for any suggestions,

like image 754
ant2009 Avatar asked Mar 11 '26 13:03

ant2009


1 Answers

Use malloc to allocate dynamically sized arrays.

You must also ensure that malloced data is eventually freed.

  • Tutorial-style malloc/free resource: http://cplus.about.com/od/learningc/ss/pointers_7.htm
like image 160
kbrimington Avatar answered Mar 14 '26 03:03

kbrimington