Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > sizeof array via pointer

Reply
Thread Tools

sizeof array via pointer

 
 
Mark S.
Guest
Posts: n/a
 
      04-08-2009
Hi,
I want to access an array via a pointer and get the size of the array,
but sadly I don't know the correct syntax for it:

int main()
{
char c[10];
char* cp = c;
cp[3] = 'b'; // works
int a = sizeof(cp); // this doesn't (returns 4 - why???)
a = sizeof(*cp); // neither does this (returns 1)
}

So how do I get the correct size of c via the pointer (of course, the
goal is to use this within a function)???

Thank you in advance!
Mark
 
Reply With Quote
 
 
 
 
Alf P. Steinbach
Guest
Posts: n/a
 
      04-08-2009
* Mark S.:
> Hi,
> I want to access an array via a pointer and get the size of the array,
> but sadly I don't know the correct syntax for it:
>
> int main()
> {
> char c[10];
> char* cp = c;
> cp[3] = 'b'; // works
> int a = sizeof(cp); // this doesn't (returns 4 - why???)


It giveth the size of the pointer.


> a = sizeof(*cp); // neither does this (returns 1)


It giveth the size of the pointer's referent, a 'char'.


> }
>
> So how do I get the correct size of c via the pointer (of course, the
> goal is to use this within a function)???


You can't get the array size via the pointer.

The information simply isn't there, at least as far as standard C++ is concerned.

Instead of raw arrays, use a std::vector or a std::string.

#include <vector>
#include <iostream>

int main()
{
using namespace std;
vector<char> c( 10 );

c.at( 3 ) = 'b';
cout << v.size() << endl;
}

Cheers & hth.,

- Alf

--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! Just going there is good. Linking
to it is even better! Thanks in advance!
 
Reply With Quote
 
 
 
 
Fred Zwarts
Guest
Posts: n/a
 
      04-08-2009
"Mark S." <(E-Mail Removed)> wrote in message news:49dc46e6$(E-Mail Removed)-ulm.de...
> Hi,
> I want to access an array via a pointer and get the size of the array,
> but sadly I don't know the correct syntax for it:
>
> int main()
> {
> char c[10];
> char* cp = c;


As you declared cp as char*, it a pointer to a char.
It is not a pointer to an array of chars.

> cp[3] = 'b'; // works
> int a = sizeof(cp); // this doesn't (returns 4 - why???)
> a = sizeof(*cp); // neither does this (returns 1)
> }
>
> So how do I get the correct size of c via the pointer (of course, the
> goal is to use this within a function)???
>
> Thank you in advance!
> Mark

 
Reply With Quote
 
Mark S.
Guest
Posts: n/a
 
      04-08-2009
Alf P. Steinbach wrote:
>> So how do I get the correct size of c via the pointer (of course, the
>> goal is to use this within a function)???

>
> You can't get the array size via the pointer.
>
> The information simply isn't there, at least as far as standard C++ is
> concerned.


That is strange because then I don't understand how this exercise is
meant (Thinking in C++, chapter 4, exercise 1:
http://www.linuxtopia.org/online_boo...ter04_019.html

Write a function that takes a char* argument. Using new, dynamically
allocate an array of char that is the size of the char array thatís
passed to the function. Using array indexing, copy the characters from
the argument to the dynamically allocated array (donít forget the null
terminator) and return the pointer to the copy. In your main( ), test
the function by passing a static quoted character array, then take the
result of that and pass it back into the function. Print both strings
and both pointers so you can see they are different storage. Using
delete, clean up all the dynamic storage.

How can I determine the size of the array if all I get is the pointer to
the array?

Thank you for your time!
 
Reply With Quote
 
Vladimir Jovic
Guest
Posts: n/a
 
      04-08-2009
Alf P. Steinbach wrote:
> * Mark S.:
>> Alf P. Steinbach wrote:
>>>> So how do I get the correct size of c via the pointer (of course,
>>>> the goal is to use this within a function)???
>>>
>>> You can't get the array size via the pointer.
>>>
>>> The information simply isn't there, at least as far as standard C++
>>> is concerned.

>>
>> That is strange because then I don't understand how this exercise is
>> meant (Thinking in C++, chapter 4, exercise 1:
>> http://www.linuxtopia.org/online_boo...ter04_019.html
>>
>>
>> Write a function that takes a char* argument. Using new, dynamically
>> allocate an array of char that is the size of the char array thatís
>> passed to the function. Using array indexing, copy the characters from
>> the argument to the dynamically allocated array (donít forget the null
>> terminator) and return the pointer to the copy. In your main( ), test
>> the function by passing a static quoted character array, then take the
>> result of that and pass it back into the function. Print both strings
>> and both pointers so you can see they are different storage. Using
>> delete, clean up all the dynamic storage.

>
> Hm, hm, best advice is to contact Bruce (the correct one![1]), enclosing
> a copy of this response, so that he can fix the exercise text.
>
>
>> How can I determine the size of the array if all I get is the pointer
>> to the array?

>
> You can't determine the size of the array itself.
>
> That's just an unfortunate wording in the exercise, not to be taken
> literally.
>


In the example, this should work:
a = sizeof(c);
no?

Not arguing that it is possible to do what is requested in the exercise
text
 
Reply With Quote
 
hanukas
Guest
Posts: n/a
 
      04-08-2009
On Apr 8, 9:40*am, "Mark S." <(E-Mail Removed)> wrote:
> Hi,
> I want to access an array via a pointer and get the size of the array,
> but sadly I don't know the correct syntax for it:
>
> int main()
> {
> * * * * char c[10];
> * * * * char* cp = c;
> * * * * cp[3] = 'b'; *// works
> * * * * int a = sizeof(cp); * * // this doesn't (returns 4 - why???)
> * * * * a = sizeof(*cp); * * * *// neither does this (returns 1)
>
> }
>
> So how do I get the correct size of c via the pointer (of course, the
> goal is to use this within a function)???


void myfunc(char* data, int size);

myfunc(c, 10);
 
Reply With Quote
 
Alf P. Steinbach
Guest
Posts: n/a
 
      04-08-2009
* Vladimir Jovic:
>
> In the example, this should work:
> a = sizeof(c);
> no?


For an array of char 'c', yes, because sizeof(char) is 1 by definition.

Otherwise you have to divide by the size of an array element, or alternatively
use a function template to obtain the size.

Dividing by the size of an element goes like this (idiomatic):

size_t const size = sizeof(a)/sizeof(*a);

It's usually encapsulated in a macro.

The problem with this solution packaged in a macro is that it is *not type
safe*, e.g., someone might use the macro with a pointer argument. One workaround
could be to compile time assert that the argument is not a pointer. But as of
C++98 that loses its advantage of being usable for locally defined types.

The basic function template goes like this:

template< typename T, size_t N >
size_t size( T const (&)[N] ) { return N; }

where the trick is that the array is passed by reference, so that it's not
decayed to pointer, so that the size information is still available.

The main advantage is that it's type safe, and the main problem is that it can't
be used for array of local type.

Another problem is that it doesn't deliver a compile time constant. When that's
needed it's reformulated as a function returning a result of a type of byte size
equal to the array's number of element. Then the client code has to apply sizeof
to the result, and to avoid doing that directly it's in turn wrapped in a macro.


Cheers & hth.,

- Alf (master of C++98 array size determination )

--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! Just going there is good. Linking
to it is even better! Thanks in advance!
 
Reply With Quote
 
Alf P. Steinbach
Guest
Posts: n/a
 
      04-08-2009
* Vladimir Jovic:
>
> In the example, this should work:
> a = sizeof(c);
> no?


For an array of char 'c', yes, because sizeof(char) is 1 by definition.

Otherwise you have to divide by the size of an array element, or alternatively
use a function template to obtain the size.

Dividing by the size of an element goes like this (idiomatic):

size_t const size = sizeof(a)/sizeof(*a);

It's usually encapsulated in a macro.

The problem with this solution packaged in a macro is that it is *not type
safe*, e.g., someone might use the macro with a pointer argument. One workaround
could be to compile time assert that the argument is not a pointer. But as of
C++98 that loses its advantage of being usable for locally defined types.

The basic function template goes like this:

template< typename T, size_t N >
size_t size( T const (&)[N] ) { return N; }

where the trick is that the array is passed by reference, so that it's not
decayed to pointer, so that the size information is still available.

The main advantage is that it's type safe, and the main problem is that it can't
be used for array of local type.

Another problem is that it doesn't deliver a compile time constant. When that's
needed it's reformulated as a function returning a result of a type of byte size
equal to the array's number of element. Then the client code has to apply sizeof
to the result, and to avoid doing that directly it's in turn wrapped in a macro.


Cheers & hth.,

- Alf (master of C++98 array size determination )

--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! Just going there is good. Linking
to it is even better! Thanks in advance!
 
Reply With Quote
 
Alf P. Steinbach
Guest
Posts: n/a
 
      04-08-2009
* Vladimir Jovic:
>
> In the example, this should work:
> a = sizeof(c);
> no?


For an array of char 'c', yes, because sizeof(char) is 1 by definition.

Otherwise you have to divide by the size of an array element, or alternatively
use a function template to obtain the size.

Dividing by the size of an element goes like this (idiomatic):

size_t const size = sizeof(a)/sizeof(*a);

It's usually encapsulated in a macro.

The problem with this solution packaged in a macro is that it is *not type
safe*, e.g., someone might use the macro with a pointer argument. One workaround
could be to compile time assert that the argument is not a pointer. But as of
C++98 that loses its advantage of being usable for locally defined types.

The basic function template goes like this:

template< typename T, size_t N >
size_t size( T const (&)[N] ) { return N; }

where the trick is that the array is passed by reference, so that it's not
decayed to pointer, so that the size information is still available.

The main advantage is that it's type safe, and the main problem is that it can't
be used for array of local type.

Another problem is that it doesn't deliver a compile time constant. When that's
needed it's reformulated as a function returning a result of a type of byte size
equal to the array's number of element. Then the client code has to apply sizeof
to the result, and to avoid doing that directly it's in turn wrapped in a macro.


Cheers & hth.,

- Alf (master of C++98 array size determination )

--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! Just going there is good. Linking
to it is even better! Thanks in advance!
 
Reply With Quote
 
Mark S.
Guest
Posts: n/a
 
      04-09-2009
blargg wrote:
> Mark S. wrote:
>> Alf P. Steinbach wrote:
>>>> So how do I get the correct size of c via the pointer (of course, the
>>>> goal is to use this within a function)???
>>> You can't get the array size via the pointer.
>>>
>>> The information simply isn't there, at least as far as standard C++ is
>>> concerned.

>> That is strange because then I don't understand how this exercise is
>> meant (Thinking in C++, chapter 4, exercise 1:
>>

> http://www.linuxtopia.org/online_boo...ter04_019.html
>> Write a function that takes a char* argument. Using new, dynamically
>> allocate an array of char that is the size of the char array thatís
>> passed to the function. Using array indexing, copy the characters from
>> the argument to the dynamically allocated array (donít forget the null
>> terminator) and return the pointer to the copy. In your main( ), test
>> the function by passing a static quoted character array, then take the
>> result of that and pass it back into the function. Print both strings
>> and both pointers so you can see they are different storage. Using
>> delete, clean up all the dynamic storage.
>>
>> How can I determine the size of the array if all I get is the pointer to
>> the array?

>
> Sounds like it means the LENGTH of the C-style string you are given a
> pointer to. In that case, juse use strlen(str) (and remember that the
> length does NOT include the terminating zero).

Oh, I thought he was just talking about a normal array. So my basic code
was:
char c[10];
char* cp = c;
int a = sizeof(c);

And I thought I would go from there. I am also not sure yet what the
sentence "In your main( ), test the function by passing a static quoted
character array, then take the result of that and pass it back into the
function." means. Does that mean that my function, which is supposed to
take the char*, is supposed to be called like this:

char* cp = f('abcd'); ???


> But it also sounds like you
> could choose a better book to learn C++ from. The author, who should be
> experienced with C++, shouldn't be writing exercises which even a learner
> can find ambiguity/error with.


Well, I chose "Thinking in C++" because it was recommended on many sites
throughout the net and it was well-written from my perspective. However,
the exercises are not really contrived perfectly. The author indirectly
admitted so himself (can't find the link though) when he stated that he
just wrote down the exercises without actually giving them much thought
them beforehand. For years he thought he could add a book with solutions
but eventually gave up as it was too time-consuming (darn, I really wish
I still had the link). Now, there is "The Annotated C++ Solutions
Guide", but it is not written by him and only contains portions of the
exercises (most of the early ones but the later the chapter, the fewer
solved exercises: http://mindview.net/Books/TICPP/Solutions/SolnList).

If you have a suggestion for a better comprehensible (!) book or
tutorial (my first book was Stroustrup's "The C++ Programming Language
which didn't help me at all), please post it as I'm always open to
improve my learning effectiveness.

Kind regards
Mark
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
[MUDFLAP] Is sizeof(ARRAY[0]) equivalent to sizeof(*ARRAY) ? m.labanowicz@gmail.com C Programming 46 01-14-2013 10:50 PM
sizeof (size_t) and sizeof (pointer) Alex Vinokur C++ 19 11-30-2007 11:11 PM
#define ARR_SIZE sizeof(arr)/sizeof(arr[0]) Vinu C Programming 13 05-12-2005 06:00 PM
sizeof(enum) == sizeof(int) ??? Derek C++ 7 10-14-2004 05:11 PM
sizeof(str) or sizeof(str) - 1 ? Trevor C Programming 9 04-10-2004 05:07 PM



Advertisments