I am trying to understand pointers a little better and have a hard time to figure out why my code causes a debug assertion failure.
When i comment out "while (*neu++ = *s++);" and comment in "strcopy(neu, s);" it works just fine. Shouldn't they do the same?
#include <iostream>
#include <cstring>
using namespace std;
void strcopy(char* ziel, const char* quelle)
{
while (*ziel++ = *quelle++);
}
char* strdupl(const char* s)
{
char *neu = new char[strlen(s) + 1];
while (*neu++ = *s++);
//strcopy(neu, s);
return neu;
}
int main()
{
const char *const original = "have fun";
cout << original << endl;
char *cpy = strdupl(original);
cout << cpy << endl;
delete[] cpy;
return 0;
}
strcopy takes a copy of the pointer neu, so neu still points to the beginning of the string when you return it. With the while loop inside of strdup1 you are modifying neu before you return it. Calling delete on this pointer causes the failure because it's different from what was new'd.
The solution is to use a temporary variable to increment and copy over the string.
char *neu = ...
char *tmp = neu;
while (*tmp++ = *s++);
return neu;
Related
I'm a newbie in C++ learning the language and playing around. I wrote a piece of code which behavior I don't understand. Could someone explain why the code below prints out random junk and not the first character of the first string in the list (that is a).
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <stdio.h>
char* str2char(std::string str)
{
char cset[str.size()+1]; // +1 for the null character
for(int i = 0; i < str.size(); i++)
{
cset[i] = str[i];
}
cset[str.size()] = '\0';
return cset;
}
int main (int argc, char * const argv[]) {
std::vector< std::string > ladontakadet;
ladontakadet.push_back("aabcbbca");
ladontakadet.push_back("abcdabcd");
ladontakadet.push_back("cbbdcdaa");
ladontakadet.push_back("aadcbdca");
ladontakadet.push_back("cccbaaab");
ladontakadet.push_back("dabccbaa");
ladontakadet.push_back("ccbdcbad");
ladontakadet.push_back("bdcbccad");
ladontakadet.push_back("ddcadccb");
ladontakadet.push_back("baccddaa");
std::string v = ladontakadet.at(0);
char *r;
r = str2char(v);
std::cout << r[0] << std::endl;
return 0;
}
Why is my returning garbage, when I'm expecting it to output a?
Thnx for any help!
P.S. The output of this code is random. It doesn't always print the same character..:S
It's because you return a pointer to a local variable, a local variable that goes out of scope when the function returns.
You are already using std::string for the argument, use it instead of the array and the return pointer.
If your aim is to pass the content of a std::string to a function modifying the content of a char*:
#include <iostream>
#include <vector>
void f(char* s) {
s[0] = 'H';
}
std::vector<char> to_vector(const std::string& s) {
return std::vector<char>(s.c_str(), s.c_str() + s.size() + 1);
}
int main(void)
{
std::string s = "_ello";
std::vector<char> t = to_vector(s);
f(t.data());
std::cout << t.data() << std::endl;
}
Your function is returning garbage because you're returning the address of a local variable which goes out of scope after your function returns. It should probably look like this:
char* str2char(const std::string &str)
{
char *const cset = new char[str.size() + 1]; // +1 for the null character
strcpy(cset, str.c_str());
return cset;
}
You will need to delete your variable r by doing delete[] r;. Ideally though you wouldn't be using raw pointers, and you would use std::string for everything, or wrap the char * in a std::unique_ptr.
I have an example that I've been looking over and I'm trying to figure out how to write the .h and .cpp files by looking at the main file and the output
I have a class called Flex:
#include <iostream>
#include "flex.h"
using namespace std;
int main()
{
Flex a, b("Merry"), c("Christmas");
cout << a << ',' << b << ',' << c << endl;
b.cat(a);
cout << b << endl;
b.cat(c);
cout << b << endl;
c.cat(c);
c.cat(c);
cout << c << endl;
return 0;
}
Execution output is:
* *,*Merry*,*Christmas*
*Merry *
*Merry Christmas*
*ChristmasChristmasChristmasChristmas*
And then, the declaration/definition files should look like this:
#include <iostream>
using namespace std;
class Flex
{
friend ostream& operator<< (ostream& s, const Flex& f);
public:
Flex(); // default constructor
Flex(const char *); // constructor with parameters
~Flex(); // destructor (not specifically required)
void cat(const Flex & f); // cat function -- concatenation
private:
char * str; // variable length string
int size;
};
and
#include <iostream>
#include <cstring>
#include "flex.h"
using namespace std;
ostream& operator<< (ostream& s, const Flex& f)
{
s << '*' << f.str << '*';
return s;
}
Flex::Flex()
{
size = 1; // size doesn't include null char
str = new char[size+1]; // allocate +1 for null char
strcpy(str," ");
}
Flex::Flex(const char * s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
}
Flex::~Flex()
// not specifically required by the specs, but a good idea to have this
{
delete [] str;
}
void Flex::cat(const Flex & f)
// this function can also be made easier through the use of the
// strcat library function for concatenating strings.
// dyanamic reallocation still required, though.
{
int newsize = size + strlen(f.str);
char * temp = new char[newsize+1]; // allocate with room for '\0'
strcpy(temp,str); // copy this string to temp
for (int i = 0; i <= f.size; i++)
temp[size+i] = f.str[i]; // concatenate f.str to temp,
// including '\0'
delete [] str; // delete old array
str = temp; // set str to new one
size = newsize; // update size tracker
}
This question might be hard to explain, but how does one look at the main program and immediately knows what class he has to write?
I need to do this for a class that involves stats. I do not have a main program yet, but what would we be different since I wouldn't use chars anymore ?
How would I go about representing a stats class just by looking at a main file and output ?
Operator << sends '*' << f.str << '*'(Where f.str it`s your, Flex object, str value ) You have constructor of class Flex
Flex::Flex()
{
size = 1; // size doesn't include null char
str = new char[size+1]; // allocate +1 for null char
strcpy(str," ");
}
Flex::Flex(const char * s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
}
When your initialize object like Flex a("Test"). Your a.str == "Test". When Flex a(), then a.str == "". Function cat is concatanation 2 value. If b.cat(a) it`s mean that b.str = b.str + a.str
I need to pass a char pointer to function, then change the value that it points to inside the function and print values outside the function.
The problem I have is that I'm losing it when I leave function and try to print it outside. What can I do to avoid this?
This is an code example:
char array[] = "Bada boom";
char *pText = array;
reverseText(pText);
cout << (pText);
cout should print
moob adaB
When I print inside the function, everything is fine(it prints reversed).
My task is to print It out outside the function (as you can see in a 4th line of code)
This is the full of code which have the bug (printing inside func works, outside didn't work)
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
char reverseText(char *text);
int main(){
char array[] = "Bada boom";
char *pTekst = array;
reverseText(pTekst);
cout << (pTekst); //in here it doesn't work
}
char reverseText(char *text){
char befRev[100]; int lenght=-1;
/*until *text doesn't meet '\0' */
for(int i=0;*text!='\0';i++){
befRev[i]=(*text);
text++;
lenght++;
}
/*reversing*/
int j=0;
for(int i=lenght;i>=0;i--){
*(text+j)=befRev[i];
j++;
}
for(int i=0;i<=lenght;i++) //in here it does print the right value
cout << text[i];
};
Just re-arrange the array in-place. The pointer itself doesn't need to change:
#include <cstring>
#include <algorithm>
void reverseText(char* array)
{
auto len = std::strlen(array);
std::reverse(array, array+len);
}
int main()
{
char array[] = "Bada boom";
char *pText = array;
reverseText(pText);
std::cout << pText << std::endl;
}
Output:
moob adaB
If you really wanted to provide a pointer that points to a different address to the caller, you could simply return it:
char* foo(char* stuff)
{
char* tmp = ....;
...
// do some stuff
...
return tmp;
}
Alternatively, you could pass the pointer by reference, but the intent is less clear than in the previous version:
void foo(char*& stuff)
{
stuff = something_else;
}
But in both cases, you must make absolutely sure the thing the new pointer points to is valid outside of the function. This might require some dynamic memory allocation. For your case, it seems the best and simplest option is to re-arrange the array in place.
To answer your question, you have an error in logic. Notice that in your first loop in reverseText you increment the local pointer text. In your second loop you did not reset text to it's original value so beforeRev is being copied over starting at location text+offset.
If you were to look at pText on return from call to reverseText you would find it contains:
"Bada boom\0moob adaB"
Your reverseText should be renamed palindrome :)
This is pretty straightforward. Some points to note:
An array decays to a pointer when you pass it to a function.
You are passing in a null terminated string. So the length of the char array you are passing in is the length of the string (including white space) +1.
Because you are using a pointer there is no need to assign a temp variable to hold everything.
Here is some code in C that is easy to translate to C++. Working out the actual reverse algorithm is left for you as an exercise.
#include<stdio.h>
void reverseText(char* text)
{
// Hint: It can be done in one loop!
int i;
for(i = 0; i < 9; i++)
{
// Your algorithm to reverse the text. I'm not doing it for you! ;)
*(text + i) = 'r';
}
}
int main()
{
char array[] = "Bada boom";
reverseText(array);
printf("The text reversed: %s\n", array);
return 0;
}
My final code:
#include <iostream>
void reverseText(char* text){
int length=-1; char tmp;
/*Length = sign from 0 to 8 without counting explicit NUL terminator*/
for(int i=0;*(text+i)!='\0';i++){
length++;
}
int j=0; int i=length;
while(j<i){
tmp=*(text+j); //tmp=first
*(text+j)=*(text+i); //first=last
*(text+i)=tmp; //last=tmp
j++;
i--;
}
}
int main(){
char array[] = "Bada boom";
char *pText = array;
reverseText(pText);
std::cout << pText;
}
I should have read more about pointers before I started this exercise.
You can either return a pointer or pass a pointer to pointer as a function argument.
//pointer to pointer
void reverseText(char** textPtr) {
char* newText = ...; //initialize;
...
*textPtr = newText; //assign newText
}
//return pointer
char* reverseText(char* text) {
char* newText = ...; //initialize
return newText;
}
Remember that if you allocate memory in this function you must do it dynamically (with new or malloc) and you have to free it afterwards (with delete or free respectively). Memory allocation in a function like this is probably a bad practice and should be avoided.
Ok so this code does compile, and it does run, but it does NOT give me the correct output for EITHER the original or reverse array, just gibberish. I spent the last 4 hours trying to see where I went wrong (it wasn't working at all before and now that I got it to at least output what SHOULD be a C-string, i get gibberish). Someone please help me see where I went wrong.
#include <iostream>
#include <cstring>
using namespace std;
char* getInput();
char* getReverse(char[], int);
void displayResults(char *, char *);
const int MAX_SIZE = 21;
int main()
{
//program to create a c-string and then output the reverse order
char *original;
char *reverse;
original = getInput();
int originalSize = strlen(original);
reverse = getReverse(original, originalSize);
displayResults(original, reverse);
return 0;
}
/***************************************************
Definition of function- getInput: *
prompts the user to enter in a line of text to a *
max amount of characters. Returns a pointer to the *
C-string array. *
****************************************************/
char* getInput()
{
char *originalptr;
char original[MAX_SIZE];
cout << "Enter a word or line of text up to a max of 20 characters\nand will have it output in reverse!" << endl;
cin.getline(original, MAX_SIZE);
originalptr = original;
return originalptr;
}
char* getReverse(char *reverseThis, int size)
{
char* reverseOutput;
char reverse[MAX_SIZE];
int counter = 0;
while(*reverseThis != '\0')
{
reverse[counter] = *(reverseThis + (size - counter));
reverseThis++;
counter++;
}
reverseOutput = reverse;
return reverseOutput;
}
void displayResults(char *original, char *reverse)
{
cout << "\nYou originally entered: " << original << endl;
cout << "In reverse order: " << reverse << endl;
}
In 'getReverse' you are allocating the variable 'reverse' on the STACK meaning the data will be GONE WHEN THE FUNCTION RETURNS, no matter how many pointers reference that data.
I would declare 'reverse' in main with 'char reverse[MAX_SIZE];', then have the function take a parameter 'char reverse[]', which the function would then modify.
You are returning a pointer to a local array. The array original is destroyed after the function getInput exits. So original in main is pointing at something which no longer exists, garbage in other words. getReverse has exactly the same problem.
One way to solve this is to declare the arrays in main, and pass pointers to those arrays to the getInput and getReverse functions, for instance.
int main()
{
//program to create a c-string and then output the reverse order
char original[MAX_SIZE];
char reverse[MAX_SIZE];
getInput(original);
int originalSize = strlen(original);
getReverse(original, originalSize, reverse);
displayResults(original, reverse);
return 0;
}
void getInput(char* original)
{
cout << "Enter a word or line of text up to a max of 20 characters\nand will have it output in reverse!" << endl;
cin.getline(original, MAX_SIZE);
}
// etc
You are wasting too much char* s and data. Why not try this :
(I have not tested the code, but it must work ,probably with minor fixes,if any.)
#define MAXSIZE 20
void getinput(char *in)
{
cin.getline(in,MAXSIZE);
return;
}
void reverse(char *in);
{
int len=strlen(in);
char *store=in;
while(int i=0;i<len/2;i++)
{
char temp;
temp=*in;
*in=*(store+len);
in++;len--;
}
return;
}
int main()
{
char data[MAXSIZE];
getinput(data);
cout<<"Original :"<<data;
reverse(data);
cout<<"reverse"<<data;
}
I have to admit, i have no idea how to use pointers, but I tried non the less. the problem with my program is that it shows the string in reverse, except for what was the first letter being missing and the entire string is moved one space forward with the first element being blank.
for example it show " olle" when typing "hello".
#include <iostream>
#include <string>
using namespace std;
string reverse(string word);
int main()
{
char Cstring[50];
cout<<"enter a word: ";
cin>>Cstring;
string results = reverse(Cstring);
cout <<results;
}
string reverse(string word)
{
char *front;
char *rear;
for (int i=0;i< (word.length()/2);i++)
{
front[0]=word[i];
rear[0]=word[word.length()-i];
word[i]=*rear;
word[word.length()-i]=*front;
}
return word;
}
The new code works perfectly. changed the strings to cstrings. the question technicaly asked for cstrings but i find strings easier so i work with strings then make the necesary changes to make it c string. figured out ho to initialize the rear and front as well.
#include <iostream>
#include <cstring>
using namespace std;
string reverse(char word[20]);
int main()
{
char Cstring[20];
cout<<"enter a word: ";
cin>>Cstring;
string results = reverse(Cstring);
cout <<results;
}
string reverse(char word[20])
{
char a='a';
char b='b';
char *front=&a;
char *rear=&b;
for (int i=0;i< (strlen(word)/2);i++)
{
front[0]=word[i];
rear[0]=word[strlen(word)-1-i];
word[i]=*rear;
word[strlen(word)-1-i]=*front;
}
return word;
}
char *front;
char *rear;
then later
front[0]=word[i];
rear[0]=word[strlen(word)-1-i];
Not good. Dereferencing uninitialized pointers invokes undefined behavior.
Apart from that, your code is overly complicated, it calls strlen() during each iteration (and even multiple times), which is superfluous, and the swap logic is also unnecessarily complex. Try using two pointers instead and your code will be much cleaner:
void rev_string(char *str)
{
char *p = str, *s = str + strlen(str) - 1;
while (p < s) {
char tmp = *p;
*p++ = *s;
*s-- = tmp;
}
}
The thing is, however, that in C++ there's rarely a good reason for using raw pointers. How about using std::reverse() instead?
string s = "foobar";
std::reverse(s.begin(), s.end());
inline void swap(char* a, char* b)
{
char tmp = *a;
*a = *b;
*b = tmp;
}
inline void reverse_string(char* pstart, char* pend)
{
while(pstart < pend)
{
swap(pstart++, pend--);
}
}
int main()
{
char pstring[] = "asfasd Lucy Beverman";
auto pstart = std::begin(pstring);
auto pend = std::end(pstring);
pend -= 2; // end points 1 past the null character, so have to go back 2
std::cout << pstring << std::endl;
reverse_string(pstart, pend);
std::cout << pstring << std::endl;
return 0;
}
you can also do it like this:
#include <iostream>
#include <cstring>
using namespace std;
string reverse(char word[20]);
int main()
{
char Cstring[20];
cout<<"enter a word: ";
cin>>Cstring;
string results = reverse(Cstring);
cout <<results;
}
string reverse(char word[20])
{
char a='a';
char b='b';
char *front=&a;
char *rear=&b;
for (int i=0;i< (strlen(word)/2);i++)
{
*front=word[i];
*rear=word[strlen(word)-1-i];
word[i]=*rear;
word[strlen(word)-1-i]=*front;
}
return word;
}
it successfully works on my system ,i.e. on emacs+gcc on windows 7
Taken from C How To Program Deitel & Deitel 8th edition:
void reverse(const char * const sPtr)
{
if (sPtr[0] == '\0')
return;
else
reverse(&sPtr[1]);
putchar(sPtr[0]);
}