2014-04-30 71 views
0

我正在嘗試爲我的C編程類中的最終項目編寫某些內容,但是我遇到了一個我無法弄清的問題。我的代碼是:嘗試將值分配給動態分配的2D數組時,程序崩潰

#include <stdio.h> 
#include <stdlib.h> 
char** allocateLevel(int sizeOfLevel); 

int main(void) 
{ 

    char** level = allocateLevel(10); 
    int one, two; 

    for(one = 0 ; one < 10 ; one++) 
    { 
     for(two = 0 ; two < 10 ; two++) 
     { 
      level[one][two]='T'; //Crashes right here 

     } 
    } 
    printf("%c", level[4][5]); //tests to see if it prints 
} 

char** allocateLevel(int sizeOfLevel) 
{ 
    char **levelPointer; 
    levelPointer = (char **)malloc(sizeOfLevel * sizeof(char **)); 
    int count = 0; 


    for(count = 0 ; count < sizeOfLevel ; count++) 
    { 
     levelPointer[count] = (char*) malloc(sizeOfLevel * sizeof(char*)); 

    } 
} 

程序分配內存正常,但當我嘗試將值分配給的要素之一崩潰。我無法弄清楚什麼是錯誤的,我的教授沒有太多幫助。有什麼不對的嗎?

+2

看看你的'sizeof'用法。 –

+2

'allocateLevel()'中的'return'語句在哪裏? – cmaster

+0

它究竟有什麼問題? – user2863558

回答

2

在你的功能allocateLevel你不要返回什麼。因此,結尾爲level的值幾乎未定義。

  1. 在函數的末尾添加return levelPointer;allocateLevel
  2. 啓用您的編譯器警告。這會告訴你「功能沒有'返回'結束。」

(編輯)@Oli說什麼 - 你的sizeof都是間接的水平。

+0

爲了避免malloc大小問題,使用這個習慣用法,其中'p'是你的指針, N'是你想要的元素數量:'p = malloc(N * sizeof * p);' –

0

在行:

levelPointer = (char **)malloc(sizeOfLevel * sizeof(char **)); 

有兩個問題,我可以看到:
1)你投的malloc()Good discussion Here
2)返回sizeof(char **);正在尋址(== 8(64位),== 4(32位)。可能不是你預期的結果?)

sizeof運算符計算一個變量或類型的字節數。您的使用是給你的,你是不是期待的結果:運行這個例子:

int main() 
{ 
    cout << "Size of char ** : " << sizeof(char **) << endl; 
    cout << "Size of char : " << sizeof(char) << endl; 
    cout << "Size of int : " << sizeof(int) << endl; 
    cout << "Size of short int : " << sizeof(short int) << endl; 
    cout << "Size of long int : " << sizeof(long int) << endl; 
    cout << "Size of float : " << sizeof(float) << endl; 
    cout << "Size of double : " << sizeof(double) << endl; 
    cout << "Size of wchar_t : " << sizeof(wchar_t) << endl; 
    return 0; 
} 

常爲char **分配內存時的使用是創建一個字符串數組(這是在轉彎char數組)。由於您正在爲char **分配內存,請將其看作是分配內存的替代方法。它提供大小參數,並返回指針和其他參數分配的內存。

有關創建存儲

char ** allocMemory(char ** a, int numStrings, int maxStrLen) 
{ 
    int i; 
    a = calloc(sizeof(char*)*(numStrings+1), sizeof(char*)); 
    for(i=0;i<numStrings; i++) 
    { 
     a[i] = calloc(sizeof(char)*maxStrLen + 1, sizeof(char)); 
    } 
    return a; 
} 

對於釋放當您完成分配的內存。

void freeMemory(char ** a, int numStrings) 
{ 
    int i; 
    for(i=0;i<numStrings; i++) 
     if(a[i]) free(a[i]); 
    free(a); 
}