-4

So I am trying to learn c however I can't figure out why this code won't run properly.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char userName[25];
    char myName[25] = "myName";

    printf("Please enter your name: \n");
    scanf("%s", userName);

    if(userName == myName)
    {
        printf("Congratulations your name is myName!!!");
    }
    else
    {
        printf("Your name is %s how disappointing...", userName);
    }


    return 0;
}

The problem is that the if statement never seems to return true. Can anyone help me with this?

Hi-Angel
  • 4,933
  • 8
  • 63
  • 86
Meikk99
  • 1
  • 2
  • Please format your code properly. – too honest for this site Jun 19 '15 at 19:41
  • C lesson, char username[25] declares a pointer, char myName[25] declares a different pointer, pointing to two different locations in memory (on the stack in this case), therefore the pointers are never equal (the contents of each memory location may be equal, but the **memory** has to be compared, not the **pointers**) – Les Jun 19 '15 at 19:48
  • regarding this line: 'scanf("%s", userName);' This call to scanf() allows the user to overrun the userName[] buffer. suggest: 'scanf("%24s", userName);' And check the returned value from scanf() (not the parameter values) to assure the operation was successful. – user3629249 Jun 19 '15 at 21:11
  • regarding this line: 'if(userName == myName)' This is comparing the addresses of the two strings, what you really want to do is compare the contents of the two strings. Suggest: 'if( !strcmp(userName, myName) )' – user3629249 Jun 19 '15 at 21:13

5 Answers5

3

This line is comparing the locations of the strings, which are different, since you are comparing two different strings.

if(userName == myName)

The correct test in C is to use a library function.

#include <string.h>
...
if(strcmp(userName,myName) == 0)
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
1

In C, you should use strcmp() to compare two strings.

So change this:

if(userName == myName)

to this:

if(strcmp(userName,myName) == 0)
gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

You cannot compare strings like that. What you are doing is comparing the pointers to the respective stings(which are obviously different). So,

 userName == myName

won't work here. You may use string functions to compare the two strings.

Raman
  • 2,735
  • 1
  • 26
  • 46
0

The statement if(userName == myName) will not work the way you are expecting it to. Use the strcmp() function to compare two strings.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
0

Use strcmp / strncmp declared in string.h to compare strings; in your program the values you are comparing (after conversion) are pointer values.

ouah
  • 142,963
  • 15
  • 272
  • 331