1

here's to my first post on this website.

I'm trying to initialize an array of 30 pointers to NULL. The array is stored as a global and I'm doing the initialization in my init() function like so:


static headerT* free_list[30];

....

init() { free_list[30] = {NULL}; }


However, I get the following complier error - "error: expected expression before ‘{’ token".

Any thoughts on what I could be doing wrong?

Thanks in advance.

4
  • 9
    They're already initialized. Commented Mar 12, 2014 at 0:17
  • 2
    Just delete the init() function. Commented Mar 12, 2014 at 0:18
  • 1
    the element free_list[30] does not exist: the array goes from free_list[0] to free_list[29] Commented Mar 12, 2014 at 0:19
  • 2
    In c? Or c++? Commented Mar 12, 2014 at 0:19

3 Answers 3

3

objects allocated with static storage duration are value initialized. Your pointers are already initialized to nullptr.

Sign up to request clarification or add additional context in comments.

Comments

2
  1. If arr is an array of n elements, then the first cell is arr[0] and the last is arr[29]. arr[30] is outside the array and referencing it can cause all sorts of problems.
  2. You can't assign a value to an entire array. Use a for loop to access every cell.

Thus we get:

init() 
{ 
    int i;
    for(i=0; i<30; i++)
        free_list[i] = NULL; 
}

2 Comments

To be clear, only pointers with static storage duration are initialized to NULL by default.
You can also initialise a (non-static) array of pointers to NULL (0) by writing T* p[30] = { 0 };, but you can't assign such a value.
-2

I prefer memset

memset( free_list, 0x0, 30 * sizeof(headerT*) );

3 Comments

This will break on a system where the null pointer is not represented by all-bits-zero.
Also it will break if the size of the list changes, you could at least have used the idiom memset( &x, 0, sizeof x ) to ensure the correct amount of memory is written.
Yes I could have but the example that was given was fairly specific and I had no problem with giving a specific answer. The specific version of this function that i coded up for myself is templated but i thought that was overkill for the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.