問題の関数内の内容が分からない上に実行結果が間違っている

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

問題の関数内の内容が分からない上に実行結果が間違っている

#1

投稿記事 by tarako » 7年前

大学でプログラㇺの問題を出題されたのですが関数内の内容が分からないのと実行結果が間違っているのでどう変更したらよいか、を教えてください。
勉強した部分は関数の呼び出し、アドレス、ポインタ、構造体のあたりです。

コード:

#include <stdio.h>

void strcopy(char *sp2, char *sp1);

int main(void)
{
	char str1[100],str2[100];
	printf("文字列を入力->");
	scanf("%s",str1);
	strcopy(str2,str1);
	printf("str1[] = %s\n",str1);
	printf("str2[] = %s\n",str2);

	return 0;
}

void strcopy(char *sp2, char *sp1)
{
#include <stdio.h>

void strcopy(char *sp2, char *sp1);

int main(void)
{
	char str1[100],str2[100];
	printf("文字列を入力->");
	scanf("%s",str1);
	strcopy(str2,str1);
	printf("str1[] = %s\n",str1);
	printf("str2[] = %s\n",str2);

	return 0;
}

void strcopy(char *sp2, char *sp1)
{
	for( ;*sp1 = '\0'; sp1++, sp2++)
	{
		*sp2 = *sp1;
	}
		*sp2 = '\0';
}

コード:

問題の実行結果

文字列を入力-> yes[Enter]
str1[] = yes
str2[] = yes

コード:

実際の実行結果

文字列を入力-> yes[Enter]
str1[] =
str2[] =

かずま

Re: 問題の関数内の内容が分からない上に実行結果が間違っている

#2

投稿記事 by かずま » 7年前

コードのコピペに失敗していますね。
最初の 18行が重複しています。

printf を挿入してデバッグしてみましょう。

コード:

#include <stdio.h>
 
void strcopy(char *sp2, char *sp1);
 
int main(void)
{
    char str1[100] = "abc", str2[100] = "def";  // for DEBUG
    printf("文字列を入力->");
    scanf("%s",str1);
    strcopy(str2,str1);
    printf("str1[] = %s\n",str1);
    printf("str2[] = %s\n",str2);
 
    return 0;
}
 
void strcopy(char *sp2, char *sp1)
{
    printf("strcopy: sp2=[%s], sp1=[%s]\n", sp2, sp1);  // DEBUG
    for( ;*sp1 = '\0'; sp1++, sp2++)
    {
        *sp2 = *sp1;
        printf("for: sp2=[%s], sp1=[%s]\n", sp2, sp1);  // DEBUG
    }
    *sp2 = '\0';
    printf("return: sp2=[%s], sp1=[%s]\n", sp2, sp1);  // DEBUG
}
実行結果

コード:

文字列を入力->yes
strcopy: sp2=[def], sp1=[yes]
return: sp2=[], sp1=[]
str1[] = 
str2[] = 
for文の中に入っていないことが分かります。

= は、代入演算子。
== と != は、等価演算子。

返信

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