Originally Posted by
nkhambal
Code:
const char *string_array = "Hello";
printf("String is: %s\n",string_array);
Code:
const char *array_of_strings[] = {
"abc",
"def",
"ghi",
"jkl"
};
for (i = 0;i<4; i++)
{
printf("String[%d] is: %s\n",i, array_of_strings[i]);
}
You have a slight problem. Add this:
Code:
for (i = 0;i<4; i++)
array_of_strings[ i ] = "hello";
for (i = 0;i<4; i++)
{
printf("String[%d] is: %s\n",i, array_of_strings[i]);
}
Then run it.
Now try this instead:
Code:
char * const array[] = { "abc", "def", "ghi", "jkl" };
This works here "correctly", because you're already assigning string literals, so you can't edit the strings anyway. So you set the pointers as constant, so now you can't change the contents of this array.
[edit]
For those of you who don't understand what's going on, I'll clarify a bit.
This is a pointer to a character. Read it from right to left: "S is a pointer to a character."
This is a pointer to a character assigned to a single character:
Code:
char c = 'a';
char *s = &c;
You can use this pointer to a character to point to arrays if you like:
Code:
char array[] = { 'a', 'b', 'c', 'd', 'e' };
char * s = array;
We can now use the pointer to move through the array, or even change its values:
Code:
while( *s != 'e' )
{
printf("*s is %c", *s );
*s = toupper( *s );
printf(", but now *s is %c\n", *s );
}
You can make it point to a string too:
Code:
char *s = "this is a string literal";
Now the deal with string literals is that you cannot change the literal iteself. That is to say, we cannot change the 'e' to an 'a' and make the string say "this is a string lateral". String literals are stored in read only memory, and you're not allowed to change them.
However! The pointer itself is not constant. You can change what the pointer points at. Not the contents of what it points at, in the case of a literal, but what the pointer itself points to:
Code:
char *s = "this is a string literal"
printf("s is \'%s\'\n", s );
s = "now a new literal is being pointed at by s!";
printf("s is \'%s\'\n", s );
As stated above, since this is in fact a string literal, you can't edit the literal iteself. But since they (the poster before me) didn't actually make the pointer constant, you can change it. (Thus they didn't fulfill what the OP was looking for. (ie: The array's contents can be changed.))
[/edit]
Quzah.