CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: sizeof fails

  1. #1
    Join Date
    Mar 2010
    Posts
    16

    sizeof fails

    Code:
    #include <iostream>
    
    int len(const char ar[]) {
    	return sizeof(ar)/sizeof(*ar);
    };
    
    int main(){
    	printf("%d",len("124567"));
    	std::getchar();
    }
    When I run this it gives me 4. What am I doing wrong ?

  2. #2
    Join Date
    Nov 2003
    Posts
    1,902

    Re: sizeof fails

    ar is just a pointer - with a size of 4 bytes on your system.

    http://c-faq.com/aryptr/aryparmsize.html

    gg

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: sizeof fails

    You are trying to determine the size of an array passed as a parameter to a function. This is not possible. Either the array is a fixed known size (eg with dimensions set by const int) or the function needs to know the number of elements passed as an additional parameter. One other alternative is to use two parameters - the first a pointer to the starting element the second a pointer to the element past the last element (similar to how STL iterators work). Arrays are effectively passed to functions as a const pointer so, (as Codeplug explained in post #2) sizeof just returns the size of the pointer (which will be either 32 or 64 bits) and *ar is a pointer to a char in this case so its sizeof is 1.

    If the array is an array of char, then it is more usual to pass as either const char * or char * (if the contents are to be modified) and use the c string libraries to manipulate (eg strlen(..) to determine the number of chars in the array etc).
    Last edited by 2kaud; August 7th, 2013 at 05:39 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: sizeof fails

    Quote Originally Posted by po0ky View Post
    Code:
    #include <iostream>
    
    int len(const char ar[]) {
    	return sizeof(ar)/sizeof(*ar);
    };
    I will add to what the others have stated:

    That code above is no different than this one:
    Code:
    #include <iostream>
    
    int len(const char* ar) {
    	return sizeof(ar)/sizeof(*ar);
    };
    Just this should now give you reason why you get sizeof() returning 4.

    When you use the [] as part of the argument, no matter how much it looks like an array, it isn't. A lot of beginners get fooled into thinking that just because the parameter argument looks like an array that they are passing arrays.

    To further give proof, try to define two functions that looks like yours and another with the same name that looks like mine. You will get a compiler error that the function already exists (that can only happen if the functions have the same argument types, since C++ allows overloading of functions):
    Code:
    #include <iostream>
    
    int len(const char ar[]) 
    {
        return sizeof(ar)/sizeof(*ar);
    }
    
    int len(const char *ar) 
    {
        return sizeof(ar)/sizeof(*ar);
    }
    You will get a compiler stating that the function was already defined. But that can only happen if the arguments are the same. Thus you see that just because an argument has [] means nothing -- it always reduces down to a pointer.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; August 7th, 2013 at 10:11 PM.

  5. #5
    Join Date
    Mar 2010
    Posts
    16

    Re: sizeof fails

    Thank you for all of your answers. It was very educating. Best way to go would probably be to use strlen.

    Strlen would probably look like something like this?

    Code:
    int len(const char ar[]) {
    	int ret = 0;
    	while(*(ar+ret++));
    	return ret;
    }

  6. #6
    Join Date
    Aug 2013
    Posts
    8

    Re: sizeof fails

    @po0ky
    almost, but notice, that you are using post incrementation here: while(*(ar+ret++));
    so your function len("abc") returns 4. Instead of you could try this:

    [code]
    int len(const char ar[]) {

    int s=0;
    for (;*ar;s++,ar++){}
    return s;
    [code]

    Btw, I hope you write this code only for training purpose. I suggest using stl in your production code: http://www.cplusplus.com/reference/string/.

    good luck

  7. #7
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: sizeof fails

    Why write your own? Why not just use the c library function strlen?

    If you had to write your own, it would look something like this

    Code:
    int len(const char* str)
    {
    const char *eos = str;
    
            while (*eos++);
            return((int)(eos - str - 1));
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  8. #8
    Join Date
    Mar 2010
    Posts
    16

    Re: sizeof fails

    Thank you again for both answers.

    Ofcourse its always better to use the library functions, but still I would like to know how these functions work.

    Even in this small code there are always better ways to write them. (Errors aside)
    Thank you for pointing out my error LukeCodeBaker.

    I cant see the code for strlen but I would think the code of 2kaud will probably come closest.
    Its going to be hard to beat that piece of code.

  9. #9
    Join Date
    Apr 1999
    Posts
    27,449

    Re: sizeof fails

    Quote Originally Posted by po0ky View Post
    Ofcourse its always better to use the library functions, but still I would like to know how these functions work.
    A loop starts from the address you give it, and searches for the first NULL character while keeping a count. Then the function returns the count.
    I cant see the code for strlen but I would think the code of 2kaud will probably come closest.
    Compiler writers implement the steps I described as optimal as possible, meaning that the code may be very hard to read C code, or can even be inline assembly code. The library code isn't going to be written for beginners (and maybe some professionals) to be understood -- it is written to be called by the program, and the library function performs what it's supposed to perform, correctly and efficiently.

    Therefore I suggest you don't spend a lot of time trying to "micro-study" how these functions work. What you should be doing is know how to use these functions properly.

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured