-2

I want the output to be XOllo, but segfault is what I am getting.

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

int main(){

  char *buf="hello";
  char *xys="XO";

  while(*buf != 'l'){
  *buf = *xys;
  xys++;
  buf++;
  }
  printf("%s \n", buf);
  return 0;
}

o/p-: segfault

I need the o/p as XOllo, but I get seg fault. Please suggest.

Please suggest. 
Paul R
  • 208,748
  • 37
  • 389
  • 560
arpita
  • 65
  • 1
  • 2
  • 8

1 Answers1

0

Variables buf and xys pointing to the string literals, which cannot not be changed, therefore trying to access to re-write the values leading to SIGFAULT, instead you need to allocate new variable and copy values into it:

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

int main(){

  char *buf="hello";
  char *xys="XO";
  char *tmp = (char *)malloc(strlen(buf));

  strcpy(tmp, xys);
  strcpy(tmp+2, buf+2);

  printf("%s \n", tmp);
  free(tmp);
  return 0;
}

If you need to find exact position of l character, you can use strchr function to get the index of it in the following way:

int index = -1
const char *ptr = strchr(buff, 'l');
if(ptr) {
   index = ptr - values;
}
Artem Barger
  • 40,769
  • 9
  • 59
  • 81