Home > Backend Development > C#.Net Tutorial > How to initialize array in c language

How to initialize array in c language

青灯夜游
Release: 2023-01-04 15:36:26
Original
23530 people have browsed it

Three ways to initialize arrays in C language: 1. Directly assign values ​​when defining, with the syntax "data type arrayName[index] = {value};"; 2. Initialize using for loops, with the syntax "for (int i=0;i

How to initialize array in c language

The operating environment of this tutorial: windows7 system, c99 version, Dell G3 computer.

Three ways to initialize arrays in C language

1. Direct assignment during definition

int arr1[3] = {0};
Copy after login

Using {0} is the most concise way and is generally used when defining.

2. For loop initialization

int arr2[3];
for (int i = 0; i 
Copy after login

The advantage of using a for loop is that each element can be set to a different value.

3. memset function

The memset function is declared as:

void *memset(void *str, int c, size_t n)

Replace n bytes (typedef unsigned int size_t) after the current position in str with c and return str.

int arr3[3];memset(arr3, 0, sizeof(int) * 3);
Copy after login

memset generally uses "0" to initialize the memory unit, usually to initialize the array or structure, or to clear the array or structure.

Generally, variables of types such as char, int, float, double, etc. can be initialized directly. If you use memset, it will be troublesome.

The sample codes of the three methods are as follows:

How to initialize array in c language

It should be noted that: the memset function initializes the memory block by bytes, so it cannot Use it to initialize an int array to a value other than 0 and -1.

memset is assigned a value of -1 or 0, and the final result is correct:

How to initialize array in c language

How to initialize array in c language

But use memset is assigned values ​​other than -1 and 0, and the final result is not the expected value. For example, if the assignment is 1, it is as shown in the figure below:

How to initialize array in c language

#Because memset assigns a value to each byte, and it is known that an int is 4 bytes, then memset assigns a value When it is binary, it is:

00000001 00000001 00000001 00000001 = 16843009

[Related recommendations: C language video tutorial, Programming teaching

The above is the detailed content of How to initialize array in c language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template