Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C initialize pointer to array literal without extra variable

Tags:

arrays

c

I have a variable that needs to hold a pointer to an array. Normally this is done by first creating a variable with the array, then saving the pointer to that variable. However, I need to do this for maybe 10 variables, and I don't want to have to create an extra array for each of them. What I first tried was

int *numList = {1, 2, 3};

But that tries to create an array of pointers to integers. I think the following has the correct type for the list, but I don't know how to cast the array to a pointer.

int (*numList)[3] = {1, 2, 3};
like image 627
Matthias Avatar asked Apr 21 '18 17:04

Matthias


People also ask

Can you initialize an array with a pointer?

The pointer amount is initialized to point to total : double time, speed, *amount = &total; The compiler converts an unsubscripted array name to a pointer to the first element in the array. You can assign the address of the first element of an array to a pointer by specifying the name of the array.

Can pointer be initialized with 0?

A pointer can also be initialized to null using any integer constant expression that evaluates to 0, for example char *a=0; .

Why is it important to initialize your pointer variable to null?

It is necessary only when you expect it to have a default value. As pointers, just like other variables will hold garbage value unless it is initialized.

Can we declare array without initialization?

So, no. You can't avoid "initializing" an array.


1 Answers

In C99 and C11, you can use a compound literal to achieve what is requested in the question title, namely initialize a pointer so it points to an array literal without any extra variables:

int *numList = (int []){ 1, 2, 3 };

The array that numList points to has the same scope and lifetime as the pointer itself — it lasts for the block it is defined in if it is inside a function, or for the duration of the program if it is outside any function.

If you were so misguided as to create static int *numList = (int []){ 1, 2, 3}; inside a function, you'd be setting yourself up for a world of hurt — don't do it. (At file scope, outside any function, it doesn't present any problem.) The pointer would be initialized no later than when the function is first called, but there's no guarantee that what it points to has static duration and subsequent calls could be pointing at garbage.

like image 129
Jonathan Leffler Avatar answered Sep 27 '22 22:09

Jonathan Leffler