This question already has answers here:
How to get the real and total length of char * (char array)?
(15 answers)
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 2 years ago.
Is there a way to determine the size of a char[] buffer via a char* pointer in C++? I'm using C++98.
The following lines of code all print out '8' (essentially sizeof(char*)). However I'm looking for the actual size of the buffer.
int maxBufferLen = 24;
char* buffer = new char[maxBufferLen];
std::cout << sizeof(buffer) << std::endl; // prints '8'
std::cout << ( sizeof(buffer) / sizeof(buffer[0]) ) << std::endl; // prints '8'
In practice, I am passing that char* buffer in between functions and I will not have access to the maxBufferLen variable that I am using to initialize it. As such, I'll need to determine the length using another way.
There is general no way of determining the size of an array based on a pointer to an element of that array.
Here are typical ways to find out the size:
Store the size in a variable
A variant of this is to store both the pointer and the size (or alternatively, pointer past the end) as members of a class. An example of this approach is the std::span class template (this standard class is not in C++98, but you can write your own, limited version).
A variant this, which is generally used when the array is allocated dynamically (such as in your example), is to deallocate the memory in the destructor of the class and conforming to the RAII idiom. Examples of this approach are std::string and std::vector.
Or choose certain element value to represent the last element of the array. When iterating the array, encountering this "terminator" element tells you that the end has been reached. This is typically used with character strings, especially in C interfaces, where the null terminator character ('\0') is used.
Related
This question already has answers here:
Char and strcpy in C
(5 answers)
Closed 2 years ago.
I want to allocate space for char array (string) in C++. When I allocate memory for 10 chars, I can also assign more characters to the char array. When I print it, it gives some of the additionally assigned characters from the array.
#include <string.h>
using namespace std;
int main()
{
char *name = new char[10];
strcpy(name, "MoreThanTenCharacters");
cout << name << endl;
}
Although the allocated memory is for 10 characters, I can assign more. Printing gives exactly the same value. What is the logic behind it?
When the buffer pointed by the first argument is shorter than the string pointed by the second argument (taking the null terminator into consideration), then the copy will overflow the buffer into surrounding memory, and the behaviour of the program is undefined.
Printing gives exactly the same value. What is the logic behind it?
You've observed some behaviour. This is an example of possible behaviours that the program could have when the behaviour is undefined.
So, what is the correct way of allocating memory for JUST 10 chars and assigning a string to it?
Your allocation is correct although not ideal. Using a bare pointer is unsafe; in the end you leak the allocation. It's the copying where your bug happens.
An efficient and simple option is to use std::string. If your goal is to store the 10 character long prefix substring of the input, then following would be correct:
std::string name("MoreThanTenCharacters", 10);
I am working on a coding assignment for my class and I ran into a problem!
I have this constructor here, for a String object:
String::String(char str[]) {
size = (sizeof(str)/sizeof(str[0]));
data = new char[size];
for (int i = 0; i < size; ++i) {
data[i] = str[i];
}
}
Here is part of the main I was provided:
char test[11] = "Hello world";
String two(test);
cout << "The length of String two is: " <<
two.length() << endl;
cout << "The value of String two is: ";
two.print();
So when I run this, I would get 8 for the size (should be 11). However, after some research, I figured out it is because the sizeof(str) is returning the byte size of a pointer, rather than the entire array.
So is there any way to get the size of the whole array with what I have? I am not supposed to manipulate the provided main, therefore I cannot add an int size to the parameters, which would be the obvious solution.
I've been stuck on this one for a bit, thanks for any help and suggestions,
Array decays to pointer when passed to a function.
You have to either pass the length to the function, pass a STL container e.g. std::vector or use strlen() inside function. (Note that strlen() need a terminating null-character to work properly and you have to add that to your array)
You can not get size of array at runtime in C. At runtime, array is just the address. The size is simply not stored anywhere. In source code, at compile time, in a place where compiler knows the size, you can use sizeof operator, but that gets essentially converted to a constant numeric literal, ie. same as writing the right number there yourself (VLAs are a bit more complex case, and of course using sizeof can create portable code unlike hard-coded number).
To make matters worse (for understanding C), when you have a function parameter that looks like an array, it really is a pointer. Even if you give it static size in the parameter list, sizeof still it gives you size of pointer, for example. Only non-parameter variables can actually be arrays, with sizeof working as expected.
You have to pass the size somehow (usually as extra parameter) or have some other way of telling where the data ends (such as strings' '\0' at the end).
Use a vector instead of char array. You can get size by calling size() method of vector container. If you want to use a char array, then it is a common practice in c programming to pass size as second parameter in the function.
You will only get size of array using sizeof() function on the function stack in which the array is defined and if the array size is known in compile time.
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 9 years ago.
char *one = new char[1024];
char one1[] = "hello";
one = hello;
cout << sizeof(one) << endl;
I really want the last line to output sizeof(one1) but I know as it stands it will output the size of the pointer which is 4 or 8. Is there a way to extract the sizeof() of the array from just the pointer to the first letter?
Is there a way to extract the sizeof() of the array from just the pointer to the first letter?
No.
Unfortunately, you have to keep track of this explicitly and maybe pass around the length as extra arguments to functions etc.
You have tagged your question "C++". In C++ we usually use std::vector, std::string or other container classes to keep track of this.
There is no way to do this - maybe use a std::vector instead, or a std::string if you just need char's.
No.
That information is simply not available at run-time. A pointer is just a pointer, there is nowhere for the extra information (about the area being pointed at) to live.
How would I get the size of this:
char* stringit[4] = {"H","H","UH","i"};
I tried:
sizeof(stringit);
and it outputed 32.
I tried to make a for loop:
for (i= 0; check != 0; ++i){
check = stringit[i];
}
and that did not work either. Is there anyway to do this without having to pass in the size of the array?
make it a NULL terminated array of pointers
char* stringit[] = {"H","H","UH","i" , NULL };
Then just count the pointers until you find a null pointer.
The right way to get the number of elements of an array is to divide its actual size (in bytes) by the size of an element:
sizeof(stringit) / sizeof(stringit[0])
But unless you have extremely specific requirements, you should use a standard container like vector (and string too instead of char* C strings):
std::vector<std::string> stringit = {"H","H","UH","i"};
std::cout << stringit.size();
As #KonradRudolph mentioned, vector is nice if your number of elements is variable. If the number of elements is known at compile time and will never change you could instead use array:
std::array<std::string, 4> stringit = {"H","H","UH","i"};
std::cout << stringit.size();
As long as you have access to the array itself, i.e. as long as you have not converted it to a pointer, the number of elements can be calculated as
sizeof stringit / sizeof *stringit
which will evaluate to a compile-time constant 4 in your case.
Whether this is what you are looking for or not depends on some additional details, which you did not provide in your question. You mention "having to pass in the size of the array". Pass where?
32 is the right size. The variable stringit is an array of 4 char pointers, and each pointer is 8 bytes.
What is it that you are trying to do?
char* stringit[4] = {"H","H","UH","i"};
is an array of 4 strings, i.e. array of 4 char* (pointer holds an address, 64bit address = 8 bytes). That's why you get 32. To retrieve the number of elements, you could do:
int count = sizeof(stringit) / sizeof(stringit[0]);
which will give you 4. But note that this kind of approach isn't much flexible and I'd rather use some STL container, i.e. std::vector<char*> or yet even better, get rid of C-style strings as well and use std::vector<std::string> instead.
The sizeof works for static arrays. It's giving you the size of the construct in bytes.
If you want length, do sizeof(stringit) / sizeof(char*).
For a more flexible solution that is probably the ``Right way" to do things in C++ (which works for dynamic arrays), just use std::array, or std::vector/std::list, if you need more dynamic allocation.
http://www.cplusplus.com/reference/array/array/
http://www.cplusplus.com/reference/vector/vector/
http://www.cplusplus.com/reference/list/list/
With this construct, you can simply use a size() member.
Remember to pass by reference when necessary to avoid needless copying.
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 10 years ago.
I am wondered about the memory usage of variables and I tried this :
#include <iostream>
int main()
{
char* testChar1 = "Hi";
char* testChar2 = "This is a test variable";
char* testChar3 = "";
std::cout <<sizeof(testChar1)<<std::endl;
std::cout <<sizeof (testChar2) <<std::endl;
std::cout <<sizeof(testChar3)<<std::endl;
}
output is :
4
4
4
I think I am not doing the right thing. I want to know how much memory every variable uses in stack .
EDIT 1
At the same time if I does char* testChar3 = NULL; the program crashes. So does it mean there is no memory usage for the same?
In addition to using strlen, you could also use sizeof on a
char testChar1[] = "Hi";
EDIT: yes, this includes the null terminator, which IMO is an advantage over strlen. The actual size does include the null terminator.
You simply print the size of the pointers, they always will be the same. What you need is to multiply strlen for the strings by the size of a single char.
EDIT: as per my comment and the correction from #Suma:
cout << (strlen(testChar) + 1) * sizeof(char) + sizeof(testChar);
The 1 is needed for the terminating zero character.
sizeof(testChar1) return size of pointer, if you want to test string length try replace sizeof with strlen
In this instance you're only printing the size of the pointers and not the chars. So really, you would want to print the pointer, then dereference it and print the size of the memory it points to as well.
You are actually printing the amonut of bytes a pointer takes on your system . I think what you need to do is to use strlen function . Check it out here . strlen
std::cout<<strlen(testChar1)<<std::endl;
std::cout <<strlen(testChar2) <<std::endl;
std::cout <<strlen(testChar3)<<std::endl;
I want to know how much memory every variable uses in stack .
What your programm print is exactly what you want.
Read the other answer if what you really want is to know how much memory (where??!!) occupy the char-strings pointed by yours variables - pointers.