简体   繁体   中英

Is there a way to initialize a pointer to an array in C (on the same line)

I have the following line (in C):

char *tmp;

Now, I want that variable tmp be initialized to some pointer in my code (a few lines bellow), and after that want be initialized to an array.

Is there a way to allocate to tmp the pointer to a new created array on the stack, without creating another variable? So, instead of:

char arr[10];
tmp = arr;

I want to have something like this:

tmp = char[10];

Is possible something like that in C? If yes, can you give me an example?

您可以使用复合文字功能来做到这一点:

tmp = (char[]){'a', 'b', 'c'};
tmp = alloca(10);

alloca(size) will enlarge the current stack frame to accommodate size more bytes and return a pointer to the newly allocated stack space.

I don't think it's a standard C function. Although it it commonly provided, its use seems to be generally frowned upon.

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