0

I keep getting a segfault, and help50 doesn't help. A lot of head scratching an googling later, I think I've narrowed it down to: you can't convert a long to a string. Is that true? The code in question:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    long card = get_long("Number: ");
    string card_str = (string) card;

    printf("Card long %i\n", card);
    printf("Card string %c\n", card_str[1]);
}

When run, I get:

~/pset1/credit/ $ ./credit 
Number: 100
Card long 100
Segmentation fault

1 Answer 1

0

As you do, you can't. I would try something like this, it might work:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    long card = get_long("Number: ");
    char card_str[256];
    sprintf(str, "%ld", card);

    printf("Card long %li\n", card);
    printf("Card string %c\n", card_str[1]);
}
3
  • Thanks! I had this and a few other solutions in mind, but mostly I am curious as to why the cast doesn't work and even more curious why it would give a seg fault. If I understand the why, it will help me avoid thinking errors like that in the future. Any ideas?
    – miekec
    Commented May 31, 2021 at 2:04
  • I suggest you a good read about memory in a C compiler, Basically and quickly I will tell you that a "data type" string is not a data type of C. This is not a tongue twister, in C, string is in actually a tipedef of a pointer: char *, a variable of type pointer is totally different from a variable of type int, for example, and the C language does not allow us to change from one to the other with a casting (at least until where I I know)
    – MARS
    Commented May 31, 2021 at 20:21
  • Thanks! I found an IRL friend who exlained basically the same to me :)
    – miekec
    Commented Jun 5, 2021 at 17:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .