[問題] C 語言新手十誡裡的某一條

看板C_and_CPP (C/C++)作者 (幾摳)時間16年前 (2009/12/14 08:04), 編輯推噓2(201)
留言3則, 2人參與, 最新討論串1/1
遇到的問題: (題意請描述清楚) 有一條是這麼寫的: 四、你不可以將字串常數賦值(assign)給 char* 變數,然後透過該變數 改寫字串的內容(只能讀不能寫)。 錯誤例子: char* pc = "john"; *pc = 'J'; printf("Hello, %s\n", pc); 但我現在讀到的課本(Computer Science - A Structured Programing Approach Using C) 有這麼一段 C provides two more ways to initialize string. A common method is to assign a string literal to a character pointer, as show below. This creates a string for the literal and stores its addres in the string pointer variable, pStr. char * pStr = "Good Day"; 這兩段文字不就有衝突?難不成因為是C99?? 有請高手解惑,感謝。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.221.170

12/14 08:10, , 1F
十誡寫的是「不能賦值然後修改」 沒衝突呀?
12/14 08:10, 1F

12/14 08:10, , 2F
沒衝突,錯誤例子是錯在*pc = 'J';
12/14 08:10, 2F
原來是自己耍笨了 那在請問各位,如果用char *宣告一個字串又想用scanf賦予它值,有解嗎? ※ 編輯: TTGSP 來自: 140.123.221.170 (12/14 08:12)

12/14 08:14, , 3F
char pc[] = "john"; *pc = 'J'; // ok
12/14 08:14, 3F
文章代碼(AID): #1B9O47z5 (C_and_CPP)
文章代碼(AID): #1B9O47z5 (C_and_CPP)