JIYIK CN >

Current Location:Home > Learning > PROGRAM > C语言 >

Copying character array in C language

Author:JIYIK Last Updated:2025/04/17 Views:

This article will demonstrate various methods on how to copy a character array in C language.


memcpyCopy a character array in C using the function

charArrays are probably the most commonly used data structure in C code, and copying array contents is one of its core operations. C-style strings charare very similar to arrays, and therefore, there are multiple ways to handle copying array contents. In the following example, we declare two arrays, arrand arr2; the former is initialized with character list notation, and the latter is initialized with a string literal. Note that this results in different array structures and sizes. arrThe object is 7 characters in memory, but arr2requires 17 characters plus the terminating null byte, resulting in an 18-byte object. Therefore, we sizeof arr2 - 1pass the value of the expression as the second argument, indicating the length of the array. On the other hand, we can print the contents of the array using printfthe function and %sthe format specifier arr2.

The same details should be considered when copying charan array to a different location. memcpyThe get_by_array function is a part of the standard library string utilities and is defined in <string.h>the get_by_array header file. It takes three parameters, the first one is the destination pointer, where the contents of the array will be copied. The second parameter is a pointer to the source array and the last parameter specifies the number of bytes to be copied. Note that sizeofthe operator returns charthe size of the array object in bytes. So we call it with mallocthe sizeof arrvalue of the expression to allocate dynamic memory. The memory area returned is large enough to hold arrthe contents of and we don't need to worry about buffer overflow bugs. Note, however, that mallocthe pointer returned from should be freed.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void printCharArray(char *arr, size_t len)
{
    for (size_t i = 0; i < len; ++i) {
        printf("%c, ", arr[i]);
    }
    printf("\n");
}

int main(int argc, char *argv[]){
    char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
    char arr2[] = "array initialized";

    printf("%lu\n", sizeof arr);
    printf("%lu\n", sizeof arr2);

    printCharArray(arr, sizeof arr);
    printCharArray(arr2, sizeof arr2 - 1);

    char *str = malloc(sizeof arr);
    memcpy(str, arr, sizeof arr);
    printf("str: ");
    printCharArray(str, sizeof arr);
    free(str);

    str = malloc(sizeof arr2);
    memcpy(str, arr2, sizeof arr2);
    printf("str: %s\n", str);
    free(str);

    exit(EXIT_SUCCESS);
}

Output:

7
18
a, b, c, d, e, f, g,
a, r, r, a, y,  , i, n, i, t, i, a, l, i, z, e, d,
str: a, b, c, d, e, f, g,
str: array initialized

memmoveCopy a character array in C using the function

memmoveis another memory area copy function in the standard library string utilities. It is implemented as a more powerful function to accommodate the case where the destination and source memory areas overlap. memmoveThe parameters are memcpythe same as .

When copying arr2the contents of , we sizeof arr2pass the expression as the third argument. This means that even the terminating null byte is copied to the destination pointer, but we therefore use this operation to call printfand %sto output the contents, rather than using printCharArray.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void printCharArray(char *arr, size_t len)
{
    for (size_t i = 0; i < len; ++i) {
        printf("%c, ", arr[i]);
    }
    printf("\n");
}

int main(int argc, char *argv[]){
    char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
    char arr2[] = "array initialized";

    char *str = malloc(sizeof arr);
    memmove(str, arr, sizeof arr);
    printf("str: ");
    printCharArray(str, sizeof arr);
    free(str);

    str = malloc(sizeof arr2);
    memmove(str, arr2, sizeof arr2);
    printf("str: %s\n", str);
    free(str);

    exit(EXIT_SUCCESS);
}

Output:

str: a, b, c, d, e, f, g,
str: array initialized

Previous: None

Next:Dynamically allocating arrays in C

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Flushing stdout output stream in C

Publish Date:2025/04/17 Views:200 Category:C语言

stdout This article will demonstrate various methods on how to flush an output stream in C language . Use function in C language fflush to refresh stdout output stream I/O The C standard library provides a stdio buffered version of the I/O

Using the feof function in C language

Publish Date:2025/04/17 Views:87 Category:C语言

feof This article will introduce several ways to use functions in C language . Use feof the function to check the end-of-file indicator on a file stream in C language feof The function is part of the C standard input/output library and is d

Use the C language setenv function to access environment variables

Publish Date:2025/04/17 Views:122 Category:C语言

setenv This article will introduce several methods of using functions to export environment variables in C language . setenv Use function to export environment variables in C language Every program running on a Unix-base system has an envir

How to get the size of an array in C

Publish Date:2025/04/17 Views:62 Category:C语言

This tutorial explains how to determine the length of an array in C. sizeof() The operator is used to get the size/length of an array. sizeof() Operator determines the size of an array in C sizeof() The operator is a compile time unary oper

Initialize array to 0 in C

Publish Date:2025/04/17 Views:133 Category:C语言

This article explains how to initialize an array to 0 in C language. The declaration of an array in C language is as follows. char ZEROARRAY[ 1024 ]; It becomes all zeros at runtime in the global scope. If it is a local array, there is a si

Structure arrays in C

Publish Date:2025/04/17 Views:188 Category:C语言

This tutorial explains how to create a structure array in C language, which is a collection of multiple structure variables, each of which contains information about a different entity. Structure arrays in C An array is a sequential collect

Printing Character Array in C

Publish Date:2025/04/17 Views:106 Category:C语言

This article will introduce various methods on how to print character array in C language. for How to use loop to print character array in C language If we want to print array elements individually and format the output with more details, f

Clearing a character array in C

Publish Date:2025/04/17 Views:119 Category:C语言

This article will introduce several methods to clear character arrays in C language. memset Use function to clear char array in C language memset The _set_storage_region function is commonly used to set a storage area to a constant value. T

Initializing character array in C

Publish Date:2025/04/17 Views:92 Category:C语言

This article will demonstrate various ways of initializing a character array in C language. {} Initializing a character array in C using curly brace list notation Character arrays are mostly declared as a fixed-size structure and are often

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial