簡體   English   中英

當我給printf一個指向char數組的指針時程序崩潰

[英]Program crashes when I give printf a pointer to a char array

當我嘗試運行以下代碼時,我得到一個seg錯誤。 我已經嘗試通過gdb運行它,並且我理解錯誤是作為調用printf一部分發生的,但是我很遺憾為什么它無法正常工作。

#include <stdlib.h>
#include <stdio.h>

int main() {
  char c[5] = "Test";
  char *type = NULL;

  type = &c[0];
  printf("%s\n", *type);
}

如果我替換printf("%s\\n", *type); with printf("%s\\n", c); 我按照預期打印“測試”。 為什么它不能用於指向char數組的指針?

你正在傳遞一個普通的charprintf試圖取消引用它。 試試這個:

printf("%s\n", type);
              ^ 

如果你傳遞*type就像告訴printf “我在T位置有一個字符串”。

另外type = &c[0]有點誤導。 你為什么不這樣做:

type = c;

不要取消引用type 它必須保持指針。

刪除printftype的解除引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM