When trying to copy lines to c, the first letter is not copied

I am trying to write a really simple program, but here I can not find the problem. Tried different methods, here 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 lines, the first letter does not seem to be copied.

My purpose is actually more, trying to copy the lines in REVERSE, but I believe that figuring out what went wrong will help me succeed.

Any help is assigned.

EDIT: enabled, code now works.

+3
source share
5 answers

Here is the C code for changing the 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--;
   }
}
+5
source

There are many problems ...

  • p h , &p. p . & .

  • , h p.

  • : *p p. , p .

  • swap() . . . , , , .

  • const. 2 .

+3

:

while(*p++=*h++){
    ;
}

, p \0 . :

while (p){
    printf("%c",p[i++]);
}

p . (.. ), , p 0 ( ). . , , , . , strcpy.

+2

strcpy

char * strcpy(char *strDest, const char *strSrc)
{
    assert(strDest!=NULL && strSrc!=NULL);
    char *temp = strDest;
    while(*strDest++ = *strSrc++); // or while((*strDest++=*strSrc++) != '\0');
    return temp;
}
+2

, :

#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);
}

, .

+1

All Articles