58422

How can I know legth of array in C++ [duplicate]

Question:

<blockquote>

<strong>Possible Duplicate:</strong><br /><a href="https://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language" rel="nofollow">Sizeof an array in the C programming language?</a>

</blockquote>

I have an array of char and I want to process it in a function, I tried code like this:

int main(){ char *word = new char [5]; /*here we make this word .... */ process(word); puts(word); } void process(char *word){ int sizeOfWord = sizeof(word)-1; /* here is cycle that process the word, I need it lenght to know how long cycle must be ..... */ }

But I can't get the length of array with sizeof. Why? And how can I get that?

Answer1:

You can't. With a pointer, there is no way to know the size.

What you should do is, pass the length of word to your process also.

<hr />

You should know that there is a difference between arrays and pointers. Arrays are indeed a number of elements and therefore sizeof of the array gives its size (in bytes). A pointer on the other hand is just an address. It may not even point to an array. Since the sizeof operator is computed at compile time (except for variable length arrays), it cannot know what you mean.

Think of this example:

void process(char *word); int main(){ char *word = new char [5]; char *word2 = new char [10]; process(word); process(word2); /* ... */ } void process(char *word){ int sizeOfWord = sizeof(word)-1; // what should this be? /* ... */ }

Now, knowing that sizeof in this case is computed at compile time, what value do you think it should get? 5? 10?

<hr />

Side note: It looks like you are using this array as a string. In that case, you can easily get its length with <a href="http://linux.die.net/man/3/strlen" rel="nofollow">strlen</a>.

Answer2:

U should use strlen() instead.

<strong>EDIT</strong>: Assuming your word is valid word with \0 at the end.

Anyway, you use c++ so you should use some container like std::string.

Answer3:

If your array is always char* or const char* and contains null terminated strings, you can use strlen, or even more easily use the std::string class and its appropriate methods.

If it is not a null terminated string (eg. its a plain byte array, or your question is about arrays in general and the char was just an example), use std::vector<char> or std::array<char, 5> and call their .size() methods.

Answer4:

Since arrays "decay" into pointers to their first elements in code like this, you can't. The pointer doesn't "know" how large a block of memory it points at. You need to pass the size separately, e.g.

void process(char *word, size_t length);

Answer5:

There is only one way to know the length of an array in C/C++: already knowing it. You will need to pass the length of the array as another parameter.

If you are talking specifically about strings, search for the null character in the array and then use its index + 1 as the length (which is basically what the strlen() function does).

Otherwise, perhaps you could just use std::string instead and then get the length property of it?

Answer6:

You either have to pass the length of the array to the process function, or use the null (\0) character to mark the end.

Assuming the latter you can use

void process(char *word) { while (*word) { //do stuff with the character *word ++word; } }

Answer7:

No, it won't work. sizeof a pointer returns only the size of the pointer type, not that of the array. When you pass an array as parameter to a function, the array <em>decays</em> into a pointer, which means that the compiler won't know anymore what exactly it points to, and if it is an array, how long it can be. The only ways for you to know it inside the function is

<ul><li>pass the length as an additional parameter, or</li> <li>add an extra terminator element to the array.</li> </ul>

Note that arrays in C and C++ don't store their size in any way, so it is the programmer who must keep it in mind and program accordingly. In the code above, you know that the actual size of a is 5, but the compiler (and the runtime) has no way of knowing it. If you declared it as an array, i.e.

char[] word = new char [5];

the compiler would keep track of its size, and sizeof would return this size (in bytes) while in the scope of this declaration. This allows one to apply a well known idiom to get the actual size of an array:

int size = sizeof(a) / sizeof(char);

But again, this works only as long as the compiler knows that a is actually an array, so it is not possible inside function calls where a is passed as a (pointer) parameter.

Answer8:

On Windows there is <a href="http://msdn.microsoft.com/en-us/library/z2s077bc%28v=vs.71%29" rel="nofollow">_msize</a> function to get the allocated memory size on heap in bytes. In VS2005 and VS2008 it worked perfectly with operator new, because it used malloc to allocate the memory. I have to note:

<strong>It is not standard way, so you should NOT use it!</strong>

Object * addr = new Object[xxx]; size_t number_of_objects = _msize(addr) / sizeof(Object);

Answer9:

The other answers have explained in detail why you cannot get the size of a classical C-array, but I want to point out the following.

Your example is missing a

delete [] word;

at the end of main. Otherwise you have a memory leak.

That shows why the preferred way of working with arrays in C++ is using std::vector or -- in case of a fixed length -- the new std::array and in case of character strings std::string. The compiler will manage the underlying storage for you. All of these classes provide a size function.

Recommend

  • Need C# Regex for replacing spaces inside of strings
  • Regular expression to delete duplicated words?
  • How to parse user search string for Postgresql query?
  • Perl: How can I split a string on an unquoted instance of a character
  • wchar_t is 2-bytes in visual studio and stores UTF-16. How do Unicode-aware applications work with c
  • Web Application and In-Memory State
  • Using replacements with a raw Sequelize query: avoiding single quotes?
  • Determine if UTF-8 encoded NSData contains a null-terminated string
  • Strings appear exact, but they do not match?
  • runtime-check whether an instance (Base*) override a parent function (Base::f())
  • How can I prevent the need to copy strings passed to a avr-gcc C++ constructor?
  • Using MouseListener to select a range of cells in a grid
  • Building Qt project for C++11 standard
  • allocating memory to an array of string
  • C++ friend class std::vector
  • C#: Import/Export Settings into/from a File
  • Error in installing package: fatal error: stdlib.h: no such file or directory
  • Syntax error on tokens, AnnotationName expected instead - error on query
  • How to explicitly/implicitly implemented interface members in C++/CLI?
  • JSR-330 support in Picocontainer : @Inject … @Named(\"xxx)
  • SAVE attribute needed for Fortran variables when only the C_LOC address is returned to a C program?
  • How can I display the parent menu item's description using Wordpress walkers?
  • Unable to decode certificate at client new X509Certificate2()
  • C: Incompatible pointer type initializing
  • OOP Javascript - Is “get property” method necessary?
  • Cancel a live stream “fast motion” catch-up in Flash
  • Fetching methods from BroadcastReceiver to update UI
  • Apache 2.4 and php-fpm does not trigger apache http basic auth for php pages
  • AES padding and writing the ciphertext to a disk file
  • VS2008 Enable C++ Exception with SEH
  • Symfony2: How to get request parameter
  • Release, debug version and Authorization Google?
  • GridView Sorting works once only
  • Is there a mandatory requirement to switch app.yaml?
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • WPF Applying a trigger on binding failure
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • LevelDB C iterator
  • How can i traverse a binary tree from right to left in java?