readFruit.name
is initialized to NULL
before I try to initialize it as a char array. I included size
to see if that was the culprit but it is exactly what it should be depending on my input. No matter what length tempString
is, readFruit.name
is allocated around 25 "characters" in memory and they're all garbage. Why isn't it being allocated a space the size of tempString.length()
and how can I fix it?
relevant CPP
std::istream & operator>>(std::istream &is, Fruit &readFruit)
{
string tempString;
is >> tempString;
int size = tempString.length();
readFruit.name = new char[tempString.length()];
for(int i = 0; i < (int)tempString.length(); i++)
{
readFruit.name[i] = tempString[i];
}
for(int i =0; i < CODE_LEN; i++)
{
is >> readFruit.code[i];
}
return is;
}
Relevant H file (constructor)
#ifndef _FRUIT_H
#define _FRUIT_H
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
enum { CODE_LEN = 4 };
enum { MAX_NAME_LEN = 30 };
class Fruit
{
private:
char *name;
char code[CODE_LEN];
public:
Fruit(const Fruit &temp);
Fruit(){name = NULL;};
bool operator<(const Fruit& tempFruit);
friend std::ostream & operator<<(std::ostream &os, const Fruit& printFruit);
bool operator==(const Fruit& other){return *name == *other.name;};
bool operator!=(const Fruit& other){return *name != *other.name;};
friend std::istream & operator>>(std::istream& is, Fruit& readFruit);
};
#endif
If you're trying to print readFruit.name
, it will display garbage value until it finds a null termination, that's what I assume you saying 25 characters "all garbage"
Allocated memory like this :
readFruit.name = new char[tempString.length()+1];
And after for
loop do:
readFruit.name[i] ='\0'; // C strings are null terminated
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments