arrays - 在c中初始化动态数组
问题描述
我使用 malloc 创建了一个动态数组,在初始化它时出现错误。我在这里做错了什么?
float* data_input = malloc(4 * sizeof(float));
data_input = {1.2, 2.4, 3.2, 4.5};
错误:
model.c: In function ‘main’:
model.c:9:18: error: expected expression before ‘{’ token
9 | data_input = {1.2, 2.4, 3.2, 4.5};
解决方案
这个赋值语句
data_input = {1.2, 2.4, 3.2, 4.5};
在 C 中是不正确的。
相反,你可以写
#include <stdlib.h>
#include <string.h>
//...
float* data_input = malloc(4 * sizeof(float));
memcpy( data_input, ( float [] ){1.2, 2.4, 3.2, 4.5 }, sizeof( float[4] ) );
这是一个演示程序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
enum { N = 4 };
float *data_input = malloc( N * sizeof( float ) );
memcpy( data_input, ( float [] ){1.2, 2.4, 3.2, 4.5 }, sizeof( float[N] ) );
for ( size_t i = 0; i < N; i++ )
{
printf( "%.1f ", data_input[i] );
}
putchar( '\n' );
free( data_input );
return 0;
}
程序输出为
1.2 2.4 3.2 4.5