+ 2
How is the memory allocation for array of char when i run the following code.. char a[2]; but i input a as computer
so what is the size of array and what is the address of "mputer "
4 Answers
+ 1
Ok. As i know, 'char[]' in C or C++ is just a pointer to first symbol of your string in memory. And as i know, there is no tools to read how much memory you've allocated for your array (string). When you are using standart tools for working with char arrays, like 'cin' and 'cout' or 'scanf' and 'printf', input tools are trying to write all data from input stream to your array, and output tools are reading data as symbols starting from the symbol pointed to by the pointer (first symbol) until they will meat there a symbol '\0'. When you are declaring the array with size 2, 'cin' and 'cout' don't know that size of the array is 2, they are working with array like its size is infinite. So, you can enter more symbols than size of your array and even work with it for some time, but computer thinks that you need only 2*sizeof(char) bits in memory after pointer, and he will take memory after these bits if he want and your programm may crash or you can lost some information.
0
So, for example, you've got 'char str[] = "computer";' in your code. 'str' - is just an array of 'char', or an array of symbols. It is the same as 'str[] = {'c', 'o', 'm', 'p', 'u', 't', 'e', 'r', '\0'};' ('\0' means the end of the 'str'). Therefore, str[2] == 'm' (indexing starts from 0, str[0] is 'c', str[1] is 'o'). As you can understand, size of an array 'str' is 9 (with symbol '\0'). And there is no index of "mputer", there is an index of 'm' and an index of 'r'. Knowing those indexes you can get symbols 'm', 'r' and all symbols between 'm' and 'r'. So, you can get substring "mputer" just adding those symbols. For example, you can just write function that returns substring of a string between two symbols, such as:
char* substring(char string[], int indexOfFirstSym, int indexOfLastSym) {
int sizeOfSubstr = indexOfLastSym - indexOfFirstSym;
char* substr = new char[sizeOfSubstr];
for (int i = 0; i < sizeOfSubstr; i++)
substr[i] = string[indexOfFirstSym + i];
return substr;
}
If you've got a string 'char str[] = "computer";' and you want to get substring "mputer", you can call this function as 'substring(str, 2, 8);'.
0
thank u..but what I actually meant was..I declared the array with size 2 and I can still enter the word computer using cin . computer's total size must be 8 ..so how is that possible?
0
thank you.