ページ 11

ポインタです

Posted: 2007年2月01日(木) 15:37
by 大工
いつもお世話になっております。


またやトラブルが・・・


#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:ポインタです

Posted: 2007年2月01日(木) 15:43
by box
> 原因はいったいなんなんでしょう??

現状では雲をつかむような話で、誰にも何もわかりません。
さて、どうしてかというと…。

ソースコードの提示がないからです。
ご理解いただけるでしょうか。

Re:ポインタです

Posted: 2007年2月01日(木) 17:13
by 大工
失礼しました。

ソースコード載せます

Re:ポインタです

Posted: 2007年2月01日(木) 17:24
by box
> 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:ポインタです

Posted: 2007年2月01日(木) 17:36
by 大工
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. が変換していますし、ポインタのポインタを使っているのもなぞです。

Re:ポインタです

Posted: 2007年2月01日(木) 18:06
by keichan
>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の実行結果はどうなるでしょうか?

Re:ポインタです

Posted: 2007年2月01日(木) 19:09
by 大工
自己解決しました。お騒がせしました