我正在尝试通过函数中的指针写入颜色数组中的元素。函数是:
void setColor(int color1[3],int color2[3], int *red, int *green, int *blue) {
int redInc = (color2[1]-color1[1])/range;
int greenInc = (color2[2]-color1[2])/range;
int blueInc = (color2[3]-color1[3])/range;
int i = 0;
while (i < range) {
*(red+i) = color1[1] + i*redInc;
printf("This is red: %s\n",*(red+i));
*(green+i) = color1[2] + i*greenInc;
*(blue+i) = color1[3] + i*blueInc;
i++;
}
return;}
Range 定义为常数 21。在主循环内部:
int color1[3] = {255,0,0};
int color2[3] = {0,255,0};
int red[21] = {0};
int green[21] = {0};
int blue[21] = {0};
setColor(color1,color2,red,green,blue);
我已经在我的 Linux 机器上试过这段代码,它似乎可以工作,但它在我的 Raspberry Pi 上出现段错误。这是我尝试访问数组的方式吗?
最佳答案
C 是零索引的,这意味着如果你有一个 3 整数长的数组,你可以使用索引 0、1 和 2 访问它
例子:
int ex[3] = {1,2,3};
printf("%d %d %d", ex[0], ex[1], ex[2]);
将输出:
1 2 3
因此,您需要做的是检查您的代码并检查您在哪里不正确地索引数组,这看起来像函数 void setColor(int color1[3],int color2[3] 中的所有数组], int *red, int *green, int *blue)
关于C: 在 Raspberry Pi 上写入数组指针时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663547/