Why wont this work:
Code:#include <iostream.h>
#include <windows.h>
void main(){
char MyString[5];
MyString = "Test";
MessageBox(NULL, MyString, "Message", MB_OK | MB_ICONINFORMATION);
}
Printable View
Why wont this work:
Code:#include <iostream.h>
#include <windows.h>
void main(){
char MyString[5];
MyString = "Test";
MessageBox(NULL, MyString, "Message", MB_OK | MB_ICONINFORMATION);
}
I got a little closer using strcat to add it to MyString but got some almost spanish sounding response in the messagebox. But it works with sprintf...
Code:#include <stdio.h>
//////////////////
char MyString[5];
sprintf(MyString, "Test");
MessageBox(NULL, MyString, "Message", MB_OK | MB_ICONINFORMATION);
It worked! Thanks! ;)
You can't just assign a string literal to a char array at runtime. You can do it when you declare the array, but that's the only time. Also, if you're assigning a string to a char array, you don't have to specify a size for the array, it will make it just big enough to fit. So this would have worked:
Getting back to the reason it didn't work, though - a string literal (I'm assuming you know what a string literal is) has a type of const char *. That string gets compiled into your executable, and when the code is loaded into memory and executed, your string is also put in memory with the rest of the exe. The string literal is seen by your compiler to be just a pointer to that string in memory. The problem with your assignment to a char array (which is of type [bconst char * also) is that arrays are, although represented as pointers, constants. You cannot change the address of an array. If you were to declare a char pointer (of type char *) instead of an array then it would work fine. In fact, when dealing with strings, the major difference between a string that is declared as a pointer, and a string that is declared as an array, is that the pointer can be reassigned and the array cannot. You can also declare strings and assign them at the same time using pointers:Code:#include <iostream>
#include <windows.h>
void main(){
char MyString[] = "Test";
MessageBox(NULL, MyString, "Message", MB_OK | MB_ICONINFORMATION);
}
That should work just the same, only you can also use your original version and get it to work if you use pointers:Code:#include <iostream>
#include <windows.h>
void main(){
char *pMyString = "Test";
MessageBox(NULL, pMyString, "Message", MB_OK | MB_ICONINFORMATION);
}
Code:#include <iostream>
#include <windows.h>
void main(){
char *pMyString;
pMyString = "Test";
MessageBox(NULL, MyString, "Message", MB_OK | MB_ICONINFORMATION);
}
Thanks for the good explanation Harry! :)