+1

What's the difference between a pointer to a string to which i have assigned malloc and an array of chars?

I'm learning in C, and i can't seem to find any differences between the two aformentioned datatypes.

4/19/2019 9:33:30 PM

Alexander Sheremet

1 Answer

New Answer

+5

Alexander Sheremet Strings and array of chars are very closely related. Btw There is no string datatype in C. A string in C is an array of char with a terminating null ('\0' or 0) char. const char* str = "hello"; //a statically allocated string. The terminating null is implicit.The type of str is const char* const char str[] = "hello";// a statically allocated array of char, but there is a implicit null char which makes it a string but the type of str1 is const char[6](includes terminating null char) char arr[] = {'a','b','c'};// array of char char arr1[] = {'a','b','c','\0'}; // the terminating null char makes it behave like string If you pass an array of char where a string is expected like printf, the function will keep on printing data till it finds first null char which means it will read into someone else's memory resulting in crash, garbage data or undefined behavior. You allocate memory for pointer to a char i.e char*. When you pass an array to a function, it decays into pointer to an array type i.e char arr[10]; fun(arr) inside fun arr is of type char*, so as a rule always pass size to function if you want to treat the pointer as array. The name of an array is also a pointer to an array(true for any type) so if you have char arr[10] then char* ptr = arr = &arr[0], all points to first element of an array. So you can do ptr = arr or ptr = &arr[0](this is normal assigning the address of char to pointer to char) *ptr or *arr will print the first element of array. You cannot do arr = ptr because the type is different(arr type is char[10], while ptr is of type char* char const* str = "hello"; char const str1[] = "hello"; sizeof(str) will print sizeof pointer = 8 (on 64bit, 4 on 32bit) sizeof(str1) prints 6, remember as i said earlier the type is different.