Re: [問題] 字串指標問題...

看板C_and_CPP (C/C++)作者 (HANA)時間16年前 (2009/12/31 21:27), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/4 (看更多)
※ 引述《tokyobabylon (paris)》之銘言: : 剛寫了這隻小程式 : 發現字串指標的一些問題還是搞不太懂... : #include <stdio.h> : #include <stdlib.h> // 用system("pause")要include stdlib.h這個header : #include <assert.h> // 用assert()時要宣告assert.h : #include<iostream.h> : #include<cstdlib> : #define EXAM_ASSERT(x) assert(x) //定義function-like macro EXAM_ASSERT : // assert() 若其argument為0 則會中斷程式 : /* : 用ASSERT保證沒有定義的特性或功能不被使用。 : */ : void exam_fun(char* test_str) //這個exam_fun檢查傳進來的char pointer若內容是 : NULL 就中斷程式 : { : EXAM_ASSERT(test_str!= NULL); : } : int main(void) : { : char *str=NULL; : //str=(char *)malloc(sizeof(char)); : //str=NULL; : //cout <<"str "<< str <<endl; //尚未指定char* str的內容之前就要看他的內容 : ,當! : printf("&str=%p\n",&str); //pointer 已存在故可以看到他的位址 : //cout <<"*str "<< *str <<endl; //一樣,char* str內容尚未指定前就要看他的內 : 容,當! : str="b"; : exam_fun(str); : printf("str已經被指定一個值b\n"); : printf("str=%p\n",str); : printf("&str=%p\n",&str); : printf("*str=%s\n",str); : cout<<*str<<endl; : system("pause"); : return 0; : } : 問題1. : 再最後一個printf中,為什麼要用printf("*str=%s\n",str)才可以過? : 原本我是寫printf("*str=%s\n",*str)卻interrupt跳掉 : 我原本就是要str內含的值阿~~~~ : 但是在更下面的cout<<*str ; : 使用cout時卻可以過 而不是使用cout<<str ; : 問題2. : 我使用dev-c compile : 雖然可以跑卻是有warning... 閒來沒事跑跑看 我用dev-c去跑沒遇到警告 或許是版本不同吧 你可以把str="b"; 改成str="bsff一堆亂七八糟的東西"; 去跑跑看 這樣比較能看出當中的差異 cout<<*str; 他當做字元處裡 而不是字串 所以只會印出b 但是 printf("*str=%s\n",str);印出完整字串 "bsff一堆亂七八糟的東西" 而如果把cout<<*str;改成 cout<<str; 他才會當成字串處裡 印出 "bsff一堆亂七八糟的東西" -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.117.169.152
文章代碼(AID): #1BFAQp1T (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1BFAQp1T (C_and_CPP)