Home >Common Problem >What are the array assignment methods in C language?

What are the array assignment methods in C language?

小老鼠
小老鼠Original
2024-05-09 23:51:211011browse

There are six methods of array assignment in C language: 1. Direct assignment; 2. Use array initializer; 3. Use pointers; 4. Use loops; 5. Use memcpy() function; 6. Use scanf () function.

What are the array assignment methods in C language?

C language array assignment method

In C language, array is a data structure that is used to A collection that stores data of the same type. Arrays can be assigned in many ways, the specific methods are as follows:

1. Direct assignment:

This is the simplest and most direct assignment method, directly assigning elements Assign the value to the array element:

<code class="c">int arr[5] = {1, 2, 3, 4, 5};</code>

2. Use the array initializer:

The array initializer is a more concise way of assigning values, it can be directly used in the array Specify the element value when defining:

<code class="c">int arr[] = {1, 2, 3, 4, 5};</code>

3. Use pointers:

Use pointers to assign array elements one by one. The syntax is as follows:

<code class="c">int arr[5];
int *ptr = arr;

*ptr = 1; // 赋值第一个元素
*(ptr + 1) = 2; // 赋值第二个元素
...</code>

4. Use loops:

Loops can be used to batch assign array elements, the syntax is as follows:

<code class="c">int arr[5];

for (int i = 0; i < 5; i++) {
  arr[i] = i + 1;
}</code>

5. Use memcpy() function:

The memcpy() function can copy a piece of memory at one time, and can also be used to assign an array:

<code class="c">int arr[5];
int src[5] = {1, 2, 3, 4, 5};

memcpy(arr, src, sizeof(src));</code>

6. Use the scanf() function:

scanf The () function can get data from user input and assign it to array elements. The syntax is as follows:

<code class="c">int arr[5];

scanf("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);</code>

The above is the detailed content of What are the array assignment methods in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn