ポインタです

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
大工

ポインタです

#1

投稿記事 by 大工 » 18年前

いつもお世話になっております。


またやトラブルが・・・


#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.

と表示されてしまいます.

原因はいったいなんなんでしょう??

box

Re:ポインタです

#2

投稿記事 by box » 18年前

> 原因はいったいなんなんでしょう??

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

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

大工

Re:ポインタです

#3

投稿記事 by 大工 » 18年前

失礼しました。

ソースコード載せます

box

Re:ポインタです

#4

投稿記事 by box » 18年前

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

#5

投稿記事 by 大工 » 18年前

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. が変換していますし、ポインタのポインタを使っているのもなぞです。

keichan

Re:ポインタです

#6

投稿記事 by keichan » 18年前

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

#7

投稿記事 by 大工 » 18年前

自己解決しました。お騒がせしました

閉鎖

“C言語何でも質問掲示板” へ戻る