How do strings and char arrays work in C?

前端 未结 3 1107
抹茶落季
抹茶落季 2020-12-06 12:30

No guides I\'ve seen seem to explain this very well.

I mean, you can allocate memory for a char*, or write char[25] instead? What\'s the di

3条回答
  •  长情又很酷
    2020-12-06 13:06

    Since other aspects are answered already, i would only add to the question "what if you want the flexibility of function passing using char * but modifiability of char []"

    You can allocate an array and pass the same array to a function as char *. This is called pass by reference and internally only passes the address of actual array (precisely address of first element) instead of copying the whole. The other effect is that any change made inside the function modifies the original array.

    void fun(char *a) {
       a[0] = 'y'; // changes hello to yello
    }
    
    main() {
       char arr[6] = "hello"; // Note that its not char * arr
       fun(arr); // arr now contains yello
    }
    

    The same could have been done for an array allocated with malloc

    char * arr = malloc(6);
    strcpy(arr, "hello");
    
    fun(arr); // note that fun remains same.
    

    Latter you can free the malloc memory

    free(arr);
    

    char * a, is just a pointer that can store address, which might be of a single variable or might be the first element of an array. Be ware, we have to assign to this pointer before actually using it.

    Contrary to that char arr[SIZE] creates an array on the stack i.e. it also allocates SIZE bytes. So you can directly access arr[3] (assuming 3 is less than SIZE) without any issues.

    Now it makes sense to allow assigning any address to a, but not allowing this for arr, since there is no other way except using arr to access its memory.

提交回复
热议问题