いつもお世話になっております。
またやトラブルが・・・
#include <stdio.h>
char *msg = "This is an apple.";
void exchange(char *);
int main(void){
char *mm = "This is a test.";
char *p = msg;
printf("%s\n", p);//This is an apple.
p = mm;
printf("%s\n", p);//This is a test.
exchange(p);
printf("%s\n", p);//This is an apple.になっているはず.
return 0;
}
void exchange(char *q){
q = msg;
}
関数(exchange(char *))内でmsgのアドレスをqに代入してmain関数内で"This is an apple."
と表示したいのですが結果が
This is an apple.
This is a test.
This is a test.
と表示されてしまいます.
原因はいったいなんなんでしょう??
ポインタです
Re:ポインタです
> void exchange(char *q){ > > q = msg; 書き換えたqの内容が、呼び出し元に反映されていません。 呼び出し元では exchange(&p); のように、pのアドレスを渡してください。 そして、exchange関数は void exchange(char **q) { *q = msg; } としてください。それから、お使いの環境によっては、msgとmmの定義を
ポインタではなく配列にしておかないと
プログラムが異常終了するかもしれません。
偶然にも似ている話題がありましたので、
参考になるかもしれません。
(参考URL)http://okwave.jp/qa2714684.html
Re:ポインタです
exchange(p); ではpのアドレスを渡していることにはならないのでしょうか??
#include <stdio.h>
char msg[/url] = "This is an apple.";
void exchange(char *);
int main(void){
char mm[/url] = "This is a test.";
char *p = msg;
printf("%s\n", p);//This is an apple.
p = mm;
printf("%s\n", p);//This is a test.
exchange(p);
printf("%s\n", p);
return 0;
}
void exchange(char *q){
q[0] = 't';
}
では This is a test. this is a test. が変換していますし、ポインタのポインタを使っているのもなぞです。
#include <stdio.h>
char msg[/url] = "This is an apple.";
void exchange(char *);
int main(void){
char mm[/url] = "This is a test.";
char *p = msg;
printf("%s\n", p);//This is an apple.
p = mm;
printf("%s\n", p);//This is a test.
exchange(p);
printf("%s\n", p);
return 0;
}
void exchange(char *q){
q[0] = 't';
}
では This is a test. this is a test. が変換していますし、ポインタのポインタを使っているのもなぞです。
Re:ポインタです
>exchange(p); ではpのアドレスを渡していることにはならないのでしょうか??
/***********************************/ /*** case 1 ***/ /***********************************/ #include <stdio.h> void foo_int(int a) { printf("%d", a); a++; } int main() { int i = 10; foo_int(i); printf("%d", i); return 0; } /***********************************/ /*** case 2 ***/ /***********************************/ #inclue <stdio.h> void foo_intp(int* a) { printf("%p", a); a++; } int main() { int i; int* p = &i; foo_intp(p); printf("%p", p); return 0; }さて、case1とcase2の実行結果はどうなるでしょうか?