2012-11-04 142 views
0

我想寫一個C程序來打印一個魔方。但是,我在建造廣場時遇到了一個錯誤。任何人都可以幫助弄清楚是什麼導致這些錯誤?以下是我的相關代碼,和我的輸出:打印二維數組打印垃圾(魔方)

代碼:

int main(void) { 
     int size = 0; 
     int r, c; 
     int i = 1; 

     printf("What is the size of the square: "); 
     scanf("%d", &size); 

     int square[size][size]; 
     int range = size * size; 
     r = 0; 
     c = size/2; 

     do { 
      square[r][c] = i; 

      i++; 
      r--; 
      c++; 

      if ((r == -1) && (c == size)) { 
       r = r + 2; 
       c--; 
      } else if (r == -1) { 
       r = size - 1; 
      } else if (c == size) { 
       c = 0; 
      } else if (square[r][c] != 0) { 
       r = r + 2; 
       c--; 
      } 
     } while (i < range); 

     for (r = 0; r < size; r++) { 
      for (c = 0; c < size; c++) { 
       printf("%d \t", square[r][c]); 
      } 
      printf("\n"); 
     } 

     return 0; 
    } 

輸出:

What is the size of the square: 3 
-4196312  1  0 
3  -4196352  -13339222 
4  -13360148  2 

回答

3

的功能範圍內的所有變量都沒有初始化爲零。相反,他們被分配到一個隨機值。

使用此:

int square[size][size] = {0}; 

您還可以使用memsetcalloc,但是這一個是最簡單的。


校正:

列表初始化不具有可變尺寸數組工作。使用memset來代替:

int square[size][size]; 
memset(square, 0, size * size * sizeof(int)); 

編輯:

整個工作代碼

#include <stdio.h> 
#include <string.h> 

int main(void) { 
    int size = 0; 
    int r, c; 
    int i = 1; 

    printf("What is the size of the square: "); 
    scanf("%d", &size); 

    int square[size][size]; 
    memset(square, 0, size * size * sizeof(int)); 
    int range = size * size; 
    r = 0; 
    c = size/2; 

    do { 
     square[r][c] = i; 

     i++; 
     r--; 
     c++; 

     if ((r == -1) && (c == size)) { 
      r = r + 2; 
      c--; 
     } else if (r == -1) { 
      r = size - 1; 
     } else if (c == size) { 
      c = 0; 
     } else if (square[r][c] != 0) { 
      r = r + 2; 
      c--; 
     } 
    } while (i < range); 

    for (r = 0; r < size; r++) { 
     for (c = 0; c < size; c++) { 
      printf("%d \t", square[r][c]); 
     } 
     printf("\n"); 
    } 

    return 0; 
} 
+0

謝謝你的回答!但是,在使用'memset'代碼後,我現在得到以下錯誤:'警告:內置函數'memset''的不兼容隱式聲明''錯誤:'int''之前的預期表達式 – user41419

+0

它是'string中的函數.h'。把'#include '放在你的第一行代碼中。 – texasbruce

+0

再次感謝!我已經這樣做了,並且刪除了第一個錯誤,但是編譯器仍然會在'int''之前說'錯誤:預期的表達式。我認爲它是指'memset'表達式中的'sizeOf(int)'。 – user41419