C Function implementation - with Pointer vs without Pointer

c, pointers

Solution

One of the problems in C is that arrays are second-class citizens. In almost all useful circumstances, among them when passing them to a function, arrays decay to pointers (thereby losing their size information).

Therefore, it makes no difference whether you take an array as `T* arg` or `T arg[]` — the latter is a mere synonym for the former. Both are pointers to the first character of the `string` variable defined in `main()`, so both have access to the original data and can modify it.

Note: C always passes arguments per copy. This is also true in this case. However, when you pass a pointer (or an array decaying to a pointer), what is copied is the address, so that the object referred to is accessible through two different copies of its address.

Problem

I've just started to work with C, and never had to deal with pointers in previous languages I used, so I was wondering what method is better if just modifying a string. pointerstring vs normal. Also if you want to provide more information about when to use pointers that would be great. I was shocked when I found out that the function "normal" would even modify the string passed, and update in the main function without a return value. ``` #include <stdio.h> void pointerstring(char *s); void normal(char s[]); int main() { char string[20]; pointerstring(string); printf("\nPointer: %s\n",string); normal(string); printf("Normal: %s\n",string); } void pointerstring(char *s) { sprintf(s,"Hello"); } void normal(char s[]) { sprintf(s,"World"); } ``` Output: ``` Pointer: Hello Normal: World ```

Original source