1. 程式人生 > >C++ 錯誤提示:無法將引數1從const char [8] 轉換為char *

C++ 錯誤提示:無法將引數1從const char [8] 轉換為char *

#include <iostream>	
using namespace std;

void test(char * p)
{
    cout << p << endl;
}

int main(void)
{
    test("geerniya");
    system("pause");
}

在將字串當做函式引數傳遞給函式時,如上所示。編譯器會報錯C2664 “void test(char *)”: 無法將引數 1 從“const char [12]”轉換為“char *”。當把test()函式中的形參改為const char * p

後,錯誤就沒有了。

原因應該是函式的實參與形參型別不匹配, 字串在記憶體中是一個常量字串陣列,因此在函式中的形參也應當加上const關鍵字才行。

改好後的程式如下:

#include <iostream>	
using namespace std;

void test(const char * p)
{
    cout << p << endl;
}

int main(void)
{
    test("geerniya");
    system("pause");
}