我创建了一个C程序,它由一个整数数组结构states[2]组成。我还需要一个uint32_t类型的数组,称为store。我只想把数组状态[0]的内容复制到存储[0]中把状态[1]的内容复制到存储[1]中。我将这种方法用于字符数组,它似乎有效。我的代码是这样的:
#include <stdlib.h>
#include <stdio.h>
int main()
{
uint32_t *store[2];
int i;
int *states[2];
int states[0] = {1,0,0,1};
int states[1] = {0,0,0,2};
for (i = 0; i < 3; i++)
{
store[i] = states[i];
i++;
}
}
然而,代码没有执行,并指出我声明的数组格式无效。我不确定这是否是正确的做法。有人能帮我一下吗?
我重写了你的例子-强制数组的大小-在这个,它工作。
编辑-增加了printf调用来显示数组存储的内容。
#include <stdlib.h>
#include <stdio.h>
int main()
{
int store[3][4];
int i;
int states[3][4] = {{1,0,0,1},{0,0,0,2}};
for(i=0; i<3; i++)
{
printf( "store[%d] = ", i );
for( int inner = 0; inner < 4; inner++ )
{
store[i][inner] = states[i][inner];
printf( "%d ", store[i][inner] );
}
printf( "n" );
}
return( 0 );
}
在数组中创建指针时,确实需要先分配然后复制。
你的代码中有两个问题,
,
int *states[2];
int states[0] = {1,0,0,1};
int states[1] = {0,0,0,2};
是有问题的。当访问变量时,不需要提及类型,仅在定义时需要。因此,使用int states[0]
或..[1]
是无效的。
然后,第二,
states[0] = {1,0,0,1};
state[0]
是int *
类型,并且您试图用括号括起来的int
s初始化列表初始化它。这也是不对的。
您可以修改代码以在访问数组元素时删除类型并使用复合文字,最终看起来像
下面的内容#include <stdlib.h>
#include <stdio.h>
#include <stdint.h> //added for uint32_t
int main(void) //corrected signature
{
uint32_t *store[2];
int i;
int *states[2];
states[0] = (int []){1,0,0,1}; //compound literal, C99 and above
states[1] = (int []){0,0,0,2};
for (i = 0; i < 2; i++) //bound corrected
{
store[i] = states[i];
//i++; remove this, you're incrementing twice
}
}