Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char* array of chars, but int* not array of ints?

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.

like image 401
jnitram78 Avatar asked Jul 01 '15 05:07

jnitram78


People also ask

What is difference between char array and int array?

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.

What is the difference between char and array?

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.

Can you have an array of 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.

Can you put a char in an int array?

Yes, we can store 'char' values in an integer array.


1 Answers

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.

like image 63
juanchopanza Avatar answered Nov 08 '22 13:11

juanchopanza