0

Hi i need help about this:

 int t;
 t = 1;
 char abc[256];
 int main() {
 scanf("%s", abc);
 if(abc == "google") {
  printf("%s \n", abc);
  system("firefox");
 } else
  printf("error");
}

it always return error please someone help! i already tried scanf("%c", &abc); and i rewrote this about 5 times with the same result. I'm new at this so this can be a very stupid thing.

Tommaso
  • 3
  • 1

4 Answers4

4
  1. if(abc == "google") {

    This doesn't do what you think it does. This checks whether the pointers to those two strings are numerically equal. They never will be, because abc is allocated in the stack, and "google" is a string literal and therefore has static storage duration.

    You should use strcmp like ameyCU points out.

  2. In general, don't use scanf like this, the code you wrote is vulnerable to buffer overflow attacks if someone passes a large string.

    You might want to look at this nice post about how to use scanf safely. How to prevent scanf causing a buffer overflow in C?

Community
  • 1
  • 1
Chris Beck
  • 15,614
  • 4
  • 51
  • 87
3

You can't compare the contents of two character arrays with ==. == will just compare the memory addresses of the arrays (after array-to-pointer decay).

Use strcmp instead:

if (strcmp(abc, "google") == 0) ...
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

The constant string "google" reside in the .rodata section of your program and if you compile with all warning -Wall you get this warning

google.c:10:12: warning: comparison with string literal results in unspecified behavior [-Waddress]
if(abc == "google") {

and this code is equivalent with

const char* const google_str = "google";
if(abc == google_str)

Here both the string "google" and the address to that string is constant. So you see you are doing a pointer comparison and not a string comparison.

printf("%p == %p\n", abc, google_str);

This code will show you that abc reside on the stack and that google_str reside in the .rodata section. String comparison should be done with

if(0 == strcmp(abc, "google")) {
leakim
  • 41
  • 4
0
<code>
if(abc == "google")
</code> 

would work in object oriented languages like java and dot net in c cpp you have to use inbuild library functions of String like strcpy,strcmp

<code> int strcmp(const char *str1, const char *str2) <code>

compares the string pointed to, by str1 to the string pointed to by str2.

So you will modify your code as

  #include <stdio.h>
     int t;
     t = 1;
     char abc[256],a[256];
    int main()
    {
        strcpy(a,"google");
        scanf("%s", abc);

        if( strcmp("abc","google")==0 ) {
            printf("%s \n", abc);
            printf("firefox");
     } else
      printf("error");

        return 0;
    }