Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to copy strings in c, first letter isn't being copied

Tags:

c

c-strings

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.

like image 325
Assaf Avatar asked Jan 23 '26 22:01

Assaf


2 Answers

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--;
   }
}
like image 54
Tharindu Kumara Avatar answered Jan 25 '26 11:01

Tharindu Kumara


Many problems here...

  1. 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.

  2. You're copying backwards in your loop, assigning h to p.

  3. 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.

  4. 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.

  5. You should declare the source string argument as const. This would have detected problem 2 above.

like image 32
TypeIA Avatar answered Jan 25 '26 12:01

TypeIA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!