简体   繁体   English

有没有办法初始化指向C中数组的指针(在同一行上)

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

I have the following line (in C): 我有以下一行(在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. 现在,我希望将变量tmp初始化为代码中的某些指针(下面几行),然后将其初始化为数组。

Is there a way to allocate to tmp the pointer to a new created array on the stack, without creating another variable? 有没有一种方法可以分配指向tmp的堆栈上新创建的数组的指针,而无需创建另一个变量? 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? 在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. alloca(size)将扩大当前堆栈帧,以适应size多个字节并返回一个指向新分配堆栈空间。

I don't think it's a standard C function. 我不认为这是标准的C函数。 Although it it commonly provided, its use seems to be generally frowned upon. 尽管通常提供它,但似乎普遍不赞成使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM