I have the below piece of code and I'm very confused by it. I'm trying to figure out how much memory (bytes of memory/space is actually being taken up by my partially filled array). I've got the below piece of code but I'm a bit confused.
If I declare a string array of 8 elements, and partially fill the elements with the two strings. The for loop will start at 0 and go until size of my array 32 possible bytes (assuming I need 4 bytes per string) divided by size of the first element in the array. That is returns 4 - the size of the element of the first string in the array. But that still doesn't tell me how many letters/characters are in that string.
I understand inside the loop we increment count when the value in the array doesn't equal a blank/null value. Giving us the total filled (non empty) positions in our array. However I still don't have a value for our actual amount of characters.
How does this tell us how many characters are in my strings?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string test_array[8] = {"henry", "henry2"};
size_t count = 0;
for (size_t i = 0; i < sizeof(test_array)/sizeof(*test_array); i++)
{
cout << "NOT THE POINTER: "<<sizeof(test_array) << endl;
cout << "POINTER: "<<sizeof(*test_array) << endl;
if(test_array[i] != "")
count ++;
}
int num_elem = sizeof(test_array)/sizeof(test_array[0]);
cout << num_elem << endl;
cout << count << endl;
return 0;
}
To know how many characters are in a std::string use the size() method.
Related
This question already has answers here:
getting size of array from pointer c++
(6 answers)
Closed 7 years ago.
Alright so this is probably a really simple question, I'm just really new to c++ and am struggling to understand most things. I've been asked to create an array that stores random numbers but the user is to define the size of the array. I then have to display all the numbers in the array. What I'm struggling with is displaying all elements of the array. At the moment, I'm pretty sure I've got the array part down, but I can only seem to display one number. Here's my code so far:
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
using namespace std;
using std::srand;
using std::rand;
using std::time;
void Display(int *, int);
int main(void)
{
int userSize;
cout << "Please enter the size of the array: ";
cin >> userSize;
int* randArray = new int[userSize];
srand(time(NULL));
for (int i = 0; i < userSize; i++) {
randArray[i] = rand() % 20 + 1;
}
//Disregard the next few lines, I was just testing to see if anything was actually in the array.
/*cout << randArray[0] << endl;
cout << randArray[1] << endl;
cout << randArray[2] << endl;
cout << randArray[19] << endl;*/
Display(randArray, sizeof(randArray) / sizeof(int));
return 0;
delete[] randArray;
}
void Display(int *arrayData, int numElements)
{
for (int counter = 0; counter < numElements; counter++)
{
std::cout << *(arrayData + counter) << std::endl;
}
return;
}
I should also mention that the teacher provided us with the code after the line that deletes the array.
This is the question I have to answer: Ask the user for the number of elements to be stored in the array. You should then dynamically allocate the memory to hold this array, which will proceed to be used in the same way as the previous task (populating the array with random data, displaying the data to the
screen).
sizeof(randArray) does not tell you the number of bytes that you've allocated. Rather, it tells you the size of a pointer, which on your system happens to be the same as the size of an integer, so sizeof(randArray) / sizeof(int) returns 1 always. Instead use userSize as your second parameter in the function call to Display.
Also, you delete[] randArray after return 0. This is incorrect; nothing after the return 0 will be executed. You want it above instead.
Further, consider the use of std::vector instead (unless you are required to use a raw pointer for this assignment)
The problem is sizeof. It gives you the size of the type of the argument, not of what is behind. Your should pass userSize to Display().
You should also delete the array before you return. Code behind return never gets executed.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For an intro to CS assignment, I am writing a C++ program in Visual Studio 2010 which returns an integer and accepts a pointer to a C-string as an argument. I know that I need to make a function besides an int main to succeed, but I am not exactly sure about how to initialize a char pointer array which points to a predefined char array, if possible.
The purpose of this program is to get a comment from a user within a predefined limit then inform said user how many characters (including whitespace) that comment is.
The error is: a value of type "char" cannot be assigned to an entity of type "char *";
Here is my program that does not compile:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
//function protoype
void evalStr(char arr[]);
//variable
int length;
//main function
int main()
{
const int SIZE = 201;
char arr[SIZE];
char *str[SIZE];
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
*str = arr[SIZE];
cin.getline(arr, SIZE);
length = strlen(*str);
evalStr(arr);
system("PAUSE");
return 0;
}
//function defintion
/* get the string
count the number of characters in the string
return that number
*/
void evalStr(char arr[])
{
printf("The length of the entered comment is %d characters\n", length);
}
If there is a general method to utilizing char pointer arrays or perhaps pointers to strings, this code could be redone to return the value of the string instead of utilizing that printf statement. What all am I doing wrong?
Edit: Here is an updated version of this program that compiles, runs, and informs the user if the character limit is reached or exceeded.
// Accept a pointer to a C-string as an argument
// Utilize the length of C-string in a function.
// Return the value of the length
// Display that value in a cout statement.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
//variables
const int SIZE = 201;
int length;
char arr[SIZE];
char *str;
//main function
int main()
{
str = &arr[0];
// Size - 1 to leave room for the NULL character
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
cin.getline(arr, SIZE);
length = strlen(str);
if (length == (SIZE - 1))
{
cout << "Your statement has reached or exceeded the maximum value of "
<< length << " characters long.\n";
}
else
{
cout << "Your statement is ";
cout << length << " characters long.\n";
}
system("PAUSE");
return 0;
}
//function defintion
/* get the string
count the number of characters in the string
return that number
*/
int countChars(int)
{
length = strlen(str);
return length;
}
Let's talk about what is happening in main instead:
int main()
{
Okay, so you're going to have strings of 201 characters. Seems reasonable.
const int SIZE = 201;
And you've declared an array of 201 characters:
char arr[SIZE];
And now you declare an array of 201 pointers to characters. I'm not sure why you would want to do that. I suspect you think this does something other than what it actually does:
char *str[SIZE];
This is reasonable (except "it's" means "it is", but you want the possessive version, "its"):
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
This assigns the 201st character to the first character pointer in your array of char pointers. This is an error because:
arrays are zero-indexed, so the 201st character (when you start counting at zero) is beyond the end of the array.
you haven't initialized the memory in arr to anything yet.
you're assigning a char to a char *.
So, given the above I'm not sure why you're doing this:
*str = arr[SIZE];
This looks reasonable:
cin.getline(arr, SIZE);
This is an error because str doesn't point to memory that contains a valid string at this point.
length = strlen(*str);
When you "point to a string", actually you point to the first character of the string. The end of the string can be found by looking at successive memory locations until you find a location containing a null byte. So your code should be:
char *str; // can point at a character
// ....
str = &arr[0]; // point to the first character of arr
// ....
length = strlen(str);
I want to cout my string, everything works as it should, but when the string is shown, it immediately shows me the "example_4578.exe has stopped running" error. I have noticed that the problem is in the i < str[32].length part, because when I change it to i < 3, it works without any problem. How should I solve this?
std::string str[32];
cin >> str[1];
cout << "str[1]=" << str[1] << endl;
cin >> str[2];
cout << "str[2]=" << str[2] << endl;
for (int i = 0; i < str[32].length; i++)
{
cout << str[i];
}
EDIT 1.
I've made a huge mistake. I actually want to find the "number" of elements/words in "str". In my example, I have only designed two cins. But I actually want to design a "for" loop later on, so that the user can input as many words as he wants, so if he inputs 4 words, I want that code to return those number of words to me. How should I do this? In other words, how can I find out how many elements are in "str"?
Couple of things:
C++ is 0-indexed. What this means is that std::string str[32] has indices that go from 0 to 31, and str[32] should not be accessed. This will cause a crash.
str[31].length() (which is presumably what you wanted) is the length of the last string, not the length of the array. The length of the array is 32, and your loop should read for(int i = 0; i < 32; i++).
The main problem is that you are accessing an element (number 32) that is out of the bounds (0 - 31). To solve this problem and not repeat it again in the future use a range-for loop:
std::string str[32];
for (auto s : str)
std::cout << s;
str[32].length is not what you think.
I guess you meant somthing like: length of a 32-elements array. Right?
What you've written is pointer to funciton length of 33rd element of array.
This is because the types are:
std::string str[32]; // `str` is 32-element array of `std::strings`
str[32]; // `std::string` taken from 33rd position in array `str` (arrays' indexing starts at 0)
std::string has a member function named size_t std::string::length(). When referenced by name, you get its address.
To achieve what you wanted, you'd need to write:
for (int i = 0; i < 32; i++) {
cout << str[i];
}
Unfortunately, plain arrays don't have length (or anything similar) built in. So, you'd either need to use a constant, or (better) use a container, such as std::vector.
I have 2 problems.
1) cout << v_setir.capacity(); is not returns the correct number.
2) I want to count of the words which lengths are even. and I should do it with vectors.
Here is my codes:
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
int say = 0;
cout << "Setiri daxil edin: ";
string setir;
getline(cin, setir);
vector<string> v_setir;
string ifadeler;
istringstream yig(setir);
while (yig >> ifadeler)
v_setir.push_back(setir);
// First problem
cout << v_setir.capacity() << endl;
// Second problem
/* for (size_t i = 0; i < v_setir.capacity(); i++)
{
if (v_setir[i].size() % 2 == 0)
say += 1;
}
cout << "Uzunlugu cut olan sozerin sayi: " << say << endl;*/
return 0;
}
For example, if I enter this string line it returns "6" (why I don't know):
hi hello how are you
What is wrong? my brain stopped and I couldn't determine what is the wrong in my code and/or algorithm.
Please, help me to solve these problems.
Best regards.
capacity() is the currently allocated space not the count of elements in the vector. Use: size() instead
See:
http://en.cppreference.com/w/cpp/container/vector/capacity
http://en.cppreference.com/w/cpp/container/vector/size
Your loop should work fine now, but you can also take a look at the example there which does something similar for integer divisible by 3.
You can count even-length words with std::count_if:
#include <algorithm>
int even_words = std::count_if(v_setir.begin(), v_setir.end(), [] (const string& str) { return str.size() % 2 == 0; });
1) cout << v_setir.capacity(); is not returns the correct number.
Use vector::size as the number of the element in the vector.
2) I want to count of the words which lengths are even. and I should do it with vectors.
Firstly you should use v_setir.size() instead of v_setir.capacity() in your loop as the condition.
And secondly, why not you cout the string to check whether it's length is even or not? Actually you put 5 'hi hello how are you' into the vector.
I think you want to put every single words into the vector, but not the whole sentence. If that use v_setir.push_back(ifadeler); instead of v_setir.push_back(setir);
vector::capacity gives capacity of vector (how much elements it can store). Here, you want to calculate number of strings whose length is even. You need to iterate over the strings and count the strings whose length is even.
std::vector::capacity >= std::vector::size
The capacity is the maximum number of elements the vector can currently hold.
The size is the number of elements in the vector.
#include<iostream>
using namespace std;
int main()
{
char arr[200];
while(1) {
cin >> arr;
int i = sizeof(arr);
cout << "The arr input is "<< arr
<< " and the size of the array is "<< i << endl;
}
return 0;
}
For the input of 34,
This code outputs :The arr input is 34 and the size of the array is 200
while I want it to get the size of the used space of the array . So for The last input i want it to output :The arr input is 34 and the size of the array is 2
Can someone tell me how?
Maybe you want strlen(arr) here. It must be null terminated, otherwise the cout << arr would not have worked.
You would need to #include <cstring>
There's no automatic way to do what you want in the general case - you'll need to keep track somehow, either with your own counter, or by seeding the array with an 'invalid' value (that you define) and search for to find the end of the used elements (that's what the '\0' terminator character in a C-style string is).
In the example code you posted, the array should receive a null terminated C-style string, you can use that knowledge to count the number of valid elements.
If you're using C++ or some other library that has some more advanced data structures, you may be able to use one that keeps track of this kind of thing for you (like std::vector<>).
the size of the used space of the array
There is no such thing. If you have an array of 200 chars, then you have 200 chars. Arrays have no concept of "used" and "unused" space. It only works with C-strings because of the convention that those are terminated by a 0 character. But then again, the array itself cannot know if it is holding a C-string.
in a less involved manner, you can just count through each character till you hit a null with just a while loop. It will do the exact same thing strlen() does. Also, in practice, you should do type checking with cin, but i'll assume this was just a test.
#include <iostream>
using namespace std;
int main()
{
char arr[200];
int i;
while(1) {
cin >> arr;
i=0;
while (arr[i] != '\0' && i<sizeof(arr))
i++;
cout << "The arr input is "<< arr
<< " and the size of the array is "<< i << endl;
}
return 0;
}
Just for completeness, here is a much more C++ like solution that is using std::string instead of a raw char array.
#include <iostream>
#include <string>
int
main()
{
while (std::cin.good()) {
std::string s;
if (std::cin >> s) {
std::cout
<< "The input is " << s
<< " and the size is " << s.length()
<< std::endl;
}
}
return 0;
}
It doesn't use an array, but it is the preferable solution for this kind of problem. In general, you should try to replace raw arrays with std::string and std::vector as appropriate, raw pointers with shared_ptr (scoped_ptr, or shared_array, whatever is most appropriate), and snprintf with std::stringstream. This is the first step to simply writing better C++. You will thank yourself in the future. I wish that I had followed this advice a few years ago.
Try it
template < typename T, unsigned N >
unsigned sizeOfArray( T const (&array)[ N ] )
{
return N;
}