Thread: Obtaining allocated string length...

  1. #1
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Waterloo, Texas

    Obtaining allocated string length...

    I know you can do:

    char word[100];

    int maxlen = sizeof(word);

    //maxlen = 100;

    But when I pass the string into a function, and then try this approach, it gives me the size of a char(4 bytes).

    I am of course, trying to avoid passing the length of the string as a parameter.

    I have tried:

    char * string_func( char *in);

    And also:

    char * string_func( char in[]);

    The results were identical.

    Any ideas?
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
        return std::pow
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > I am of course, trying to avoid passing the length of the string as a parameter.
    Well you can't.

    All arrays are passed as pointers to the first element, so all sizeof will be able to tell you is the size of that pointer.

  3. #3


    Instead of:
    int maxlen = sizeof(word);

    int maxlen = strlen(word);

    Since sizeof(word) will give the you size of the pointer to word (as it points to a char array). strlen(word) would be a better choice since it will return an int value that is the length of the word word is pointing to.

    And don't forget #include<string.h>

    Just a thought

    Get off my Intarweb!!!!

  4. #4
    Registered User goran's Avatar
    Join Date
    Sep 2001
    while calling, call as string_func(word);

    and while declaring

    use char *string_func( char word[100])

    inside this function try strlen() to get the size of the string.

    I don't wait for the future; it comes soon enough.

  5. #5
    strlen() only works on 'c' strings. If you wanted to check the length of any dynamically allocated pointer, just examine the block header.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. C++ FTP class won't work
    By lord mazdak in forum C++ Programming
    Replies: 8
    Last Post: 12-18-2005, 07:57 AM
  4. Weird modification to string length
    By ChwanRen in forum C Programming
    Replies: 0
    Last Post: 08-17-2003, 10:45 AM
  5. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM