OK, so let me demonstrate:
Code:
int main()
{
char* mystr = "My string";
foo(mystr); /* Will segfault because mystr is read-only */
char* mystr2 = malloc(sizeof("My string") + 1);
strcpy(mystr2, "My string");
foo(mystr2); /* Will work because you allocated memory you can read/write to */
char mystr3[] = "My string";
foo(mystr3); /* Works because it's read/write memory allocated on the stack */
return 0;
}
void foo(char* pStr)
{
pStr[0] = toupper(pStr[0]);
}
This shows the difference between all 3 methods.
Scope demonstration:
Code:
int main()
{
char* pStr = foo(); /* Doesn't work! */
char mystr[] = "my string";
foo2(mystr); /* foo2 can do whatever it wants to mystr because it will go out of scope once main ends */
}
char* foo()
{
char mystr[] = "my string";
mystr[0] = toupper(mystr[0]); /* Works because mystr exists in this function */
return mystr; /* Won't work because mystr will go out of scope */
}
void foo2(char* pStr)
{
pStr[0] = toupper(pStr[0]);
}
Originally Posted by
cas
Well... Arrays are different than pointers, and the difference can come into play. As my example alluded to, applying & to a pointer to char yields something different than when it's applied to an array of char. A more common--from what I've seen--misconception is that an array of array (i.e. a 2d array) is the same thing as a pointer to pointer. I imagine there have been posts here where a person is confused as to why:
Code:
int f(int **a);
int a[5][5];
f(a);
doesn't work, for example.
There's no question that pointers and arrays are intimately connected, and that for the most part an array can be treated as a pointer to its first element. However, there is a difference, and it behooves a programmer to know what the difference is so it won't bite him.
I'm assuming that the standard wants the compiler to have some kind of knowledge about what type is passed. But it doesn't really matter because even if you use such syntax, it's still used as a pointer, hence it is a pointer and not an array. You can't get the size of the array, you can't see the contents of the array because it's a pointer.