I newly started C++ and it feels pretty wired while writing Java for a while. So, I have this array,
char values[][10] = {"miami", "seattle", "berlin"};
int rows = sizeof values / sizeof values[0];
This is this is the function where I would like to pass the value,
// a function to reverse the strings
void App::reverse(char *str) {
}
When I do the loop, I can't apparently pass the value there,
for (int i = 0; i < rows; ++i) {
// first character of the string
char *firstPtr = values[i];
reverse(firstPtr);
}
The line reverse(firstPtr) provides error which I don't understand. The error message says Too few arguments, expected 2.
What is the issue here? I apologize for any mistakes as writing the C++ for the first time and the pointer stuff feels strange.
UPDATE
This is the piece of code I would like to exexute,
void App::reverse(char* str) {
// get the first character of the string
char *ptrEnd = str;
char temp;
if (str){
while (*ptrEnd) {
ptrEnd++;
}
ptrEnd--;
// as long the first adddress is lesser than the end
while (str < ptrEnd) {
temp = *str;
*str++ = *ptrEnd;
*ptrEnd-- = temp;
}
}
}
There is too little information here to be sure, but it looks like you have
using namespace std;
Somewhere in your code. Don't do this! In this case, the standard library has a function reverse() in std that takes two parameters.
Furthermore, you have void App::reverse(char *str), but that cannot be seen from void myArray::reverse(char* str), so your own reverse() cannot be called as-is - you would need to do App::reverse() if the function is a class static.
Related
As in the title, I need to add user-specified number of spaces at the beginning of some word, using array of chars. I need to do it in a function which takes my array as a parameter and returns it. Here's my code:
#include <iostream>
using namespace std;
void writeDownCharArray(char t[], int sizee)
{
for (int i=0;i<sizee;i++)
{
cout<<t[i];
}
}
char * addSpaces(char t[], int ammountOfSpaces)
{
int numberOfCharacters=0;
for (int i=0; t[i]!=NULL; i++){numberOfCharacters++;} //checking the amount of characters in my array
char t2[numberOfCharacters+10];
for (int i=0; i<ammountOfSpaces; i++) {t2[i]=' ';} //adding the sapces
for (int i=ilosc;i<numberOfCharacters+ammountOfSpaces;i++) {t2[i]=t[i-ammountOfSpaces];} //filling my new array with characters from the previous one
return t2;
}
int main()
{
int numberOfSpaces;
char t[10];
cout << "Text some word: ";
cin.getline(t,10);
cout<<"How many spaces?: ";cin>>numberOfSpaces;
writeDownCharArray(addSpaces(t, numberOfSpaces), HERE);
return 0;
}
And now: How do I print it to the screen? If I say cout<<addSpaces(t, numberOfSpaces); it actually prints something strange to the screen (not numbers, just strange characters). And if I say writeDownCharArray, then what should I put in "HERE" place?
The C++ way to solve this would be to use a std::string like
std::string add_spaces(const std::string & line, std::size_t number_of_spaces)
{
std::string spaces(number_of_spaces, ' ');
return spaces + line;
}
If you cannot use std::string then you are doing to have to deal with dynamic memory allocations and change
char t2[numberOfCharacters+10];
to
char * ts = new char[numberOfCharacters + ammountOfSpaces + 1];
We have to have this as Variable length arrays are not standard and trying to return a pointer to an array declared in a function will leave you with a dangling pointer and trying to use it is undefined behavior.
Since new[] was used in the function you will need to remember to call delete[] on the pointer that is returned after you are done with it. This is another benefit of using a std::string as it takes care of itself.
As far as writeDownCharArray is concerned you do not need a size parameter as cout can handle null terminated c-strings. You can simply have
void writeDownCharArray(char t[])
{
cout<<t;
}
And then you main would look like
char * foo = addSpaces(t, numberOfSpaces);
writeDownCharArray(foo);
delete [] foo;
[PLEASE CHECK FINAL EDIT BELOW FOR UPDATE]
My C++ is a bit rusty (to say the least) and I'm having an issue trying to pass a char array into a function to manipulate the values. Example code below:
void myFunction(char* splitStrings,String stringToSetInLoop) {
char substringPtr[stringToSetInLoop.length()];
stringToSetInLoop.toCharArray(substringPtr, stringToSetInLoop.length());
for(int i = 0; i < 10; i++) {
splitStrings[i] = *substringPtr;
}
}
char *mySplitStrings[10];
myFunction(*mySplitStrings,String("Repeat Me"));
Serial.println(mySplitStrings[0]);
The code does not crash, but it outputs a blank line. I suspect that I need to initialize a 2 dimensional array outside the function to pass in so that memory space is allocated. I'm guessing that, although the substring pointer exists inside the function, the memory is destroyed, leaving the char* array mySplitStrings[0] pointing at nothing. Also, I think I need to pass in the reference to the array memory space, not as a pointer.
The ultimate goal here is to be able to pass a char array into a function, assign some values to it, then use those values back in the main code loop. If there's a better way to achieve this, then please let me know.
Thanks in advance. Please free me from my personal pointer/reference hell!
EDIT: Further note, this code is being run on an arduino, so the C++ is limited.
EDIT: When I try to pass in a reference to the char* pointer, I get this error, which I'm not sure how to change the function parameters to fix: error: cannot convert char* ()[10] to char for argument 1 to void myFunction(char*, String). Can anybody please take a stab at showing me a working example?
EDIT:
Thanks to the responses... I now have a working static library function that splits strings passed as a char* array. I know it's not pretty, but it does work. Thanks you to those who contributed. Code below:
void ExplodeString::explode(char* explodeResults[], String str, String delimiter) {
int delimiterPosition;
int explodeResultsCounter=0;
String subString;
do {
delimiterPosition = str.indexOf(delimiter);
if(delimiterPosition != -1) {
subString = str.substring(0,delimiterPosition);
char *subStringPtr[subString.length()+1];
subString.toCharArray(*subStringPtr, subString.length()+1);
explodeResults[explodeResultsCounter++] = strdup(*subStringPtr);
str = str.substring(delimiterPosition+1, str.length());
} else { // here after the last delimiter is found
if(str.length() > 0) {
subString = str;
char *subStringLastPtr[subString.length()+1];
subString.toCharArray(*subStringLastPtr, subString.length()+1);
explodeResults[explodeResultsCounter++] = strdup(*subStringLastPtr);
}
}
} while (delimiterPosition >=0);
}
Usage:
char* explodeResults[10];
ExplodeString::explode(explodeResults, String("cat:dog:chicken"), String(":"));
Serial.println(explodeResults[0]);
Serial.println(explodeResults[1]);
Serial.println(explodeResults[2]);
EDIT: Man, this is sooo much easier when you use the stdlib:
void ExplodeString::explode(std::vector<std::string> &explodeResults, std::string str, char delimiter) {
std::stringstream data(str);
std::string line;
while(std::getline(data,line,delimiter))
{
explodeResults.push_back(line);
}
}
Usage:
std::vector<std::string> commandsResult;
char delimiter[] = ",";
std::string _inputString = "my,string,to,parse";
ExplodeString::explode(commandsResult, _inputString, delimiter[0]);
How to pass an array of char*:
void myFunction(char* splitStrings[10], String stringToSetInLoop) {
// ...
char *mySplitStrings[10];
myFunction(mySplitStrings, String("Repeat Me"));
This will also work:
void myFunction(char* splitStrings[], String stringToSetInLoop) {
and this:
void myFunction(char** splitStrings, String stringToSetInLoop) {
Also, seems there is STL for avr platform - include it, C++ without STL is smth strange.
You are not allocating space for character arrays and just passing pointer of character array.
Instead of using char*splitStrings[10], you can use 2d char array with sufficient space to accomodate max length string. Assuming you max string length is less that 64 you can do something like this.
char splitString[10][64];
void myFunction(char**splitStrings,String stringToSetInLoop)
or
void myFunction(char splitString[][64], String stringToSetInLoop)
{
int len = stringToSetInLoop.length();
for(int i = 0; i<10; i++)
{
for(int j = 0; i<len; j++)
{
splitString[i][j] = stringToSetInLoop.charAt(j);
}
}
}
I am new to C++ and this is the error I keep getting and I have no idea what it is. It says that at the display function line. It has this error
invalid conversion from 'char' to 'char*' [-fpermissive]|
May I know what is the meaning of this error and how to solve it ?
void passChar()
{
char letter[] = {'H','E','L','L','O','!'};
for(int i = 0; i<6; i++)
{
while(true)
{
display(letter[i]);
swapLetter(letter[i]);
}
}
}
Here is my display function
void display(char letter[])
{
for(int i = 0 ; i<6 ; i++)
{
switchStatement(letter[i]);
}
}
Here is my swapletter function
void swapLetter(char letter[])
{
char temp = letter[0];
for(int i = 1; i < 6; i++)
{
letter[i-1] = letter[i];
}
letter[5]= temp;
}
My aim is to have endless loop for the word hello.
Your code is invalid in whole because this loop
while(true)
{
display(letter[i]);
swapLetter(letter[i]);
}
is infinite unless either display or swapLetter does not have call to exit.
As for error then it is obvious from the error message that the function expects to get some string instead of on character. So its parameter is declared something as char s[] or char *s, or const char s[], or const char *s and so on.
And even if you would pass to it your array letter it would be a mistake because your array has no the terminating zero. I think you should declare your array as
char letter[] = {'H','E','L','L','O','!', '\0'};
Or function display should be declared as
void display( char c );
Presumably because your display() function looks like the following:
void display(char* value)
{ }
letter[i] is of type char, the above function expects char*...
It means that you are passing a char as a parameter to a function that expects char*.
Your functions actually expect you to pass the entire string rather than a single character. So your code should be:
display(letter);
swapLetter(letter);
Of course, I suspect that renders the outer loop in passChar meaningless. And the infinite while(true) loop seems odd, although you claim in the question that it is intentional. In which case the code should read:
void passChar()
{
char letter[] = {'H','E','L','L','O','!'};
while(true)
{
display(letter);
swapLetter(letter);
}
}
Personally I think I would code display and swapLetter to accept char* and use the null-terminator to detect length.
void passChar()
{
char letter[] = "HELLO!";
while(true)
{
display(letter);
swapLetter(letter);
}
}
and then modify display and swapLetter to use the null-terminator to locate the end of the string.
So I'm making a function that is similar to SubStr. This is an assignment so I cannot use the actual function to do this. So far I have created a function to take a string and then get the desired substring. My problem is returning the substring. In the function when I do Substring[b] = AString[b]; the substring is empty, but if I cout from inside the function I get the desired substring. So what is wrong with my code?
Here is a working demo: http://ideone.com/4f5IpA
#include <iostream>
using namespace std;
void subsec(char AString[], char Substring[], int start, int length);
int main() {
char someString[] = "abcdefg";
char someSubString[] = "";
subsec(someString, someSubString, 1, 3);
cout << someSubString << endl;
return 0;
}
void subsec(char AString[], char Substring[], int start, int length) {
for (int b = start; b <= length; b++) {
Substring[b] = AString[b];
}
}
Maybe this does what you're looking for? It's hard to say as your initial implementation used the length parameter as more of an end position.
#include <iostream>
using namespace std;
void subsec(char AString[], char Substring[], int start, int length)
{
const int end = start + length;
int pos = 0;
for(int b = start; b < end; ++b)
{
Substring[pos++] = AString[b];
}
Substring[pos] = 0;
}
int main()
{
char someString[50] = "abcdefghijklmnopqrstuvwxyz";
char someSubString[50];
subsec(someString, someSubString, 13, 10);
cout << someSubString << endl;
return 0;
}
There are several problems with the code:
1) The char arraysomeSubString has size 1 which cannot hold the substring.
2) The subsec is not correctly implemented, you should copy to the Substring from index 0.
Also remember to add \0 at the end of the substring.
void subsec(char AString[], char *Substring, int start, int length) {
int ii = 0;
for (int jj = start; jj <= length; jj++, ii++) {
Substring[ii] = AString[jj];
}
Substring[ii] = '\0';
}
You need to allocate more than 1 byte for someSubString i.e.
char someSubString[] = "xxxxxxxxxxxxxxxxxx";
or just
char someSubString[100];
if you know the max size you'll ever need.
Either would allocate enough space for the string you're copying to it. Then, you're not doing anything about the terminating 0 either. At the end of a C-style string there needs to be a terminating null to signify end of string. Otherwise cout will print something like;
abcdefgxxxxxxx
if you initialized with x's as I indicated.
There are a few problems with your code as it stands. Firstly, as your compiler is no doubt warning you, in C++ a string literal has type const char[], not just char[].
Secondly, you need to have enough space to store your substring. A good way to do this is for your function to allocate the space it needs, and then pass back a pointer to this memory. This is the way things are typically done in C code. The only thing is that you have to remember to delete the allocated array when you're done with it. (There are other, better ways to do this in C++, with things like smart pointers and wrapper objects, but those come later :-) ).
Thirdly, you'll have a problem if you request a length which is actually longer than the passed-in string -- you'll run off the end and start copying random memory (or just crash), which is definitely not what you want. C strings are terminated with a "nul byte" -- so you need to check whether you've come across this.
Speaking of the nul, you need to make sure that your substring ends with one.
Lastly, it's not really a problem but there's no need for the start parameter, you can just pass a pointer to the middle of the array if you want to.
char* substring(const char* str, int length)
{
// Allocate memory for substring;
char* subs = new char[length+1];
// Copy characters from given string
int i = 0;
while (i < length && str[i] != '\0') {
subs[i] = str[i];
i++;
}
// Append the nul byte
subs[i] = '\0';
return subs;
}
int main()
{
const char someString[] = "foobarbaz"; // Note -- must be const in C++
char* subs = substring(someString + 3, 3);
assert(strcmp(subs, "bar") == 0);
delete subs;
}
EDIT: I don't want to delete the post because I have learned a lot very quickly from it and it might do someone else good, but there is no need for anyone else to spend time answering or viewing this question. The problems were in my programming fundamentals, and that is something that just can't be fixed in a quick response. To all who posted, thanks for the help, quite humbling!
Hey all, I'm working on building my own string class with very basic functionality. I am having difficulty understand what is going on with the basic class that I have define, and believe there is some sort of error dealing with the scope occurring. When I try to view the objects I created, all the fields are described as (obviously bad pointer). Also, if I make the data fields public or build an accessor method, the program crashes. For some reason the pointer for the object is 0xccccccccc which points to no where.
How can a I fix this? Any help/comments are much appreciated.
//This is a custom string class, so far the only functions are
//constructing and appending
#include<iostream>
using namespace std;
class MyString1
{
public:
MyString1()
{
//no arg constructor
char *string;
string = new char[0];
string[0] ='\0';
std::cout << string;
size = 1;
}
//constructor receives pointer to character array
MyString1(char* chars)
{
int index = 0;
//Determine the length of the array
while (chars[index] != NULL)
index++;
//Allocate dynamic memory on the heap
char *string;
string = new char[index+1];
//Copy the contents of the array pointed by chars into string, the char array of the object
for (int ii = 0; ii < index; ii++)
string[ii] = chars[ii];
string[index+1] = '\0';
size = index+1;
}
MyString1 append(MyString1 s)
{
//determine new size of the appended array and allocate memory
int newsize = s.size + size;
MyString1 MyString2;
char *newstring;
newstring = new char[newsize+1];
int index = 0;
//load the first string into the array
for (int ii = 0; ii < size; ii++)
{
newstring[ii] = string[ii];
index++;
}
for(int jj = 0; jj < s.size; jj++, ii++)
{
newstring[ii] = s.string[jj++];
index++;
}
//null terminate
newstring[newsize+1] = '\0';
delete string;
//generate the object for return
MyString2.string=newstring;
MyString2.size=newsize;
return MyString2;
}
private:
char *string;
int size;
};
int main()
{
MyString1 string1;
MyString1 string2("Hello There");
MyString1 string3("Buddy");
string2.append(string3);
return 0;
}
EDIT:
Thank you everyone so far who has responded and dealing with my massive lack of understanding of this topic. I'll begin to work with all of the answers, but thanks again for the good responses, sorry my question is vague, but there isn't really a specific error, but more of a lack of understanding of arrays and classes.
Here's just the mistakes from the first constructor.
MyString1()
{
//no arg constructor
char *string; //defines local variable that hides the member by that name
string = new char[0]; //sort of meaningless
string[0] ='\0'; //not enough room for that (out-of-bounds)
std::cout << string;
size = 1; //I don't think you should count null as part of the string
}
Similar mistakes elsewhere.
Also you should pass parameters in a more careful way.
MyString1(const char* source); //note const
MyString1 append(const MyString1& what); //note const and reference
If the latter is correct, also depends on what it is supposed to do. Based on std::string the expected result would be:
MyString1 a("Hello "), b("world");
a.append(b);
assert(a == "Hello world");
Some comments on your code:
MyString1()
{
//no arg constructor
Perhaps your instruction requires it, but in general this is the kind of comment that's worse than useless. Comments should tell the reader things that aren't obvious from the first glance at the code.
char *string;
string = new char[0];
string[0] ='\0';
This invokes undefined behavior. Calling new with zero elements is allowed, but you can't dereference what it returns (it may return a null pointer, or it may return a non-null pointer that doesn't refer to any storage). In most cases, you're better off just setting the pointer to NULL.
std::cout << string;
What's the point of writing out an empty string?
size = 1;
The string is empty so by normal figuring, the size is zero.
//constructor receives pointer to character array
Still useless.
MyString1(char* chars)
Since you aren't (or shouldn't be anyway) planning to modify the input data, this parameter should be char const *.
{
int index = 0;
//Determine the length of the array
while (chars[index] != NULL)
index++;
While this works, "NULL" should really be reserved for use as a pointer, at least IMO. I'd write it something like:
while (chars[index] != '\0')
++index;
Unless you're using the previous value, prefer pre-increment to post-increment.
//Allocate dynamic memory on the heap
As opposed to allocating static memory on the heap?
MyString1 MyString2;
Using the same naming convention for types and variables is confusing.
while (string[index] != NULL)
Same comment about NULL as previously applies here.
MyString1 append(MyString1 s)
IMO, the whole idea of this function is just plain wrong -- if you have a string, and ask this to append something to your string, it destroys your original string, and (worse) leaves it in an unusable state -- when you get around to adding a destructor that frees the memory owned by the string, it's going to cause double-deletion of the storage of a string that was the subject (victim?) of having append called on it.
I'd consider writing a private "copy" function, and using that in the implementations of some (most?) of what you've shown here.
As a bit of more general advice, I'd consider a couple more possibilities: first of all, instead of always allocating exactly the amount of space necessary for a string, I'd consider rounding the allocation to (say) a power of two. Second, if you want your string class to work well, you might consider implementing the "short string optimization". This consists of allocating space for a short string (e.g. 20 characters) in the body of the string object itself. Since many strings tend to be relatively short, this can improve speed (and reduce heap fragmentation and such) considerably by avoiding doing a heap allocation if the string is short.
index doesn't start at 0 in the second while loop in your append function. You should probably be using for loops. Oh, and you're using the wrong form of delete. You should be using delete[] string because string is an array.
There are numerous other style issues, and outright errors, but the thing I mentioned first is the basic error you were encountering.
I would write the append function in this way:
void append(MyString1 s)
{
//determine new size of the appended array and allocate memory
int newsize = s.size + size;
char *newstring = new char[newsize+1];
int destindex = 0;
for (int index = 0; index < size; ++index) {
newstring[destindex++] = string[index];
}
for (int index = 0; index < s.size; ++index) {
newstring[destindex++] = s.string[index];
}
newstring[destindex] = '\0';
delete[] string;
string = newstring;
}