文字列sorceを文字列strにコピーし、入力された文字数をカウントする関数を作っています。たとえば、文字列sorceにhello!と入力したところ、コピー先の文字列にはフフフフフフフフフフフフフフフフhello!と表示されてしまいました。以前にも同じ内容の質問があったのですが、どうしても分からなかったたまえ、質問させていただきました。また、ビルトしたときに、scanfのところにエラーが表示されました。どこが間違っているかも合わせて教えていただけたら幸いです。よろしくお願いい致します。
#include <stdio.h> #define ARRAY_SIZE 50 int str_copy(char str[], char sorce[]); int count = 0; int str_copy(char str[], char sorce[]) { //sorceがコピー元、strがコピー先 char temp; temp = sorce[ARRAY_SIZE]; str[ARRAY_SIZE] = temp; for (int i = 0; sorce[i] != '\0'; i++) { count = i; } return count; } int main(void) { printf("Put sentences.\n"); char sorce[ARRAY_SIZE]; scanf("%s", &sorce); char str[ARRAY_SIZE - 1]; str_copy(str,sorce); printf("%s\0",str); printf(", length %d \n", count); return 0; }
プログラム中に、コピーしている部分がありませんが、コピペミスでしょうか?
#include <stdio.h>
#define ARRAY_SIZE 50
int str_copy(char str[], char sorce[]);
int count = 0;
int str_copy(char str[], char sorce[]) { //sorceがコピー元、strがコピー先
for (int i = 0; sorce[i] != '\0'; i++) {
str[i] = sorce[i];
}
printf("これはもとの\n");
printf("%s\n", sorce);
printf("これはコピー先\n");
printf("%s\n", str);
for (int i = 0; str[i] != '\0'; i++) {
count += 1;
}
return count;
}
int main(void)
{
printf("Input sentences.\n");
char sorce[ARRAY_SIZE];
scanf("%s", sorce);
char str[ARRAY_SIZE];
str_copy(str,sorce);
printf("%s",str);
printf(", length %d \n", count);
return 0;
}
修正しました。よろしくお願いい致します。
回答2件
あなたの回答
tips
プレビュー