nbk
nbk

Reputation: 543

Grabbing The First Character of a String

I am taking in a string from the stdinput via readline() a la:

char * cmdLine = readline();

Then I want to see if the first character of the string produced via readline() is an exclamation point. But the code

if(cmdLine[0]=="!")

doesn't do that for me like I would have thought. I thought that if the string snagged from stdin was "!1" for instance then it would be true that

cmdLine[0]=="!"

If cmdLine is a pointer to a string then can't I look at each character in the string with array brackets? I know this is a stupid basic c / pointer question but this is really tripping me up...

Upvotes: 3

Views: 217

Answers (3)

sjsam
sjsam

Reputation: 21965

The double-quotes in C is used to represent an array of characters. The null-character will by default be appended to the whatever you put inside the double quotes. So

"!" // makes for two characters the '!' and the terminating null character '\0'.

Your intention clearly is to compare single character, a single character should be enclosed in single quotes. So the right comparison would be

if(cmdLine[0]=='!')

What happens with cmdLine[0]=="!"?

As the first part of my answer says, the "!" makes a null terminated array of characters or a valid string. This (constant) string is stored in the data-segment part of an object file. A reference to "x" gives you the starting address of the string, ie you get a pointer. Hence when you do

 if(cmdLine[0]=='!')

You're comparing an integer (mind that char is an integer type) with a pointer. Though this may not produce an error (this is addressed in point 2 of [ this ] answer), you will not get the intended results.

Upvotes: 1

Heinzi
Heinzi

Reputation: 172270

You have two bugs:

  1. The first (less important) one is that you are comparing a char to a pointer. element11's answer addresses this point.

  2. The second (more important) bug is that the warning level of your build process is too low. Fixing that is more important, because it will not only help you find bug #1, but probably a lot of other bugs as well.

How to do that depends on your compiler. When using gcc, the -Wall -pedantic options are a good start:

$ gcc -Wall -pedantic test.c
test.c: In function ‘main’:
test.c:7:16: warning: comparison between pointer and integer
  if (cmdLine[0]=="!") {
                ^
test.c:7:16: warning: comparison with string literal results in unspecified behavior [-Waddress]

Upvotes: 4

element11
element11

Reputation: 4475

Change "!" to '!'. You are comparing a single char to another single char.

In C you specify a char with single quotes

Upvotes: 8

Related Questions