0

Hello i'm from Indonesia. and i'm verry beginner on C++ programming. I have some problem when i learn about string on C++ . First i declared array of char and i want to initialize a value separately in different command. After i initialize the value my compiler say "Invalid Argument".

    #include <iostream>

    using namespace std;

    int main() {

    char Name[5];

    Name = "Luke";

    cout<<"Character 0 :"<<Name[0]<<endl;
    cout<<"Character 1 :"<<Name[1]<<endl;
    cout<<"Character 2 :"<<Name[2]<<endl;
    cout<<"Character 3 :"<<Name[3]<<endl;
    cout<<"Character 4 :"<<Name[4]<<endl;

    return 0;

    }

sorry if my english is bad :(

3 Answers3

2

A character array(including a C string) can not have a new value assigned to it after it is declared.

The C++compiler interprets these assignment statements as attempts to change the address stored in the array name, not as attempts to change the contents of the array.

However you can use

char name[] = "Luke";
Community
  • 1
  • 1
Digvijaysinh Gohil
  • 1,367
  • 2
  • 15
  • 30
0

A char[] can't be assigned with a string with the = operator, except for on its initialization. That's why char Name[5]; Name = "Luke"; is invalid while char Name[5] = "Luke"; is.

Assigning strings to char[] can be done with strcpy() / memcpy()-like functions.

So you have two ways of action (assuming you want to work with char[]):

  1. char Name[5] = "Luke";
  2. char Name[5]; strcpy(Name, "Luke"); /* don't forget to #include <string.h>*/
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
0

Just for sake of education (since the other answers are on-point to answer the question), here's how I would have written your code to do nearly the same thing.

The changes demonstrate:

  • used a more appropriate container (a string instead of a char[])
  • checked for access overruns
  • moved "one unit of work" into its own subroutine

Code was compiled as C++17 with /usr/bin/clang++ -Weverything -Wno-c++98-compat --std=c++1z:

#include <cstddef>
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

void PrintCharAtPos(string const& s, string::size_type pos);

int main() {
  auto Name = string{"Luke"};

  PrintCharAtPos(Name, 0);
  PrintCharAtPos(Name, 1);
  PrintCharAtPos(Name, 2);
  PrintCharAtPos(Name, 3);
  PrintCharAtPos(Name, 4);

  return EXIT_SUCCESS;
}

void PrintCharAtPos(string const& s, string::size_type pos) {
  if (pos < s.length())
    cout << "Character " << pos << " : " << s[pos] << endl;
  else
    cout << "Character " << pos << " : (out of bounds)" << endl;
}
Eljay
  • 4,648
  • 3
  • 16
  • 27