[英]Why is passing a string literal into a char* argument only sometimes a compiler error?
[英]Passing string literal to function taking 'char *' and getting a compiler warning
只是一個語法問題,這是我的代碼段。 (抱歉,瀏覽器無法讓我正確粘貼到堆棧溢出中。)
#include <iostream> /* 'iostream.h' is deprecated. */
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std; /* Required. */
FILE *OpenFile(char *Filename)
{
FILE *FP;
if((FP = fopen(Filename, "r")) == NULL)
{ /* Error opening file. */
std::cout << "[!!] Unable to open database!"
<< " Are you sure it exists?\n"
<< "[<<] Database Unchanged.\n";
exit(EXIT_FAILURE); /* End program. */
}
else /* Properly opened the file. */
return FP;
}
int main(void)
{
FILE *Data; /* Our database file pointer. */
Data = OpenFile("Data.txt");
printf("Success!\n");
return 0;
}
編譯時,出現以下警告:
$ g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:27:28: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
$
我要去哪里錯了?
C ++中的字符串文字的類型為“ n const char
數組”(其中n是字符串中的字符數,包括終止NUL)。 這樣聲明您的功能:
FILE *OpenFile(const char *Filename)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.