• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# pointer aritmatic problem - SEGV

## Recommended Posts

1 #include <stdio.h> 2 #include <stdlib.h> 3 4 char * 5 rev(char *s,int i) 6 { 7 char *p; 8 9 while(*s++) { 10 *p++ = s[strlen(s) - (i++)]; 11 } 12 return p; 13 } 14 15 16 int 17 main(void) 18 { 19 char *s; 20 char *word = "Hello World"; 21 22 s = rev(word,strlen(word)+1); 23 printf("%s\n",s); 24 25 exit(EXIT_SUCCESS); 26 } I dont know why the current code is not working ive tried alot of approaches, im trying to better understand pointers yes I know I could do a simple forloop using char arrys but im using pointers to better understand them.

##### Share on other sites
How about initializing p before using it?

And by the way, your loop seems like it''s not doing anything proper at all really. What do you expect it to do anyway?^

1. Allocate something for p, or take a target buffer as a parameter.
2. Learn to use a debugger to find where your code breaks.
3. Either use array indexes on s or do pointer arithmetics on s - doing both in the same piece of code is probably a bad idea.
4. I assume that i is the length? Name it length then, or len, or at least something that hints on the purpouse of the variable.
5. Do you really want to include that ''\0'' in the reversing process? That''d put the end of the new string at position 0.
6. If in doubt, run your code on a piece of paper and convince yourself it''s doing the right thing.

Reversing a string:
void rev(char *target, const char *src, int len) {  target += len - 1;  while (*src)    *target-- = *src++;}

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627671
• Total Posts
2978552

• 11
• 10
• 10
• 12
• 22