LoginSignup
1
1

More than 5 years have passed since last update.

strcatの問題

Posted at

どもどもー
なぜかC++のジェダイ(自称)から素敵な問題を出されたので解いてみましたー

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char * argv[]) {
 char str[10] = {};
 char str2 = 'C';

 strcat(str,&str2);

 printf("%s",str);
}

結果が C にならない問題を解決してみましょう。。

作者の回答

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char * argv[]) {
    char str[10] = {};
    char str2[] = {'C', '\0'};

    strcat(str,str2);

    printf("%s",str);
    return 0;
}

最近C書いてないから、2分かかってしまった。。
しかもこれは、ダメな例。

ジェダイの回答

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char * argv[]) {
    char str[10] = {};
    char str2[] = "C";

    strcat(str,str2);

    printf("%s",str);
    return 0;
}

解説

この問題は、
文字の最後にヌル文字が入ってない為、Cと表示されません。
これを解決するには、 ヌル文字を入れてあげれば良いので、
"C"のみでOKです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1