How this program executed? Pls Explain..

Write your question here.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class strings
{
char s[20];
public:
strings()
{
s[0]='\0';
}
strings(char *c)
{
strcpy(s,c);
}
char *operator+(strings x1)
{
char *temp;
strcpy(temp,s);
strcat(temp,x1.s);
return temp;
}

};
void main()
{
clrscr();
strings s1("test"), s2("run\0");
char *concatstr;
concatstr=s1+s2;
cout<<"\n Concatenated string"<<concatstr;
getch();
}


Can any one explain this step only. How will working this function.

strings(char *c)
{
strcpy(s,c);
}

char *operator+(strings x1)
{
char *temp;
strcpy(temp,s);
strcat(temp,x1.s);
return temp;
}


Last edited on
How this program executed?
it isn't executed. There are very many errors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream.h>
#include <conio.h>
#include <string.h>

class strings
{
    char s[];
    public:
    strings()
    {
        s[0]='\0';
    }
    
    strings(char *c)
    {
        strcpy(s,c);
    }
    
    char *operator+(strings x1)
    {
        char *temp;
        strcpy(temp,s);
        strcat(temp,x1.s);
        return temp;
    }
};

void main()
{
    clrscr();
    strings s1("test"), s2("run\0");
    char *concatstr;
    concatstr=s1+s2;
    cout<<"\n Concatenated string"<<concatstr;
    getch();
}

Lines 1 and 3 - obsolete headers.
line 28 void main() is not valid. it should always be int main()

line 7 char s[]; zero size array is forbidden.

line 11 - assigning to non-existent array element.

line 16 - strcpy attempts to store result in non-existent array.

lines 21-24. temp is an uninitialised pointer. it may not be de-referenced.

There may be other issues, but that's enough to begin with.
Kindly sent to correct code for me...
Line 7 - decide how large you want the array to be and declare it accordingly. (how many characters will the string have, perhaps 50 or 100 might do to begin with).

line 21. First use strlen() to determine the sizes of s and x1.s. Add those together plus 1 for null terminator. That gives the required number of characters for the concatenated string. Then use new[] to allocate the memory:
 
    char * temp = new char[len];
where len is the size just calculated.
Topic archived. No new replies allowed.