2017-06-20 48 views
1

我想通过函数中的指针写入颜色数组中的元素。该功能是:C:向Raspberry Pi上的数组指针写入时出现分段错误

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;}  

范围被定义为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机器上的代码,它似乎工作,但它在我的树莓派上分割故障。这是我想如何访问数组?

+3

'color1 [3]'超出范围。 – mch

+2

几乎所有的编程语言中,数组索引都从0开始,而不是1。 – Barmar

+1

投入一些时间学习使用宏而不是丑陋的数字时玩数组 – Zakir

回答

0

这是我如何访问数组?

是的!数组索引从0开始并以大小-1结束,其中大小是数组的长度。


这里:

*(blue+i) = color1[3] + i*blueInc; 

color1超出范围,因为它有3尺寸:

int color1[3] = {255,0,0}; 

,你访问它过去color1[2],这将导致未定义行为,并且很可能是您提到的分段错误。

2

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)

+0

好的。不能相信我错过了错过的错误。这已被纠正。但它在我的Linux机器上工作。它只是应该为每个条增量使用不同颜色的状态栏。但是当我在我的Raspberry Pi上编译它时,它会发生故障。 – calvinjarrod

+0

@calvinjarrod正如其他答案中所提到的,索引超过数组的末尾是未定义的行为。所以有时候它不会让程序崩溃,但这并不意味着它按照你的意图工作。这可能与你的变量'范围'有关。我正在查看帖子,而您没有提供它的定义。你说“......在主循环中”。如果'范围'始终是相同的值,我建议'#define'它。您是否尝试过使用调试器单步执行代码? – jacoblaw

0

正如你intialized的arraycolor1[3],索引可以使用的01,并且2,所以你应该改变这种价值,因为当您尝试访问在array位置3,它给出了一个分段错误,因为它已经超出索引。 希望你明白!