I'm trying to calculate length of different types of objects with sizeof(), particularly arrays and pointers.But I'm confused with the result of str1. I'm also not very sure if I can calculate the lengths of all types of array with the:
size_t size = sizeof(str1) / sizeof(*str1)
Any help will be appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main(){
int arr1[]= {1, 2, 3, 4, 5};
char * str1 = "This is a test for sizeof()";
char str2[] = "This is a test for sizeof()";
char str3[] = { 'C', '+' , '+' };
cout << "Sizeof arr1 " << sizeof(arr1) << endl;
cout << "Sizeof str1 " << sizeof(str1) << endl;
cout << "Sizeof str2 " << sizeof(str2) << endl;
cout << "Sizeof str3 " << sizeof(str3) << endl;
cout << "Length of arr1 by formula " << sizeof(arr1) / sizeof(*arr1) << endl;
cout << "Length of str1 by formula " << sizeof(str1) / sizeof(*str1) << endl;
cout << "Length of str2 by formula " << sizeof(str2) / sizeof(*str2) << endl;
cout << "Length of str3 by formula " << sizeof(str3) / sizeof(*str3) << endl;
Prints:
Sizeof arr1 20 // 4*5=20 OK Sizeof str1 8 // ??
Sizeof str2 28 // 1*28=28 OK
Sizeof str3 3 // 1*3=3 OK
Length of arr1 by formula 5 Length of str1 by formula 8
Length of str2 by formula 28
Length of str3 by formula 3
in you first post you missed '*' in this 'cout << "Sizeof str1 " << sizeof(str1) << endl;'
the right is: 'cout << "Sizeof str1 " << sizeof(*str1) << endl;'
When we pass an array name(which is also a pointer) to sizeof() then it gives the total size of array in bytes. On the other hand, when we pass a plain pointer it gives the address length. So I can conclude that it can understand whether we passed an array or a plain pointer.
When we pass an array to a function the the function cannot understand whether we passed an array. This is what I understand from the second example. Is that correct?
As coder777 said everything is very clear here ( ref to first post ).
Sizeof arr1 20 // 4*5=20 OK
Sizeof str1 8 // ?? -- This is OK, sizeof(char*) = 8 , in your machine
Sizeof str2 28 // 1*28=28 OK
Sizeof str3 3 // 1*3=3 OK
Length of arr1 by formula 5
Length of str1 by formula 8 -- This is OK too, this means 8/1 = 8
Length of str2 by formula 28
Length of str3 by formula 3
Answer for the 'Oh my god' post,
void foe(int a[])
Here variable 'a' is considered as type int*. Yes this is a big harm for the uniformness of C++ language. My personal opinion in creator could have forbidden using array types as function arguments so that users could use do it only in following form