2017-04-08 133 views
-1

所以,我要做的就是創建一個數組將包含數N的多個表,IE:Ç - 數組,它包含有一個malloc()函數的多個表

"Enter a number = 6" 
"1 2 3 4 5 6" 
"2 4 6 8 10 12" and so on untill 36 

這是我的代碼:

int * initiallizeArray(int * rows) 
{ 
    int i = 0, j = 0; 
    int * twoDArray = 0; 
    printf("Enter a number: "); 
    scanf("%d", rows); 
    twoDArray = (int*)malloc(sizeof(int) * (*rows * *rows)); 
    for (i = 0; i < *rows; i++) 
    { 
     for (j = 0; j < *rows; j++) 
     { 
      //twoDArray[i * *rows + j] = 
     } 
    } 
    return twoDArray; 
} 

與「//」的線是什麼,我不知道該怎樣實現它裏面 基本上它循環所有的陣列上,但我不知道該怎麼投入的具體cell

+0

NeXoR。好奇:誰或什麼文本建議在'twoDArray =(int *)malloc(...'? – chux

回答

-3

這應該工作:

int * initiallizeArray(int * rows) 
{ 
    int i = 0, j = 0; 
    int * twoDArray; 
    printf("Enter a number: "); 
    scanf("%d", rows); 
    twoDArray = (int*)malloc(sizeof(int) * 2 * (*rows)); 
    for (i = 0; i < *rows; i++) 
    { 
     for (j = 0; j < *rows; j++) 
     { 
      twoDArray[i * (*rows) + j] = (i+1) * (j+1); 
     } 
    } 
    return twoDArray; 
} 
+0

''中輸入'(int *)'''就是這樣,j +1 * i + 1,Ty – NeXoR

+2

如果'* rows> 2 ','twoDArray [i *(* rows)+ j] = ...'試圖超出分配的內存寫入。 – chux

3

由於twoDArray其實一個二維數組,你可能會更好過重命名它的東西更清楚。建議不要使用返回值malloc,因爲它是不必要的,並且如果您更改了分配的指針的類型,則可能會引入錯誤。 for循環的主體很簡單:(i + 1) * (j + 1)

int* initiallizeArray(int* rows) 
{ 
    int i = 0, j = 0; 
    int* mult_table = NULL; 
    printf("Enter a number: "); 
    scanf("%d", rows); 
    mult_table = malloc((sizeof *mult_table) * (*rows) * (*rows)); 
    for (i = 0; i < *rows; i++) 
    { 
     for (j = 0; j < *rows; j++) 
     { 
      mult_table[i * (*rows) + j] = (i + 1) * (j + 1); 
     } 
    } 
    return mult_table; 
} 
+1

好的答案:小點:最好使用malloc(sizeof(int)*(* rows)*( * rows));'考慮類型和減少溢出的可能性 – chux

+0

@chux是因爲'sizeof(int)'是一個'size_t'並因此大於'int'? – iafisher

+2

@chux可以糾正我,如果我錯了,但我相信問題是用'(* rows)*(* rows)* sizeof(int)'左邊的兩個「int」的乘積首先出現,如果它們的值很大,則有可能發生溢出。對於sizeof(int)*(* rows)*(* rows),size_t和int的乘積首先出現,因此int和第一乘法的結果被轉換爲size_t。 (假設'size_t'較大比'int'),減少了溢出的可能性。 –

相關問題