I am trying to write a really simple program, but I can't find the problem here. Tried different methods, this is what I tried now:
#include <stdio.h>
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}
}
main(){
char p[]="abcde";
char h [sizeof(p)];
copyStr(p,h);
}
When I copy these strings, the first letter doesn't seem to be copied.
My assignment is actually bigger, trying to copy the strings in REVERSE, but I believe finding out what went wrong here will help me succeed.
Any help is appriciated.
EDIT: solved, code is now working.
Here is the C code to reverse a string,
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = strlen(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
Many problems here...
Pass p and h as arguments, don't use &p. The variable p is already a pointer to the array of characters. & makes it a pointer-to-pointer.
You're copying backwards in your loop, assigning h to p.
Your print loop is broken: the termination condition should be *p not p. Also p has already been advanced to the end of the string by your copy code.
swap() is a misleading name. It's not swapping two strings. It's copying one to the other. Even later when you add reversing, it's still reversing, not swapping.
You should declare the source string argument as const. This would have detected problem 2 above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With