#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
string a = "bob";
string b = "steve'";
for (int c = 0, n = strlen(b); c < n; c++)
{
a[c] = b[c];
if (a[c] == '\0')
{
a[c+1] = '\0';
a[c] = b[c];
}
if (b[c] == '\0')
{
a[c] = '\0';
break;
}
}
printf("%s", a);
}
The error happens at the line that says a[c] = b[c] first, or the 12th line of code. The point of the code is to try and change string a to string b. However, it seems that I cant make two characters of arrays equal. Is there some way this is possible?
To make the those strings the same, I simply tried making their characters equal. It resulted in a Segmentation fault (core dumped).
For starters it seems there is a typo
"steve'"
^^
Nevertheless pointers a
and b
declared like
string a = "bob";
string b = "steve'";
where the name string
is an alias for the type char *
point to string literals "bob"
and "steve"
.
In this for loop
for (int c = 0, n = strlen(b); c < n; c++)
{
a[c] = b[c];
//...
you are trying to change a string literal. Any attempt to change a string literal results in undefined behavior. Moreover within the if statement
if (a[c] == '\0')
{
a[c+1] = '\0';
a[c] = b[c];
}
you are trying even to write in memory outside the string literal.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
Instead of pointers to string literals you need to declare at least one character array where a string literal will be copied.
For example you could write
#include <stdio.h>
int main(void)
{
char b[] = "steve";
char a[sizeof( b )] = "bob";
for ( size_t i = 0; ( a[i] = b[i] ) != '\0'; );
puts( a );
}