In C99 a string is typically initialized by using the char*
data type since there is no primitive "string" data type. This effectively creates an array of chars by storing the address of the first char in the variable:
FILE* out = fopen("out.txt", "w");
char* s = argv[1];
fwrite(s, 12, 1, out);
fclose(out);
//successfully prints out 12 characters from argv[1] as a consecutive string.
How does the compiler know that char* s
is a string and not just the address of a singular char
? If I use int*
it will only allow one int
, not an array of them. Why the difference?
My main focus is understanding how pointers, referencing and de-referencing work, but the whole char*
keeps messing with my head.
A character array contains characters; an integer array contains integers. And assuming you know the difference between a character and an integer, that's all the explanation you need… that's about it.
Character Arrays String refers to a sequence of characters represented as a single data type. Character Array is a sequential collection of data type char.
A char array can be initialized by conferring to it a default size. char [] JavaCharArray = new char [ 4 ]; This assigns to it an instance with size 4.
Yes, we can store 'char' values in an integer array.
How does the compiler know that
char* s
is a string and not just the address of a singular char?
It doesn't. As far as "the compiler" is concerned, char* s
is a pointer to char.
On the other hand, there are many library functions that assume that a char*
points to an element of a null-terminated sequence of char
(see for example strlen
, strcmp
etc.).
Note that fwrite
does not make this assumption. It requires that you tell it how many bytes you want to write (and that this number doesn't take you beyond the bounds of the buffer pointed at by the first argument.)
If I use
int*
it will only allow one int, not an array of them. Why the difference?
That is incorrect. The C language does not have a special case for char*
. An int*
can also point to an element of an array of int
. In fact, you could write a library that uses 0
or another sentinel value to indicate the end of a sequence of int
, and use it much in the same was as char*
are used by convention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With