Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Is it possible to count the length of the contents of an array of pointers:
For example
char *str[MAX] = {"kendrick", "lamar"};. the length of str[0] is 8 and str[1] is 5. Is there a way of getting these values.
You can verify if each pointer is NULL or not:
int count = 0;
for(int i = 0; i < MAX; i++)
if(str[i] != NULL)
count++;
printf("Count: %d\n", count);
As noted by others, it is not clear what you are exactly asking about.
In a hurry, I wrote the following code to give multiple outputs so you may find what you are looking for:
1- Length of each item by using strlen() function.(ilength)
2- Total length of the items by adding up individual lengths. (ilength).
3- Number of items in the array by counting non NULL (items).
int main()
{
const int MAX = 10;
char* str[MAX] = {"Hello", " World","!",""};
int ilength, length = 0, items = 0;
for(int i = 0; i < MAX; ++i)
if (str[i] != NULL)
{ ilength = strlen (str[i]);
// WARNING!!! ISO C++ forbids converting a string constant to 'char*'
cout << i << " item length is " << ilength << "\n";
length = length + ilength;
items += 1;
}
cout << "\nTotal length of all items is: " << length << "\n\n";
cout << "\nThere is/are " << items << " in the array.\n\n";
}
NOTE: If you use C++ compiler, pay attention to the warning:
WARNING!!! ISO C++ forbids converting a string constant to 'char*'
If you know the strings are all null-terminated, you can use strlen.
Your question is a bit confusing as it is not clear what length you want. Therefore for both possibilities:
Length of array in use:
char *str[MAX] = {"kendrick", "lamar"}; is an array of size MAX with two entries, which are pointers to strings. The compiler will initialize all other entries to zero, so counting how many entries of str are non-zero will give you that answer.
Length of the strings:
A string in C is null terminated. So for each entry of str that is not null you can advance and advance until you encounter a null character. That tells you the length of that entry.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!
...
//initializing first 2D dynamic array
int x=2;
int y=2;
int** array = new int*[x];
for(int i=0; i<x; i++) array[i] = new int[y];
//initializing second 2D dynamic array
int new_x=3;
int new_y=3;
int** temp = new int*[new_x];
for(int i=0; i<new_x; i++) temp[i] = new int[new_y];
//assigning values
array[0][0] = 1;
cout << array[0][0] << endl; //output is 1
//before assigning values to temp[0][0]
cout << temp[0][0] << endl; //out is a huge random number
temp[0][0] = array[0][0];
cout << temp[0][0] << endl; //output is the same huge random number
temp[0][0] = 2;
cout << temp[0][0] << endl; //output is 2
...
Memory under temp[0][0] is allocated dynamically, therefore that's why you're getting some random (garbage) stuff out of it before assigning 2. When you're assigning 2, the random garbage that's been there gets "overwritten" by a meaningful value, in your case 2 of int type
The code snippet you posted works exaclty as it should:
First cout prints 1 witch is the value of array[0][0].
Second cout prints the uninitialized temp[0][0], I compiled it here, and in this case the value is 0, but it could be anything.
Third cout prints 1 due to the assingment temp[0][0] = array[0][0].
Fourth cout prints the value of 2 assigned to temp[0][0].
If there are problems in your code it's not in the posted bit, aside from the fact that you are trying to print an unitialized variable in the second cout
I have tried running the code,and the output indeed is 1 after assigning the value.
This question already has answers here:
Cout a whole array in c++
(7 answers)
Closed 3 years ago.
I'm trying to implement a function that will parse numbers for a calculator assignment that I have been given. A for loop has been set up that will iterate through each index in the input array which is a arithmetic equation e.g "1+2+3+4+5". I created a function isDigit() that will return true or false if the character is between 0 and 9. This is how I am parsing the numbers. My problem is that the numbers are not being permanently stored in my numbers[] array which I would like to return.
Currently the numbers are being printed to the console with the first cout as "12345" but with the second cout (currently commented) which to check what my returned array stores is an ambiguous hex number. Can someone please help me to return "12345" in numbers[].
int * parseNumbers(char input[])
{
static int numbers[10];
for (int i = 0; i < strlen(input); i++)
{
if (isDigit(input[i]))
{
numbers[i] = input[i] - '0';
cout << numbers[i];
}
}
//cout << numbers << endl;
return(numbers);
}
numbers = 1, 2, 3, 4, 5
currently getting numbers = 002D26E8
I think what you're looking for is atoi to convert char to int.
Instead of using numbers[i] = input[i] - '0';
try this:
numbers[i] = atoi(input[i]);
Make sure to have #include <stdlib.h> if not aready added
Reference: http://www.cplusplus.com/reference/cstdlib/atoi/
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 6 years ago.
Improve this question
Here it is:
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>
using namespace
int main()
{
//cout << "How many players?" << endl;
int numplayers=1;
//cin >> numplayers;
int players[numplayers];
int x=0,y=0;
srand(time(0));
x=(rand() % 6 + 1);
y=(rand() % 6 + 1);
players[1]=players[1]+x+y;
cout << ("Your score is" + players[1]) << endl;
cin >> numplayers;
}
Ok My original problem was that this always crashed, now it prints "#"???
C++ arrays are 0 based.
players[1] is accessing a location outside the range of the array.
You will want: players[0].
cout << ("Your score is" + players[1]) << endl;
Here you're trying to use direct string concatenation, but you can't concatenate a string literal with an integer like that. You end up doing pointer arithmetic, which is definitely not what you intended.
You should instead use cout's built-in formatting:
cout << "Your score is" << players[1] << endl;
Your next problem is that players is not declared correctly; an array cannot have runtime bounds, and numplayers (despite having only the one initial value) is ultimately a "runtime" variable. You would be better off with a std::vector if the size of the array is going to change later; otherwise make numplayers a constexpr.
Your last problem is that, if the array declaration were valid, you'd be trying to access the second element of a one-element array! The first element is players[0], not players[1].
There are many things you're doing not good.
I believe you're using C++, there is no known way to me about creating arrays of dynamic size i.e. int players[numplayers]. In C++ either we can create array of fixed size i.e. int players[10] or use pointer to an array for dynamically allocated memory e.g. int* players = new int[numplayers]. This allocates an array of size numplayers and an int pointer named players is pointing to it. We can use this pointer as normal array e.g. printing 1st index of array is written as player[0] or another syntax is *(player + 0). Remember to delete this dynamically allocated memory at the end of program i.e. delete[] player.
Second thing is when you have allocated an array and are using its value for computation, always initialize it to 0 as newly allocated array contains garbage value and it will affect your computations. code for initializing it to zero may be like this:
Here is the loop:
for(int i = 0 ; i < numplayers ; i++){
player[i]=0;
//another syntax is : *(player + i) = 0;
}
C++ does not concat as you did in your std::cout statement. Make it like this:
cout << "Your score is" << players[0] << endl;
In C++, arrays always start with index zero, so 1st index will be 0 in this case. So your program will work well if it is like this:
int numplayers = 1;
int* players = new int[numplayers];
int x = 0, y = 0;
srand(time(0));
x = (rand() % 6 + 1);
y = (rand() % 6 + 1);
players[0] = 0;
players[0] = players[0] + x + y;
cout << "Your score is" << players[0] << endl;
delete[] players;
return 0;
Definitely it crashes for the below line:
players[1]=players[1]+x+y;
Because size of players array is 1, so it has only index 0. And in above line, it tries to access index 1. Take a look at Buffer Overflow and array index out of bounds.
Try to define an array with constant size.
If you need a dynamic array, use linked list or vector.
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 6 years ago.
Improve this question
This is the code:
int main(){
string word= "word";
char ciphered[word.length()];
for(int i=0; i<word.length(); i++)
{
int current_position = (int) word[i];
int new_position = current_position + 2;
char this_char = (char) new_position;
ciphered[i] = this_char;
}
string str(ciphered);
cout << str << endl ;
}
When i run this it prints this:
But when i do this:
for(int i = 0; i<sizeof(ciphered); i++)
{
cout << ciphered[i] << endl ;
}
it prints out the same thing but without last three signs and that is correct
but whenever i try to convert this char array to string it adds these last three weird signs and i dont know why
First of all, this:
char ciphered[word.length()];
is not legal C++ code, though gcc may accept it. But second that you do not need really that char array, as you can access individual symbols with std::string itself:
string word= "word";
string ciphered( word.length(), ' ' );
for(int i=0; i<word.length(); i++)
{
ciphered[i] = word[i] + 2;
}
cout << ciphered << endl;
your code prints additional symbols because you did not put null terminator on C-style string and sent it through std::ostream which leads to UB and prints garbage that happens in memory after your char array until it suddenly finds null terminator or crash because of access of invalid memory.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to store this string into an an array.
space= 0
A,a =1
B, b =2
C , c = 3
.
.
Z, z= 26
string myArray[26] =
{ "A", "B", "C", "D",”E”,”F”,”G”,”H”,”I”,”J”,”K”,”L”,”M”,”N”,”O”,”P”,
”Q”,”R”,”S”,T”,”U”,”V”,W”,X”,”Y”, ”z” };
for (int i = 0; i < myArray; i++)
{
myArray[] = myArray[i]
cerr << myArray[i] << endl << endl;
}
Is that how to get each character with number?
What you've got is an array of strings, not an array of characters. A string is a container of characters, in the sense that it is capable of holding multiple characters. Your task can be solved with one or two strings, depending on your design preferences (see below).
A, a =1
B, b =2
You are placing two characters per position. However, strings cannot hold more than one character at a single index. If you need both the upper and lower case character to occupy the same spot, you need to make either two strings, or two spots.
Here is the first approach (two strings):
string upper = " ABCDEF...";
string lower = " abcdef...";
int pos = ...; // The desired position
cout << upper[pos] << endl;
cout << lower[pos] << endl;
Here is the second approach (two positions):
string pairs = " AaBbCcDdEeFf...";
int pos = ...; // The desired position
cout << pairs[2*pos] << endl; // Upper
cout << pairs[2*pos+1] << endl; // Lower