I am new student in c language and I just come up with this. I code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[80];
printf("Enter sth: ");
char st1 = gets(str);
printf("Enter sth: ");
char st2 = gets(str);
if(strcpy(st1,st2))
printf("Same\n");
else
printf("Different\n");
return 0;
}
My goal is to check if the 2 strings i enter from the keyboard are the same. I compile it and i get some warnings:
hello.c: In function ‘main’: hello.c:9:16: warning: initialization makes integer from pointer without a cast [enabled by default]
hello.c:12:16: warning: initialization makes integer from pointer without a cast [enabled by default]
hello.c:14:5: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast [enabled by default]
/usr/include/string.h:128:14: note: expected ‘char * restrict’ but argument is of type ‘char’
hello.c:14:5: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [enabled by default]
/usr/include/string.h:128:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
Enter sth: asd
Enter sth: asd
Output: Segmentation fault (core dumped)
Segmentation Fault i saw that is an error when you want to access sth that it doesnt exist!
I search it a little here in Stackoverflow with similar questions and here but i dont understand why this code isnt working. Thank you!
You are treating an address of char
variable as string and using strcpy
instead of strcmp
. This:
char st1 = gets(str);
char st2 = gets(str);
if(strcpy(st1,st2))
was meant to be:
char st1[255], st2[255];
scanf("%254s", st1);
scanf("%254s", st2);
if(strcmp(st1, st2) == 0)