简体   繁体   English

(C/C++) 在同一行初始化并返回数组

[英](C/C++) Initialize and return array in the same line

I was wondering how I could initialize and return an array on the same line using c/c++.我想知道如何使用 c/c++ 在同一行上初始化和返回一个数组。

My intuition says that the syntax should look somewhat like this: return (int8_t*) {hours, minutes, seconds};我的直觉是语法应该看起来像这样: return (int8_t*) {hours, minutes, seconds};

Am I correct?我对么? Is the cast mandatory?演员表是强制性的吗? Or is there another/better way of doing this?或者是否有另一种/更好的方法来做到这一点?

EDIT: I'm asking this because I cannot test the code right now.编辑:我问这个是因为我现在无法测试代码。 I won't be in front of a computer for some days.有几天我不会在电脑前。

ANSWER:回答:

  • for C follow the steps in the verified answer对于 C,请按照已验证答案中的步骤进行操作
  • for C++ you would use a std::vector or std::array as the return type and then have return { 1, 2, ..., N };对于 C++,您将使用std::vectorstd::array作为返回类型,然后使用return { 1, 2, ..., N };

This will not work as you expect.这不会像您期望的那样工作。

The exact syntax for what you're trying to do would be:您尝试执行的操作的确切语法是:

return (int8_t []){hours, minutes, seconds};

Which creates a compound literal of array type.它创建了一个数组类型的复合文字 However, this literal has the lifetime of the enclosing scope.但是,此文字具有封闭范围的生命周期。 So when the function returns, the returned pointer is now pointing to invalid memory, and attempting to dereference that pointer invokes undefined behavior .因此,当函数返回时,返回的指针现在指向无效内存,并尝试取消引用该指针会调用未定义的行为

You'll need to dynamically allocate the memory, then assign each member of the array:您需要动态分配内存,然后分配数组的每个成员:

int8_t *p = malloc(3 * sizeof(int8_t));
p[0] = hours;
p[1] = minutes;
p[2] = seconds;
return p;

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

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