Number of elements in an dynamically allocated array
I have a char* Name; and I need to know how many letters are in it, so I tried to do this
sizeof(Name)/sizeof(Name[0]) but it always equals 4 then I tried sizeof(*Name)/sizeof(*Name[0]) that returned a big 1, Im kinda confused on how to do this at the moment although I think I know how to do it and I just forgot..
thanks, Xero-X2
The sizeof operator returns the length of the type. Arrays and pointers are different things, and sizeof is telling you the size of the pointer.
Use the strlen (in string.h) function in C or std::strlen (in cstring) in C++ to determine the length of a null terminated char string.
Use the strlen (in string.h) function in C or std::strlen (in cstring) in C++ to determine the length of a null terminated char string.
C does not store the size of an array with a pointer. However, it looks as though that might be a char* to a string (ie. char *str = "Test"). You can get the length of zero-terminated strings with the C standard library function strlen(char*).
If that is not a zero terminated string, you will either need to store the size by yourself, or use something like vector in C++.
However, you may have also been attempting something like this:
char array = {1, 4, 5}; // Pre initialized
in which case sizeof(array)/sizeof(array[0]); will work.
Edit: Null and Void has beaten me to the draw .
[edited by - premandrake on November 30, 2002 10:48:30 PM]
If that is not a zero terminated string, you will either need to store the size by yourself, or use something like vector in C++.
However, you may have also been attempting something like this:
char array = {1, 4, 5}; // Pre initialized
in which case sizeof(array)/sizeof(array[0]); will work.
Edit: Null and Void has beaten me to the draw .
[edited by - premandrake on November 30, 2002 10:48:30 PM]
Im certainly aware of the diffrence between pointers and arrays I also understand that my value i returned was the size of my pointer varible. I do appreciate your quick answer, but I would like to know a metheod to do this that is not totally devoted to the null terminated stings. thanks.
Premandrake: I need to do that but I need to get around the fact that I have a pointer to the array, Thats where my issue is.
[edited by - Xero-X2 on November 30, 2002 10:51:11 PM]
Premandrake: I need to do that but I need to get around the fact that I have a pointer to the array, Thats where my issue is.
[edited by - Xero-X2 on November 30, 2002 10:51:11 PM]
quote:Original post by Xero-X2
but I would like to know a metheod to do this that is not totally devoted to the null terminated stings.
There are none, short of storing it yourself in another variable.
Use a std::vector or a std::string.
Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement