Dynamic allocated arrays

I dynamicly allocated char array with lenght of 30. Then I put x characters int it. Then i dynamicly allocated new char array with lenght of x. I transfered characters from old to new array and when I wanted to print out new array, it printed to me characters from old array as I excepted, and some other unknown characters(like dash). I don't see where is the trouble so I am asking you to help.
Here is the code:
#include <iostream>

using namespace std;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
    char *unos=new char[30];
    cin>>unos;
    int x=-1;
    do{
        ++x;
    }while(unos[x]!=0);
    cout<<x<<endl;
    char *ispis=new char[x];
    for(int a=0;a<x;a++){
        ispis[a]=unos[a];
    }
    delete [] unos;
    cout<<ispis<<endl;
    delete [] ispis;
    return 0;
}


Example:
IN: abcd
OUT: abcd-

cout outputs all the character till it find a '\0'
however you are not copying that character (you don't even reserve the space)
So when you try to output it goes out of bounds.
This shouldn't change anything, since '\0' has an ascii value of 0, but when you're making a end-of-string test, you should compare the character to '\0' (the end-of-string character), not to 0. So, it should be
while(unos[x]!='\0')

As well, as is, your for loop isn't including the end-of-string character. In the example given (abcd), the do-while-loop will end when x=4. Thus, the for-loop will NOT run when a=4. And so, your ispis array will be ['a' 'b' 'c' 'd'] without the end-of-string character, when it SHOULD be ['a' 'b' 'c' 'd' '\0'].

So, changing the for-loop to for(int a=0;a<x+1;a++) should fix it.
Last edited on
It is solved! Thanks for help!
But you need to reserve enough space char *ispis=new char[x+1];
Yes, I have done it. And after copying one space left me free in which I put '/0'. My code now looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int main()
{
    char *unos=new char[30];
    cin>>unos;
    int x=-1;
    do{
        ++x;
    }while(unos[x]!=0);
    cout<<x<<endl;
    char *ispis=new char[x+1];
    for(int a=0;a<x;a++){
        ispis[a]=unos[a];
    }
    ispis[x]='\0';
    delete [] unos;
    cout<<ispis<<endl;
    delete [] ispis;
    return 0;
}


Thanks for help!
Topic archived. No new replies allowed.