【问题标题】:possible to set all elements of pointer to float after malloc可以在 malloc 之后将指针的所有元素设置为浮动
【发布时间】:2016-08-11 14:35:11
【问题描述】:

在 C 中是否可以做以下事情?

float *t = (float*)malloc(t_size*sizeof(float));
t = {
  1,0,0,
 -1,0,0,
  0,1,0
};

类似于下面的标准

float t[9] = {
1,0,0,
-1,0,0,
0,1,0
};

【问题讨论】:

  • C 还是 C++?不一样。
  • 让我们坚持使用 C++
  • std::vector<float> vec{ 1,0,0, -1,0,0, 0,1,0 }; :)
  • 出于好奇,如果您知道大小和所有值,为什么不创建一个普通数组?
  • 在 C++11 中,您可以使用 t = new float [9]{ 1,0,0, -1,0,0, 0,1,0 };。虽然我不知道为什么你需要在那之前使用malloc。这不是展示位置new

标签: c++ c pointers malloc


【解决方案1】:

如要求, 灵魂可以使用 compound literals 完成

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    #define  t_size  9
    float *t = malloc(t_size*sizeof(*t));

    if (t != NULL)
    {
       memcpy(t, (float[t_size]){1,0,0,-1,0,0,0,1,0}, t_size*sizeof(*t));

       for (size_t i=0; i<t_size; i++)
          printf("t[%zu] = %g\n", i, t[i]);
    }

    free(t);

    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2014-09-02
    • 2023-03-31
    • 2016-05-24
    相关资源
    最近更新 更多