0

I'm practicing C language and just built a simple program that inverts sequence of alphabets in a word.

#include <stdio.h>

int main(void)
{
  char str[50];

  printf("Enter a word: ");
  scanf("%s", str);

  int i, len=0;
  char temp;

  while(str[len]!='\0')
  {
    len++;
  }
  /*
  for(i=0; i<len/2; i++)
  {
      temp=str[i];
      str[i]=str[(len-i)-1];
      str[(len-i)-1]=temp;
  }
  */

  while(i!=len-1)
  {
    temp=str[i];
    str[i]=str[len-1];
    str[len-1]=temp;
    i++;
    len--;
  }

 printf("%s\n", str);

 return 0;
 }

I got two versions and one is working very well but the other makes "Segmentation error: 11" I guess I might have accessed wrong memory position but it's quite tricky to figure out what have I done wrong.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
A.Lee
  • 69
  • 3
  • 2
    Please take some time to read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert, and learn how to use a debugger to catch crashes or simply step through your program line by line. – Some programmer dude Sep 28 '17 at 09:04
  • It isn't off-topic because of the content! This will most likely get closed as "off topic because problem was created by a simple typo" however, because it was simply a missing variable initialization. – Lundin Sep 28 '17 at 09:10

1 Answers1

6

You need to initialize i to 0 :

int i = 0;

so that you start from the beginning of your string. Right now, i has an undefined value and accesses memory out of your string's bounds.

Also you need to change your condition from :

while (i != len-1)

to :

while (i <= len-1)

so that you stop when you reach the end of your string.

Marievi
  • 4,951
  • 1
  • 16
  • 33