Why do arrays start on 0 instead of 1? (C, C++) [duplicate] - c++

This question already has answers here:
Why does the indexing start with zero in 'C'?
(16 answers)
Closed 3 years ago.
Not really a code problem but a doubt, why do arrays on C and C++ start on 0? Does it have anything to do with some internal process?
int array[4]={1,2,3,4};
cout<<array[0];
cout<<array[1];
cout<<array[2];
cout<<array[3]; ///This prints 1234
But why that instead of
int array[4]={1,2,3,4};
cout<<array[1]; //as the first element
cout<<array[2];
cout<<array[3];
cout<<array[4];
?

Because the notation does pointer arithmetic. array[0] actually means the location of the array plus the size of 0 elements.
As always in C, you're working close to the hardware.

Consider int arr[i] elements.
arr[i] is interpreted as *(arr + i). Now, arr is the address of the array or address of the 0th index element of the array. So, address of next element in the array is arr + 1 (because elements in the array are stored in consecutive memory locations).
So if you do *(arr+0) it gives the starting memory location of the array.
and *(arr+1) gives next memory location. so this i i.e 0,1,..etc can use like offset.
As #ravnsgaard said in C, you're working close to the hardware.

Related

Value returned by sizeof operator in case of arrays [duplicate]

This question already has answers here:
sizeof on array variable Vs sizeof on pointer in c [duplicate]
(3 answers)
Why size of int pointer is different of size of int array? [duplicate]
(2 answers)
How does sizeof know the size of array? [duplicate]
(7 answers)
Closed 8 months ago.
Let's say we have an integer array of size 5 and an int takes 4 bytes of memory.
int arr[5] = {1,2,3,4,5};
cout<<sizeof(arr);
it basically prints 20. If arr points to base address of array. Shouldn't it output p where p is the size of a pointer variable then?
As described here: https://en.cppreference.com/w/cpp/language/sizeof
sizeof - Queries size of the object or type.
Therefore you have received correctly the size of your table.
sizeOf() always returns the total number of bytes occupied in memory.
When the sizeof operator is applied to an array, it yields the total
number of bytes in that array, not the size of the pointer represented
by the array identifier.
read more
You can still get the size/length of the array by dividing the total number of bytes the whole array occupying by the total number of bytes a single element occupying.
int size = sizeof(array) / sizeof(array[0]

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]?
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.
It will store 10 items in total, including the '\0'. So, 9 characters, and one '\0' null terminator at ar[9].
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/
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.

what is space overhead (when referring to a c++ array)?

I'm reading a lecture slide in my data structures class for arrays, but there is something that sort of confused me.
The example is in an array called x, defined as follows:
1-dimensional array x = [a, b, c, d]
location(x[i]) = start + i
I'm not really understanding this, so could somebody explain this?
start is a variable, which holds address to the array. Since a pointer in 32-bit system has 4 bytes, it will occupy these four bytes. So if you want 4-byte array, you will actually need 8 bytes of memory: 4 for the array and another 4 for pointer to the first element of this array.

Difference of two addresses in C [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Pointer Arithmetic
The given code
int arr[12];
int * cur = arr;
cur++;
cout<<"cur-arr = "<<cur-arr<<endl;
Outputs 1, but I expected sizeof(int). Can someone please explain the nature of this behavior?
It's a defined behavior of C pointer arithmetic. It uses the size of pointed type as a unit. If you change subtraction in the last line to
(char *)cur - (char *)arr
you get 4 in the output.
This is the number of elements (ints here) between arr and cur (which is arr+1 at the time of subtraction). Compiler takes note that cur is a pointer to an integer and arr is an integer array. To get total number of bytes, try this:
(cur - arr) * sizeof(arr[0]);
cur is a pointer to int, initialized to some value (arr - the semantics of array-to-pointer conversion are irrelevant here), incremented (cur++) and compared to its old value. Unsurprisingly, it grew by one through the increment operation.
Pointer arithmetic with a given type works just like regular arithmetic. While the pointer is advanced by sizeof(int) bytes in this example, the difference between pointers is also calculated in units of sizeof(int), so you see plain simple arithmetics.
Addition and substraction for pointers works in accordance to the pointer type.

what does this notation mean in c++

so I have:
char inBuf[80]
and then there's another line
inBuf+9
what does it mean when I add that +9 to the array's name?
It is same as referencing element number 9(0 based).
An equivalent notation would be:
&inBuf[9]
If you want to get the value, you could use *(inBuf+9)
This would point to the 10th element of the array. So for example:
*(inBuf + 9) = 10
would assign 10 to the 10th element.
Answer has been given already. I may only be repeating it.
This is called pointer arithmetic, because pointers are involved in the arithmetic operation. there are certain things only you can do with pointers. like you can add an integer to it, but you can subtract an integer only if pointer points to some array in the memory. also you can not subtract the pointers, because that may lead to some crucial memory location (for the OS).
addition in pointer arithmetic is special in a way that it takes care of the data type of the array elements, so when you say
char inBuf[80]
inBuf + 9
it advances 9 memory location sufficient enough to hold the 9 character (9*1 bytes typically)
int inBuf[80]
inBuf + 9
this will add 9 memory location sufficient enough to hold the 9 integers (9*4 bytes typically).
array and pointers are not always same, refer to "expert C programming" for that Also never use pointer arithmetic polymorphic-ally, refer "scott meyers book" for that
Using inBuf with no qualifier for an array index to use will be the same as seeing char *inBuf. inBuf + 9 would be the same as inBuf[9].
inBuf+9 means increasing the address of inBuf by 9.
inBuf refer the base address. but inBuf+ 9 locates the 10th element from the base address.
*(inBuf + 9) = 34;
This would assign the value 34 to the 10th element in the inBuf array.
When you perform addition with it, an array identifier such as your inBuf decays to a pointer to the first element in the array, and the number added is multiplied by the size of the array element (in this case char, which has size 1) to produce a new address.
So, inBuf + 9 is the address of the 10th element in the array, which could also be expressed as &inBuf[9]. You can use it as in:
*(inBuf + 9) = '\0'; // overwrite the 10th element in inBuf with a NUL
const char* p = strchr(inBuf + 9, ' '); // find space at or beyond 10th char
inBuf is like to write &inBuf[0].
So inBuf +9 means address of inBuf added with 9 chars length (&inBuf[9]).