我有一个动态分配的 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/