Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #8587
| From | Victor Bazarov <v.bazarov@comcast.invalid> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Re: Don't understand sizeof char* array |
| Date | 2011-08-09 08:48 -0400 |
| Organization | A noiseless patient Spider |
| Message-ID | <j1rabc$3a7$1@dont-email.me> (permalink) |
| References | <925ae74e-7c1e-401e-908e-36a2760f362b@y16g2000yqk.googlegroups.com> |
On 8/9/2011 5:34 AM, Angus wrote:
> I have this array:
> char* s[] = {"cat", "cat", "dog", "mouse", "rat"};
> int sz = sizeof(s); // 20 why 20???
>
> I would expect sizeof to report 17. Why is it reporting 20?
Why it is reporting 20 you've already found out (can you multiply 4 by
5?) but what is a mystery to me is how you came up with 17? For
instance, sizeof("cat") is 4 (it's an array of four characters that *has
to* include the terminating null character), and sizeof("mouse") is 6
(same principle). Even if you put those characters all in one array:
char s[] = "cat" "cat" "dog" "mouse" "rat";
sizeof(s) will be 18 because it has to add the terminating null character...
And, just for the sake of our children who will be forced to live in the
world where you're going to be programming, don't initialize a pointer
to NON-CONST char with a literal, OK? Your declaration should be
const char* s[] = ...
>
> to work out the number of elements works ok:
> sz = sizeof(char*); // 4 - (size of a pointer)
> sz = sizeof(s) / sizeof(char*); // 5 (correct)
>
> I suppose if sizeof(s) had returned 17 then the calculation of the no.
> of elements would not be correct. But I would be interested to know
> how the array takes up 20 (bytes?)?
Array takes up [sizeof(element) x numberofelements] bytes. Since it's
an array of pointers... Well, you have your explanation.
V
--
I do not respond to top-posted replies, please don't ask
Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Don't understand sizeof char* array Angus <anguscomber@gmail.com> - 2011-08-09 02:34 -0700
Re: Don't understand sizeof char* array Ian Collins <ian-news@hotmail.com> - 2011-08-09 21:41 +1200
Re: Don't understand sizeof char* array Juha Nieminen <nospam@thanks.invalid> - 2011-08-09 11:30 +0000
Re: Don't understand sizeof char* array Victor Bazarov <v.bazarov@comcast.invalid> - 2011-08-09 08:48 -0400
Re: Don't understand sizeof char* array gwowen <gwowen@gmail.com> - 2011-08-10 01:23 -0700
Re: Don't understand sizeof char* array Victor Bazarov <v.bazarov@comcast.invalid> - 2011-08-10 09:00 -0400
Re: Don't understand sizeof char* array Immortal Nephi <Immortal_Nephi@hotmail.com> - 2011-08-10 18:17 -0700
Re: Don't understand sizeof char* array Paavo Helde <myfirstname@osa.pri.ee> - 2011-08-11 00:30 -0500
csiph-web