adafrwefsefr
adafrwefsefr

Reputation: 393

char Array in C++ is not functioning properly

I am coding a C++ program using char array.But i think it is giving problems.

This is my code:

#include <iostream>
#include<string.h>
using namespace std;

int main() {
    long int t;
    cin>>t;
    char total[500],a[500],b[500];
    cin>>total;
    int len=strlen(total);
    //cout<<strlen(total);
    for(int i=0;i<len/2;i++){
        a[i]=total[i];
    }
    for(int i=0;i<len/2;i++){
        b[i]=total[i];
    }
    cout<<a<<endl;
    cout<<b;
    return 0;
}

It is not printing the arrays. But when i commented out

/*for(int i=0;i<len/2;i++){
    b[i]=total[i];
}*/

it is printing array a as expected. What is the problem here?

Upvotes: 0

Views: 86

Answers (1)

StenSoft
StenSoft

Reputation: 9617

You arrays are not NULL-terminated. If I add a[len/2]=0; and b[len/2] = 0; after the for loops, it works correctly.

Upvotes: 1

Related Questions