I just wanted to clarify about Character pointers and Arrays. Sorry for asking so much in one post but they are very short questions.. Thank you!

Code:

int main()
{
char *p="FIVE";

char k[]="FIVE";

cout << p << endl;
cout << k << endl;
}

1. Why is *p='s' invalid while k[0]='s' valid?

2. The double quote on the word FIVE means that the character pointer and the array ends with a NULL character. Right?

3. cout in this case just works like printf("%s", p) and printf("%s",k) right?

Code:

int main()
{
char *colour;

colour=new char[1];
colour="Black";

cout << colour <<endl;
}

4. "Use dynamic memory allocation for colour."-This was the instruction given in my assignment. But I don't really know what it means. Does the above code satisfy the instruction given?

5.

Code:

int main()
{
char *p="FIVE";

char k[]="FIVE";

char *s;

s=p;

strcpy(s,"WOW");

cout << s << endl;
cout << p << endl;
}

The above code compiles fine but shows an error when running the program. What I know: p contains the address of the character 'F'. This address is assigned to s.

02-07-2010

anon

Code:

char *p="FIVE";

p is a pointer to an immutable literal string. Even though it is legal, your compiler might complain that you really should be using a pointer to const here:

Code:

//correct
const char* p = "FIVE";

Code:

char k[]="FIVE";

k is a modifyable array of five characters (including terminating null).

Code:

colour=new char[1];
colour="Black";

First line allocates one character, the next line makes the pointer point to a string literal instead. There are no more pointers to the dynamically allocated character, hence it is leaked. (The idea is that you allocate an array large enough, and then strcpy the word "Black" to that array.)