How to copy a string using pointers in the C language?

In C programming language, you can copy strings using pointers. This can be done using the strcpy function or a custom function.

  1. Use the strcpy function:
#include <stdio.h>
#include <string.h>

int main() {
    char str1[20] = "Hello";
    char str2[20];

    strcpy(str2, str1); // 使用strcpy函数将str1复制到str2

    printf("str1: %s\n", str1);
    printf("str2: %s\n", str2);

    return 0;
}
  1. Custom function:
#include <stdio.h>

void stringCopy(char *dest, const char *src) {
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = '\0';
}

int main() {
    char str1[20] = "Hello";
    char str2[20];

    stringCopy(str2, str1); // 调用自定义的函数stringCopy进行字符串复制

    printf("str1: %s\n", str1);
    printf("str2: %s\n", str2);

    return 0;
}
bannerAds