Syntax question with a char type array.

Hello. Thanks in advance for the answer to what Im sure is a simple question.

I've isolated a more complicated issue to this example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//chararray.cpp -- testing out how to feed characters into character array.
//Michael R. Benecke
#include <iostream>
int main()
{
    using namespace std;

    char name[20] = {"Michael"}; //Works fine
    cout << name;

    char name1[20];
    name1 = {"Michael"}; //Doesn't work. 
    cout << name1;

    return 0;
}


As you can see in the comments, "name1" can't be assigned values. It seems like this would be the same thing as "name" getting initialized a few lines above. So I'm just wondering why it doesn't work, and how I can assign a value to name1 after the declaration statement without actually initializing it (and without having to assign an individual character to each array element on separated code.).
I can't explain you why, but assigning a value to an array in that way can only be done at the definition of the variable. To set a value afterwards you can use http://www.cplusplus.com/reference/cstring/strcpy/
Last edited on
maeriden, thank you! it turns out that my book mentions the strcpy() function a few pages past where i ran into that problem.
// name1 = {"Michael"}; //Doesn't work.

// This does not work because you cannot do aggregate operations
// on a char array after it has been declared. if "name1" was to work
// you would trying to put "Michael" into name[0] hence the compiler
// is complaining see http://oc.course.com/computerscience/malikcpp5e/index.cfm?page=chapter-overview&chapter=9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//chararray.cpp -- testing out how to feed characters into character array.
//Michael R. Benecke
#include <iostream>
int main()
{
    using namespace std;

    char name[20] = {"Michael"}; //Works fine
    cout << name;

    char name1[20];
    name1 = {'M','i','c','h','a','e','l'}; //Should work 
    cout << name1;

    return 0;
}
Always test code first:
http://ideone.com/f3QpQd
Topic archived. No new replies allowed.