I was write this code in Visual Studio and it's work okey. Everything is fine.
I was start to learn C in cs50.dev. Sometimes i write in cs50.dev. Because it's easy to take input from user. But a question give me a headache. Why same code give me an error. I was copy paste it.
I was write this code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
s
int add(char *name, int pow, char class);
int delete(char *name);
int print();
typedef struct addhero
{
char name[50];
int pow;
char class;
struct addhero *next;
} addhero;
addhero *first = NULL;
addhero *last = NULL;
int main()
{
char yn = ' ';
while (1){
char hn[50];
int hp = 0;
char hc = ' ';
printf("Enter hero name: ");
scanf(" %s", hn);
printf("Enter hero power: ");
scanf(" %d", &hp);
printf("Enter hero class: ");
scanf(" %c", &hc);
add(hn, hp, hc);
printf("Keep going to add? (Y/N): ");
scanf(" %c", &yn);
if (islower(yn)) yn = toupper(yn);
if (yn == 'N')
break;
}
print();
}
int add(char *name, int pow, char class)
{
if (strcmp(first->name, "\0") == 0){
addhero *new = (addhero *)malloc(sizeof(addhero));
strcpy(new->name, name);
new->pow = pow;
new->class = class;
new->next = NULL;
first = last = new;
}
else{
addhero *new = (addhero *)malloc(sizeof(addhero));
strcpy(new->name, name);
new->pow = pow;
new->class = class;
new->next = NULL;
last->next = new;
last = new;
}
return 0;
}
int delete(char *name)
{
addhero *prev = NULL;
addhero *index = first;
if (first == NULL){
printf("There is no hero now.");
return 0;
}
// Baştaki eleman siindiyse güncelle.
if (strcmp(first->name, name) == 0){
addhero *temp = first;
first = first->next;
free(temp);
return 0;
}
while (index != NULL && !(strcmp(index->name, name))){
prev = index;
index = index->next;
}
if (index == NULL){
printf("There is no hero in this name.\n");
return 0;
}
prev->next = index->next;
// Sondaki eleman silindiyse güncelle.
if (strcmp(last->name, name) == 0){
last = prev;
}
free(index);
return 0;
}
int print()
{
printf("\n-> ╠══ Your Heroes ══╬\n");
printf("-----------------------\n");
addhero *index = first;
while (index->next != NULL)
{
printf("-> Hero: %s ══ %d | %c\n", index->name, index->pow, index->class);
index = index->next;
}
printf("-> Hero: %s ══ %d | %c\n", last->name, last->pow, last->class);
printf("-----------------------\n");
return 0;
}
It's look okey in VS but in cs50 givin error: "Segmentation fault (core dumped)" So why is that? Can someone explain this please?
I expect to in my cs50.dev worspaces work as work as in VS. So i want to learn why is this error in cs50.dev.