简体   繁体   中英

Implementing strcpy function without using in-built strcpy

EDIT: The issue is solved and I am very thankful to everyone who helped me, and if you are seeing this post in the future, here's the working code to implement strcpy function in C:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
        if(a[i+1] == '\0')
            b[i+1]='\0';
    }
}
int main()
{
    printf("Enter the string: ");
    char a[10];
    scanf("%s",&a);
    printf("Input string: %s", a);
    char b[sizeof(a)]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:

Enter the string: helloworld
Input string: helloworld 
Output string: helloworld



Question begins here:

I am trying to implement a strcpy function without using inbuilt function. I have searched online but I only found the programs to do this task but not functions .

I tried various approaches but no luck. At the end (Try 4) , I wrote a code that works but I dont understand why the hell is that thing working but previous approaches aren't

Just looking for a function that can copy value of one string into another when called from main() and displays correct value in output string. I would be really thankful if I could get that. And ofcourse, I cant use the inbuilt function because I am forced to do this cuz of an exam on Monday where we will have to implement any of the random 7 string functions and explain the code too..

EDIT: Also found this https://www.programmersought.com/article/29163684184/ code to implement the same thing but it is written in C++. Why does schools/colleges still teach C after the invention of C++? Anyone knows any C++ to C converters?

Try 1:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    char a[10];
    printf("Enter string: ");
    scanf("%s", &a);
    printf("Input string: %s", a);
    char b[(sizeof(a))];
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:

Enter string: helloworld
Input string: helloworld
Output string: helloworldhelloworld





Try 2:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    int n;
    printf("Enter the string size: ");
    scanf("%d",&n);
    char a[n];
    printf("Enter string: ");
    scanf(" %s",&a);
    printf("Input string: %s", a);
    char b[n]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Ouput:

Enter the string size: 7
Enter string: helloworld
Input string: helloworld  
Output string: helloworldö





Try 3:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    int n;
    printf("Enter the string size: ");
    scanf("%d",&n);
    n++;
    char a[n];
    printf("Enter string: ");
    // scanf(" %s",&a);
    fgets(a,n,stdin);
    fgets(a,n,stdin);  //need to write twice or it wont work
    printf("Input string: %s", a);
    char b[n]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:

Enter the string size: 5
Enter string: helloworld
Input string: hello  
Output string: hello⌂





Try 4:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    int n;
    printf("Enter the string: ");
    scanf("%d",&n);
    n++;
    char a[n];
    scanf(" %s",&a);
    // printf("Enter string: ");
    // fgets(a,n,stdin);
    // fgets(a,n,stdin);
    printf("Input string: %s", a);
    char b[n]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:

Enter the string: helloworld
Input string: helloworld 
Output string: helloworld





EDIT:

Trying approach given by a friend in answers:

Code:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i+1] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    // int n;
    printf("Enter the string: ");
    // scanf("%d",&n);
    // n++;
    char a[10];
    scanf("%s",&a);
    // printf("Enter string: ");
    // fgets(a,n,stdin);
    // fgets(a,n,stdin);
    printf("Input string: %s", a);
    char b[sizeof(a)]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:

Enter the string: helloworld
Input string: helloworld
Output string: helloworl





EDIT 2:

Trying do-while loop:

Code:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    // for (int i = 0; a[i+1] != '\0'; i++)
    // {
    //     b[i] = a[i];
    // }
    int i=0;
    do{
        b[i]=a[i];
        i++;
    }while(a[i] != '\0');
}
int main()
{
    // int n;
    printf("Enter the string: ");
    // scanf("%d",&n);
    // n++;
    char a[10];
    scanf("%s",&a);
    // printf("Enter string: ");
    // fgets(a,n,stdin);
    // fgets(a,n,stdin);
    printf("Input string: %s", a);
    char b[sizeof(a)]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:

Enter the string: helloworld Input string: helloworld Output string: helloworldhelloworld

OP's strcopy() has various problems in trying to mimic the standard library function:

char *strcpy(char * restrict s1, const char * restrict s2);

Missing null character in the destination array

This is OP 's primary issue. Somehow a null character must be assigned in the destination. OP's various codes fail that.

Tip: think about copying a string "" which assign only a null character '\\0' to the destination.

Wrong parameter order

The first parameter should be the destination to match strcpy()

Missing return value

strcpy() returns the original destination pointer.

Advanced: Parameters missing restrict/const attributes

Simply use the library function signature above.

Advanced: Fails for long strings

OP's code uses int to index which is insufficient for long strings. Better to use size_t .

Tip: Add output clarity

When printing the result, add sentinel characters like < > and a final '\\n' .
For debug efforts, make destination string 2x as big.

// char b[sizeof(a)]; 
char b[sizeof(a) *2]; 
strcopy(a,b);
// printf("\nOutput string: %s", b);
printf("\nOutput string: <%s>\n", b);

OP's asserts this in not a homework coding task, so a candidate solution:

char *strcpy(char * restrict s1, const char * restrict s2) {
  // Use unsigned char as all str functions behave as if char was unsigned
  // Also need to save s1 for return
  unsigned char *us1 = (unsigned char *)s1;
  const unsigned char *us2 = (const unsigned char *)s2;

  while (*us2) {
    *us1++ = *us2++;
  }

  return s1;
}

In the olden days when K&R was king, we'd tie a onion to our belts, as was the style at the time and do something like

void strcopy(char *a, char *b)
{
   while ( *b++ = *a++ ) {}
}

Now I think the old ways are depreciated

It has been suggested that I explain why this works.

*b = *a does the core function of copying of one byte

*b++ = *a++ Adding the auto-increments, moves both the pointers to the next locations in memory after the assignment is done

while (*b++ = *a++) {} loops while the byte copied is non-zero. the empty {} is just to complete the syntax of the while statement

So the while loop will run copying bytes then incrementing both pointers to the next location until the byte copied was zero, being the end of string

您没有添加终止\\0

All of your implementations have the same essential bug; "try 4" works only by accident. The problem is with the loop termination condition in strcopy . When you reach the NUL character that ends the source string, you are stopping the loop and not copying it. This means that the destination string is not ended and printf walks past its end, printing whatever happens to be in memory beyond. You must instead copy the NUL and then stop the loop.

You also have errors in how you allocate memory for the strings a and b -- different in each implementation, but none of them look abstractly correct to me. Talk to your instructor about how to do this correctly, it's one of the most complicated subjects in C and I don't have enough information about what techniques you are allowed to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM