Why sigmentation fault for this snippet

when I am submitting this code it giving SIGSEGV fault
constrains are:
1 ≤ N ≤ 16
1 ≤ N ≤ 10^3
1 ≤ N ≤ 10^5
for the first condition, it is working
#include
using namespace std;
int main()
{
int t;
cin>>t;
while(t–)
{
string a,b;
string z;
cin>>a>>b;
int n=a.length();
for(int i=0;i<n;i++)
{
if(a[i]==‘W’ && b[i]==‘W’)
z[i]=‘B’
else if(a[i]==‘W’ && b[i]==‘B’)
z[i]=‘W’;
else
z[i]=‘B’;
}
cout<<z<<endl;
}
}
but when I am performing arithmetic operation for append character in string it is working fine why it is happening
program:
#include
using namespace std;
int main()
{
int t;
cin>>t;
while(t–)
{
string a,b;
string z;
cin>>a>>b;
int n=a.length();
for(int i=0;i<n;i++)
{
if(a[i]==‘W’ && b[i]==‘W’)
z+=‘B’;
else if(a[i]==‘W’ && b[i]==‘B’)
z+=‘W’;
else
z+=‘B’;
}
cout<<z<<endl;
}
}

String z is empty, it has a size of 0.

but it is working for 1st testcase
string are dynamic memory allooction

Yes, they are dynamically given a size of 0. You need to initialise the string for it to actually have the index you are accessing.
Also please use ```(3 backticks) above and below your code on forum.

#include <iostream>
using namespace std;
int main(){
    int t;
    cin >> t;
    while (t--){
        string a, b;
        cin >> a >> b;
        int n = a.length();
        string z(n, '-');
        for (int i = 0; i < n; i++){
            if (a[i] =='W' && b[i] =='W'){
                z[i] ='B';
            }
            else if (a[i] =='W' && b[i] =='B'){
                    z[i] ='W';
            }
            else{
                z[i] = 'B';
            }
        }
        cout << z << endl;
    }
}
1 Like