D
DanielJohnson
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.
// 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
example: "I love You" should print as "I evoL uoY". I get Segmentation
Fault (core dumped) error upon running the program. It compiles fine.
// 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