在 C 语言中,初始化数组的方法有六种:直接初始化、指针初始化、循环初始化、部分初始化、使用 calloc 和使用 memset。

如何在 C 语言中初始化数组
1. 直接初始化
使用大括号 {} 初始化数组,并指定每个元素的值。例如:
int array[5] = {1, 2, 3, 4, 5};
2. 使用指针初始化
使用指针将数组元素初始化为其他变量、数组或常量的值。例如:
int array[5]; int *ptr = array; *ptr = 1; *(ptr + 1) = 2; *(ptr + 2) = 3; *(ptr + 3) = 4; *(ptr + 4) = 5;
3. 使用循环初始化
使用循环逐个初始化数组元素。例如:
int array[5];
for (int i = 0; i <p><strong>4. 部分初始化</strong></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/ai/2638" title="Woy AI"><img
src="https://img.php.cn/upload/ai_manual/001/246/273/6972000e2bd59887.png" alt="Woy AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/ai/2638" title="Woy AI" class="overflowclass">Woy AI</a>
<p class="overflowclass">一款AI工具,主要用于通过 Woy.ai AI 导航站发现 2024 年顶尖的 AI 工具!,适合需要提升相关任务效率的用户。</p>
</div>
<a rel="nofollow" href="/ai/2638" title="Woy AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>可以使用部分初始化语法,仅初始化数组的一部分元素。例如:</p><pre class="brush:php;toolbar:false;">int array[5] = {1, 2};
在这种情况下,数组的第一个和第二个元素被初始化为 1 和 2,其余元素被初始化为 0。
5. 使用 calloc 初始化
可以使用 calloc 函数分配并初始化内存空间,并将其用作数组。calloc 将所有位初始化为 0,因此对于需要从 0 开始的数组非常有用。例如:
int *array = calloc(5, sizeof(int));
6. 使用 memset 初始化
可以使用 memset 函数将数组的所有元素初始化为指定的值。例如:
int array[5]; memset(array, 0, sizeof(array));
13万字C语言保姆级教程(深入):立即使用
在学习笔记中,你将探索c语言的核心概念和高级技巧!










