Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char arrays length in C

Tags:

c

In C, you have to declare the length of an array:

int myArray[100];

But when you're dealing with chars and strings, the length can be left blank:

char myString[] = "Hello, World!";

Does the compiler generate the length for you by looking at the string?

like image 224
Espresso Avatar asked Jun 27 '11 18:06

Espresso


People also ask

How long is a char array in C?

The first - arr object size is printed to be 24 bytes because the strlen function iterates through a char array until the terminating null byte is encountered.

What is size of char in C?

Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use. Here, a signed character is capable of holding negative values. Thus, the defined range here is -128 to +127.

What is the size of char a 10 in C?

The size of char is 1 byte, and wikipedia says: sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type. However, i can store 11 bytes in unsigned char array[10] 0.. 10 but when i do sizeof(array) i get 10 bytes.

How do you find the size of an array in C?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);


2 Answers

This is not unique to char. You could do this, for instance:

int myNumbers[] = { 5, 10, 15, 20, 42 };

This is equivalent to writing:

int myNumbers[5] = { 5, 10, 15, 20, 42 };

Initialising a char array from a string literal is a special case.

like image 65
Oliver Charlesworth Avatar answered Oct 10 '22 19:10

Oliver Charlesworth


Yes, it's the length including the terminating '\0'.

like image 31
Karoly Horvath Avatar answered Oct 10 '22 20:10

Karoly Horvath