c - 使用 uint8_t 为双数组分配内存

标签 c pointers casting malloc

我有一个动态分配的 uint8_t 内存数组

uint8_t* array = malloc( sizeof( double ) * 100 );

我想将 double 存储到内存中。这会被视为已定义的行为,还是我需要担心一些对齐问题?

double* d = ( void* )array ;

for( int i = 0 ; i < 100 ; i++ )  
    d[i] = 3.1415 ;    //any double will do here

d 的行为应该与我将 d 分配为相同:

double* d = malloc( sizeof( double ) * 100 );

此外,如果我像这样更改指针数组以进一步指向内存:

 double* d = ( void* )(array + sizeof( double ) * 50 ) ;
 for( int i = 0 ; i < 50; i++ )  
    d[i] = 3.1415 ;    //any double will do here

d 的行为是否与

相同
double* d = malloc( sizeof( double ) * 50);

(如何正确释放内存不是这里的问题)

最佳答案

C 标准保证

The pointer returned [by malloc] if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated

7.20.3《内存管理函数》[#1]

因此您的代码是安全的。

关于c - 使用 uint8_t 为双数组分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20862792/

相关文章:

mysql - mysql中数字的隐式转换

c++ - 模板转换运算符 C++

c++ - 跨 dll 强制转换 void 指针

c - 使用 fgets 时 EOF 不起作用

c - 如何使用 NativeCall 处理可变参数

c - 用 C 编写的服务器中最有效的文件登录是什么?

c++ - 指针和引用传递 C++

c++ - 智能指针如何影响5的规则?

python - 如何为 pytest 执行的 SWIG 编译的 C 代码生成代码覆盖率报告

在 C 中连接两个 const char *