1
#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).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Harr
  • 101
  • 5
  • I believe in cs50 `string` is just a `typedef char*`, meaning that `"bob"` and `"steve"` are string literals, and [modifying string literals is undefined behavior](https://stackoverflow.com/questions/5464183/modifying-string-literal). Instead, try `char a[] = "bob";`, etc. – yano Jun 22 '23 at 23:27
  • Futhermore, you're overwriting the bounds of `a` by looping on `strlen(b)`. Can do something like `char a[32] = "bob"` to add more space. – yano Jun 22 '23 at 23:29
  • 1
    That typedef is incredibly misleading. – Daniel Kamil Kozar Jun 22 '23 at 23:34

1 Answers1

1

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 );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335