【问题标题】:Store integers (32 bit) in array (which type? ) C programming将整数(32 位)存储在数组中(哪种类型?) C 编程
【发布时间】:2016-11-23 21:53:04
【问题描述】:

我得到了 32 位整数,我想将它们存储在 动态分配的数组中,然后将此数组发送给其他进程(在 MPI 中)

   int32_t data;

我很困惑,我应该使用哪种类型的数据,这样我才能拥有一个大小为 32 位整数的 N 数组? 如何实现?

【问题讨论】:

  • 我想你可能想了解一下 malloc/realloc/free。
  • int32_t* array = malloc(sizeof(int32_t)*N); 怎么样?
  • 我相信int32_t* array = malloc(sizeof(*array) * N);更好。
  • @Shiva 是一种非常有趣的鼓励类型安全的方法,我以前从未见过
  • 其实你应该使用calloc而不是乘法。

标签: c arrays types integer


【解决方案1】:

...我应该使用哪种类型的数据,以便我可以拥有一个大小为 32 位整数的数组 N

// The type of `p` is a pointer to a 32-bit signed integer.
int32 *p;

如何实现?

// No need to use `int32_t` in the next line of code
//              size of 1 element ---v-------v * v--- element count
p = /* no cast needed here */ malloc(sizeof *p * N);
if (p == NULL) return Handle_Failure();

for (size_t i=0; i<N; i++) {
  // do something with p[i]
  p[i] = 42;
}

// free when done
free(p);

【讨论】:

    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 2012-04-10
    • 2013-09-18
    • 1970-01-01
    相关资源
    最近更新 更多