Ronald Mathews
Ronald Mathews

Reputation: 2248

Character array and its memory allocation in C++

I am bit confused after reading a text book. Consider a character array ar[10] in C++. In the text book it says that 10 bytes will be allocated for the array.

Starting from subscript ar[0], how many elements can I store in the given array? Is it 10? If yes can I store data at ar[10]? I want to know how many bytes will be allocated for the array in total since I came to know that every string ends with \0. Will overflow happen if I try to store a character into ar[10]?

Upvotes: 1

Views: 946

Answers (4)

Saiful Azad
Saiful Azad

Reputation: 1911

Hence, you have declared a[10] so it carries 10 values. As it is char array which contains string and string is terminated by '\0'. '\0' is also a value.

So if you string length is n then your array size will be n+1 to keep n length string. Otherwise, the overflow will occur.

Observe the following example

int main(){

char a[1], r, t;

printf("Size %d Byte\n", sizeof(a));

a[0] ='a';
a[1] ='b';
a[2] ='c';

printf("%c\n",r); //c
printf("%c\n",t); //b

}

As your array size is 1. Though you have not assigned value of r,t it is auto assigned by a[2] and a[1] respectively.

Upvotes: 0

VHS
VHS

Reputation: 103

You can store ten values, from index 0 to index 9. This seems really wrong at first, but remember that 0 is technically a value and must be counted as one. It's sort of like how unsigned ints will hold 2^32 values, but the highest usable number is actually (2^32)-1.

Note that if you want to have the array be null-terminated you will only be able to store 9 characters, as ar[9] will hold '\0'. You could store another character there instead, but will have to write your code around the fact that your C-string is not null-terminated.

That all said, it's generally considered bad practice to use character arrays for strings in C++. It's a lot more error-prone than just using the string standard library.

More info: http://www.cplusplus.com/reference/string/string/

Upvotes: 0

junoon53
junoon53

Reputation: 41

It will store 10 items in total, including the '\0'. So, 9 characters, and one '\0' null terminator at ar[9].

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

If yes can I store data at ar[10]

No.

In your example, ar is an array with ten values. The first value is index #0, so you have ar[0] through ar[9], inclusively. That's the ten values in this array. Count them. Most of us conveniently have exactly ten fingers. Start counting on your fingers, starting with ar[0], and stop when you've used all your ten fingers. You'll stop on ar[9].

Attempting to access ar[10] is undefined behavior.

Upvotes: 4

Related Questions