Printing a char array

Hi,

Can someone tell me why I can print a char only if it is initialized in the var declaration.

I other words if I do this it works.

1
2
char name[50] = "Jeff";   
printf("My Name is %s", name);


But if I do this it doesn't work.

1
2
3
char name[50];
name = "Jeff";    
printf("My Name is %s", name);


Can someone explain why would something like this make a difference?

What is the proper way to print/cout a char using the second example?

Thanks a lot


@fstigre.

because you are using character array , right?
so when you display them out , you have to use a looping to print each array of it

Example:
1
2
3
4
5
6
char name[5] = "Jeff";
//use looping 

for(int i - 0 ; i < 5 ; i ++ ){
      cout << name[i] ;//Looping 5 times to print out [0],[1],[2],[3],[4]
}
Last edited on
for your code .
This the way I implement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

using namespace std;

int main(){

	char names[50] = "Jeff";

	for( int i = 0 ; i < strlen(names) ; i ++ ){
		cout << names[i]; 
	}
	cout << endl;


	system( "pause" );
	return 0;
}


In the code above , you can see that i using strlen
This is to determine the string sizeof it , because if you using char names[50] = "Jeff" .
You only using the [0] = J , [1] = e , [2] = f , [3] = f, so from [4] to [50] will be = "/0" , if you use looping , the space will be print out .
char name[50] = "Jeff"; works as it translates to "initialize an array of 50 chars with jeff"


name = "Jeff"; doesnt work as you are trying assign 5 chars to an array of 50

GCC will say "error: incompatible types in assignment of ‘const char [5]’ to ‘char [50]’"

clang will say "error: array type 'char [50]' is not assignable"
This works, because the compiler is setting the initial value for the char array:
char name[50] = "Jeff";

But this doesn't work, the second line doesn't even compile.
1
2
char name[50];
name = "Jeff"; 

The solution is to use the strcpy() function.
1
2
    char name[50];
    strcpy(name,"Jeff");

If you are going to use c-strings like this, it's worth becoming familiar with the related functions, such as strcat, strlen etc. http://www.cplusplus.com/reference/clibrary/cstring/

Alternatively, just use the C++ string instead:
1
2
    string name1;
    name1 = "Geoff";
Last edited on
Thank you all very much for the good advice, it now makes more sense.
Topic archived. No new replies allowed.