On Feb 18, 12:31 am, gordonb.x6...@burditt.org (Gordon Burditt) wrote:
> >I wrote this small program to reverse each word in the string. For
> >example: "I love You" should print as "I evoL uoY". I get Segmentation
> >Fault (core dumped) error upon running the program. It compiles fine.
>
> You stored the test string in a quoted string literal. C is permitted
> to store such data in a read-only section of the program. If you
> try writing on it, KABOOM!
>
> Note also that you keep incrementing p, losing track of where the
> beginning of the string is. That's not good when you try to print it.
>
>
>
> >// Program to reverse each word in the string
> >#include<stdio.h>
>
> >int main()
> >{
> > void reverse_string(char *, int, int);
> > char *p = "my name is daniel";
> > // keeps count of number is char in the word to reverse
> > int count = 0;
> > // keeps track of where I started this current word from
> > int current_pos = 0;
> > // Conitnue till you reach \0
> > while(1){
> > if (*p == '\0') break;
> > count = 0;
> > while(*p != ' '){
> > if (*p == '\0') break;
> > count++;
> > p++;
> > }
> > reverse_string(p, current_pos, count);
> > if (*p == ' '){
> > p++;
> > count++;
> > current_pos = count;
> > }
> > }
> > puts(p);
> > return 0;
> >}
>
> >void reverse_string(char* s, int start, int count){
> > int counter = count/2;
> > int i = 0;
> > while(i < counter){
> > *s = *(s-count);
> > s--;
> > i++;
> > }
> >}
>
> >Any suggestions......Every help is appreciated.
>
> >Thanks
What should I do prevent KABOOM...I am newbie..give me some tips...
|