Home > Software design >  Comparing elements of char*
Comparing elements of char*

Time:11-12

Hello i am new to programming in C and have a question: Why does this not work to get the return value 1 for strings with same char in first and last position:

function1(char* str){
   if(str[0]==str[strlen(str)-1]){
       return 1;
    }
    return 0;
   }

EDIT: solution in my case was that in my string the last element hast the index strlen(str)-2.

CodePudding user response:

This works:

#include <stdio.h>
#include <string.h>

int function1(char* str)
{
    if(!(strlen(str) == 0))
    {
        if(str[0] == str[strlen(str)-1])
            return 1;
        return 0;
    }
    return 0;
}
   
int main()
{
    printf("I am same: %i\n", function1("HaH"));
    printf("I am not same: %i\n", function1("HaR"));
    return 0;
}
  • You're missing a return type for your function :) EDIT: Also, you should take care if the str is empty or not.

CodePudding user response:

it seems like in my case strlen -2 is the index of the last char in the string

  • Related