#include<cstring>
#include<iostream>
using namespace std ;
class CSR
{
private:
char* csrName;
public:
void setName(char* n)//a setter for name
{
csrName = n;
}
char* getName()//a getter for employee’s name
{
return csrName;
}
};
int main()
{
CSR employees[7];
for(int i=0;i<7;i )
{
char name[] = { 'E', 'M', 'P', char(i 49), '\0' };
employees[i].setName( name);
}
for(int i=0;i<7;i )
{
cout<<employees[i].getName()<<endl;
}
}
/* I am not getting the desired output which is EMP1 EMP2 EMP3 EMP4 EMP5 EMP6 EMP7 When I run this program I am getting EMP7 EMP7 EMP7 EMP7 EMP7 EMP7 EMP7 */
CodePudding user response:
char name[] = { 'E', 'M', 'P', char(i 49), '\0' };
This array is declared inside the first for
loop. This means that at the end of every loop's iteration this array gets destroyed. As soon as the loop reaches it's end, and i
gets incremented, this array gets destroyed. This is how all objects declared in automatic scope work in C .
But the shown code saves a pointer to these destroyed arrays in other objects, before these arrays get destroyed.
Just because you save a pointer to this array in another object, it doesn't mean that the referenced array gets automatically duplicated, in its own memory location. Pointers in C don't work this way.
After the for
loop terminates, the shown code then attempts to use all those pointers to destroyed arrays.
This is undefined behavior, and the reason for your unexpected output.
It just so happens that because of the way your specific C compiler works, every one of the arrays, that get created and destroyed on every iteration of the loop, ends up in the same memory address, hence the reason you see the same output each time.
CodePudding user response:
What you are basically doing is that you are pointing your name variable towards the memory that is allocated to the parameter i.e (n) but the problem is that n gets destroyed every time the function stops its execution.
What you should do is point your name variable to a new memory location and run a loop so that it holds the same value as the parameter and not the same memory location.
Like so
void setName(char* n)//a setter for name
{
csrName = new char [30]; // I just took the size as random, you can
change it.
for (int i = 0; n[i - 1] != '\0'; i )
{
csrName[i] = n[i];
}
}