karthik gorijavolu
karthik gorijavolu

Reputation: 860

what is this program (Reversing a String) in C not working?

#include<stdio.h>
int main()
{
    int i,n=0;
char str[]="karthik";
while(*(str+n)!='0')
n++;
for(i=0;i<n/2;i++)
{char temp=str[i];
str[i]=str[n-i-1];str[n-i-1]=temp;
}
printf("%s",str);
}

I know this is Pretty common question but when i tried i am not getting any output.I know that there is some error in below two lines because when i used strlen() it worked well.

while(*(str+n)!='0')
n++;

so please say why is it wrong to use like this. please remember i am a beginner in c

Upvotes: 1

Views: 135

Answers (4)

Abhineet
Abhineet

Reputation: 5389

Check for NULL in while loop. Change from

while(*(str+n)!='0')

To

while(*(str+n)!='\0')

Upvotes: 0

Lundin
Lundin

Reputation: 213678

In addition to the null termination issue, you must adopt a conventional coding style. One example:

#include <stdio.h>

int main()
{
  int i;
  int n=0;
  char str[]="karthik";

  while(str[n] != '\0')
  {
    n++;
  }

  for(i=0; i<n/2; i++)
  {
    char temp=str[i];
    str[i]=str[n-i-1];
    str[n-i-1]=temp;
  }

  printf("%s",str);

  return 0;
}

Upvotes: 1

Alok Save
Alok Save

Reputation: 206518

while(*(str+n)!='0') 
n++; 

The idea is to iterate through the array for the entire length of the string.
You should be checking for \0. Because c strings are null terminated(\0)

while(*(str+n)!='\0')
                 ^^

Also, on a side note You should return a value from your main() function, irrelevant to the problem but it is a good practice.

Upvotes: 3

maialithar
maialithar

Reputation: 3123

End of a char array in c == '\0'

Upvotes: 1

Related Questions