简体   繁体   中英

Returning character pointer and comparing with string

I am having one function which is returning character pointer and it prototype is shown below.

char *substring(char *string, int position, int length);

calling function

char *temp1;
temp1 = substring(de1Binary, FieldNo - 1, 1);

return pointer if it is printed with %s it is showing temp1 = 1 After this the below code is executed

if (temp1 == "1")
{
     Inside loop
}

But it is not going inside loop.Here I think I am missing some basic concept in C program. Please guide me.

If you want to compare the two strings use the strcmp() function it is in string.h header file.

Instead of if(temp1 == "1") you can use the below if statement.

if((strcmp(temp1, "1")) == 0)
{
     Inside loop
}

The problem is that if you even write

if ("1" == "1")

there is no guarantee that this condition will yield true . It depends on the compiler options. It can store each of identical string literals separatly and in this case they will have different addresses or store only one string literal of identical literals.

String literals have type of character arrays. In the if-condition string literals are converted implicitly to pointers to their first characters. So in this statement

if (temp1 == "1")

there is compared the address stored in temp1 with the address of the first character of string literal "1" that is stored in memory like

{ '1', '\0' }

So this condition will always yield false or either true or false (depending on the compiler options) if you write before the if statement

temp1 = "1"; 

You need to compare the strings pointed to by these two pointers not the pointers themselves. You could do this for example the following way

if ( temp1[0] == "1"[0] && temp1[1] == '\0' )  {*...*/ }

or

if ( temp1[0] == '1' && temp1[1] == '\0' )  {*...*/ }

Imagine for example that you have a manifest constant

#define One "1"

In this case you could write indeed

if ( temp1[0] == One[0] && temp1[1] == '\0' )  {*...*/ }

But it is much better to use standard C function strcmp declared in header <string.h> that returns 0 if two strings are equal.

if ( strcmp( temp1, "1" ) == 0 ) { /*...*/ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM