character array please Help!!!
void main()
{
char name[20];
name = "omshanti";
cout << name;
}
In the above program , if we won't initialize name as the type of its definition , why there's compile time error :
cannot convert from 'char [9]' to 'char [20]'.???????
while using other data type such as int , float , double , we can initialize them after defining them .But same is not the case with character string. WHY???????
Re: character array please Help!!!
Quote:
But same is not the case with character string.
Because a string is an array of characters. Use memcpy to put characters in a character array.
Edit : That needs to be strcpy.
Re: character array please Help!!!
You can't assign a string literal to a char array like that. Use strcpy.
Re: character array please Help!!!
Quote:
Originally Posted by
Skizmo
Because a string is an array of characters. Use
memcpy to put characters in a character array.
Why memcpy instead of strcpy?
Re: character array please Help!!!
Quote:
Originally Posted by
GCDEF
Why memcpy instead of strcpy?
Doh... sorry. Not having my day today. Of course it has to be strcpy.
Re: character array please Help!!!
Code:
strcpy(name,"omshanti");
Re: character array please Help!!!
Quote:
Originally Posted by
Tanushreeagr
Code:
void main()
{
...
}
You are using incorrect signature for main(): it must be int instead of void and it must return an integer value.
Re: character array please Help!!!
Why not std::string?
Code:
#include <string>
// ...
std::string name = "omshanti";
or
Code:
#include <string>
// ...
std::string name;
name = "omshanti";
Re: character array please Help!!!
Quote:
Originally Posted by
Tanushreeagr
while using other data type such as int , float , double , we can initialize them after defining them .But same is not the case with character string. WHY???????
You can't do that with other built-in types either.
Code:
int main()
{
int a[3];
a = { 1, 2, 3 }; // error
}
You cannot assign to an array.
Re: character array please Help!!!
Also, in the case of char name[20] both name and "omshanti" are interpreted by the compiler as pointers. name is essentially the same thing as &name[0].
So you have a pointer to a locally allocated array of chars and you want to assign it the address of a string literal. Doesn't really make conceptual sense.