0
How can i use a char pointer to write a string in c++
char pointer as string
8 Réponses
+ 4
char word[] = "Hello World!";
or
char word[] = {'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};
Both notations do the exact same thing.
word can now be used like a string. You DON'T need to dereference it using * (unless you want a single char and not the whole string).
A c-style string like this always ends with the character '\0'. If you use the notation above the '\0 ' will automatically get added.
The array above will have the length 13 (12 characters + '\0'). You can't assign anything longer to it. You can make it shorter though. The string ends once it reaches '\0', so by setting word[4] = '\0'; word will now be "Hell".
To output this string just use:
cout << word << endl;
Again: Even though c-type strings are pointers (arrays), you don't dereference them!
+ 1
Try using the dereference operater (*) and then concatenating the characters together.
+ 1
Hmm, I don't think there's much I could add to my explanation, what is it you don't understand?
Oh, and you should create the string with a char array, not a char pointer, a pointer might give you a warning when compiling. You can, however, let a char pointer point to an element of an already existing array.
char s1[] = "Hello World!";
char *s2 = s1 + 6; /* points s2 to the seventh character of s1. s1+6 is the same as writing &s[6] */
cout << s2 << endl; /* will output s1 starting from the 7th character till the end ("World!") */
+ 1
Oh, that.
Yes, 'word' in my example is a pointer, but c/c++ will automatically use any char* like a string. This also works the other way around, a string like "Hello World!" will aromatically get converted into a list of chars so you can initialize your char arrays with it. It's just something the language does to make your life easier.
0
can you write a sample code
0
Sure I can try.
0
i tried this code and it worked. but i didnt understand how did it work.
char *p="yusef" ;
cout <<p;
0
how do this work. why a pointer behave like this. whats is the mechanism of this examples. a pointer is a memory address variable. isnt it.