0
#include <bits/stdc++.h>
using namespace std;

int main(){
    char a[100];
    char c[1];
    cin >> a;
    c[0] = a[8];
    cout << c;
}

input: asdfghjklmn
output: lasdfghjklmn

I don't understand how it does element assignment.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    This has nothing to do with "element assignment". But the subsequent use of `<<` results in undefined behavior. How do your C++ textbook describe the `<<` overload for a plain character pointer, and how it must be used? And, by the way, which C++ textbook told you to use `bits/stdc++.h`? This is not a standard C++ header file, this is bad textbook. You should get rid of it and get a better textbook that teacher proper, standard, C++. – Sam Varshavchik Apr 16 '22 at 01:36

1 Answers1

5
#include<bits/stdc++.h>

Don't. This header is non-standard, non-portable, leads to terrible compilation times and is all around a bad habit born from "competitive" coding sites that revel in bad habits. #include <iostream> (i.e., including only what you actually use) would be better in all respects.

using namespace std;

Also considered bad practice. Try to keep your namespace minimal.

int main(){
    char a[100];

No. Don't. <string> exists. char[] is a C string, a thing of backward compatibility. In C++, a "string" is a std::string object. There is nothing "elite" about using C constructs in C++ code, just lots of potential errors and mistakes.

    char c[1];
    cin>>a;
    c[0]=a[8];

You do not check that a actually has a character at that index...

    cout<<c;
}

c is not (and, due to its one-byte size, cannot be) null-terminated, i.e. not a string. Yet cout << c treats it as one and will keep printing characters from memory until it hits a zero byte; you're looking at undefined behavior. In this case c sits in memory right before a, so you see c and a printed subsequently, but that is in no way guaranteed. One of those things you completely avoid when actually using the language, i.e. <string>.

#include <iostream>
#include <string>

int main()
{
    std::string a;
    std::string c;

    std::cin >> a;

    if ( a.length() > 8 )
    {
        c.push_back( a[8] );
    }

    std::cout << c;
}

There you go.

DevSolar
  • 67,862
  • 21
  • 134
  • 209