由于大小分配导致的数组错误

时间:2018-04-21 16:00:41

标签: c arrays multidimensional-array

我正在为C编程类做示例:

#define xSize 2
#define ySize 3

int x,y, a[xSize][ySize];
for (x=1; x<=xSize; x++){

for (y=1; y<=ySize; y++){
a[x][y]=(x*x)+(y*y);}}

for (x=1; x<=xSize; x++){

for (y=1; y<=ySize; y++){
printf("a[%d][%d]= %d   ", x, y, a[x][y]);}}

当我尝试编译&#34; Xcode-macOS&#34;

时出现错误

但是当我给 int x,y,a [xSize + 1] [ySize + 1] 时,它编译得很好,为什么会发生呢?

2 个答案:

答案 0 :(得分:2)

数组索引从0开始。在for循环中,使用x = 1&amp;&amp;进行迭代。 X&LT =大小。条件应为x = 0&amp;&amp; x&lt;尺寸。同样适用于阵列的所有尺寸。

答案 1 :(得分:2)

指定 select a.MONTH, a.TOTAL, a.TOTAL - b.TOTAL, ((a.TOTAL - b.TOTAL)/ a.TOTAL )*100 from ( SELECT coalesce(date_format(TRANSACTION_DATE, '%M'), 'Grand Total') AS MONTH, ROUND(SUM(SALES_AMOUNT),2) TOTAL FROM SALES WHERE YEAR(TRANSACTION_DATE) = 2018 GROUP BY month ) a inner join ( SELECT coalesce(date_format(TRANSACTION_DATE, '%M'), 'Grand Total') AS MONTH, ROUND(SUM(SALES_AMOUNT),2) TOTAL FROM SALES WHERE YEAR(TRANSACTION_DATE) = 2017 GROUP BY month ) b ON a.month = b.month a[xSize]时。数组b[ySize]最多可存储a个值,而xSize最多可存储b个值。但是,它分别从数组ySizexSize-1中的索引0到ySize-1和0到a开始。因此,当您使用for循环时,您正在使用索引从1到b迭代循环,而实际上数组的最大索引限制为xSize