weird problem with c-style string and sizeof()

Greetings,

The following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

void strdup( char* str )
{
    cout << str << ", " << sizeof(str) << "\n";
}

int main()
{
    char cStr[] = "bananas";
    strdup( cStr );

    return 0;
}


produces the output...

 
bananas, 4


how is it possible that the word "bananas" has sizeof equal to 4

Thanks in advance...
Fred
Last edited on
str is a pointer so sizeof(str) gives you the size of a pointer, which happen to be 4 with your compiler.

You can use std::strlen if you want to get the length of a C-string.
http://www.cplusplus.com/reference/cstring/strlen/
Last edited on
It is possible because the sizeof operator is reporting the size of the pointer you passed into your function. The "size" information is lost when you pass an array into a function, so if you actually need to know the sizeof your array you need to pass this into the function as well.

However in this case you probably want to know the length of the string, not the actual sizeof the array. You can get the length of a C-string by using the strlen() function. But really you should be using C++ strings instead of C-strings, since they know their own sizes and are much less error prone.

Thanks guys. I am slapping my forehead now.

jlb I agree with your remark about using c++ strings. c-strings are a pain in the butt, but this was extracted from a book exercise dealing with arrays and such, and it specifically asked for c-style strings.

regards.
Then perhaps you should find another book, one that stresses C++ instead of C?

It's still good to understand how arrays and C-strings work even if you use C++.
Yes, but IMO that should be after it has already used C++ strings, vectors and other C++ features. It seems to me like this assignment is fairly early in the book because it looks a lot like a try at implementing a strcpy() look a like.


Topic archived. No new replies allowed.