Thread: A newby question on the sizeof operator

  1. #1
    Registered User
    Join Date
    Jul 2002

    A newby question on the sizeof operator

    letīs say you got this function:

    void DoSomething( char* mystring)

    and you pass an array to it like this:

    char teststring[] = "this is some text";
    DoSomething( teststring );

    how in GODS NAME! can you get the number of elements of the array INSIDE the function?? (without using strlen() ofcourse, or supose the array is of integers)
    iībe tried the usual:
    int mylen = sizeof mystring / sizeof mystring[0];
    but it wont work, my guess is that im getting the size of THE POINTER to the array NOT the array itself.
    i also tried changing the function to take an array NOT a pointer (but of course its the same thing, since only the address of the array gets passed. (right?)

    is there a way to solve this? (not including passing the size to the function as an argument of course)

  2. #2
    Registered User quagsire's Avatar
    Join Date
    Jun 2002
    There is no way in C/C++ that I know of. I use the first element of the array to hold the number of elements (like in turbo pascal with strings : string[0] holds length). If you are using char, then it will limit you to 255 elements.

    #include <string.h>
    #include <stdlib.h>
    #include <iostream.h>
    void doSomething(char *cptr)
       int numElements = cptr[0];
       for (int i = 1; i <= numElements; i++)
          cout << "Element " << i << " = " << cptr[i] << endl;
    int main()
       char teststring[] = "this is some text";
       int len = strlen(teststring);
       char * temp = new char[len + 1];
       temp[0] = len;
       strcpy(&temp[1], teststring);
       delete[] temp;
       return 0;
    This works fine in Borland C++ 5.02. You can also try using list, vector, etc.

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    How about passing a second parameter that denotes the array length to the function.

    >void doSomething(char *cptr, int len)
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about an operator
    By Programmer_P in forum C++ Programming
    Replies: 6
    Last Post: 05-10-2009, 08:58 PM
  2. Operator overloading question
    By 39ster in forum C++ Programming
    Replies: 3
    Last Post: 07-07-2007, 12:26 PM
  3. Question about sizeof()
    By spank in forum Linux Programming
    Replies: 12
    Last Post: 05-13-2007, 04:18 AM
  4. Operator overloading question
    By Great Satchmo in forum C++ Programming
    Replies: 1
    Last Post: 09-18-2004, 07:41 PM
  5. C number operator question
    By unanimous in forum C Programming
    Replies: 6
    Last Post: 10-26-2001, 09:36 PM