筆試題(Test函式)

才智咖 人氣:2.43W

void GetMemory(char *p)

筆試題(Test函式)

{

p = (char *)malloc(100);

}

void Test(void)

{

char *str = NULL;

GetMemory(str);

strcpy(str, "hello world");

printf(str);

}

請問執行Test函式會有什麼樣的結果?

答:試題傳入GetMemory( char *p )函式的形參為字串指標,在函式內部修改形參並不能真正的改變傳入形參的值,執行完 char *str = NULL; GetMemory( str ); 後的str仍然為NULL;

char *GetMemory(void)

{

char p[] = "hello world";

return p;

}

void Test(void)

{

char *str = NULL;

str = GetMemory();

printf(str);

}

請問執行Test函式會有什麼樣的結果?

答:可能是亂碼。 char p[] = "hello world";

      return p; 
的p[]陣列為函式內的'區域性自動變數,在函式返回後,記憶體已經被釋放。這是許多程式設計師常犯的錯誤,其根源在於不理解變數的生存期。