iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
自我挑戰組

C 語言筆記系列 第 23

[C 語言筆記--Day22] warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

  • 分享至 

  • xImage
  •  

在寫 C 語言時

char *week[] = {
  "Friday",
  "Saturday",
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday"
};

是沒問題的,

但是在寫 C++ 時,

char *week[] = {
  "Friday",
  "Saturday",
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday"
};

卻會跑出警告:

test.cpp:2:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    2 |   "Friday",
      |   ^~~~~~~~
test.cpp:3:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    3 |   "Saturday",
      |   ^~~~~~~~~~
test.cpp:4:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    4 |   "Sunday",
      |   ^~~~~~~~
test.cpp:5:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    5 |   "Monday",
      |   ^~~~~~~~
test.cpp:6:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    6 |   "Tuesday",
      |   ^~~~~~~~~
test.cpp:7:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    7 |   "Wednesday",
      |   ^~~~~~~~~~~
test.cpp:8:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    8 |   "Thursday"
      |   ^~~~~~~~~~

解決方法:加上 const 就可以了

const char *week[] = {
  "Friday",
  "Saturday",
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday"
};

參考資料:
https://blog.csdn.net/whatday/article/details/106267398


上一篇
[C 語言筆記--Day22] 6.S081 Lab syscall: 在 xv6 中新增一個 System Call
下一篇
[C 語言筆記--Day24] sleep
系列文
C 語言筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言