<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C语言 &#8211; FoxDevelop</title>
	<atom:link href="https://www.foxdevelop.com/zh/category/c%E8%AF%AD%E8%A8%80/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.foxdevelop.com</link>
	<description>独立软件开发工作室</description>
	<lastBuildDate>Tue, 29 Sep 2026 03:55:51 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.2</generator>

<image>
	<url>https://www.foxdevelop.com/wp-content/uploads/2026/05/fox-svgrepo-com-1.png</url>
	<title>C语言 &#8211; FoxDevelop</title>
	<link>https://www.foxdevelop.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>总结</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e6%80%bb%e7%bb%93/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e6%80%bb%e7%bb%93/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:55:37 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13548</guid>

					<description><![CDATA[C语言基础回顾 C语言历史与计算机结构 1972年贝尔实验室 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">C语言基础回顾</h3>



<h4 class="wp-block-heading">C语言历史与计算机结构</h4>



<p class="wp-block-paragraph">1972年贝尔实验室 Dennis Ritchie 和 Ken Thompson 在开发 UNIX 时设计 C 语言。</p>



<p class="wp-block-paragraph">C语言在 B 语言（汤普逊发明）的基础上进行设计。</p>



<p class="wp-block-paragraph">由于 C 语言与 UNIX 关系密切，UNIX 系统通常会将 C 编译器作为软件包的一部分。安装 Linux 时，通常也会安装 C 编译器。</p>



<p class="wp-block-paragraph">功能强大且灵活的 UNIX 操作系统，大部分是用 C 语言写的。</p>



<p class="wp-block-paragraph">很多其它的语言（如 FORTRAN、Perl、Python、Pascal、LISP、Logo、BASIC）的许多编译器和解释器都是用 C 语言编写的。也就是用 C 开发的工具去把这些语言的源码转换为计算机可以执行的程序。</p>



<p class="wp-block-paragraph">另外，大多数 C 实现都有一个大型的库，包含众多有用的 C 函数。这些函数用于处理程序员经常需要解决的问题。</p>



<p class="wp-block-paragraph">先了解计算机的结构：</p>



<ol class="wp-block-list">
<li>中央处理单元（CPU）承担绝大部分的运算工作</li>



<li>随机存取内存（RAM）是存储程序和文件的工作区</li>



<li>永久内存存储设备（过去一般指机械硬盘，现在还包括固态硬盘）即使在关闭计算机后，也不会丢失之前储存的程序和文件</li>



<li>外围设备（如键盘、鼠标、触摸屏、监视器）提供人与计算机之间的交互</li>
</ol>



<p class="wp-block-paragraph">CPU 的工作是核心，其实它的工作也是很简单枯燥：它就是从内存中读取一条条的指令，执行一条指令再到下一条指令，指令执行的时候，可能需要用到一些数据。</p>



<p class="wp-block-paragraph">CPU 就是这样不断在执行这些指令。只不过是它的执行速度非常快。每秒钟可以达到十几亿次。以后还会更快。</p>



<p class="wp-block-paragraph">就是因为它快，所以我们的计算机可以同时多个软件在运行。</p>



<p class="wp-block-paragraph">CPU 由若干个寄存器组成，每个寄存器都可以储存一个数字。这些数字有可能代表一个数据，比如 12、2、3 这些，也可能表示一条指令，比如 mov 移动等。</p>



<p class="wp-block-paragraph">CPU 能理解的指令有限（这些指令的集合叫作指令集）。而且，这些指令相当具体，其中的许多指令都是用于请求计算机把一个数字从一个位置移动到另一个位置。例如，从内存移动到寄存器。</p>



<p class="wp-block-paragraph">比如下面要求两个数的和：</p>



<ol class="wp-block-list">
<li>从内存位置 2000 上把一个数字拷贝到寄存器 A。</li>



<li>从内存位置 2004 上把另一个数字拷贝到寄存器 B。</li>



<li>把寄存器 B 中的内容与寄存器 A 中的内容相加，把结果储存在寄存器 A 中。</li>



<li>把寄存器 A 中的内容拷贝到内存位置 2008。</li>
</ol>


<pre class="wp-block-code"><span><code class="hljs">mov 2000 A
mov 2004 B
add B A
mov A 2008</code></span></pre>


<p class="wp-block-paragraph">上面的指令就完成了两个数的和，具体就是 2000 内存中的数和 2004 内存中的数的和。</p>



<p class="wp-block-paragraph">机器语言、汇编语言、高级语言</p>



<p class="wp-block-paragraph">高级语言的目的就是抽象和简化低级语言，使得程序员可以使用更接近人类思维的语言来要求计算机做事情。</p>



<p class="wp-block-paragraph">例如我们之前要求两个数的和，汇编语言可能是这样子（如下代码只是例子，不是正确的代码）：</p>


<pre class="wp-block-code"><span><code class="hljs">mov 2000 A
mov 2004 B
add B A
mov A 2008</code></span></pre>


<p class="wp-block-paragraph">如果是机器语言，比如以前的卡片机。bug 为什么叫 bug？</p>



<p class="wp-block-paragraph">现在高级语言就简单了：</p>


<pre class="wp-block-code"><span><code class="hljs">int a = 1;
int b = 2;
int c = a + b;</code></span></pre>


<p class="wp-block-paragraph">对于我们人来说看上面的高级语言可能非常好理解，但是对于计算机来说那就是一堆无法理解的无用数据。</p>



<p class="wp-block-paragraph">编译器在这里派上了用场。编译器是把高级语言程序翻译成计算机能理解的机器语言指令集的程序。</p>



<p class="wp-block-paragraph">程序员进行高级思维活动，而编译器则负责处理冗长乏味的细节工作。</p>



<p class="wp-block-paragraph">编译器还有一个优势：它可以把同一份代码，转换为不同的 CPU 的机器语言。因为不同的 CPU 它们的架构是不一样的，指令也就不一样。比如对于 Intel 的 CPU 可能 0111110 是加，而对于 ARM 的 CPU 可能 01101010 是加。</p>



<p class="wp-block-paragraph">因此，使用合适的编译器或编译器集，便可把一种高级语言程序转换成供各种不同类型 CPU 使用的机器语言程序。一旦解决了一个编程问题，便可让编译器集翻译成不同 CPU 使用的机器语言。</p>



<p class="wp-block-paragraph">简而言之，高级语言（如 C、Java、Pascal）以更抽象的方式描述行为，不受限于特定 CPU 或指令集。而且，高级语言简单易学，用高级语言编程比用机器语言编程容易得多。</p>



<h4 class="wp-block-heading">程序开发过程</h4>



<p class="wp-block-paragraph">最早的编译器</p>



<p class="wp-block-paragraph">我们如果要开发一个程序，那么要经过那些过程呢？</p>



<ol class="wp-block-list">
<li>程序的作用和目的是什么？想要程序去做什么首先自己要明确自己想做什么，思考你的程序需要哪些信息，要进行哪些计算和控制，以及程序应该要报告什么信息，也就是程序是做什么的。要用户提供什么，最后给什么结果用户。</li>



<li>设计程序，给程序设计，要什么数据，提供什么，那个地方放什么，比如按钮、图片等等，还有程序分多少个模块等等这些。</li>



<li>编写代码。代码是一串文本，我们可以使用一些工具来编写。</li>
</ol>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int dogs;
    printf(<span class="hljs-string">"How many dogs do you have?\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;dogs);
    printf(<span class="hljs-string">"So you have %d dog(s)!\n"</span>, dogs);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">C 是最广泛使用的计算机编程语言之一。C 之所以如此受欢迎是因为它可靠、简单且易于使用。这就是为什么尽管出现了许多新语言的事实，但 C 仍然是使用最广泛的语言。</p>



<h5 class="wp-block-heading">C的特点</h5>



<ul class="wp-block-list">
<li>快</li>



<li>简单易学</li>



<li>最强大的编程语言</li>



<li>具有许多内置功能和运算符，可简化复杂程序</li>



<li>可以在多种计算机平台上进行编译</li>



<li>快速高效</li>



<li>用 C 编写的程序是可移植的，即，为一种类型的计算机或操作系统编写的程序可以在最小的修改下就可以在另一种类型的计算机或操作系统上运行</li>



<li>也广泛用于许多大型项目</li>
</ul>



<h5 class="wp-block-heading">如何开始？</h5>



<p class="wp-block-paragraph">在整个 C 教程中，我们将学习编写 C 程序。但是之后呢？</p>



<p class="wp-block-paragraph">编写完任何程序后，我们需要编译并运行它以查看程序的输出。</p>



<p class="wp-block-paragraph">那么，编译是什么意思？</p>



<p class="wp-block-paragraph">当我们用 C 语言编写程序时，需要将其转换为机器语言（由 0 和 1 组成的二进制语言），以便计算机能够理解并执行它。这种转换称为编译程序。我们借助编译器来编译代码。</p>



<h5 class="wp-block-heading">集成开发环境（IDE）</h5>



<p class="wp-block-paragraph">为了编写和编译我们的 C 程序，我们提供了许多 IDE。</p>



<p class="wp-block-paragraph">IDE 由文本编辑器和编译器组成。我们在文本编辑器中键入程序，然后由编译器进行编译。</p>



<p class="wp-block-paragraph">文本编辑器：我们在文本编辑器中编写程序。包含我们程序的文件称为源文件，并以 <code>.c</code> 扩展名保存。</p>



<p class="wp-block-paragraph">C 编译器：将程序保存在扩展名为 <code>.c</code> 的文件中后，我们需要对其进行编译。如我们所见，我们需要编译代码以将其转换为计算机可以理解的机器语言。</p>



<p class="wp-block-paragraph">现在让我们看看如何在不同的操作系统上编译和执行 C 程序。</p>



<p class="wp-block-paragraph"><strong>在 Windows 上编写和编译 C 程序</strong>​</p>



<p class="wp-block-paragraph">尽管有很多 IDE 可以用于 Windows 的 C 程序的编辑和编译，但在这里我们讨论的是使用 DevC++ 进行编辑和编译的程序，它允许我们编辑、编译和运行程序。我们可以使用 DevC++ 本身编写和保存程序，然后使用该程序进行编译。</p>



<p class="wp-block-paragraph">在学习用 DevC++ 编写程序之前，请首先确保已将其安装在计算机中。如果没有，请下载并安装它。</p>



<p class="wp-block-paragraph">要在 DevC++ 中编写和编译，请按照以下步骤操作：</p>



<ol class="wp-block-list">
<li>打开 DevC++ 时，您将看到一个窗口。单击&#8221;源文件&#8221;选项。</li>



<li>如下所示，在空白处编写 C 程序并保存。</li>
</ol>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    printf(<span class="hljs-string">"Hello World\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<ol class="wp-block-list">
<li>编写程序后，单击&#8221;编译并运行&#8221;。</li>



<li>将出现一个输出窗口，显示打印为&#8221;Hello World&#8221;的结果。</li>
</ol>



<p class="wp-block-paragraph"><strong>在 Linux 上编写和编译 C 程序</strong>​</p>



<p class="wp-block-paragraph">对于 Linux，您可以使用各种文本编辑器（如 vim、gedit 或 Emacs）编写 C 程序。假设文本编辑器是 gedit，以下步骤显示了如何编辑和编译 C 程序。</p>



<ol class="wp-block-list">
<li>打开终端（ctrl+alt+T）。</li>



<li>在您喜欢的编辑器中打开一个扩展名为 <code>.c</code> 的新文件（在我们的情况下文件名为 <code>hello.c</code>）。命令是：<code>gedit hello.c</code></li>



<li>文本编辑器窗口将打开。在下面键入下面的 C 程序并保存。</li>
</ol>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    printf(<span class="hljs-string">"Hello World\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<ol class="wp-block-list">
<li>要编译程序，请键入 <code>cc -c hello.c</code>，然后按 Enter。</li>



<li>现在键入 <code>cc hello.c -o hello</code> 并按 Enter。这将创建名称为 <code>hello</code> 的可执行文件。</li>



<li>要运行程序，请键入 <code>./hello</code>，然后按 Enter。这将显示程序的输出。</li>
</ol>



<h4 class="wp-block-heading">第一个C程序解析</h4>



<p class="wp-block-paragraph">现在让我们从停下来的&#8221;Hello World&#8221;代码开始。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    printf(<span class="hljs-string">"Hello World\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">编译以上代码后，&#8221;Hello World&#8221;将显示在屏幕上。</p>



<p class="wp-block-paragraph"><code>printf("Hello World\n");</code> → <code>printf</code> 是一个函数，它在屏幕上显示括号内的内容。</p>



<p class="wp-block-paragraph">我们使用了单词函数，所以让我们讨论一下它是什么。函数就像一个机器，需要从我们这里得到东西（不一定），然后执行操作。简而言之，函数从用户那里获取输入，然后返回输出。</p>



<p class="wp-block-paragraph">在上面的示例中，<code>printf</code> 以&#8221;Hello World\n&#8221;作为输入，并在屏幕上显示&#8221;Hello World&#8221;，但不带有&#8221;\n&#8221;。因此，让我们讨论一下它是什么。</p>



<p class="wp-block-paragraph"><code>\n</code> 是称为换行符的特殊字符，用于更改行或打印新行。因此，&#8217;Hello World&#8217;之后的&#8217;\n&#8217;更改了行或打印了新行。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    printf(<span class="hljs-string">"Hello\n World\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">如您所见，&#8221;\n&#8221;在&#8221;Hello&#8221;和&#8221;World&#8221;之间打印了新行。因此，&#8221;\n&#8221;用于在程序中打印新行。</p>



<p class="wp-block-paragraph">最后尝试编写不带&#8217;\n&#8217;的相同代码，您将看到光标不会更改行，并且将开始在同一行上打印所有内容。</p>



<p class="wp-block-paragraph"><code>;</code>（分号）告诉编译器语句结束。我们需要输入&#8221;;&#8221;在每个语句的末尾，例如函数调用、变量声明等。</p>



<p class="wp-block-paragraph">因此，通过输入&#8221;;&#8221;在末尾 <code>printf("Hello World\n");</code>，我们已经在此处结束了该声明。此后写的所有内容将是新的声明。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    printf(<span class="hljs-string">"Hello World\n"</span>); <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>int main()</code> → <code>main</code> 也是一个函数。它是在执行 C 代码时首先编译的，也就是说，任何 C 程序的执行都从该 <code>main()</code> 函数开始。<code>int</code> 在 <code>main</code> 之前表示该函数将返回（或返回给我们）一个整数。</p>



<p class="wp-block-paragraph">由于每个 C 程序的执行均从该 <code>main</code> 功能开始，因此所有 C 程序都必须具有此 <code>main()</code> 功能。</p>



<p class="wp-block-paragraph"><code>{ }</code>（大括号）在刚过 <code>main()</code> 功能包围该功能的主体。这意味着它表示&#8221;主体&#8221;内部的事物。</p>



<p class="wp-block-paragraph"><code>return 0</code> → 如前所述，该 <code>main</code> 函数返回一个整数值（<code>int main()</code>），因此此处返回 0。<code>return</code> 是一个关键字，用于从函数返回一些值。返回 0 表示我们的程序已成功运行，并且我们使用此 <code>return</code> 语句终止 <code>main</code> 函数。</p>



<p class="wp-block-paragraph"><code>#include &lt;stdio.h&gt;</code> → <code>stdio.h</code> 代表标准输入输出。它是 C 语言的一个库，其中包含函数的定义，例如 <code>printf</code>。因此，它将告诉编译器&#8221;printf&#8221;应如何工作。<code>#include</code> 是一个预处理器，用于将程序与 <code>stdio.h</code> 链接。</p>



<h4 class="wp-block-heading">注释</h4>



<p class="wp-block-paragraph">注释是在代码内部编写的语句，在编译我们的代码时，编译器只会忽略它们。编写注释以使我们的代码对人类更具可读性。</p>



<p class="wp-block-paragraph">注释介于 <code>/* ... */</code> 或 <code>//</code> 之间。</p>



<p class="wp-block-paragraph">为什么要注释：如前所述，它使我们的代码更具可读性。假设您已经编写了一个软件，并在发布它之后，雇用了一些优秀的程序员来进行软件维护。没有注释，对他们来说，理解您的代码将是非常困难的工作。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">//This is single line comment</span>
<span class="hljs-comment">//This is also a comment</span>
<span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    printf(<span class="hljs-string">"Hello World\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">/*Hello World code*/</span>
<span class="hljs-comment">/* Comments will not be compiled and will be ignored */</span>
<span class="hljs-comment">/* It is a
multiline
comment*/</span>
<span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    <span class="hljs-comment">//printf function</span>
    printf(<span class="hljs-string">"Hello World\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">接受用户输入</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a;
    printf(<span class="hljs-string">"Enter an integer"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;a);
    printf(<span class="hljs-string">"Entered value is : %d\n"</span>, a);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>int a;</code> → 这是一条声明变量&#8221;a&#8221;是整数的语句。通过此声明，&#8221;a&#8221;进入了我们程序的世界。</p>



<p class="wp-block-paragraph"><code>scanf</code> 是另一个功能，用于从键盘取值。<code>%d</code> 用于 C 中的整数，在这里，它表示 <code>scanf</code> 将从键盘获取整数值。<code>&amp;a</code> → 表示在&#8217;a&#8217;的地址上。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int x;
    int y;
    printf(<span class="hljs-string">"Enter two integers\n"</span>);
    scanf(<span class="hljs-string">"%d %d"</span>, &amp;x, &amp;y);
    int z = x + y;
    printf(<span class="hljs-string">"Entered value is : %d and %d and their sum is %d\n"</span>, x, y, z);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">数据类型与变量</h4>



<p class="wp-block-paragraph">在程序中使用变量之前，需要对其进行声明。数据类型用于为变量分配类型。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int x;
    x = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>%d</code> 用于 int，<code>%c</code> 用于 char，<code>%f</code> 用于 float。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    float a;
    int b;
    char ch;

    printf(<span class="hljs-string">"\nEnter value of float\n"</span>);
    scanf(<span class="hljs-string">"%f"</span>, &amp;a);

    printf(<span class="hljs-string">"\nEnter value of int\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;b);

    printf(<span class="hljs-string">"\nEnter value of char\n"</span>);
    scanf(<span class="hljs-string">" %c"</span>, &amp;ch);

    printf(<span class="hljs-string">"\nValue of float : %f"</span>, a);
    printf(<span class="hljs-string">"\nValue of int : %d"</span>, b);
    printf(<span class="hljs-string">"\nValue of char : %c"</span>, ch);
    printf(<span class="hljs-string">"\nValue of float(rounded) : %.2f\n"</span>, a);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>%.2f</code> 表示要打印的变量将为 float 类型，而&#8217;.2&#8217;表示将仅舍入到小数点后两位的数字。</p>



<p class="wp-block-paragraph">有符号和无符号：有符号和无符号变量告诉我们它是否可以采取正值、负值或同时采取这两种方法。<code>signed</code> 关键字用于那些可以取正值也可以取负值的变量。<code>unsigned</code> 关键字用于那些只能接受零或正值的变量。</p>


<pre class="wp-block-code"><span><code class="hljs">unsigned int x;</code></span></pre>


<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>类型</th><th>大小</th><th>取值范围</th></tr></thead><tbody><tr><td>int</td><td>2或4个字节</td><td>-32,768至32,767或-2,147,483,648至2,147,483,647</td></tr><tr><td>unsigned int</td><td>2或4个字节</td><td>0至65,535或0至4,294,967,295</td></tr><tr><td>char</td><td>1个字节</td><td>-128至127或0至255</td></tr><tr><td>signed char</td><td>1个字节</td><td>-128至127</td></tr><tr><td>unsigned char</td><td>1个字节</td><td>0至255</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">在 <code>printf</code> 中，<code>%d</code> 用于有符号整数，而 <code>%u</code> 用于无符号整数。</p>



<p class="wp-block-paragraph">如何存储字符值：只要将字符值赋予 char 类型的变量，就会存储其 ASCII 值。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    char ch;
    printf(<span class="hljs-string">"\nEnter value of char\n"</span>);
    scanf(<span class="hljs-string">"%c"</span>, &amp;ch);
    printf(<span class="hljs-string">"\nCharacter value of character = %c"</span>, ch);
    printf(<span class="hljs-string">"\nASCII value = %d\n"</span>, ch);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">类型转换：类型转换是变量从一种数据类型到另一种数据类型的转换。</p>



<p class="wp-block-paragraph">隐式转换：假设我们在 C 中添加一个整数和一个字符，例如 <code>2 + 'a'</code>。这是 C 语言中的有效表达式，因为 C 语言会自动将字符值&#8221;a&#8221;转换为整数（ASCII 值），然后将它们加起来。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">12</span>;
    char ch = <span class="hljs-string">'h'</span>;
    int sum = a + ch;
    printf(<span class="hljs-string">"Sum = %d\n"</span>, sum);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">显式转换：我们还可以手动将值从一种数据类型转换为另一种数据类型，如下所示：<code>(数据类型)值;</code></p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    float x = <span class="hljs-number">2.45</span>;
    printf(<span class="hljs-string">"%d\n"</span>, (int)x);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">运算符</h4>



<p class="wp-block-paragraph">运算符是告诉编译器对变量执行某些操作的符号。</p>



<h5 class="wp-block-heading">算术运算符</h5>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>运算符</th><th>描述</th><th>例</th></tr></thead><tbody><tr><td>+</td><td>添加操作数</td><td>a + b</td></tr><tr><td>&#8211;</td><td>从第一个减去第二个操作数</td><td>a &#8211; b</td></tr><tr><td>*</td><td>将两个操作数相乘</td><td>a * b</td></tr><tr><td>/</td><td>用分子除以分母</td><td>a / b</td></tr><tr><td>%</td><td>模运算符，在整数除法后返回余数</td><td>a % b</td></tr></tbody></table></figure>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">25</span>;
    int b = <span class="hljs-number">8</span>;
    printf(<span class="hljs-string">"sum = %d"</span>, (a+b));
    printf(<span class="hljs-string">"\ndifference = %d"</span>, (a-b));
    printf(<span class="hljs-string">"\nproduct = %d"</span>, (a*b));
    printf(<span class="hljs-string">"\nremainder = %d\n"</span>, (a%b));
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">如果我们将两个整数相除，则结果将是一个整数。<code>5/2 = 2</code>（不是 2.5）。要获得 2.5，分子或分母中的至少一个必须具有十进制（浮点）值。</p>



<p class="wp-block-paragraph">运算符优先级：首先对方括号'()&#8217;中的表达式求值。之后遵循优先级表。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>优先级</th><th>类别</th><th>运算符</th><th>关联性</th></tr></thead><tbody><tr><td>1</td><td>乘除取模</td><td>* / %</td><td>左到右</td></tr><tr><td>2</td><td>加减</td><td>+ &#8211;</td><td>左到右</td></tr><tr><td>3</td><td>赋值</td><td>=</td><td>右到左</td></tr></tbody></table></figure>



<h5 class="wp-block-heading">关系运算符</h5>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>运算符</th><th>描述</th><th>例</th></tr></thead><tbody><tr><td>==</td><td>等于</td><td>(a == b)</td></tr><tr><td>!=</td><td>不等于</td><td>(a != b)</td></tr><tr><td>&gt;</td><td>比&#8230;更大</td><td>(a &gt; b)</td></tr><tr><td>&lt;</td><td>少于</td><td>(a &lt; b)</td></tr><tr><td>&gt;=</td><td>大于或等于</td><td>(a &gt;= b)</td></tr><tr><td>&lt;=</td><td>小于或等于</td><td>(a &lt;= b)</td></tr></tbody></table></figure>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">5</span>, b = <span class="hljs-number">6</span>;
    printf(<span class="hljs-string">"\n%d"</span>, a == b);
    printf(<span class="hljs-string">"\n%d"</span>, a != b);
    printf(<span class="hljs-string">"\n%d"</span>, a &gt; b);
    printf(<span class="hljs-string">"\n%d"</span>, a &lt; b);
    printf(<span class="hljs-string">"\n%d"</span>, a &gt;= b);
    printf(<span class="hljs-string">"\n%d"</span>, a &lt;= b);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>=</code> 和 <code>==</code> 之间的差异：<code>=</code> 是赋值运算符，而 <code>==</code> 是相等运算符。</p>



<h5 class="wp-block-heading">逻辑运算符</h5>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>运算符</th><th>描述</th><th>例</th></tr></thead><tbody><tr><td>&amp;&amp;</td><td>逻辑与</td><td>(a == b) &amp;&amp; (a == 8)</td></tr><tr><td>||</td><td>逻辑或</td><td>(a != b) || (a == 5)</td></tr><tr><td>!</td><td>逻辑非</td><td>!(a == 5)</td></tr></tbody></table></figure>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">5</span>, b = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"\n%d"</span>, a &amp;&amp; b);
    printf(<span class="hljs-string">"\n%d"</span>, a || b);
    printf(<span class="hljs-string">"\n%d"</span>, !a);
    printf(<span class="hljs-string">"\n%d"</span>, !b);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">赋值运算符</h5>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>运算符</th><th>描述</th><th>例</th></tr></thead><tbody><tr><td>=</td><td>将右操作数的值分配给左操作数</td><td>C = A + B</td></tr><tr><td>+=</td><td>将右操作数的值添加到左操作数</td><td>C += A</td></tr><tr><td>-=</td><td>将右操作数的值减去左操作数</td><td>C -= A</td></tr><tr><td>*=</td><td>将右操作数的值与左操作数相乘</td><td>C *= A</td></tr><tr><td>/=</td><td>将左操作数的值与右操作数相除</td><td>C /= A</td></tr><tr><td>%=</td><td>使用两个操作数取模</td><td>C %= A</td></tr></tbody></table></figure>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">25</span>;
    int b = <span class="hljs-number">8</span>;
    a += b;
    printf(<span class="hljs-string">"%d\n"</span>, a);
    a -= b;
    printf(<span class="hljs-string">"%d\n"</span>, a);
    a *= b;
    printf(<span class="hljs-string">"%d\n"</span>, a);
    a /= b;
    printf(<span class="hljs-string">"%d\n"</span>, a);
    a %= b;
    printf(<span class="hljs-string">"%d\n"</span>, a);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">增减运算符</h5>



<p class="wp-block-paragraph"><code>++</code> 和 <code>--</code> 分别称为增量和减量运算符。<code>a++</code> 将变量&#8217;a&#8217;的值增加 1，而 <code>a--</code> 将 a 的值减小 1。</p>



<p class="wp-block-paragraph">前缀和后缀之间的区别：<code>a++</code> 在&#8217;a&#8217;的值递增之前返回&#8217;a&#8217;的值，而 <code>++a</code> 首先将&#8217;a&#8217;的值增加 1，然后返回递增值&#8221;a&#8221;。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">15</span>, b = <span class="hljs-number">15</span>, c = <span class="hljs-number">15</span>, d = <span class="hljs-number">15</span>;
    printf(<span class="hljs-string">"\nvalue of a++ = %d"</span>, a++);
    printf(<span class="hljs-string">"\nvalue of ++b = %d"</span>, ++b);
    printf(<span class="hljs-string">"\nvalue of c-- = %d"</span>, c--);
    printf(<span class="hljs-string">"\nvalue of --d = %d"</span>, --d);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">sizeof 运算符</h5>



<p class="wp-block-paragraph"><code>sizeof()</code> 运算符用于返回变量的大小。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int i = <span class="hljs-number">6</span>;
    int j;
    char c;
    float f;
    double d;
    printf(<span class="hljs-string">"size of integer variable i = %d"</span>, sizeof(i));
    printf(<span class="hljs-string">"\nsize of integer variable j = %d"</span>, sizeof(j));
    printf(<span class="hljs-string">"\nsize of character variable = %d"</span>, sizeof(c));
    printf(<span class="hljs-string">"\nsize of float variable = %d"</span>, sizeof(f));
    printf(<span class="hljs-string">"\nsize of double variable = %d"</span>, sizeof(d));
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">决策与条件</h4>



<p class="wp-block-paragraph">很多时候，我们需要先查看条件，然后做出决定。这种决策方式是通过在 C 中使用 <code>if</code> 语句完成的。</p>



<h5 class="wp-block-heading">if 语句</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">5</span>;
    int b = <span class="hljs-number">5</span>;
    <span class="hljs-keyword">if</span> (a == b)
    {
        printf(<span class="hljs-string">"a and b are equal\n"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">if&#8230;else 语句</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">5</span>;
    int b = <span class="hljs-number">8</span>;
    <span class="hljs-keyword">if</span> (a == b)
    {
        printf(<span class="hljs-string">"a and b are equal\n"</span>);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"a and b are not equal\n"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">else if 语句</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">if</span>(a == <span class="hljs-number">30</span>)
    {
        printf(<span class="hljs-string">"It is 30\n"</span>);
    }
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(a == <span class="hljs-number">10</span>)
    {
        printf(<span class="hljs-string">"It is 10\n"</span>);
    }
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(a == <span class="hljs-number">5</span>)
    {
        printf(<span class="hljs-string">"It is 5\n"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">如果有一条语句在 <code>if</code>、<code>else</code> 或者 <code>else if</code> 里面，我们可以跳过括号（{}）。</p>



<h5 class="wp-block-heading">if/else 嵌套</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">8</span>;
    int b = <span class="hljs-number">4</span>;
    int c = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">if</span> (a &gt; b)
    {
        <span class="hljs-keyword">if</span> (a &gt; c)
        {
            printf(<span class="hljs-string">"a is the greatest number.\n"</span>);
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">三元运算符</h5>



<p class="wp-block-paragraph">条件 <code>?</code> expression1 <code>:</code> expression2 <code>;</code></p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int age;
    printf(<span class="hljs-string">"Enter age"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;age);
    (age &gt; <span class="hljs-number">18</span>) ? printf(<span class="hljs-string">"eligible to vote\n"</span>) : printf(<span class="hljs-string">"not eligible to vote\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">循环</h4>



<h5 class="wp-block-heading">while 循环</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">while</span> (a &lt;= <span class="hljs-number">10</span>)
    {
        printf(<span class="hljs-string">"Hello World\n"</span>);
        a++;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">for 循环</h5>


<pre class="wp-block-code"><span><code class="hljs">for (初始化; 条件; 改变)
{
    语句
}</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a;
    <span class="hljs-keyword">for</span> (a = <span class="hljs-number">1</span>; a &lt;= <span class="hljs-number">10</span>; a++)
    {
        printf(<span class="hljs-string">"Hello World\n"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">嵌套循环</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int i;
    int j;
    <span class="hljs-keyword">for</span>(i = <span class="hljs-number">12</span>; i &lt;= <span class="hljs-number">14</span>; i++)
    {
        printf(<span class="hljs-string">"Table of %d\n"</span>, i);
        <span class="hljs-keyword">for</span>(j = <span class="hljs-number">1</span>; j &lt;= <span class="hljs-number">10</span>; j++)
        {
            printf(<span class="hljs-string">"%d*%d\t=\t%d\n"</span>, i, j, i*j);
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">do&#8230;while 循环</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">do</span>
    {
        printf(<span class="hljs-string">"Hello World\n"</span>);
        a++;
    }
    <span class="hljs-keyword">while</span>(a &lt;= <span class="hljs-number">10</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">无限循环</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    <span class="hljs-keyword">for</span>(;;)
    {
        printf(<span class="hljs-string">"This is not gonna end!\n"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">要终止无限循环，请按 Ctrl+C。</p>



<h4 class="wp-block-heading">switch..case 语句</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">switch</span>(expression)
{
    <span class="hljs-keyword">case</span> constant1:
        statement(s);
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> constant2:
        statement(s);
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">default</span>:
        statement(s);
}</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    char grade;
    printf(<span class="hljs-string">"Enter your grade\n"</span>);
    scanf(<span class="hljs-string">" %c"</span>, &amp;grade);
    <span class="hljs-keyword">switch</span>(grade)
    {
        <span class="hljs-keyword">case</span> <span class="hljs-string">'A'</span>:
            printf(<span class="hljs-string">"Excellent!\n"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">'B'</span>:
            printf(<span class="hljs-string">"Outstanding!\n"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">'C'</span>:
            printf(<span class="hljs-string">"Good!\n"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">'D'</span>:
            printf(<span class="hljs-string">"Can do better\n"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">'E'</span>:
            printf(<span class="hljs-string">"Just passed\n"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">'F'</span>:
            printf(<span class="hljs-string">"You failed\n"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:
            printf(<span class="hljs-string">"Invalid grade\n"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">break 和 continue</h4>



<p class="wp-block-paragraph"><code>break</code> 用于在需要时中断或终止循环。<code>continue</code> 语句将控制权传递给条件测试，跳过了循环的其余语句。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a;
    <span class="hljs-keyword">for</span>(a = <span class="hljs-number">1</span>; a &lt;= <span class="hljs-number">10</span>; a++)
    {
        printf(<span class="hljs-string">"Hello World\n"</span>);
        <span class="hljs-keyword">if</span>(a == <span class="hljs-number">2</span>)
        {
            <span class="hljs-keyword">break</span>;
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a;
    <span class="hljs-keyword">for</span>(a = <span class="hljs-number">1</span>; a &lt;= <span class="hljs-number">10</span>; a++)
    {
        printf(<span class="hljs-string">"Hello World\n"</span>);
        <span class="hljs-keyword">if</span> (a == <span class="hljs-number">2</span>)
        {
            <span class="hljs-keyword">continue</span>;
        }
        printf(<span class="hljs-string">"a is not 2\n"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">函数</h4>



<p class="wp-block-paragraph">函数不过是一组代码并命名而来。而且可以随时调用它们而无需一次又一次地编写整个代码。</p>



<h5 class="wp-block-heading">库函数和用户定义函数</h5>



<p class="wp-block-paragraph">库函数是 C 中的预定义函数，如 <code>printf()</code> 和 <code>scanf()</code>。</p>



<p class="wp-block-paragraph">用户定义函数：我们还可以在 C 中定义我们自己的函数。</p>


<pre class="wp-block-code"><span><code class="hljs">return_type function_name(parameters);</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs">float average(int num1, int num2);</code></span></pre>


<p class="wp-block-paragraph">定义函数：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">float average(int num1, int num2)
{
    float avg;
    avg = (num1 + num2) / <span class="hljs-number">2.0</span>;
    <span class="hljs-keyword">return</span> avg;
}</code></span></pre>


<p class="wp-block-paragraph">调用函数：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

float average(int num1, int num2)
{
    float avg;
    avg = (num1 + num2) / <span class="hljs-number">2.0</span>;
    <span class="hljs-keyword">return</span> avg;
}

int main()
{
    int num1, num2;
    float c;
    printf(<span class="hljs-string">"Enter first number\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;num1);
    printf(<span class="hljs-string">"Enter second number\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;num2);
    c = average(num1, num2);
    printf(<span class="hljs-string">"Average is %.2f\n"</span>, c);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">如果一个函数不返回任何东西，则其返回类型为 <code>void</code>。</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">void</span> display(int n)
{
    printf(<span class="hljs-string">"Number is %d\n"</span>, n);
}</code></span></pre>


<p class="wp-block-paragraph">在另一个内部调用一个函数：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int div_2(int a)
{
    <span class="hljs-keyword">if</span>(a % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }
    <span class="hljs-keyword">else</span>
    {
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    }
}

void div_6(int b)
{
    <span class="hljs-keyword">if</span>(div_2(b) == <span class="hljs-number">1</span> &amp;&amp; b % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>)
    {
        printf(<span class="hljs-string">"Yes, the number is divisible by 6.\n"</span>);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"No, the number is not divisible by 6.\n"</span>);
    }
}

int main()
{
    div_6(<span class="hljs-number">12</span>);
    div_6(<span class="hljs-number">25</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">递归：递归是在同一函数内调用一个函数。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int factorial(int a)
{
    <span class="hljs-keyword">if</span>(a == <span class="hljs-number">0</span> || a == <span class="hljs-number">1</span>)
    {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }
    <span class="hljs-keyword">else</span>
    {
        <span class="hljs-keyword">return</span> a * factorial(a - <span class="hljs-number">1</span>);
    }
}

int main()
{
    int n;
    printf(<span class="hljs-string">"Enter number\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;n);
    int fact = factorial(n);
    printf(<span class="hljs-string">"Factorial of %d is %d\n"</span>, n, fact);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">指针</h4>



<p class="wp-block-paragraph">指针指向某个变量，即它存储变量的地址。例如，如果&#8221;a&#8221;具有地址 9562628，则指向&#8221;a&#8221;的指针将在其中存储值 9562628。</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">int a = 44;
int *b;
b = <span class="hljs-symbol">&amp;a;</span></code></span></pre>


<p class="wp-block-paragraph"><code>int *b</code> 表示&#8221;b&#8221;是一个指向整数的指针。<code>b = &amp;a</code> 意味着&#8221;b&#8221;现在存储&#8221;a&#8221;的地址。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int a = <span class="hljs-number">10</span>;
    int *p;
    p = &amp;a;
    printf(<span class="hljs-string">"p = %u\n"</span>, p);
    printf(<span class="hljs-string">"*p = %d\n"</span>, *p);
    printf(<span class="hljs-string">"&amp;p = %u\n"</span>, &amp;p);
    printf(<span class="hljs-string">"*&amp;p = %u\n"</span>, *&amp;p);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">将指针传递给函数：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
void swap(int *a, int *b)
{
    int t;
    t = *a;
    *a = *b;
    *b = t;
}

int main()
{
    int num1, num2;
    printf(<span class="hljs-string">"Enter first number\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;num1);
    printf(<span class="hljs-string">"Enter second number\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;num2);
    swap(&amp;num1, &amp;num2);
    printf(<span class="hljs-string">"First number : %d\n"</span>, num1);
    printf(<span class="hljs-string">"Second number : %d\n"</span>, num2);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">数组</h4>



<p class="wp-block-paragraph">简单来说，数组就是一个集合。在 C 语言中，它是一组相似类型的数据。</p>



<h5 class="wp-block-heading">声明数组</h5>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">int</span> <span class="hljs-selector-tag">n</span><span class="hljs-selector-attr">&#91;6]</span>;</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs">int n&#91;] = {2, 3, 15, 8, 48, 13};</code></span></pre>


<p class="wp-block-paragraph">数组索引从 0 开始。<code>n[0]</code> 是第一个元素。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    int marks&#91;<span class="hljs-number">3</span>];
    float average;

    printf(<span class="hljs-string">"Enter marks of first student\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;marks&#91;<span class="hljs-number">0</span>]);

    printf(<span class="hljs-string">"Enter marks of second student\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;marks&#91;<span class="hljs-number">1</span>]);

    printf(<span class="hljs-string">"Enter marks of third student\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;marks&#91;<span class="hljs-number">2</span>]);

    average = (marks&#91;<span class="hljs-number">0</span>] + marks&#91;<span class="hljs-number">1</span>] + marks&#91;<span class="hljs-number">2</span>]) / <span class="hljs-number">3.0</span>;
    printf(<span class="hljs-string">"Average marks : %f\n"</span>, average);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">指向数组的指针</h5>



<p class="wp-block-paragraph">数组的名称是指向数组第一个元素的指针。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
int main()
{
    float n&#91;<span class="hljs-number">5</span>] = {<span class="hljs-number">20.4</span>, <span class="hljs-number">30.0</span>, <span class="hljs-number">5.8</span>, <span class="hljs-number">67</span>, <span class="hljs-number">15.2</span>};
    float *p;
    int i;
    p = n;
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++)
    {
        printf(<span class="hljs-string">"*(p + %d) = %f\n"</span>, i, *(p + i));
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h5 class="wp-block-heading">在函数中传递数组</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
float average(float a&#91;], int size)
{
    int i;
    float avg, sum = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span>(i = <span class="hljs-number">0</span>; i &lt; size; i++)
    {
        sum += a&#91;i];
    }
    avg = sum / size;
    <span class="hljs-keyword">return</span> avg;
}

int main()
{
    int size, j;
    printf(<span class="hljs-string">"Enter the size of array"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;size);
    float b, n&#91;size];
    <span class="hljs-keyword">for</span>(j = <span class="hljs-number">0</span>; j &lt; size; j++)
    {
        printf(<span class="hljs-string">"Value of n&#91;%d] : "</span>, j);
        scanf(<span class="hljs-string">"%f"</span>, &amp;n&#91;j]);
    }
    b = average(n, size);
    printf(<span class="hljs-string">"Average of numbers=%.2f\n"</span>, b);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">使用指针将数组传递给函数：</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">#include <span class="hljs-tag">&lt;<span class="hljs-name">stdio.h</span>&gt;</span>
display(int *p)
{
    int i;
    for(i = 0; i <span class="hljs-tag">&lt; <span class="hljs-attr">8</span>; ++<span class="hljs-attr">i</span>)
    {
        <span class="hljs-attr">printf</span>("<span class="hljs-attr">n</span>&#91;%<span class="hljs-attr">d</span>] = <span class="hljs-string">%d\n</span>", <span class="hljs-attr">i</span>, *<span class="hljs-attr">p</span>);
        <span class="hljs-attr">p</span>++;
    }
}

<span class="hljs-attr">int</span> <span class="hljs-attr">main</span>()
{
    <span class="hljs-attr">int</span> <span class="hljs-attr">n</span>&#91;] = <span class="hljs-string">{1,</span> <span class="hljs-attr">2</span>, <span class="hljs-attr">3</span>, <span class="hljs-attr">4</span>, <span class="hljs-attr">5</span>, <span class="hljs-attr">6</span>, <span class="hljs-attr">7</span>, <span class="hljs-attr">8</span>};
    <span class="hljs-attr">display</span>(<span class="hljs-attr">n</span>);
    <span class="hljs-attr">return</span> <span class="hljs-attr">0</span>;
}</span></code></span></pre>


<h4 class="wp-block-heading">二维数组</h4>



<p class="wp-block-paragraph">二维数组是数组的数组。</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">int board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
    {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
    {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
    {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
};</code></span></pre>


<h3 class="wp-block-heading">数组</h3>



<p class="wp-block-paragraph">简单来说，数组就是一个集合。</p>



<p class="wp-block-paragraph">同样在 C 语言中，它是一组相似类型的数据，可以是 int，float，double，char（字符串）等。所有数据类型必须相同。例如，我们不能有一个数组，其中一些数据是整数，有些数据是浮点数。</p>



<h4 class="wp-block-heading">为什么要数组？</h4>



<p class="wp-block-paragraph">假设我们需要在一个班级中存储 50 名学生的分数并计算平均分数。因此，声明 50 个单独的变量将完成这项工作，但是没有程序员愿意这样做。数组就派上用场了。</p>



<h4 class="wp-block-heading">如何声明数组</h4>


<pre class="wp-block-code"><span><code class="hljs language-css">数据类型 <span class="hljs-selector-tag">array_name</span><span class="hljs-selector-attr">&#91;array_size]</span>;</code></span></pre>


<p class="wp-block-paragraph">例如，采用整数 <code>n</code> 的数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">int</span> <span class="hljs-selector-tag">n</span><span class="hljs-selector-attr">&#91;6]</span>;</code></span></pre>


<p class="wp-block-paragraph"><code>n[ ]</code> 用于表示数组 <code>n</code>。这意味着 <code>n</code> 是一个数组。</p>



<p class="wp-block-paragraph">因此，<code>int n[6]</code> 意味着 <code>n</code> 是 6 个整数的数组。在这里，6 是数组的大小，即数组 <code>n</code> 中有 6 个元素。</p>



<p class="wp-block-paragraph">我们需要给出数组的大小，因为编译器需要在内存中分配空间，而这在不知道大小的情况下是不可能的。编译器借助数组中元素的数量和数组中存在的数据类型的大小来确定数组所需的大小。</p>



<p class="wp-block-paragraph">在这里 <code>int n[6]</code> 将空间分配给 6 个整数。</p>



<p class="wp-block-paragraph">我们还可以通过其他方法声明数组：</p>


<pre class="wp-block-code"><span><code class="hljs">int n&#91;] = {2, 3, 15, 8, 48, 13};</code></span></pre>


<p class="wp-block-paragraph">在这种情况下，我们要同时声明并为数组分配值。此处，无需指定数组大小，因为编译器从 <code>{2,3,15,8,48,13}</code> 中获取它。</p>



<h4 class="wp-block-heading">数组索引</h4>



<p class="wp-block-paragraph">数组的每个元素都有其索引。我们使用其索引访问数组的任何元素。</p>



<p class="wp-block-paragraph">上述数组的图片视图为：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>元素</th><th>2</th><th>3</th><th>15</th><th>8</th><th>48</th><th>13</th></tr></thead><tbody><tr><td>索引</td><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">0、1、2、3、4 和 5 是索引。就像它们是数组的 6 个不同元素的标识一样。索引始终从 0 开始。因此，数组的第一个元素的索引为 0。</p>



<p class="wp-block-paragraph">数组的索引从 0 开始。</p>



<p class="wp-block-paragraph">我们使用其索引访问数组的任何元素，并且语法如下：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">array_name</span><span class="hljs-selector-attr">&#91;index]</span></code></span></pre>


<p class="wp-block-paragraph">例如，如果数组的名称为 <code>n</code>，那么我们要编写访问第一个元素（索引为 0 的元素）<code>n[0]</code>。</p>



<p class="wp-block-paragraph">在这里：</p>



<ul class="wp-block-list">
<li><code>n[0]</code> 是 2</li>



<li><code>n[1]</code> 是 3</li>



<li><code>n[2]</code> 是 15</li>



<li><code>n[3]</code> 是 8</li>



<li><code>n[4]</code> 是 48</li>



<li><code>n[5]</code> 是 13</li>
</ul>



<p class="wp-block-paragraph"><code>n[0]</code>、<code>n[1]</code> 等等。就像我们使用的是任何其他变量，我们可以设置值作为 <code>n[0] = 5;</code> 像我们这样做与任何其他变量（<code>x = 5;</code>，<code>y = 6;</code> 等）。</p>



<h4 class="wp-block-heading">给数组赋值</h4>



<p class="wp-block-paragraph">通过编写 <code>int n[] = {2,4,8};</code>，我们可以同时声明并向数组分配值，从而对其进行初始化。</p>



<p class="wp-block-paragraph">但是，当我们声明类似的数组时 <code>int n[3];</code>，我们需要分别为其分配值。因为 <code>int n[3];</code> 肯定会在内存中分配 3 个整数的空间，但是该空间中没有整数。</p>



<p class="wp-block-paragraph">要对其进行初始化，请为数组的每个元素分配一个值。</p>


<pre class="wp-block-code"><span><code class="hljs">n&#91;0] = 2;
n&#91;1] = 4;
n&#91;2] = 8;</code></span></pre>


<p class="wp-block-paragraph">就像我们声明一些变量，然后为它们分配值一样。</p>


<pre class="wp-block-code"><span><code class="hljs">int x, y, z;
x = 2;
y = 4;
z = 8;</code></span></pre>


<p class="wp-block-paragraph">因此，将值分配给数组元素的第一种方法是在声明数组时进行：</p>


<pre class="wp-block-code"><span><code class="hljs">int n&#91;] = {2, 4, 8};</code></span></pre>


<p class="wp-block-paragraph">第二种方法是先声明数组，然后为它的元素赋值：</p>


<pre class="wp-block-code"><span><code class="hljs">int n&#91;3];
n&#91;0] = 2;
n&#91;1] = 4;
n&#91;2] = 8;</code></span></pre>


<p class="wp-block-paragraph">您可以通过将对待 <code>n[0]</code>、<code>n[1]</code> 和 <code>n[2]</code> 与之前使用的不同变量类似来理解这一点。</p>



<p class="wp-block-paragraph">就像变量一样，数组也可以是任何其他数据类型。</p>


<pre class="wp-block-code"><span><code class="hljs">float f&#91;] = {1.1, 1.4, 1.5};</code></span></pre>


<p class="wp-block-paragraph">在这里，<code>f</code> 是一个浮点数数组。</p>



<p class="wp-block-paragraph">首先，让我们看一下计算 3 个学生的平均分数的示例。在此，<code>marks[0]</code> 代表第一个学生的成绩，<code>marks[1]</code> 代表第二个学生的成绩，<code>marks[2]</code> 代表第三个学生的成绩。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    int marks&#91;<span class="hljs-number">3</span>];
    float average;

    printf(<span class="hljs-string">"Enter marks of first student\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;marks&#91;<span class="hljs-number">0</span>]);

    printf(<span class="hljs-string">"Enter marks of second student\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;marks&#91;<span class="hljs-number">1</span>]);

    printf(<span class="hljs-string">"Enter marks of third student\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;marks&#91;<span class="hljs-number">2</span>]);

    average = (marks&#91;<span class="hljs-number">0</span>] + marks&#91;<span class="hljs-number">1</span>] + marks&#91;<span class="hljs-number">2</span>]) / <span class="hljs-number">3.0</span>;
    printf(<span class="hljs-string">"Average marks : %f\n"</span>, average);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，您看到了一个数组的工作示例，我们对待数组元素的方式与对待普通变量的方式完全相似。<code>&amp;marks[0]</code>、<code>&amp;marks[1]</code> 和 <code>&amp;marks[2]</code> 分别表示 <code>marks[0]</code>、<code>marks[1]</code> 和 <code>marks[2]</code> 的地址。</p>



<p class="wp-block-paragraph">在上面的示例中，应牢记两点：</p>



<ul class="wp-block-list">
<li>平均值应为 <code>float</code> 类型，因为整数的平均值也可以为 float。</li>



<li>其次，在取平均值时，将数字的总和除以 <code>3.0</code> 而不是 <code>3</code>，否则平均值将作为整数而不是浮动的。</li>
</ul>



<p class="wp-block-paragraph">我们也可以使用 <code>for</code> 循环，如下面的示例所示：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    int n&#91;<span class="hljs-number">10</span>]; <span class="hljs-comment">/* declaring n as an array of 10 integers */</span>
    int i, j;
    <span class="hljs-comment">/* initializing elements of array n */</span>
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++)
    {
        printf(<span class="hljs-string">"Enter value of n&#91;%d]"</span>, i);
        scanf(<span class="hljs-string">"%d"</span>, &amp;n&#91;i]);
    }
    <span class="hljs-comment">/* printing the values of elements of array */</span>
    <span class="hljs-keyword">for</span> (j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">10</span>; j++)
    {
        printf(<span class="hljs-string">"n&#91;%d] = %d\n"</span>, j, n&#91;j]);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">上面的代码只是让您熟悉对数组使用循环，因为您将在以后做很多次。</p>



<p class="wp-block-paragraph">代码很简单，因为数组的索引从 0 开始到 9（对于 10 个元素），所以 <code>i</code> 和 <code>j</code> 从 0 开始。因此，<code>i</code> 和 <code>j</code> 上升到 9 而不是 10（<code>i &lt; 10</code> 和 <code>j &lt; 10</code>）。因此，在代码 <code>n[i]</code> 中将是 <code>n[1]</code>、<code>n[2]</code>、&#8230;、<code>n[9]</code>，事情将因此而去。</p>



<p class="wp-block-paragraph">如果我们声明了一个具有一定数组大小的数组，并且仅对该数组的某些元素分配了值，则其他元素的值将自动分配为零。</p>



<p class="wp-block-paragraph">假设我们声明并初始化一个数组为：</p>


<pre class="wp-block-code"><span><code class="hljs">int n&#91;5] = {12, 13, 5};</code></span></pre>


<p class="wp-block-paragraph">这意味着 <code>n[0] = 12</code>，<code>n[1] = 13</code> 和 <code>n[2] = 5</code>，其余所有元素均为零，即 <code>n[3] = 0</code> 和 <code>n[4] = 0</code>。</p>



<p class="wp-block-paragraph">同样：</p>


<pre class="wp-block-code"><span><code class="hljs">int n&#91;5];
n&#91;0] = 12;
n&#91;1] = 13;
n&#91;2] = 5;</code></span></pre>


<p class="wp-block-paragraph">在上面的代码中，<code>n[0]</code>、<code>n[1]</code> 和 <code>n[2]</code> 分别初始化为 12、13 和 5。因此，<code>n[4]</code> 和 <code>n[5]</code> 均为 0。</p>



<p class="wp-block-paragraph">数组分配连续的内存。因此，如果整数数组的第一个元素的地址为 223698688，则第二个元素的地址将为 223698692（223698688 + 4（4 是一个整数的大小）），第三个元素的地址将为 223698696，依此类推。这意味着数组的所有元素的内存都分配在一起并且是连续的。</p>



<h3 class="wp-block-heading">指向数组的指针</h3>



<p class="wp-block-paragraph">到目前为止，我们已经看到了如何声明和初始化数组。现在，我们将看到如何也可以拥有指向数组的指针。</p>



<p class="wp-block-paragraph">众所周知，指针是一个变量，其值是其他变量的地址，即，如果变量 <code>y</code> 指向另一个变量 <code>x</code>，则意味着变量 <code>y</code> 的值就是 <code>x</code>。</p>



<p class="wp-block-paragraph">同样，如果我们说变量 <code>y</code> 指向数组 <code>n</code>，则意味着 <code>y</code> 的值是数组第一个元素的地址，即 <code>n[0]</code>。这意味着数组的指针是其第一个元素的指针。</p>



<p class="wp-block-paragraph">数组的名称是指向数组第一个元素的指针。</p>



<p class="wp-block-paragraph">如果 <code>p</code> 是指向数组 <code>age</code> 的指针，则意味着 <code>p</code>（或 <code>age</code>）指向 <code>age[0]</code>。</p>


<pre class="wp-block-code"><span><code class="hljs">int age&#91;50];
int *p;
p = age;</code></span></pre>


<p class="wp-block-paragraph">上面的代码为 <code>p</code> 分配了数组 <code>age</code> 的第一个元素的地址。</p>



<p class="wp-block-paragraph">现在，由于 <code>p</code> 指向数组 <code>age</code> 的第一个元素，因此 <code>*p</code> 是数组的第一个元素的值。</p>



<p class="wp-block-paragraph">由于 <code>*p</code> 表示第一个数组元素，因此 <code>*(p + 1)</code> 和 <code>*(p + 2)</code> 分别表示第二个元素和第三个元素，依此类推。</p>



<p class="wp-block-paragraph">因此，<code>*p</code> 是 <code>age[0]</code>，<code>*(p + 1)</code> 是 <code>age[1]</code>，<code>*(p + 2)</code> 是 <code>age[2]</code>。</p>



<p class="wp-block-paragraph">类似地，<code>*age</code> 是 <code>age[0]</code>（年龄值），<code>*(age + 1)</code> 是 <code>age[1]</code>（年龄+1 值），<code>*(age + 2)</code> 是 <code>age[2]</code>（年龄+2 值）等等。</p>



<p class="wp-block-paragraph">这就是所有指向数组的指针。</p>



<p class="wp-block-paragraph">现在让我们看一些例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    float n&#91;<span class="hljs-number">5</span>] = {<span class="hljs-number">20.4</span>, <span class="hljs-number">30.0</span>, <span class="hljs-number">5.8</span>, <span class="hljs-number">67</span>, <span class="hljs-number">15.2</span>}; <span class="hljs-comment">/* declaring n as an array of 5 floats */</span>
    float *p; <span class="hljs-comment">/* p as a pointer to float */</span>
    int i;
    p = n; <span class="hljs-comment">/* p now points to array n */</span>
    <span class="hljs-comment">/* printing the values of elements of array */</span>
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++)
    {
        printf(<span class="hljs-string">"*(p + %d) = %f\n"</span>, i, *(p + i)); <span class="hljs-comment">/* *(p+i) means value at (p+0),(p+1)...*/</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">因为 <code>p</code> 指向数组的第一个元素，所以 <code>*p</code> 或 <code>*(p+0)</code> 表示 <code>p[0]</code> 处的值或 <code>p</code> 的第一个元素处的值。类似地，<code>*(p+1)</code> 表示 <code>p[1]</code> 处的值。并且分别 <code>*(p+3)</code> 和 <code>*(p+4)</code> 代表 <code>p[3]</code> 和 <code>p[4]</code>。因此，事情就已经印出来了。</p>



<p class="wp-block-paragraph">以上示例总结了以上概念。现在，让我们打印数组的地址以及数组的各个元素：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    int n&#91;<span class="hljs-number">4</span>] = {<span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">5</span>, <span class="hljs-number">67</span>}; <span class="hljs-comment">/* declaring n as an array of 4 integers */</span>
    int *p; <span class="hljs-comment">/* a pointer */</span>
    int i;
    p = n; <span class="hljs-comment">/* p is pointing to array n */</span>
    <span class="hljs-comment">/* printing the address of array */</span>
    printf(<span class="hljs-string">"Address of array n&#91;4] = %u\n"</span>, p); <span class="hljs-comment">/* p points to array means store the address of the first element of array */</span>
    <span class="hljs-comment">/* printing the addresses of elements of array */</span>
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">4</span>; i++)
    {
        printf(<span class="hljs-string">"Address of n&#91;%d] = %u\n"</span>, i, &amp;n&#91;i]);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">您已经注意到 <code>n</code> 和 <code>p</code> 的第一个元素的地址相同，这意味着我没有说谎！</p>



<p class="wp-block-paragraph">您也可以使用 <code>(p + 1)</code>、<code>(p + 2)</code> 和 <code>(p + 3)</code> 打印其他元素的地址。</p>



<h3 class="wp-block-heading">在函数中传递整个数组</h3>



<p class="wp-block-paragraph">在 C 语言中，我们可以将数组的元素或整个数组作为参数传递给函数。</p>



<p class="wp-block-paragraph">首先让我们传递单个数组元素以起作用：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

void display(int a)
{
    printf(<span class="hljs-string">"%d\n"</span>, a);
}

int main()
{
    int n&#91;] = {<span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">23</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">41</span>, <span class="hljs-number">8</span>};
    display(n&#91;<span class="hljs-number">2</span>]);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">在函数中传递整个数组</h4>



<p class="wp-block-paragraph">我们还可以通过将数组名称作为参数来传递整个数组给一个函数。是的，诀窍是我们将传递数组的地址，即数组的第一个元素的地址。因此，通过拥有第一个元素的指针，我们可以像上面的示例中那样获得整个数组。</p>



<p class="wp-block-paragraph">让我们看一个例子来理解它：</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">#include <span class="hljs-tag">&lt;<span class="hljs-name">stdio.h</span>&gt;</span>

float average(float a&#91;])
{
    int i;
    float avg, sum = 0;
    for (i = 0; i <span class="hljs-tag">&lt; <span class="hljs-attr">8</span>; ++<span class="hljs-attr">i</span>)
    {
        <span class="hljs-attr">sum</span> += <span class="hljs-string">a&#91;i];</span>
    }
    <span class="hljs-attr">avg</span> = <span class="hljs-string">sum</span> / <span class="hljs-attr">8</span>;
    <span class="hljs-attr">return</span> <span class="hljs-attr">avg</span>;
}

<span class="hljs-attr">int</span> <span class="hljs-attr">main</span>()
{
    <span class="hljs-attr">float</span> <span class="hljs-attr">b</span>, <span class="hljs-attr">n</span>&#91;] = <span class="hljs-string">{20.6,</span> <span class="hljs-attr">30.8</span>, <span class="hljs-attr">5.1</span>, <span class="hljs-attr">67.2</span>, <span class="hljs-attr">23</span>, <span class="hljs-attr">2.9</span>, <span class="hljs-attr">4</span>, <span class="hljs-attr">8</span>};
    <span class="hljs-attr">b</span> = <span class="hljs-string">average(n);</span>
    <span class="hljs-attr">printf</span>("<span class="hljs-attr">Average</span> <span class="hljs-attr">of</span> <span class="hljs-attr">numbers</span>=<span class="hljs-string">%.2f\n</span>", <span class="hljs-attr">b</span>);
    <span class="hljs-attr">return</span> <span class="hljs-attr">0</span>;
}</span></code></span></pre>


<p class="wp-block-paragraph"><code>average(float a[])</code> → 该函数正在获取一个 float 数组。并且该功能的其余部分正在相应地执行。</p>



<p class="wp-block-paragraph"><code>b = average(n)</code> → 您在此处应注意的一件事是，我们传递了 <code>n</code>。如前所述，<code>n</code> 是指向第一个元素的指针或指向数组的指针 <code>n[]</code>。因此，我们实际上已经传递了指针。</p>



<p class="wp-block-paragraph">在上面的示例中，我们计算了数组元素的平均值，我们已经知道数组的大小，即 8。</p>



<p class="wp-block-paragraph">假设我们从用户那里获取数组的大小。在这种情况下，数组的大小是不固定的。在这里，我们需要将数组的大小作为第二个参数传递给函数。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

float average(float a&#91;], int size)
{
    int i;
    float avg, sum = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; size; i++)
    {
        sum += a&#91;i];
    }
    avg = sum / size;
    <span class="hljs-keyword">return</span> avg;
}

int main()
{
    int size, j;
    printf(<span class="hljs-string">"Enter the size of array"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;size);
    float b, n&#91;size];
    <span class="hljs-keyword">for</span> (j = <span class="hljs-number">0</span>; j &lt; size; j++)
    {
        printf(<span class="hljs-string">"Value of n&#91;%d] : "</span>, j);
        scanf(<span class="hljs-string">"%f"</span>, &amp;n&#91;j]);
    }
    b = average(n, size);
    printf(<span class="hljs-string">"Average of numbers=%.2f\n"</span>, b);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">该代码与上一个代码相似，除了我们显式传递了数组的大小。</p>



<p class="wp-block-paragraph">我们还可以使用指针将数组传递给函数。让我们看看如何：</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">#include <span class="hljs-tag">&lt;<span class="hljs-name">stdio.h</span>&gt;</span>

display(int *p)
{
    int i;
    for (i = 0; i <span class="hljs-tag">&lt; <span class="hljs-attr">8</span>; ++<span class="hljs-attr">i</span>)
    {
        <span class="hljs-attr">printf</span>("<span class="hljs-attr">n</span>&#91;%<span class="hljs-attr">d</span>] = <span class="hljs-string">%d\n</span>", <span class="hljs-attr">i</span>, *<span class="hljs-attr">p</span>);
        <span class="hljs-attr">p</span>++;
    }
}

<span class="hljs-attr">int</span> <span class="hljs-attr">main</span>()
{
    <span class="hljs-attr">int</span> <span class="hljs-attr">n</span>&#91;] = <span class="hljs-string">{1,</span> <span class="hljs-attr">2</span>, <span class="hljs-attr">3</span>, <span class="hljs-attr">4</span>, <span class="hljs-attr">5</span>, <span class="hljs-attr">6</span>, <span class="hljs-attr">7</span>, <span class="hljs-attr">8</span>};
    <span class="hljs-attr">display</span>(<span class="hljs-attr">n</span>);
    <span class="hljs-attr">return</span> <span class="hljs-attr">0</span>;
}</span></code></span></pre>


<p class="wp-block-paragraph">在上面的示例中，将数组的地址（即 <code>n[0]</code> 的地址）传递给函数的形式参数。</p>



<p class="wp-block-paragraph"><code>display(int *p)</code> → 这意味着函数 <code>display</code> 正在使用指向整数的指针。</p>



<p class="wp-block-paragraph">现在我们根据函数 <code>display</code> 的要求传递了整数指针，即数组 <code>n[]</code> 的指针。</p>



<p class="wp-block-paragraph">由于 <code>p</code> 是函数 <code>display</code> 中数组 <code>n[]</code> 的地址，即数组第一个元素（<code>n[0]</code>）的地址，因此 <code>*p</code> 表示 <code>n[0]</code> 的值。在 <code>for</code> 循环功能中，<code>p++</code> 将 <code>p</code> 的值增加 1。因此，当 <code>i = 0</code> 时，将打印 <code>*p</code> 的值。然后 <code>p++</code> 将 <code>*p</code> 增加到 <code>*(p + 1)</code>，在第二个循环中，<code>*(p + 1)</code> 的值，即 <code>n[1]</code> 也被打印出来。当 <code>*(p + 7)</code> 的值（即 <code>n[7]</code>）被打印时，此循环一直持续到 <code>i = 7</code>。</p>



<h3 class="wp-block-heading">二维数组</h3>



<p class="wp-block-paragraph">如果数组是二维的怎么办？</p>



<p class="wp-block-paragraph">是的，二维数组也存在，通常称为 matrix。这些由行和列组成。</p>



<p class="wp-block-paragraph">在进入其应用程序之前，让我们首先了解如何声明和初始化 2D 数组。</p>



<h4 class="wp-block-heading">二维数组声明</h4>



<p class="wp-block-paragraph">与一维数组相似，我们定义如下的二维数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">int</span> <span class="hljs-selector-tag">a</span><span class="hljs-selector-attr">&#91;2]</span><span class="hljs-selector-attr">&#91;4]</span>;</code></span></pre>


<p class="wp-block-paragraph">这里，<code>a</code> 是整数的 2D 阵列，其由 2 行和 4 列。</p>



<p class="wp-block-paragraph">它就像是：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>第0栏</th><th>第1栏</th><th>第2栏</th><th>第3栏</th></tr></thead><tbody><tr><td>第0行</td><td>a[0][0]</td><td>a[0][1]</td><td>a[0][2]</td><td>a[0][3]</td></tr><tr><td>第1行</td><td>a[1][0]</td><td>a[1][1]</td><td>a[1][2]</td><td>a[1][3]</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">现在让我们看一下如何初始化二维数组。</p>



<h4 class="wp-block-heading">将值分配给二维数组</h4>



<p class="wp-block-paragraph">与一维数组相同，我们也可以通过 2 种方式为二维数组的元素分配值。</p>



<p class="wp-block-paragraph">在第一种方法中，只需为数组的元素分配一个值。如果未将任何值分配给任何元素，则假定其值为零。</p>



<p class="wp-block-paragraph">假设我们声明了一个二维数组 <code>a[2][2]</code>。现在，我们需要为其元素分配值。</p>


<pre class="wp-block-code"><span><code class="hljs">int a&#91;2]&#91;2];
a&#91;0]&#91;0] = 1;
a&#91;0]&#91;1] = 2;
a&#91;1]&#91;0] = 3;
a&#91;1]&#91;1] = 4;</code></span></pre>


<p class="wp-block-paragraph">第二种方法是与一维数组同时声明和分配值：</p>


<pre class="wp-block-code"><span><code class="hljs">int a&#91;2]&#91;3] = {1, 2, 3, 4, 5, 6};</code></span></pre>


<p class="wp-block-paragraph">此处，<code>a[0][0]</code> 的值为 1，<code>a[0][1]</code> 为 2，<code>a[0][2]</code> 为 3，<code>a[1][0]</code> 为 4，<code>a[1][1]</code> 为 5，<code>a[1][2]</code> 为 6。</p>



<p class="wp-block-paragraph">我们也可以将以上代码编写为：</p>


<pre class="wp-block-code"><span><code class="hljs">int a&#91;2]&#91;3] = {
    {1, 2, 3},
    {4, 5, 6}
};</code></span></pre>


<p class="wp-block-paragraph">在声明时将值分配给数组时，不需要在一维数组中指定大小，但是在 2D 数组中，我们至少需要给出第二维的值。</p>



<p class="wp-block-paragraph">让我们考虑在声明时将值分配给数组的不同情况：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">int a&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>] = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}; <span class="hljs-comment">/* 有效 */</span>
int a&#91;]&#91;<span class="hljs-number">2</span>] = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}; <span class="hljs-comment">/* 有效 */</span>
int a&#91;<span class="hljs-number">2</span>]&#91;] = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}; <span class="hljs-comment">/* 无效 */</span>
int a&#91;]&#91;] = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}; <span class="hljs-comment">/* 无效 */</span></code></span></pre>


<h4 class="wp-block-heading">为什么要使用二维数组</h4>



<p class="wp-block-paragraph">假设我们有 3 个学生，每个学生都在学习 2 个主题（主题 1 和主题 2），并且我们必须在这 3 个学生的两个主题中都显示分数。让我们输入用户的标记。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    float marks&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">2</span>];
    int i, j;
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++)
    {
        <span class="hljs-comment">/* input of marks from the user */</span>
        printf(<span class="hljs-string">"Enter marks of student %d\n"</span>, (i + <span class="hljs-number">1</span>));
        <span class="hljs-keyword">for</span> (j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">2</span>; j++)
        {
            printf(<span class="hljs-string">"Subject %d\n"</span>, (j + <span class="hljs-number">1</span>));
            scanf(<span class="hljs-string">"%f"</span>, &amp;marks&#91;i]&#91;j]);
        }
    }
    <span class="hljs-comment">/* printing the marks of students */</span>
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++)
    {
        printf(<span class="hljs-string">"Marks of student %d\n"</span>, (i + <span class="hljs-number">1</span>));
        <span class="hljs-keyword">for</span> (j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">2</span>; j++)
        {
            printf(<span class="hljs-string">"Subject %d : %f\n"</span>, (j + <span class="hljs-number">1</span>), marks&#91;i]&#91;j]);
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">这就像：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>主题1</th><th>主题2</th></tr></thead><tbody><tr><td>学生1</td><td>78</td><td>67</td></tr><tr><td>学生2</td><td>79</td><td>87</td></tr><tr><td>学生3</td><td>90</td><td>89</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">字符串</h3>



<p class="wp-block-paragraph">数学和数学，代码与代码，但是在现实世界中，我们必须处理单词，句子等。C 语言中是否有任何东西可以处理这些类型的事物？答案是肯定的，它们被称为 string。</p>



<p class="wp-block-paragraph">我们可以将字符串视为字符数组，例如 <code>Sam</code> 是字符串。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>字符</th><th>S</th><th>a</th><th>m</th><th>\0</th></tr></thead><tbody><tr><td>下标</td><td>0</td><td>1</td><td>2</td><td>3</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">因此，<code>Sam</code> 是字符 <code>S</code>、<code>a</code>、<code>m</code> 和 <code>\0</code> 的数组。</p>



<p class="wp-block-paragraph">查看第 3 个索引处的字符。它代表空字符。ASCII 值的 <code>\0</code> 是 0 和的正常 0 是 48。它表示字符串的终止（结束）。</p>



<p class="wp-block-paragraph">我们将字符串声明为：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char name&#91;] = <span class="hljs-string">"Sam"</span>;</code></span></pre>


<p class="wp-block-paragraph">如您所见，字符串（<code>char name[]</code>）的语法还告诉我们它是一个字符数组。</p>



<p class="wp-block-paragraph">我们总是在 <code>""</code> 中放置一个字符串，在 <code>''</code> 中放置一个字符。</p>



<p class="wp-block-paragraph">我们还可以使用字符声明一个字符串变量，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char name&#91;] = {<span class="hljs-string">'S'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'m'</span>, <span class="hljs-string">'\0'</span>};</code></span></pre>


<p class="wp-block-paragraph">让我们看两个示例，分别显示不带 <code>for</code> 循环和带循环的字符串。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    char str&#91;] = <span class="hljs-string">"Hello"</span>;
    printf(<span class="hljs-string">"%s\n"</span>, str);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">请注意，<code>%s</code> 用于字符串。</p>



<p class="wp-block-paragraph">在上面的示例中，我们一次打印了整个字符串。现在，我们将看到相同的示例，但使用 <code>for</code> 循环打印单个字符。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    char str&#91;] = <span class="hljs-string">"Hello"</span>;
    int i;
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">6</span>; i++)
    {
        printf(<span class="hljs-string">"%c\n"</span>, str&#91;i]);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在第一个示例中，我们打印了字符串，并为此 <code>%s</code> 与 <code>printf</code> 函数一起使用。而在第二个示例中，我们每次只打印单个字符，因此我们使用 <code>%c</code> 该 <code>printf</code> 函数。</p>



<p class="wp-block-paragraph">现在，让我们看一个从用户输入字符串的示例：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    char name&#91;<span class="hljs-number">25</span>];
    printf(<span class="hljs-string">"Enter your name\n"</span>);
    scanf(<span class="hljs-string">"%s"</span>, name);
    printf(<span class="hljs-string">"Your name is %s\n"</span>, name);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">您一定想知道在声明名称数组时将数组大小写为 25 的原因。这样做是因为我们不知道用户将输入的名称的长度。如果在上面的示例中，我们将数组的大小指定为 2，则字符串变量将不会采用输入，因为输入的大小大于数组的大小。因此，为了安全起见，请采用大于假定的输入大小的数组大小。</p>



<p class="wp-block-paragraph">在使用 <code>scanf</code> 从用户那里获取字符串时，请勿在字符串名称前使用 <code>&amp;</code>，因为在 <code>name[25]</code> 中，<code>name</code> 本身就是指向 <code>name[25]</code> 的指针。</p>



<p class="wp-block-paragraph"><code>scanf</code> 从用户到字符串变量仅需要一个词。它以任何空白结尾。尝试在空格后写点什么，这只会占用第一个单词。</p>



<p class="wp-block-paragraph">例如，如果在上面的示例中，我们输入 <code>Sam Brad</code> 作为名称，则输出将仅是 <code>Sam</code>，因为 <code>scanf</code> 仅考虑一个单词并在第一个单词之后终止。</p>



<h4 class="wp-block-heading">如何获取多行字符串</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    char name&#91;<span class="hljs-number">25</span>];
    printf(<span class="hljs-string">"Enter your name\n"</span>);
    gets(name);
    printf(<span class="hljs-string">"Your name is "</span>);
    puts(name);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">我们可以使用 <code>gets</code> 和 <code>puts</code> 接受输入并给出包含多个单词的字符串的输出，其中 <code>gets</code> 用于获取用户的字符串输入，而 <code>puts</code> 用于显示字符串。</p>



<p class="wp-block-paragraph">考虑以下示例。</p>



<p class="wp-block-paragraph">如果您收到关于 <code>gets</code> 的任何警告，请忽略它。</p>



<p class="wp-block-paragraph">要进行打印，您也可以使用 <code>printf</code> 代替 <code>puts</code>。</p>



<p class="wp-block-paragraph">您也可以使用 <code>scanf("%[^\n]s", name);</code> 用于获取多字串。</p>



<h4 class="wp-block-heading">指针和字符串</h4>



<p class="wp-block-paragraph">字符串也可以使用指针声明。让我们考虑一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    char name&#91;] = <span class="hljs-string">"Sam"</span>;
    char *p;
    p = name; <span class="hljs-comment">/* for string, only this declaration will store its base address */</span>
    <span class="hljs-keyword">while</span> (*p != <span class="hljs-string">'\0'</span>)
    {
        printf(<span class="hljs-string">"%c"</span>, *p);
        p++;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在上面的示例中，<code>p</code> 存储 <code>name[0]</code> 的地址，因此 <code>*p</code> 的值等于 <code>name[0]</code> 的值，即 <code>S</code>。因此，在 <code>while</code> 循环中，第一个字符被打印出来，并将 <code>p++</code> 的值加 1，以便现在 <code>p + 1</code> 指向 <code>name[1]</code>。这一直持续到指针到达字符串的末尾，即，在 <code>*p</code> 等于 <code>\0</code> 之前。</p>



<h4 class="wp-block-heading">将字符串传递给函数</h4>



<p class="wp-block-paragraph">这与我们处理其他阵列相同。唯一的区别是这是一个字符数组。而已！</p>



<p class="wp-block-paragraph">让我们来看一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

void display(char ch&#91;])
{
    printf(<span class="hljs-string">"String :"</span>);
    puts(ch); <span class="hljs-comment">/* display string */</span>
}

int main()
{
    char arr&#91;<span class="hljs-number">30</span>];
    printf(<span class="hljs-string">"Enter string\n"</span>);
    gets(arr); <span class="hljs-comment">/* input string from user */</span>
    display(arr);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">预定义的字符串函数</h4>



<p class="wp-block-paragraph">我们可以执行不同类型的字符串功能，例如连接 2 个字符串，将一个字符串与另一个字符串进行比较或找到字符串的长度。让我们看一下这些函数的列表。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>函数</th><th>用途</th></tr></thead><tbody><tr><td><code>strlen</code></td><td>计算字符串的长度</td></tr><tr><td><code>strcat</code></td><td>在另一个字符串的末尾附加一个字符串</td></tr><tr><td><code>strncat</code></td><td>在另一个字符串的末尾追加字符串的前 n 个字符</td></tr><tr><td><code>strcpy</code></td><td>将字符串复制到另一个</td></tr><tr><td><code>strncpy</code></td><td>将一个字符串的前 n 个字符复制到另一个</td></tr><tr><td><code>strcmp</code></td><td>比较两个字符串</td></tr><tr><td><code>strncmp</code></td><td>比较两个字符串的前 n 个字符</td></tr><tr><td><code>strchr</code></td><td>查找字符串中给定字符的首次出现</td></tr><tr><td><code>strrchr</code></td><td>查找字符串中给定字符的最后一次出现</td></tr><tr><td><code>strstr</code></td><td>查找另一个字符串中给定字符串的首次出现</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">这些函数在 <code>string.h</code> 头文件中定义，因此我们需要通过编写以下代码在代码中包含该头文件：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-id">#include</span> &lt;<span class="hljs-selector-tag">string</span><span class="hljs-selector-class">.h</span>&gt;</code></span></pre>


<p class="wp-block-paragraph">我们将看到一些例子 <code>strlen</code>、<code>strcpy</code>、<code>strcat</code> 和 <code>strcmp</code> 因为这些是最常用的。</p>



<p class="wp-block-paragraph"><code>strlen(s1)</code> 计算字符串 <code>s1</code> 的长度。空格也以字符串的长度计算。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main()
{
    char name&#91;] = <span class="hljs-string">"Hello"</span>;
    int len1, len2;
    len1 = strlen(name);
    len2 = strlen(<span class="hljs-string">"Hello World"</span>);
    printf(<span class="hljs-string">"length of %s = %d\n"</span>, name, len1);
    printf(<span class="hljs-string">"length of %s = %d\n"</span>, <span class="hljs-string">"Hello World"</span>, len2);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在计算字符串的长度时，<code>strlen</code> 不会计数 <code>\0</code>。</p>



<p class="wp-block-paragraph"><code>strcpy(s1, s2)</code> 将第二个字符串 <code>s2</code> 复制到第一个字符串 <code>s1</code>。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;string.h&gt;</span>
<span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    char s2&#91;] = <span class="hljs-string">"Hello"</span>;
    char s1&#91;<span class="hljs-number">10</span>];
    strcpy(s1, s2);
    printf(<span class="hljs-string">"Source string = %s\n"</span>, s2);
    printf(<span class="hljs-string">"Target string = %s\n"</span>, s1);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>strcat(s1, s2)</code> 将第二个字符串 <code>s2</code> 连接（连接）到第一个字符串 <code>s1</code>。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main()
{
    char s2&#91;] = <span class="hljs-string">"World"</span>;
    char s1&#91;<span class="hljs-number">20</span>] = <span class="hljs-string">"Hello"</span>;
    strcat(s1, s2);
    printf(<span class="hljs-string">"Source string = %s\n"</span>, s2);
    printf(<span class="hljs-string">"Target string = %s\n"</span>, s1);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">请注意，在上面的示例中，我们将数组大小指定为 <code>s1</code>，因为我们要向其中添加另一个字符串的字符。给定的数组大小应大于或等于串联后的字符串数组的大小。</p>



<p class="wp-block-paragraph"><code>strcmp(s1, s2)</code> 比较两个字符串，找出它们是否相同。它逐字符比较两个字符串，直到不匹配为止。如果两个字符串相同，则返回 0。如果不是，则返回第一个非匹配字符对的 ASCII 值之间的差。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main()
{
    char s1&#91;] = <span class="hljs-string">"Hello"</span>;
    char s2&#91;] = <span class="hljs-string">"World"</span>;
    int i, j;
    i = strcmp(s1, <span class="hljs-string">"Hello"</span>);
    j = strcmp(s1, s2);
    printf(<span class="hljs-string">"%d \n %d\n"</span>, i, j);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">二维字符数组</h4>



<p class="wp-block-paragraph">与整数和其他数据类型的 2D 数组相同，我们也有 2D 字符数组。</p>



<p class="wp-block-paragraph">例如，我们可以写：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char names&#91;<span class="hljs-number">4</span>]&#91;<span class="hljs-number">10</span>] = {
    <span class="hljs-string">"Andrew"</span>,
    <span class="hljs-string">"Kary"</span>,
    <span class="hljs-string">"Brown"</span>,
    <span class="hljs-string">"Lawren"</span>
};</code></span></pre>


<h3 class="wp-block-heading">C语言中的预处理器</h3>



<p class="wp-block-paragraph">预处理程序在进入编译器之前会处理我们的程序。</p>



<h4 class="wp-block-heading">如何声明？</h4>



<p class="wp-block-paragraph">预处理程序指令以哈希符号（<code>#</code>）开头。预处理程序指令是预处理程序命令。</p>



<p class="wp-block-paragraph">最常见的预处理器指令是 <code>#include</code>。</p>



<p class="wp-block-paragraph">这 <code>#include</code> 是一个预处理程序指令，它使诸如 <code>stdio.h</code> 的头文件对我们可用。</p>



<p class="wp-block-paragraph">让我们再举一个预处理器指令的例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-id">#define</span> <span class="hljs-selector-tag">PI</span> 3<span class="hljs-selector-class">.14</span></code></span></pre>


<p class="wp-block-paragraph">这 <code>#define</code> 是预处理程序指令。它用于定义某些内容，例如此处我们已定义 <code>PI</code> 为 3.14。因此，在进入编译器之前，如果 <code>PI</code> 出现在程序中的任何位置，它将被 3.14 替换。</p>



<p class="wp-block-paragraph">它与普通变量不同，因为普通变量是在编译期间处理的。但是，定义中的任何内容 <code>#define</code> 在编译之前都会被其值替换。</p>



<p class="wp-block-paragraph">同样，<code>#include</code> 在开始编译之前，链接任何头文件。</p>



<p class="wp-block-paragraph">以下是一个 C 程序来查找圆的区域：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#define PI 3.14</span>

int main()
{
    int radius;
    float area;
    printf(<span class="hljs-string">"Enter radius of circle\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;radius);
    area = PI * radius * radius;
    printf(<span class="hljs-string">"Area of circle is %.2f\n"</span>, area);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">您在这里应该唯一了解的是，即使在编译之前，只要程序中有 <code>PI</code>，<code>PI</code> 就会被 3.14 替换。因此，<code>PI * radius * radius</code> 将是 <code>3.14 * radius * radius</code>。</p>



<h4 class="wp-block-heading">带参数的宏</h4>



<p class="wp-block-paragraph"><code>#define</code> 也可以用来编写宏定义，如下所示。宏也类似于函数，但与此有所不同。他们也可以争论。让我们看一个示例，以了解如何使用它们。</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-id">#define</span> <span class="hljs-selector-tag">area</span>(<span class="hljs-selector-tag">r</span>) (3<span class="hljs-selector-class">.14</span> * <span class="hljs-selector-tag">r</span> * <span class="hljs-selector-tag">r</span>)</code></span></pre>


<p class="wp-block-paragraph">让我们看一个使用宏打印圆形区域的示例：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#define area(r) (3.14 * r * r)</span>

int main()
{
    int radius;
    float area;
    printf(<span class="hljs-string">"Enter radius of circle\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;radius);
    area = area(radius);
    printf(<span class="hljs-string">"Area of circle is %.2f\n"</span>, area);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">我们定义了一个宏 <code>area</code>，它接受一个参数 <code>r</code>。所以，当我们叫 <code>area(radius)</code>，它得到了替换 <code>3.14 * radius * radius</code>（如 <code>area(r)</code> 为 <code>3.14 * r * r</code>）。</p>



<p class="wp-block-paragraph">与 <code>area(x)</code> 在编译过程中调用的函数不同，我们代码中的任何地方，在编译之前都会被直接替换 <code>3.14 * x * x</code>。</p>



<p class="wp-block-paragraph">因此，以上代码等效于：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    int radius;
    float area;
    printf(<span class="hljs-string">"Enter radius of circle\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;radius);
    area = <span class="hljs-number">3.14</span> * radius * radius;
    printf(<span class="hljs-string">"Area of circle is %.2f\n"</span>, area);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">让我们将宏与函数进行比较</h4>



<p class="wp-block-paragraph">我们刚刚看到了使用宏打印圆形区域的示例。现在，让我们看看使用函数的相同示例。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

float CircleArea(int r)
{
    float a;
    a = <span class="hljs-number">3.14</span> * r * r;
    <span class="hljs-keyword">return</span> a;
}

int main()
{
    int radius;
    float area;
    printf(<span class="hljs-string">"Enter radius of circle\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;radius);
    area = CircleArea(radius);
    printf(<span class="hljs-string">"Area of circle is %.2f\n"</span>, area);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">让我们看一下宏和函数之间的基本区别：</p>



<ul class="wp-block-list">
<li>第一个区别是宏用其值替换代码（因为它用 <code>(3.14 * r * r)</code> 替换了 <code>area(r)</code>）。因此，每次都会为代码分配一些空间。这意味着每次出现 <code>area(r)</code> 时，都会在内存中分配空间。但这不是函数的情况。</li>



<li>其次，函数调用需要一些时间，但是在实际程序之前定义了宏。因此，宏更快。</li>
</ul>



<h3 class="wp-block-heading">结构</h3>



<p class="wp-block-paragraph">我们已经处理了数组。数组用于存储相似类型的数据。您是否曾经想过是否有任何方法可以存储不同的数据？</p>



<p class="wp-block-paragraph">答案是肯定的。我们使用结构来存储不同类型的数据。例如，您是一名学生。您的名字是一个字符串，您的电话号码和 <code>roll_no</code> 是整数。因此，这里的姓名、地址和电话号码是这些不同类型的数据。在这里，结构出现在图片中。</p>



<h4 class="wp-block-heading">定义结构</h4>



<p class="wp-block-paragraph">结构的语法为：</p>


<pre class="wp-block-code"><span><code class="hljs">struct structure_name
{
    数据类型 member-1;
    数据类型 member-2;
    数据类型 member-3;
    数据类型 member-4;
};</code></span></pre>


<p class="wp-block-paragraph">在我们的例子中，我们将该结构命名为 <code>student</code>。在我们的案例中，该结构的成员为 <code>name</code>、<code>roll_no</code> 和 <code>phone_number</code>。</p>



<p class="wp-block-paragraph">因此，我们的结构如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs">struct student
{
    int roll_no;
    char name&#91;30];
    int phone_number;
};</code></span></pre>


<h4 class="wp-block-heading">结构变量声明</h4>



<p class="wp-block-paragraph">正如我们声明 <code>int</code>、<code>char</code> 等类型的变量一样，我们也可以声明结构的变量。</p>



<p class="wp-block-paragraph">假设我们要存储三个学生的名册编号、姓名和电话号码。为此，我们将定义一个名称为 <code>student</code> 的结构（如上所述），然后声明结构 <code>student</code> 的三个变量，分别为 <code>p1</code>、<code>p2</code> 和 <code>p3</code>（分别代表三个学生）。</p>


<pre class="wp-block-code"><span><code class="hljs">struct student
{
    int roll_no;
    char name&#91;30];
    int phone_number;
};

main()
{
    struct student p1, p2, p3;
}</code></span></pre>


<p class="wp-block-paragraph">在此，<code>p1</code>、<code>p2</code> 和 <code>p3</code> 是结构 <code>student</code> 的变量。</p>



<p class="wp-block-paragraph">我们还可以在定义结构时声明结构变量，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs">struct student
{
    int roll_no;
    char name&#91;30];
    int phone_number;
} p1, p2, p3;</code></span></pre>


<p class="wp-block-paragraph">现在，让我们看看如何输入每个学生的详细信息，例如 <code>roll_no</code>、姓名和电话号码。</p>



<p class="wp-block-paragraph">假设我们要为第一个学生分配一个卷号。为此，我们需要访问第一个学生的卷号。我们通过写来做到这一点：</p>


<pre class="wp-block-code"><span><code class="hljs">p1.roll_no = 1;</code></span></pre>


<p class="wp-block-paragraph">这意味着使用点（<code>.</code>）在结构中使用变量。<code>p1.roll_no</code> 可以理解为 <code>p1</code> 的 <code>roll_no</code>。</p>



<p class="wp-block-paragraph">如果要为变量分配任何字符串值，将使用 <code>strcpy</code>，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">strcpy(p1.name, <span class="hljs-string">"Brown"</span>);</code></span></pre>


<p class="wp-block-paragraph">现在，让我们存储所有三个学生的详细信息：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main()
{
    struct student
    {
        int roll_no;
        char name&#91;<span class="hljs-number">30</span>];
        int phone_number;
    };
    struct student p1 = {<span class="hljs-number">1</span>, <span class="hljs-string">"Brown"</span>, <span class="hljs-number">123443</span>};
    struct student p2, p3;
    p2.roll_no = <span class="hljs-number">2</span>;
    strcpy(p2.name, <span class="hljs-string">"Sam"</span>);
    p2.phone_number = <span class="hljs-number">1234567822</span>;
    p3.roll_no = <span class="hljs-number">3</span>;
    strcpy(p3.name, <span class="hljs-string">"Addy"</span>);
    p3.phone_number = <span class="hljs-number">1234567844</span>;
    printf(<span class="hljs-string">"First Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p1.roll_no);
    printf(<span class="hljs-string">"name : %s\n"</span>, p1.name);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p1.phone_number);
    printf(<span class="hljs-string">"Second Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p2.roll_no);
    printf(<span class="hljs-string">"name : %s\n"</span>, p2.name);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p2.phone_number);
    printf(<span class="hljs-string">"Third Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p3.roll_no);
    printf(<span class="hljs-string">"name : %s\n"</span>, p3.name);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p3.phone_number);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">始终使用 <code>strcpy</code> 将字符串值分配给字符串变量。</p>



<p class="wp-block-paragraph">原因是在 C 语言中，我们不能将两个字符串（即字符数组）等价。如果我们写了 <code>p1.name = "Brown";</code>，那会给出一个错误。因此，通过编写 <code>strcpy(p1, "Brown")</code>，我们将字符串 <code>Brown</code> 复制到字符串变量 <code>p1.name</code>。</p>



<p class="wp-block-paragraph"><code>struct student p1 = {1, "Brown", 123443};</code> → 这也是我们初始化结构的方法之一。在下一行中，我们只是给变量赋值并打印出来。</p>



<p class="wp-block-paragraph">结构使用连续的内存位置。</p>



<h4 class="wp-block-heading">结构数组</h4>



<p class="wp-block-paragraph">我们还可以制作结构数组。在结构的第一个示例中，我们存储了 3 个学生的数据。现在假设我们需要存储 100 个此类孩子的数据。声明 100 个单独的结构变量绝对不是一个好选择。为此，我们需要创建一个结构数组。</p>



<p class="wp-block-paragraph">让我们看一个 5 个学生的例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

struct student
{
    int roll_no;
    char name&#91;<span class="hljs-number">30</span>];
    int phone_number;
};

int main()
{
    struct student stud&#91;<span class="hljs-number">5</span>];
    int i;
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">4</span>; i++)
    {
        printf(<span class="hljs-string">"Student %d\n"</span>, i + <span class="hljs-number">1</span>);
        printf(<span class="hljs-string">"Enter roll no. :\n"</span>);
        scanf(<span class="hljs-string">"%d"</span>, &amp;stud&#91;i].roll_no);
        printf(<span class="hljs-string">"Enter name :\n"</span>);
        scanf(<span class="hljs-string">"%s"</span>, stud&#91;i].name);
        printf(<span class="hljs-string">"Enter phone number :\n"</span>);
        scanf(<span class="hljs-string">"%d"</span>, &amp;stud&#91;i].phone_number);
    }
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">4</span>; i++)
    {
        printf(<span class="hljs-string">"Student %d\n"</span>, i + <span class="hljs-number">1</span>);
        printf(<span class="hljs-string">"Roll no. : %d\n"</span>, stud&#91;i].roll_no);
        printf(<span class="hljs-string">"Name : %s\n"</span>, stud&#91;i].name);
        printf(<span class="hljs-string">"Phone no. : %d\n"</span>, stud&#91;i].phone_number);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，<code>stud[0]</code> 存储第一个学生的信息，<code>stud[1]</code> 第二个以此类推。</p>



<p class="wp-block-paragraph">我们也可以一次复制两个结构：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main()
{
    struct student
    {
        int roll_no;
        char name&#91;<span class="hljs-number">30</span>];
        int phone_number;
    };
    struct student p1 = {<span class="hljs-number">1</span>, <span class="hljs-string">"Brown"</span>, <span class="hljs-number">123443</span>};
    struct student p2;
    p2 = p1;
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p2.roll_no);
    printf(<span class="hljs-string">"name : %s\n"</span>, p2.name);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p2.phone_number);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">我们只写了 <code>p2 = p1</code> 就是这样。<code>p1</code> 的所有元素都已复制到 <code>p2</code>。</p>



<h4 class="wp-block-heading">指向结构的指针</h4>



<p class="wp-block-paragraph">就像我们有用于 <code>int</code>、<code>char</code> 和其他数据类型的指针一样，我们也有指向结构的指针。这些指针称为结构指针。</p>



<p class="wp-block-paragraph">现在，如何定义一个指向结构的指针？答案如下：</p>


<pre class="wp-block-code"><span><code class="hljs">struct structure_name
{
    数据类型 member-1;
    数据类型 member-1;
    数据类型 member-1;
    数据类型 member-1;
};

main()
{
    struct structure_name *ptr;
}</code></span></pre>


<p class="wp-block-paragraph">让我们考虑一个使用结构指针的示例：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    struct student
    {
        char name&#91;<span class="hljs-number">30</span>];
        int roll_no;
    };
    struct student stud = {<span class="hljs-string">"sam"</span>, <span class="hljs-number">1</span>};
    struct student *ptr;
    ptr = &amp;stud;

    printf(<span class="hljs-string">"%s %d\n"</span>, stud.name, stud.roll_no);
    printf(<span class="hljs-string">"%s %d\n"</span>, ptr-&gt;name, ptr-&gt;roll_no);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>struct stud *ptr;</code> → 我们已经声明 <code>ptr</code> 是结构 <code>student</code> 的指针。</p>



<p class="wp-block-paragraph"><code>ptr = &amp;stud;</code> → 我们使指针 <code>ptr</code> 指向结构 <code>stud</code>。</p>



<p class="wp-block-paragraph">这是我们到目前为止所做的相同的事情。现在，来到 <code>printf</code>。</p>



<p class="wp-block-paragraph"><code>printf("%s %d\n", ptr-&gt;name, ptr-&gt;roll_no);</code> → 是的，我们用来 <code>-&gt;</code> 从其指针访问结构。就像我们在结构中使用（<code>.</code>）一样，我们在指针中使用 <code>-&gt;</code>。</p>



<h4 class="wp-block-heading">将结构传递给函数</h4>



<p class="wp-block-paragraph">我们还可以将结构传递给函数。</p>



<p class="wp-block-paragraph">我们可以通过两种方法将结构传递给函数：</p>



<ul class="wp-block-list">
<li>值传递</li>



<li>通过引用</li>
</ul>



<p class="wp-block-paragraph"><strong>值传递</strong>：在此，我们将结构变量作为参数传递给函数。通过一个例子，这将变得清楚。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

struct student
{
    int roll_no;
    char name&#91;<span class="hljs-number">30</span>];
    int phone_number;
};

void display(struct student st)
{
    printf(<span class="hljs-string">"Roll no : %d\n"</span>, st.roll_no);
    printf(<span class="hljs-string">"Name : %s\n"</span>, st.name);
    printf(<span class="hljs-string">"Phone no : %d\n"</span>, st.phone_number);
}

int main()
{
    struct student s;
    s.roll_no = <span class="hljs-number">4</span>;
    strcpy(s.name, <span class="hljs-string">"Ron"</span>);
    s.phone_number = <span class="hljs-number">888888</span>;
    display(s);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在此示例中，我们使用功能打印卷号、学生的姓名和电话号码。我们首先声明一个名为 <code>student</code> 的结构，其名称为 <code>roll_no</code>、名称和电话为成员，变量为 <code>s</code>。然后，我们将编号、姓名和电话号码的值分配给结构变量 <code>s</code>。就像我们将其他任何变量传递给函数一样，我们也将结构变量 <code>s</code> 传递给函数 <code>display</code>。</p>



<p class="wp-block-paragraph">现在，在定义函数时，我们传递了变量 <code>s</code> 的副本作为其参数，并在其前面写入了 <code>struct student</code>，因为传递的变量是一个名为 <code>student</code> 的类型结构。最后，在函数中，我们将打印结构变量的名称、编号和电话号码。</p>



<p class="wp-block-paragraph"><strong>通过引用</strong>：通过引用传递时，结构变量的地址传递给函数。在这种情况下，如果我们更改函数内部的结构变量，则用于调用该函数的原始结构变量将发生变化。按值调用不是这种情况。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

struct student
{
    int roll_no;
    char name&#91;<span class="hljs-number">30</span>];
    int phone_number;
};

void display(struct student *st)
{
    printf(<span class="hljs-string">"Roll no : %d\n"</span>, st-&gt;roll_no);
    printf(<span class="hljs-string">"Name : %s\n"</span>, st-&gt;name);
    printf(<span class="hljs-string">"Phone no : %d\n"</span>, st-&gt;phone_number);
}

int main()
{
    struct student s;
    s.roll_no = <span class="hljs-number">4</span>;
    strcpy(s.name, <span class="hljs-string">"Ron"</span>);
    s.phone_number = <span class="hljs-number">888888</span>;
    display(&amp;s);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">这种情况与前一种情况相似，唯一的区别是这一次，我们将结构变量的地址传递给了函数。在声明该函数时，我们的函数采用结构 <code>st</code> 的指针。由于指针是一个名为 <code>student</code> 的类型结构变量，因此我们在函数参数的指针名称之前写了 <code>struct student</code>。在函数中，如前所述，我们使用 <code>-&gt;</code> 符号访问了指针的成员。</p>



<p class="wp-block-paragraph">尝试在两种情况下都更改函数内部变量的值，并查看实际变量的更改。</p>



<h3 class="wp-block-heading">纸牌游戏</h3>



<p class="wp-block-paragraph">游戏规则：</p>



<ol class="wp-block-list">
<li>第一名玩家将选择一张牌。</li>



<li>现在，第二个玩家将选择一张牌。</li>



<li>如果第二位玩家选择的值与第一位玩家选择的卡相同，则将获得积分。</li>



<li>现在，第二位玩家将首先选择一张牌，然后是第一位玩家。</li>



<li>如果第一位玩家选择的值与第二位玩家选择的牌相同，那么他将获得积分。</li>



<li>重复步骤 1 至 5。</li>



<li>得分更高的玩家将赢得比赛。</li>
</ol>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt; //for srand and screen clear and echo off and on</span>
<span class="hljs-comment">#include &lt;time.h&gt;   //for shuffling</span>

main()
{
    system(<span class="hljs-string">"clear"</span>); <span class="hljs-comment">//screen clear</span>
    int i, j, z, k, lp;
    char s, rc;
    struct card
    {
        char *value;
        char *suite;
    };
    struct card temp, <span class="hljs-keyword">list</span>&#91;<span class="hljs-number">52</span>], player1&#91;<span class="hljs-number">26</span>], player2&#91;<span class="hljs-number">26</span>];
    <span class="hljs-comment">//temp for swaping</span>

    char *value&#91;] = {<span class="hljs-string">"A"</span>, <span class="hljs-string">"2"</span>, <span class="hljs-string">"3"</span>, <span class="hljs-string">"4"</span>, <span class="hljs-string">"5"</span>, <span class="hljs-string">"6"</span>, <span class="hljs-string">"7"</span>, <span class="hljs-string">"8"</span>, <span class="hljs-string">"9"</span>, <span class="hljs-string">"10"</span>, <span class="hljs-string">"K"</span>, <span class="hljs-string">"Q"</span>, <span class="hljs-string">"J"</span>};
    char *suite&#91;] = {<span class="hljs-string">"diamond"</span>, <span class="hljs-string">"spade"</span>, <span class="hljs-string">"heart"</span>, <span class="hljs-string">"club"</span>};
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">52</span>; i++)
    {
        <span class="hljs-keyword">if</span> (i &lt; <span class="hljs-number">13</span>)
        {
            <span class="hljs-keyword">list</span>&#91;i].suite = *(suite);
            <span class="hljs-keyword">list</span>&#91;i].value = *(value + i);
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (i &gt;= <span class="hljs-number">13</span> &amp;&amp; i &lt; <span class="hljs-number">26</span>)
        {
            <span class="hljs-keyword">list</span>&#91;i].suite = *(suite + <span class="hljs-number">1</span>);
            <span class="hljs-keyword">list</span>&#91;i].value = *(value + (i - <span class="hljs-number">13</span>));
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (i &gt;= <span class="hljs-number">26</span> &amp;&amp; i &lt; <span class="hljs-number">39</span>)
        {
            <span class="hljs-keyword">list</span>&#91;i].suite = *(suite + <span class="hljs-number">2</span>);
            <span class="hljs-keyword">list</span>&#91;i].value = *(value + (i - <span class="hljs-number">26</span>));
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (i &gt;= <span class="hljs-number">39</span>)
        {
            <span class="hljs-keyword">list</span>&#91;i].suite = *(suite + <span class="hljs-number">3</span>);
            <span class="hljs-keyword">list</span>&#91;i].value = *(value + (i - <span class="hljs-number">39</span>));
        }
    }

    <span class="hljs-keyword">do</span> <span class="hljs-comment">//do while to ask after game play more ?y or n:</span>
    {

        <span class="hljs-comment">//shuffling</span>

        int n = <span class="hljs-number">52</span>;
        srand(time(<span class="hljs-keyword">NULL</span>));
        <span class="hljs-keyword">for</span> (i = n - <span class="hljs-number">1</span>; i &gt; <span class="hljs-number">0</span>; i--)
        {
            int j = rand() % (i + <span class="hljs-number">1</span>);
            temp.value = <span class="hljs-keyword">list</span>&#91;i].value;
            temp.suite = <span class="hljs-keyword">list</span>&#91;i].suite;
            <span class="hljs-keyword">list</span>&#91;i].value = <span class="hljs-keyword">list</span>&#91;j].value;
            <span class="hljs-keyword">list</span>&#91;i].suite = <span class="hljs-keyword">list</span>&#91;j].suite;
            <span class="hljs-keyword">list</span>&#91;j].value = temp.value;
            <span class="hljs-keyword">list</span>&#91;j].suite = temp.suite;
        }

        <span class="hljs-comment">//distributing cards</span>
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">52</span>; i++)
        {
            <span class="hljs-keyword">if</span> (i &lt; <span class="hljs-number">26</span>)
            {
                player1&#91;i].value = <span class="hljs-keyword">list</span>&#91;i].value;
                player1&#91;i].suite = <span class="hljs-keyword">list</span>&#91;i].suite;
            }
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (i &gt;= <span class="hljs-number">26</span>)
            {
                player2&#91;i - <span class="hljs-number">26</span>].value = <span class="hljs-keyword">list</span>&#91;i].value;
                player2&#91;i - <span class="hljs-number">26</span>].suite = <span class="hljs-keyword">list</span>&#91;i].suite;
            }
        }

        <span class="hljs-comment">//for cards info</span>
        printf(<span class="hljs-string">"Player1 has:\t\t\tPlayer2 has:\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">26</span>; i++)
            printf(<span class="hljs-string">"%d\t%s\t%s\t\t%d\t%s\t%s\n"</span>, i + <span class="hljs-number">1</span>, player1&#91;i].value, player1&#91;i].suite, i + <span class="hljs-number">1</span>, player2&#91;i].value, player2&#91;i].suite);

        printf(<span class="hljs-string">"YOUR INPUT WILL NOT BE VISIBLE\n"</span>);

        int p1score = <span class="hljs-number">0</span>, p2score = <span class="hljs-number">0</span>;
        char a&#91;<span class="hljs-number">10</span>], b&#91;<span class="hljs-number">10</span>];
        char c&#91;<span class="hljs-number">10</span>], d&#91;<span class="hljs-number">10</span>];

        <span class="hljs-keyword">for</span> (j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">26</span>; j++)
        {

            system(<span class="hljs-string">"stty -echo"</span>); <span class="hljs-comment">//echo off. input will not be visible</span>

            <span class="hljs-comment">//even value of i will first let player1 to play and odd value to player 2</span>
            <span class="hljs-keyword">if</span> (j % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
            {

                int x = <span class="hljs-number">0</span>;
                <span class="hljs-keyword">do</span>
                {
                    printf(<span class="hljs-string">"Player1: type value and suite:"</span>);
                    scanf(<span class="hljs-string">"%s %s"</span>, &amp;a&#91;<span class="hljs-number">0</span>], &amp;b&#91;<span class="hljs-number">0</span>]);

                    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">26</span>; i++)
                    {
                        <span class="hljs-comment">//checking if player owns card or not</span>
                        z = strcmp(player1&#91;i].value, a);
                        k = strcmp(player1&#91;i].suite, b);

                        <span class="hljs-keyword">if</span> (z == <span class="hljs-number">0</span> &amp;&amp; k == <span class="hljs-number">0</span>)
                        {
                            <span class="hljs-comment">//removing used cards</span>
                            player1&#91;i].value = <span class="hljs-string">"\0"</span>;
                            player1&#91;i].suite = <span class="hljs-string">"\0"</span>;

                            x++;
                        }
                    }
                    <span class="hljs-keyword">if</span> (x == <span class="hljs-number">0</span>)
                        printf(<span class="hljs-string">"ENTER CORRECT CARD\n"</span>);
                } <span class="hljs-keyword">while</span> (x == <span class="hljs-number">0</span>);

                int y = <span class="hljs-number">0</span>;
                <span class="hljs-keyword">do</span>
                {
                    printf(<span class="hljs-string">"Player2: type value and suite:"</span>);
                    scanf(<span class="hljs-string">"%s %s"</span>, &amp;c&#91;<span class="hljs-number">0</span>], &amp;d&#91;<span class="hljs-number">0</span>]);

                    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">26</span>; i++)
                    {

                        z = strcmp(player2&#91;i].value, c);
                        k = strcmp(player2&#91;i].suite, d);

                        <span class="hljs-keyword">if</span> (z == <span class="hljs-number">0</span> &amp;&amp; k == <span class="hljs-number">0</span>)
                        {
                            player2&#91;i].value = <span class="hljs-string">"\0"</span>;
                            player2&#91;i].suite = <span class="hljs-string">"\0"</span>;

                            y++;
                        }
                    }
                    <span class="hljs-keyword">if</span> (y == <span class="hljs-number">0</span>)
                        printf(<span class="hljs-string">"ENTER CORRECT CARD\n"</span>);
                } <span class="hljs-keyword">while</span> (y == <span class="hljs-number">0</span>);

                <span class="hljs-comment">//score if player2 choose same card</span>
                lp = strcmp(a, c);

                <span class="hljs-keyword">if</span> (lp == <span class="hljs-number">0</span>)
                    p2score = p2score + <span class="hljs-number">10</span>;
            }
            <span class="hljs-keyword">else</span> <span class="hljs-comment">//if i is odd first turn to player2</span>
            {

                int y = <span class="hljs-number">0</span>;
                <span class="hljs-keyword">do</span>
                {
                    printf(<span class="hljs-string">"Player2: type value and suite:"</span>);
                    scanf(<span class="hljs-string">"%s %s"</span>, &amp;c&#91;<span class="hljs-number">0</span>], &amp;d&#91;<span class="hljs-number">0</span>]);

                    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">26</span>; i++)
                    {

                        z = strcmp(player2&#91;i].value, c);
                        k = strcmp(player2&#91;i].suite, d);

                        <span class="hljs-keyword">if</span> (z == <span class="hljs-number">0</span> &amp;&amp; k == <span class="hljs-number">0</span>)
                        {
                            player2&#91;i].value = <span class="hljs-string">"\0"</span>;
                            player2&#91;i].suite = <span class="hljs-string">"\0"</span>;

                            y++;
                        }
                    }
                    <span class="hljs-keyword">if</span> (y == <span class="hljs-number">0</span>)
                        printf(<span class="hljs-string">"ENTER CORRECT CARD\n"</span>);
                } <span class="hljs-keyword">while</span> (y == <span class="hljs-number">0</span>);

                int x = <span class="hljs-number">0</span>;
                <span class="hljs-keyword">do</span>
                {
                    printf(<span class="hljs-string">"Player1: type value and suite:"</span>);
                    scanf(<span class="hljs-string">"%s %s"</span>, &amp;a&#91;<span class="hljs-number">0</span>], &amp;b&#91;<span class="hljs-number">0</span>]);

                    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">26</span>; i++)
                    {

                        z = strcmp(player1&#91;i].value, a);
                        k = strcmp(player1&#91;i].suite, b);

                        <span class="hljs-keyword">if</span> (z == <span class="hljs-number">0</span> &amp;&amp; k == <span class="hljs-number">0</span>)
                        {
                            player1&#91;i].value = <span class="hljs-string">"\0"</span>;
                            player1&#91;i].suite = <span class="hljs-string">"\0"</span>;

                            x++;
                        }
                    }
                    <span class="hljs-keyword">if</span> (x == <span class="hljs-number">0</span>)
                        printf(<span class="hljs-string">"ENTER CORRECT CARD\n"</span>);
                } <span class="hljs-keyword">while</span> (x == <span class="hljs-number">0</span>);

                lp = strcmp(a, c);

                <span class="hljs-keyword">if</span> (lp == <span class="hljs-number">0</span>)
                    p1score = p1score + <span class="hljs-number">10</span>;
            }

            <span class="hljs-comment">//to see remaining cards</span>

            printf(<span class="hljs-string">"\nPlayer1 has:\t\t\tPlayer2 has:\n"</span>);
            <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">26</span>; i++)
                printf(<span class="hljs-string">"%d\t%s\t%s\t\t%d\t%s\t%s\n"</span>, i + <span class="hljs-number">1</span>, player1&#91;i].value, player1&#91;i].suite, i + <span class="hljs-number">1</span>, player2&#91;i].value, player2&#91;i].suite);

            printf(<span class="hljs-string">"\nPLAYER1 SCORE:%d\tPLAYER2 SCORE:%d\n\n"</span>, p1score, p2score);

            system(<span class="hljs-string">"stty echo"</span>); <span class="hljs-comment">//echo on</span>
        }

        <span class="hljs-keyword">if</span> (p1score &gt; p2score)
            printf(<span class="hljs-string">"PLAYER1 WINS\n"</span>);
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (p1score &lt; p2score)
            printf(<span class="hljs-string">"PLAYER2 WINS\n"</span>);
        <span class="hljs-keyword">else</span>
            printf(<span class="hljs-string">"MATCH DRAWS\n"</span>);

        <span class="hljs-comment">//if one has to play more...do while loop</span>

        printf(<span class="hljs-string">"want to play more? y or n:"</span>);
        scanf(<span class="hljs-string">" %c"</span>, &amp;s);
    } <span class="hljs-keyword">while</span> (s == <span class="hljs-string">'y'</span>);
}</code></span></pre>


<p class="wp-block-paragraph">真正的游戏是这样制作的吗？</p>



<p class="wp-block-paragraph">是的，我们刚刚制作了游戏的结构以将其链接到图形。完成本课程后，您可以扩展知识。</p>



<p class="wp-block-paragraph">使它变得更好。</p>



<p class="wp-block-paragraph">使用函数来减少代码的长度，询问用户播放器的数量，或实现您所拥有的其他想法。</p>



<h3 class="wp-block-heading">文件</h3>



<p class="wp-block-paragraph">当程序运行时，数据在内存中，但是当程序结束或计算机关闭时，数据将会丢失。为了永久保留数据，我们需要将其写入文件。</p>



<p class="wp-block-paragraph">文件用于存储数据。在本主题中，我们将学习从文件中读取数据以及在文件中写入数据的知识。</p>



<p class="wp-block-paragraph">首先，让我们看看如何声明文件。</p>



<p class="wp-block-paragraph">使用文件类型的指针声明文件，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs">FILE *fr;</code></span></pre>


<p class="wp-block-paragraph">我们可以对文件执行许多功能。下面列出了其中一些功能。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>函数</th><th>描述</th></tr></thead><tbody><tr><td><code>fopen()</code></td><td>创建一个新文件或打开一个现有文件</td></tr><tr><td><code>fclose()</code></td><td>关闭档案</td></tr><tr><td><code>fgetc()</code></td><td>从文件中读取字符</td></tr><tr><td><code>fputc()</code></td><td>写一个字符到文件</td></tr><tr><td><code>fscanf()</code></td><td>从文件中读取字符串</td></tr><tr><td><code>fprintf()</code></td><td>将字符串写入文件</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">让我们看看如何将数据写入文件，打开，关闭或读取文件。</p>



<h4 class="wp-block-heading">打开文件</h4>



<p class="wp-block-paragraph">我们使用 <code>fopen()</code> 功能打开文件或创建新文件。让我们看一下语法的 <code>fopen()</code>。</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">int main()
{
    FILE *fr;
    fr = fopen(<span class="hljs-string">"filename"</span>, <span class="hljs-string">"mode"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">这里 <code>fr</code> 是指向文件的指针，<code>filename</code> 是我们要打开的文件的名称，也是我们要打开文件 <code>mode</code> 的原因。</p>



<p class="wp-block-paragraph">模式可以采用以下值：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>模式</th><th>描述</th></tr></thead><tbody><tr><td><code>r</code></td><td>打开一个文本文件以供阅读</td></tr><tr><td><code>w</code></td><td>打开一个文本文件进行写入</td></tr><tr><td><code>a</code></td><td>打开一个文本文件进行追加。（追加意味着在末尾添加文本）</td></tr><tr><td><code>r+</code></td><td>打开一个文本文件进行读写</td></tr><tr><td><code>w+</code></td><td>打开一个文本文件以供读取和写入。（它首先将文件的长度减少为零（如果存在），或者如果不存在则创建一个文件）</td></tr><tr><td><code>a+</code></td><td>在读写模式下打开一个文本文件。（如果文件不存在，它将创建一个文件。读取将从头开始，而写入只能从头开始）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">这些是文本文件的模式。如果必须处理二进制文件，则模式如下：</p>



<p class="wp-block-paragraph"><code>rb</code>、<code>wb</code>、<code>ab</code>、<code>rb+</code>、<code>wb+</code>、<code>ab+</code></p>



<p class="wp-block-paragraph">但是，在我们的教程中，我们将只处理文本文件。</p>



<p class="wp-block-paragraph">当我们使用 <code>fopen</code> 它时，它将搜索磁盘上的文件，然后将文件加载到称为缓冲区的内存中。我们在关闭之前所做的更改是在缓冲存储器中进行的。进行更改时，可避免通过一次又一次访问磁盘来节省缓冲存储器。</p>



<h4 class="wp-block-heading">关闭文件</h4>



<p class="wp-block-paragraph">我们使用 <code>fclose()</code> 函数关闭打开的文件。</p>



<p class="wp-block-paragraph"><code>fclose()</code> 的语法如下：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    FILE *fr;
    fclose(fr);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>fclose()</code> 如果文件成功关闭，函数将返回零。如果关闭文件时出现错误，则返回 <code>EOF</code>（文件末尾）。</p>



<p class="wp-block-paragraph">我们刚刚看到了如何打开和关闭文件。现在，我们将了解如何在文件中进行读写。</p>



<h4 class="wp-block-heading">读取和写入文件</h4>



<p class="wp-block-paragraph">我们用于读取和写入的功能取决于我们要处理的是字符还是字符串。</p>



<p class="wp-block-paragraph">例如，函数 <code>fgetc()</code> 和 <code>fputc()</code> 用于读取和写入文件中的字符。同样，函数 <code>fscanf()</code> 和 <code>fprintf()</code> 用于读取和写入文件中的字符串。</p>



<p class="wp-block-paragraph">让我们来看每个示例，然后逐行了解它。</p>



<p class="wp-block-paragraph"><strong>使用 <code>fgetc()</code> 和 <code>fputc()</code></strong>：<code>fgetc()</code> 读取在打开的文件的字符读模式使用 <code>fopen()</code>。它 <code>EOF</code> 在到达文件末尾时返回。</p>



<p class="wp-block-paragraph"><code>fputc()</code> 将一个字符写入到打开的文件中写入模式使用 <code>fopen()</code>。</p>



<p class="wp-block-paragraph">现在，让我们看一个从文件读取的示例：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    FILE *fr;
    char c;
    fr = fopen(<span class="hljs-string">"prog.txt"</span>, <span class="hljs-string">"r"</span>);
    <span class="hljs-keyword">while</span> (c != EOF)
    {
        c = fgetc(fr); <span class="hljs-comment">/* read from file*/</span>
        printf(<span class="hljs-string">"%c"</span>, c); <span class="hljs-comment">/* display on screen*/</span>
    }
    fclose(fr);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在上面的示例中，首先我们以读取模式打开了一个名为 <code>prog.txt</code> 的文件，以便我们可以从该文件读取数据。为此，您的计算机中必须存在 <code>prog.txt</code>。</p>



<p class="wp-block-paragraph">在 <code>while</code> 循环中，<code>fgetc(fr)</code> 从文件 <code>prog.txt</code> 中读取 <code>c</code> 的值。从文件中读取 <code>c</code> 的整个值并 <code>EOF</code> 达到（文件末尾）后，<code>fclose(fr)</code> 关闭文件。</p>



<p class="wp-block-paragraph">就如此容易！</p>



<p class="wp-block-paragraph">我们 <code>fgetc()</code> 使用变量 <code>c</code> 读取文件的内容。在 <code>while</code> 期间，<code>printf</code> 函数在屏幕上打印 <code>c</code> 的值。之后，我们将使用关闭文件 <code>fclose</code>。</p>



<p class="wp-block-paragraph"><strong>使用 <code>fscanf()</code> 和 <code>fprintf()</code></strong>：虽然 <code>getc</code> 和 <code>putc</code> 用于字符，但是我们使用 <code>fscanf()</code> 和 <code>fprintf</code> 来读取和写入字符串到文件。</p>



<p class="wp-block-paragraph">让我们借助示例来理解：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    FILE *fr;
    char s&#91;<span class="hljs-number">40</span>];
    int n;
    fr = fopen(<span class="hljs-string">"welcome.txt"</span>, <span class="hljs-string">"w"</span>);
    printf(<span class="hljs-string">"Enter a string and a number"</span>);
    scanf(<span class="hljs-string">"%s%d"</span>, s, &amp;n); <span class="hljs-comment">/* read from keyboard */</span>
    fprintf(fr, <span class="hljs-string">"%s %d"</span>, s, n); <span class="hljs-comment">/* write to file */</span>
    fclose(fr);
    fr = fopen(<span class="hljs-string">"welcome.txt"</span>, <span class="hljs-string">"r"</span>);
    fscanf(fr, <span class="hljs-string">"%s%d"</span>, s, &amp;n); <span class="hljs-comment">/* read from file */</span>
    printf(<span class="hljs-string">"%s %d"</span>, s, n); <span class="hljs-comment">/* display on screen */</span>
    fclose(fr);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，我们首先创建了一个名为 <code>welcome.txt</code> 的文件，并使用 <code>fopen</code> 功能在写入模式下将其打开。然后，我们使用 <code>scanf</code> 功能从键盘输入一个字符串和一个整数值，并将这些值分别存储在变量 <code>s</code> 和 <code>n</code> 中。</p>



<p class="wp-block-paragraph">然后，<code>fprintf</code> 将字符串和整数值都写入文件。之后，<code>fclose(fr)</code> 关闭文件。</p>



<p class="wp-block-paragraph">现在，我们将读取文件的内容，然后将其打印在屏幕上。为此，我们将首先使用 <code>fopen</code> 函数以读取模式打开文件。之后，<code>fscanf</code> 函数将读取文件的内容，<code>printf</code> 函数将在屏幕上显示文件的内容。</p>



<p class="wp-block-paragraph">现在看到该程序将一个文件复制到另一个文件：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    FILE *s, *t;
    char c;
    s = fopen(<span class="hljs-string">"source.txt"</span>, <span class="hljs-string">"r"</span>);
    t = fopen(<span class="hljs-string">"target.txt"</span>, <span class="hljs-string">"w"</span>);
    <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>)
    {
        c = fgetc(s);

        <span class="hljs-keyword">if</span> (c == EOF)
        {
            <span class="hljs-keyword">break</span>;
        }
        <span class="hljs-keyword">else</span>
        {
            fputc(c, t);
        }
    }

    fclose(s);
    fclose(t);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>fputc(c, t)</code> 将存储在 <code>c</code> 中的字符放入以 <code>t</code> 打开的文件中。</p>



<p class="wp-block-paragraph">这是一项令人印象深刻的工作，您刚刚编写了复制两个文件的代码。为了使该程序正常运行，您必须具有一个名为 <code>source.txt</code> 的文件，或在代码本身中更改该文件的名称，以匹配存储在光盘中的文件。</p>



<h3 class="wp-block-heading">动态内存分配</h3>



<p class="wp-block-paragraph">假设您想将玩具放在盒子里，但是您只知道它的大小。为此，您需要一个盒子，盒子的大小等于玩具的近似大小。</p>



<p class="wp-block-paragraph">当我们想将一个句子作为字符数组输入但不确定该数组中的字符数时，我们也会遇到类似的情况。</p>



<p class="wp-block-paragraph">现在，在声明字符数组时，如果我们指定其大小小于输入字符串的大小，则由于分配给数组的内存中的空间小于输入字符串的大小，我们将收到错误消息。这与尝试将大玩具放入较小的盒子中的情况相同。如果我们指定它的大小远大于输入字符串的大小，那么将在内存中为该数组分配一个比输入字符串的大小大得多的空间，因此即使在不需要时也不必要地消耗了更多的内存。这就像将一个小玩具放在一个大盒子里。</p>



<p class="wp-block-paragraph">在上述情况下，直到编译时（当计算机编译代码并由用户输入字符串时），我们才知道数组的大小。在这种情况下，我们使用 <code>malloc()</code> 函数。</p>



<h4 class="wp-block-heading">malloc</h4>



<p class="wp-block-paragraph"><code>malloc</code> 函数在运行时分配内存。它采用字节大小，并在内存中分配那么多空间。这意味着 <code>malloc(50)</code> 将在内存中分配 50 个字节。它返回一个空指针，并在 <code>stdlib.h</code> 中定义。</p>



<p class="wp-block-paragraph">让我们借助示例来了解它：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main()
{
    char name&#91;<span class="hljs-number">20</span>];
    char *address;

    strcpy(name, <span class="hljs-string">"Harry Lee"</span>);
    address = (char *)malloc(<span class="hljs-number">50</span> * sizeof(char)); <span class="hljs-comment">/* allocating memory dynamically */</span>
    strcpy(address, <span class="hljs-string">"Lee Fort, 11-B Sans Street"</span>);

    printf(<span class="hljs-string">"Name = %s\n"</span>, name);
    printf(<span class="hljs-string">"Address: %s\n"</span>, address);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在上面的示例中，我们像以前一样分配并打印了名称。对于地址，我们估计字符数应为 50 个左右。因此，地址的大小将为 <code>50 * sizeof(char)</code>。</p>



<p class="wp-block-paragraph"><code>char *address</code> → 在这里，我们声明了指向地址字符的指针，而没有指定需要多少内存。</p>



<p class="wp-block-paragraph"><code>address = (char *)malloc(50 * sizeof(char))</code> → 通过编写此代码，我们为地址分配了 <code>50 * sizeof(char)</code> 字节的内存。我们曾经 <code>(char *)</code> 将 <code>malloc</code> 返回的指针类型转换为 character。</p>



<p class="wp-block-paragraph"><code>strcpy(address, "Lee Fort, 11-B Sans Street")</code> → 通过编写此代码，最后我们分配了地址。</p>



<p class="wp-block-paragraph">默认情况下，<code>malloc</code> 返回一个类型为 <code>void</code> 的指针，但是我们可以将其类型转换为任何其他形式的指针（在上面的示例中，我们将其转换为字符类型）。</p>



<p class="wp-block-paragraph">如果 <code>malloc</code> 分配的内存空间不足，则分配失败，并且 <code>malloc</code> 返回 <code>NULL</code> 指针。</p>



<p class="wp-block-paragraph">我们来看另一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int n, i, *p;
    printf(<span class="hljs-string">"Enter number of elements: "</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;n);
    p = (int *)malloc(n * sizeof(int)); <span class="hljs-comment">//memory allocated using malloc</span>
    <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">NULL</span>)
    {
        printf(<span class="hljs-string">"memory cannot be allocated\n"</span>);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"Enter elements of array:\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; ++i)
        {
            scanf(<span class="hljs-string">"%d"</span>, &amp;*(p + i));
        }
        printf(<span class="hljs-string">"Elements of array are\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; i++)
        {
            printf(<span class="hljs-string">"%d\n"</span>, *(p + i));
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在此示例中，首先，我们声明了一个 <code>int</code> 类型的指针 <code>p</code>，其中包含 <code>n</code> 个元素。因此，<code>p</code> 是包含 <code>n</code> 个元素的整数数组。因此，我们 <code>n * sizeof(int)</code> 为指针 <code>p</code> 所指向的数组分配了一个大小为大小的内存。因此，我们现在有一个存储空间分配给由 <code>n</code> 个元素组成的整数数组。此外，我们要求用户输入数组元素的值并显示这些值。</p>



<h4 class="wp-block-heading">calloc</h4>



<p class="wp-block-paragraph">现在，假设您要在一个盒子里放多个玩具，而您只对玩具的数量和大小有一个大概的了解。为此，您需要一个盒子，盒子的大小等于所有玩具的大小之和。</p>



<p class="wp-block-paragraph">在这种情况下，我们使用 <code>calloc</code> 函数。与 <code>malloc</code> 一样，<code>calloc</code> 也在运行时分配内存，并在 <code>stdlib.h</code> 中定义。它需要元素的数量和每个元素的大小（以字节为单位），将每个元素初始化为零，然后将空指针返回到内存。</p>



<p class="wp-block-paragraph">它的语法是：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">void</span> *calloc(n, element-size);</code></span></pre>


<p class="wp-block-paragraph">在这里，<code>n</code> 是元素的数量，<code>element-size</code> 是每个元素的大小。</p>



<p class="wp-block-paragraph">让我们再次看一下 <code>malloc</code> 的最后一个示例，但是这次是 <code>calloc</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int n, i, *p;
    printf(<span class="hljs-string">"Enter number of elements: "</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;n);
    p = (int *)calloc(n, sizeof(int)); <span class="hljs-comment">//memory allocated using calloc</span>
    <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">NULL</span>)
    {
        printf(<span class="hljs-string">"memory cannot be allocated\n"</span>);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"Enter elements of array:\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; ++i)
        {
            scanf(<span class="hljs-string">"%d"</span>, &amp;*(p + i));
        }
        printf(<span class="hljs-string">"Elements of array are\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; i++)
        {
            printf(<span class="hljs-string">"%d\n"</span>, *(p + i));
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">因此，这与 <code>malloc</code> 的示例相同，但 <code>calloc</code> 的语法有所不同。在这里，我们写了 <code>(int *)calloc(n, sizeof(int))</code>，其中 <code>n</code> 是整数数组中的元素数量（在这种情况下 <code>sizeof(int)</code> 为 5），并且是每个元素的大小。因此，数组的总大小为 <code>n * sizeof(int)</code>。</p>



<p class="wp-block-paragraph"><code>calloc</code> 将分配的内存初始化为零值，<code>malloc</code> 否则不初始化。</p>



<p class="wp-block-paragraph">为了证明这一点，让我们看两个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int n, i, *p;
    printf(<span class="hljs-string">"Enter number of elements: "</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;n);
    p = (int *)calloc(n, sizeof(int));
    <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">NULL</span>)
    {
        printf(<span class="hljs-string">"memory cannot be allocated\n"</span>);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"Elements of array are\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; i++)
        {
            printf(<span class="hljs-string">"%d\n"</span>, *(p + i));
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，我们指定了元素的数量，即 5，但是没有初始化任何元素。因此，<code>calloc</code> 将每个元素初始化为 0，从而将每个元素的值打印为 0。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int n, i, *p;
    printf(<span class="hljs-string">"Enter number of elements: "</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;n);
    p = (int *)malloc(n, sizeof(int));
    <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">NULL</span>)
    {
        printf(<span class="hljs-string">"memory cannot be allocated\n"</span>);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"Elements of array are\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; i++)
        {
            printf(<span class="hljs-string">"%d\n"</span>, *(p + i));
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">由于 <code>malloc</code> 未将元素初始化为 0，因此在这种情况下会出现错误。</p>



<p class="wp-block-paragraph"><code>calloc</code> 用于将内存分配给大多数数组和结构。</p>



<h4 class="wp-block-heading">realloc</h4>



<p class="wp-block-paragraph">如果假设我们分配的内存多于或少于所需，则可以使用 <code>realloc</code> 更改先前分配的内存空间的大小。其语法如下：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">void</span> *realloc(pointer, <span class="hljs-keyword">new</span>-size);</code></span></pre>


<p class="wp-block-paragraph">让我们看一个关于 <code>realloc</code> 的例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main()
{
    char *p1;
    int m1, m2;
    m1 = <span class="hljs-number">10</span>;
    m2 = <span class="hljs-number">20</span>;
    p1 = (char *)malloc(m1);
    strcpy(p1, <span class="hljs-string">"Codesdope"</span>);
    p1 = (char *)realloc(p1, m2);
    strcat(p1, <span class="hljs-string">"Practice"</span>);
    printf(<span class="hljs-string">"%s\n"</span>, p1);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在上面的示例中，我们声明了一个指针 <code>p1</code>，该指针将用于动态分配内存空间。</p>



<p class="wp-block-paragraph"><code>p1 = (char *)malloc(m1)</code> → 通过编写此代码，我们分配了指针 <code>p1</code> 指向的 10 个字节的存储空间。我们曾经 <code>(char *)</code> 将 <code>malloc</code> 返回的指针类型转换为 character。</p>



<p class="wp-block-paragraph"><code>strcpy(p1, "Codesdope")</code> → 这会将字符串值 <code>Codesdope</code> 分配给指针 <code>p1</code> 指向的内存。当前，存储空间为 10 个字节，可以轻松存储字符串 <code>Codesdope</code>，但如果现在我们希望该存储空间存储字符串 <code>CodesdopePractice</code> 怎么办？为此，我们需要扩展内存空间的大小，这可以通过 <code>realloc</code> 轻松实现。</p>



<p class="wp-block-paragraph"><code>p1 = (char *)realloc(p1, m2)</code> → 这样会将内存空间（其地址存储在 <code>p1</code> 中）的大小增加到 20 个字节（由于 <code>m2</code> 的值为 20），因此可以轻松存储字符串 <code>CodesdopePractice</code>。</p>



<p class="wp-block-paragraph"><code>strcat(p1, "Practice")</code> → 这会将字符串 <code>Practice</code> 添加到存储在 <code>p1</code> 指向的内存（即 <code>Codesdope</code>）中的字符串的末尾。因此，现在，由 <code>p1</code> 指向的内存现在存储字符串值 <code>CodesdopePractice</code>。</p>



<h4 class="wp-block-heading">free</h4>



<p class="wp-block-paragraph"><code>free</code> 函数用于在程序完成后释放或释放内存，该内存是在程序中动态分配的。建议在程序完成后释放动态分配的内存，以便将来使用。</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">void</span> free(pointer);</code></span></pre>


<p class="wp-block-paragraph">这是 <code>free</code> 函数的语法，其返回类型为 <code>void</code>。现在，让我们看一个示例，其中我们在程序结尾使用 <code>free</code> 释放了动态分配的内存。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int n, i, *p;
    printf(<span class="hljs-string">"Enter number of elements:\n"</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;n);
    p = (int *)malloc(n * sizeof(int));
    <span class="hljs-keyword">if</span> (p == <span class="hljs-keyword">NULL</span>)
    {
        printf(<span class="hljs-string">"memory cannot be allocated\n"</span>);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"Enter elements of array:\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; ++i)
        {
            scanf(<span class="hljs-string">"%d"</span>, &amp;*(p + i));
        }
        printf(<span class="hljs-string">"Elements of array are\n"</span>);
        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; n; i++)
        {
            printf(<span class="hljs-string">"%d\n"</span>, *(p + i));
        }
    }
    free(p);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">因此，在这里，通过编写 <code>free(p)</code>，我们释放了使用 <code>malloc</code> 动态分配的内存。</p>



<h3 class="wp-block-heading">枚举</h3>



<p class="wp-block-paragraph">枚举（<code>enum</code>）是用户定义的数据类型（与结构相同）。它由该类型的各种元素组成。枚举没有这种特定的用途，我们只是为了使我们的代码更整洁，更易读而使用。我们也可以在不使用枚举的情况下编写 C 程序。</p>



<p class="wp-block-paragraph">例如，夏季，春季，冬季和秋季是四个季节的名称。因此，可以说这些是季节类型。因此，这成为以季节和夏季，春季，冬季和秋季为名称的枚举。</p>



<p class="wp-block-paragraph">因此，您很清楚枚举的基本概念。现在让我们看看如何定义它。</p>



<h4 class="wp-block-heading">定义枚举</h4>



<p class="wp-block-paragraph">枚举以与结构相同的方式定义，其中关键字 <code>struct</code> 被关键字替换为关键字 <code>enum</code>，而元素由 <code>逗号</code> 分隔，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs">enum enum_name
{
    element1,
    element2,
    element3,
    element4,
};</code></span></pre>


<p class="wp-block-paragraph">现在让我们定义上述季节示例的枚举：</p>


<pre class="wp-block-code"><span><code class="hljs">enum Season
{
    Summer,
    Spring,
    Winter,
    Autumn
};</code></span></pre>


<p class="wp-block-paragraph">在这里，我们定义了一个名为 <code>Season</code> 和 <code>Summer</code>、<code>Spring</code>、<code>Winter</code> 和 <code>Autumn</code> 的枚举作为元素。</p>



<h4 class="wp-block-heading">枚举变量声明</h4>



<p class="wp-block-paragraph">我们还以与结构相同的方式声明枚举变量。我们如下创建一个枚举变量：</p>


<pre class="wp-block-code"><span><code class="hljs">enum season
{
    Summer,
    Spring,
    Winter,
    Autumn
};

main()
{
    enum season s;
}</code></span></pre>


<p class="wp-block-paragraph">因此，这里的 <code>s</code> 是名为 <code>season</code> 的枚举的变量。这个变量代表一个季节。我们还可以如下声明一个枚举变量：</p>


<pre class="wp-block-code"><span><code class="hljs">enum season
{
    Summer,
    Spring,
    Winter,
    Autumn
} s;</code></span></pre>


<h4 class="wp-block-heading">枚举成员的价值观</h4>



<p class="wp-block-paragraph">枚举的所有元素都有一个值。默认情况下，第一个元素的值为 0，第二个元素的值为 1，依此类推。</p>



<p class="wp-block-paragraph">让我们来看一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

enum season
{
    Summer,
    Spring,
    Winter,
    Autumn
};

int main()
{
    enum season s;
    s = Spring;
    printf(<span class="hljs-string">"%d\n"</span>, s);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，我们首先定义了一个名为 <code>Season</code> 的枚举，并在主函数中声明了它的变量 <code>s</code>，如我们之前所见。<code>Summer</code>、<code>Spring</code>、<code>Winter</code> 和 <code>Autumn</code> 的值分别为 0、1、2 和 3。因此，通过编写 <code>s = Spring</code>，我们将变量 <code>s</code> 赋值为 <code>1</code>，因为 <code>Spring</code> 的值为 1。</p>



<p class="wp-block-paragraph">我们还可以更改默认值，并将我们选择的任何值分配给枚举元素。一旦我们更改了任何枚举元素的默认值，其后所有元素的值也将相应地更改。一个例子将使这一点更清楚：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

enum days
{
    sun,
    mon,
    tue = <span class="hljs-number">5</span>,
    wed,
    thurs,
    fri,
    sat
};

int main()
{
    enum days day;
    day = thurs;
    printf(<span class="hljs-string">"%d\n"</span>, day);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">默认值 <code>sun</code> 将为 0，<code>mon</code> 将为 1，<code>tue</code> 将为 2，依此类推。在上面的示例中，我们将 <code>tue</code> 的值定义为 5。因此，<code>wed</code>、<code>thurs</code>、<code>fri</code> 和 <code>sat</code> 的值将分别变为 6、7、8 和 9。对 <code>sun</code> 和 <code>mon</code> 的值将分别保持为 0 和 1 无效。因此，<code>thurs</code> 的值（即 7）将被打印出来。</p>



<p class="wp-block-paragraph">让我们再看一个枚举的例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

enum days
{
    sun,
    mon,
    tue,
    wed,
    thurs,
    fri,
    sat
};

int main()
{
    enum days day;
    day = thurs;
    printf(<span class="hljs-string">"%d\n"</span>, day + <span class="hljs-number">2</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在此示例中，<code>thurs</code>（即 4）的值分配给变量 <code>day</code>。由于我们正在打印 <code>day + 2</code>，即 6（= 4 + 2），因此输出为 6。</p>



<h3 class="wp-block-heading">C语言的union</h3>



<p class="wp-block-paragraph">声明和使用结构的方式相同。像结构一样，它也用于存储不同类型的数据。</p>



<p class="wp-block-paragraph">在探讨结构和联合之间的区别之前，让我们首先了解如何定义联合。</p>



<h4 class="wp-block-heading">定义union</h4>



<p class="wp-block-paragraph">让我们看一下联合的语法：</p>


<pre class="wp-block-code"><span><code class="hljs">union union_name
{
    数据类型 member-1;
    数据类型 member-2;
    数据类型 member-3;
    数据类型 member-4;
};</code></span></pre>


<p class="wp-block-paragraph">这不是结构的语法吗，除了我们写了关键词 <code>union</code> 来代替 <code>struct</code> 之外，这与结构的语法不同吗？</p>



<p class="wp-block-paragraph">让我们以我们在结构中使用的相同示例为例。在这里，我们将 <code>union</code> 的名称称为 <code>student</code>，并将 <code>name</code>、<code>roll_no</code> 和 <code>phone_number</code> 用作其成员，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs">union student
{
    int roll_no;
    char name&#91;30];
    int phone_number;
};</code></span></pre>


<h4 class="wp-block-heading">union 变量声明</h4>



<p class="wp-block-paragraph">声明联合变量的方式与声明结构变量的方式相同。</p>



<p class="wp-block-paragraph">同样，让我们以相同的示例为例，我们要存储三个学生的名册编号，姓名和电话号码。为此，我们将按照上面的定义定义一个名为 <code>student</code> 的联合，然后在主函数中声明其三个变量 <code>p1</code>、<code>p2</code> 和 <code>p3</code>（分别代表三个学生）。</p>


<pre class="wp-block-code"><span><code class="hljs">union student
{
    int roll_no;
    char name&#91;30];
    int phone_number;
};

main()
{
    union student p1, p2, p3;
}</code></span></pre>


<p class="wp-block-paragraph">还有另一种声明联合变量的方法，我们在定义联合时按如下方式声明它们：</p>


<pre class="wp-block-code"><span><code class="hljs">union student
{
    int roll_no;
    char name&#91;30];
    int phone_number;
} p1, p2, p3;</code></span></pre>


<p class="wp-block-paragraph">与结构类似，我们通过访问其姓名、<code>roll_no</code> 和电话号码来分配第一个学生的姓名、名次和电话号码（假设 <code>p1</code>），如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs">p1.roll_no = 1;</code></span></pre>


<p class="wp-block-paragraph">在这里，<code>p1.roll_no</code> 意味着 <code>p1</code> 的 <code>roll_no</code>。</p>



<p class="wp-block-paragraph">总是使用 <code>strcpy</code> 为变量分配字符串值，因为我们为 <code>p1</code>（第一个学生）分配了名称 <code>Brown</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">strcpy(p1.name, <span class="hljs-string">"Brown"</span>);</code></span></pre>


<p class="wp-block-paragraph">到现在为止，您必须已经找到类似于结构的联合。现在让我们看一下两者之间的区别。</p>



<h4 class="wp-block-heading">联合与结构之间的区别</h4>



<p class="wp-block-paragraph">在讨论差异之前，让我们先来看一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

struct student1
{ <span class="hljs-comment">//defining a union</span>
    int roll_no;
    char name&#91;<span class="hljs-number">40</span>];
    int phone_number;
};

union student2
{
    int roll_no;
    char name&#91;<span class="hljs-number">40</span>];
    int phone_number;
};

int main()
{
    struct student1 s1;
    union student2 u1;
    printf(<span class="hljs-string">"size of structure = %d\n"</span>, sizeof(s1));
    printf(<span class="hljs-string">"size of union = %d\n"</span>, sizeof(u1));
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">谈论上面的示例，存储结构所需的内存量是其所有成员的内存大小的总和。在上面的示例中，变量 <code>roll_no</code> 和 <code>phone_number</code> 的内存大小将分别为 4 个字节（因为两者均为整数类型），而字符数组 <code>name[40]</code> 的内存大小将为 40 个字节（由于数组占用了内存）最多 40 个字符，并且 <code>char</code> 的大小为 1）。因此，该结构占用的内存将是 <code>4 + 40 + 4 = 48 bytes</code>。</p>



<p class="wp-block-paragraph">现在进入联合，联合的内存大小等于其成员占据内存最大空间的大小。<code>roll_no</code> 和 <code>phone_number</code> 的大小分别为 4 个字节，<code>name[40]</code> 的大小为 40 个字节。因此，联合将占用 40 个字节的存储空间。</p>



<p class="wp-block-paragraph">我们一次只能访问一个工会成员，因为我们在内存中只有一个位置，因此一次只能使用其中一个成员。所有其他成员将包含垃圾值（即会损坏）。对于可以同时访问所有成员变量的结构而言，情况并非如此，因为每个成员变量占用的存储空间不同。</p>



<p class="wp-block-paragraph">现在让我们看一个联合的例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

union student
{
    int roll_no;
    int phone_number;
    char name&#91;<span class="hljs-number">30</span>];
};

int main()
{
    union student p1;
    p1.roll_no = <span class="hljs-number">1</span>;
    p1.phone_number = <span class="hljs-number">1234567822</span>;
    strcpy(p1.name, <span class="hljs-string">"Brown"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p1.roll_no);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p1.phone_number);
    printf(<span class="hljs-string">"name : %s\n"</span>, p1.name);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">如您所见，名称按原样打印，垃圾值作为卷号和电话号码打印。让我们看看为什么会这样。</p>



<p class="wp-block-paragraph">如您现在所知，我们一次只能访问一个工会成员，而其他成员则受到损坏。因此，当我们编写时 <code>p1.roll_no = 1</code>，访问了成员 <code>roll_no</code> 并为其分配了一个值 <code>1</code>。之后，通过写入 <code>p1.phone_number = 1234567822</code>，我们为成员 <code>phone_number</code> 分配了一个值。最后，我们为成员 <code>name</code> 分配了一个字符串值 <code>Brown</code> <code>strcpy(p1.name, "Brown")</code>，现在，其他两个成员 <code>roll_no</code> 和 <code>phone_number</code> 包含一个垃圾值。因此，<code>name</code> 的值按原样打印，输出中其他两个变量的值就是这两个变量的垃圾值。</p>



<p class="wp-block-paragraph">让我们再看一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

union student
{
    int roll_no;
    char name&#91;<span class="hljs-number">30</span>];
    int phone_number;
};

int main()
{
    union student p1;
    p1.roll_no = <span class="hljs-number">1</span>;
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p1.roll_no);
    strcpy(p1.name, <span class="hljs-string">"Brown"</span>);
    printf(<span class="hljs-string">"name : %s\n"</span>, p1.name);
    p1.phone_number = <span class="hljs-number">1234567822</span>;
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p1.phone_number);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，首先我们将 <code>roll_no</code> 的值分配为 1 并打印出来。因此，当前其他成员的值是一些垃圾值，而 <code>roll_no</code> 的值是 1，因此按原样打印。之后，我们给名称分配了一个字符串值 <code>Brown</code>，所以现在 <code>roll_no</code> 和 <code>phone_number</code> 包含垃圾值并且名称被打印出来。同样，我们打印了 <code>phone_number</code>。</p>



<h3 class="wp-block-heading">C语言中的typedef</h3>



<p class="wp-block-paragraph"><code>typedef</code> 关键字用于为类型分配新名称。这只是为了防止我们编写更多内容。</p>



<p class="wp-block-paragraph">例如，如果我们要声明一些 <code>type</code> 变量 <code>unsigned int</code>，则必须在程序中编写 <code>unsigned int</code>，这对于我们中的某些人可能非常忙。因此，我们可以使用 <code>typedef</code> 为 <code>unsigned int</code> 分配选择的新名称，该名称可以在我们想在程序中使用 <code>unsigned int</code> 的任何时间使用。</p>


<pre class="wp-block-code"><span><code class="hljs">typedef current_name new_name;
typedef unsigned int uint;
uint i, j;</code></span></pre>


<p class="wp-block-paragraph">现在，我们可以在整个程序中编写 <code>uint</code> 而不是 <code>unsigned int</code>。上面的代码与编写相同：</p>


<pre class="wp-block-code"><span><code class="hljs">unsigned int i, j;</code></span></pre>


<p class="wp-block-paragraph">让我们来看一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    typedef unsigned int ui;
    ui i = <span class="hljs-number">5</span>, j = <span class="hljs-number">8</span>;
    printf(<span class="hljs-string">"i = %d\n"</span>, i);
    printf(<span class="hljs-string">"j = %d\n"</span>, j);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">因此，我们可以为任何数据类型分配一个新名称。</p>



<p class="wp-block-paragraph">同样，我们也可以使用 <code>typedef</code> 为结构分配一个新名称，该结构是用户定义的数据类型，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs">typedef struct structure_name
{
    数据类型 member-1;
    数据类型 member-2;
    数据类型 member-3;
    数据类型 member-4;
} type_name;</code></span></pre>


<p class="wp-block-paragraph">现在，在声明这种结构类型的变量的同时，我们可以 <code>type_name</code> 代替 <code>struct structure_name</code> 整个程序编写代码。</p>



<p class="wp-block-paragraph">让我们以在 <code>结构</code> 主题中看到的名为 <code>student</code> 的结构为例：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

typedef struct student
{
    int roll_no;
    char name&#91;<span class="hljs-number">30</span>];
    int phone_number;
} st;

int main()
{
    st p1, p2, p3;
    p1.roll_no = <span class="hljs-number">1</span>;
    strcpy(p1.name, <span class="hljs-string">"Brown"</span>);
    p1.phone_number = <span class="hljs-number">123443</span>;
    p2.roll_no = <span class="hljs-number">2</span>;
    strcpy(p2.name, <span class="hljs-string">"Sam"</span>);
    p2.phone_number = <span class="hljs-number">1234567822</span>;
    p3.roll_no = <span class="hljs-number">3</span>;
    strcpy(p3.name, <span class="hljs-string">"Addy"</span>);
    p3.phone_number = <span class="hljs-number">1234567844</span>;
    printf(<span class="hljs-string">"First Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p1.roll_no);
    printf(<span class="hljs-string">"name : %s\n"</span>, p1.name);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p1.phone_number);
    printf(<span class="hljs-string">"Second Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p2.roll_no);
    printf(<span class="hljs-string">"name : %s\n"</span>, p2.name);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p2.phone_number);
    printf(<span class="hljs-string">"Third Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p3.roll_no);
    printf(<span class="hljs-string">"name : %s\n"</span>, p3.name);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p3.phone_number);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，整个示例与在 <code>Structure</code> 中所做的相同，唯一的区别是我们用 <code>st</code> 代替代替，<code>struct student</code> 即我们使用了新类型（名为 <code>st</code>）来声明该结构类型的变量（命名为 <code>student</code>）。</p>



<p class="wp-block-paragraph">我们也可以结合使用 <code>typedef</code> 和联合。为此，所有内容都将与关键字关键字 <code>union</code> 代替 <code>struct</code> 的结构相同。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

typedef union student
{
    int roll_no;
    int phone_number;
    char name&#91;<span class="hljs-number">30</span>];
} st;

int main()
{
    st p1, p2, p3;
    p1.roll_no = <span class="hljs-number">1</span>;
    p1.phone_number = <span class="hljs-number">123443</span>;
    strcpy(p1.name, <span class="hljs-string">"Brown"</span>);
    p2.roll_no = <span class="hljs-number">2</span>;
    p2.phone_number = <span class="hljs-number">1234567822</span>;
    strcpy(p2.name, <span class="hljs-string">"Sam"</span>);
    p3.roll_no = <span class="hljs-number">3</span>;
    p3.phone_number = <span class="hljs-number">1234567844</span>;
    strcpy(p3.name, <span class="hljs-string">"Addy"</span>);
    printf(<span class="hljs-string">"First Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p1.roll_no);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p1.phone_number);
    printf(<span class="hljs-string">"name : %s\n"</span>, p1.name);
    printf(<span class="hljs-string">"Second Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p2.roll_no);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p2.phone_number);
    printf(<span class="hljs-string">"name : %s\n"</span>, p2.name);
    printf(<span class="hljs-string">"Third Student\n"</span>);
    printf(<span class="hljs-string">"roll_no : %d\n"</span>, p3.roll_no);
    printf(<span class="hljs-string">"phone_number : %d\n"</span>, p3.phone_number);
    printf(<span class="hljs-string">"name : %s\n"</span>, p3.name);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h3 class="wp-block-heading">C中的存储类</h3>



<p class="wp-block-paragraph">每个变量都有一个存储类，用于定义该变量的功能。它告诉编译器变量的存储位置，其初始值，作用域（可见性级别）和生存期（全局或局部）。</p>



<p class="wp-block-paragraph">C 中有四个存储类：</p>



<ul class="wp-block-list">
<li><code>auto</code></li>



<li><code>extern</code></li>



<li><code>static</code></li>



<li><code>register</code></li>
</ul>



<p class="wp-block-paragraph">让我们一一理解。</p>



<h4 class="wp-block-heading">auto</h4>



<p class="wp-block-paragraph">默认情况下，在函数或块（块是一组代码的一部分，例如，用花括号括起来的语句构成代码块）中定义的变量属于自动存储类。这些变量也称为局部变量，因为它们是函数的局部变量，并且默认情况下为它们分配了一些垃圾值。由于这些变量是在函数内部声明的，因此只能在该函数内部访问。在声明这些变量时无需放置 <code>auto</code>，因为默认情况下它们是 <code>auto</code>。</p>



<p class="wp-block-paragraph">虽然您在整个 C 教程中都使用了这些 <code>auto</code>（local）变量，但让我们看一个示例：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int sum(int n1, int n2)
{
    auto int s; <span class="hljs-comment">//declaration of auto(local) variable</span>
    s = n1 + n2;
    <span class="hljs-keyword">return</span> s;
}

int main()
{
    int i = <span class="hljs-number">2</span>, j = <span class="hljs-number">3</span>, k;
    k = sum(i, j);
    printf(<span class="hljs-string">"sum is : %d\n"</span>, k);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在此，变量 <code>s</code> 在函数 <code>sum</code> 内部声明，因此只能在函数内部使用。在声明时无需放置 <code>auto</code>。</p>



<h4 class="wp-block-heading">extern</h4>



<p class="wp-block-paragraph">我们在变量之前编写 <code>extern</code> 关键字，以告诉编译器该变量在其他地方声明。基本上，通过在任何变量告诉我们该变量是在其他程序文件中声明的全局变量之前编写 <code>extern</code> 关键字。</p>



<p class="wp-block-paragraph">现在让我们看看实际发生了什么。</p>



<p class="wp-block-paragraph">您必须知道什么是全局变量。全局变量是在所有函数外部声明的变量。可以在整个程序中访问它，我们可以在任何函数中随时更改其值，如下所示：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int g;

void <span class="hljs-keyword">print</span>()
{
    g = <span class="hljs-number">10</span>;
    printf(<span class="hljs-string">"g = %d\n"</span>, g);
}

int main()
{
    g = <span class="hljs-number">7</span>;
    printf(<span class="hljs-string">"g = %d\n"</span>, g);
    <span class="hljs-keyword">print</span>();
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，<code>g</code> 是在所有功能之外定义的全局变量。在 <code>main</code> 函数中，将其值分配为 7，在 <code>print</code> 函数中将其值分配为 10。</p>



<p class="wp-block-paragraph">在声明全局变量时，将像所有其他变量一样在内存中分配一些空间。我们可以像在上面的示例中一样，在声明它的同一程序文件中为其分配值。但是，如果我们要使用它或在任何其他程序文件中为其分配值，该怎么办。</p>



<p class="wp-block-paragraph">我们可以使用 <code>extern</code> 关键字来做到这一点，如下所示。</p>



<p class="wp-block-paragraph"><code>firstfile.c</code>：</p>


<pre class="wp-block-code"><span><code class="hljs">int g = 0;</code></span></pre>


<p class="wp-block-paragraph">在第一个程序文件中 <code>firstfile.c</code>，我们声明了一个全局变量 <code>g</code>。</p>



<p class="wp-block-paragraph">现在，我们将在头文件中将此变量 <code>g</code> 声明为 <code>extern</code> <code>firstfile.h</code>，然后将其包含在我们要使用此变量的第二个文件中。</p>



<p class="wp-block-paragraph"><code>firstfile.h</code>：</p>


<pre class="wp-block-code"><span><code class="hljs">extern int g;</code></span></pre>


<p class="wp-block-paragraph">现在在第二个程序文件中 <code>secondfile.c</code>，为了使用全局变量 <code>g</code>，我们需要通过写入在其中包含头文件 <code>#include "firstfile.h"</code>。在这里，我们为变量 <code>g</code> 分配了值 4，因此该程序中的 <code>g</code> 的值变为 4。</p>



<p class="wp-block-paragraph"><code>secondfile.c</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include "firstfile.h"</span>

main()
{
    g = <span class="hljs-number">4</span>;
    printf(<span class="hljs-string">"%d"</span>, g);
}</code></span></pre>


<h4 class="wp-block-heading">static</h4>



<p class="wp-block-paragraph">初始化后声明为静态的变量将一直存在，直到程序结束。如果在函数内部声明了静态变量，则该静态变量将一直存在，直到程序结束，并且不会因为该函数的存在而被销毁（如 <code>auto</code> 中一样）。如果在程序中所有函数之外声明了静态变量，则只能在声明了该变量的程序中使用它，而对其他程序文件不可见（如 <code>extern</code>）。</p>



<p class="wp-block-paragraph">让我们看一个静态变量的例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

<span class="hljs-keyword">static</span> int g = <span class="hljs-number">5</span>;

void fn()
{
    <span class="hljs-keyword">static</span> int i = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"g = %d\t"</span>, g--);
    printf(<span class="hljs-string">"i = %d\n"</span>, i++);
}

int main()
{
    <span class="hljs-keyword">while</span> (g &gt;= <span class="hljs-number">2</span>)
        fn();
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里，<code>g</code> 和 <code>i</code> 是静态变量，其中 <code>g</code> 是全局变量，<code>i</code> 是局部变量。如果我们未 <code>static</code> 在声明 <code>i</code> 之前编写过代码，则每次将调用函数 <code>fn()</code> 时，每次都会将 <code>i</code> 声明为初始值 0 并作为函数 <code>fn()</code> 将退出，也将被摧毁。</p>



<h4 class="wp-block-heading">register</h4>



<p class="wp-block-paragraph">它告诉编译器变量将被存储在寄存器中，而不是存储在内存（RAM）中。我们可以比普通变量更快地访问寄存器变量。并非所有定义为的寄存器 <code>register</code> 都将存储在寄存器中，因为它取决于实现和硬件的各种限制。</p>



<p class="wp-block-paragraph">我们无法访问此类变量的地址，因为它们没有一个存储位置，通过以下示例可以清楚地看到这些位置：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main()
{
    register int n = <span class="hljs-number">20</span>;
    int *ptr;
    ptr = &amp;n;
    printf(<span class="hljs-string">"address of n : %u"</span>, ptr);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e6%80%bb%e7%bb%93/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>数组与指针</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e6%95%b0%e7%bb%84%e4%b8%8e%e6%8c%87%e9%92%88/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e6%95%b0%e7%bb%84%e4%b8%8e%e6%8c%87%e9%92%88/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:53:44 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13547</guid>

					<description><![CDATA[数组与指针的关系 什么是数组？什么是指针？ 数组是相同类型的 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">数组与指针的关系</h3>



<h4 class="wp-block-heading">什么是数组？什么是指针？</h4>



<p class="wp-block-paragraph">数组是相同类型的对象集合，可以用一个名称引用。</p>



<p class="wp-block-paragraph">例如：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">int</span> <span class="hljs-selector-tag">scores</span><span class="hljs-selector-attr">&#91;50]</span>;</code></span></pre>


<p class="wp-block-paragraph">它可以包含 50 场篮球赛的比分。</p>



<p class="wp-block-paragraph">使用不同的索引值可以引用数组中的每个元素。<code>scores[0]</code> 是第一个分数，<code>scores[49]</code> 是最后一个分数。</p>



<p class="wp-block-paragraph">如果每个月有 10 场比赛，就可以用多维数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">scores</span><span class="hljs-selector-attr">&#91;12]</span><span class="hljs-selector-attr">&#91;10]</span>;</code></span></pre>


<p class="wp-block-paragraph">如果一月开始比赛，则五月的第三场比赛用：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">scores</span><span class="hljs-selector-attr">&#91;4]</span><span class="hljs-selector-attr">&#91;2]</span>;</code></span></pre>


<p class="wp-block-paragraph">指针是一个变量，它的值是给定类型的另一个变量或常量的地址。</p>



<p class="wp-block-paragraph">使用指针可以在不同的时间访问不同的变量，只要它们的类型相同即可。</p>



<p class="wp-block-paragraph">数组和指针似乎完全不同，但它们有非常密切的关系，有时还可以互换。</p>



<p class="wp-block-paragraph">下面看一个例子：</p>



<p class="wp-block-paragraph">字符串是 char 类型的数组。如果用 scanf 输入一个字符：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char single = <span class="hljs-number">0</span>;
scanf(<span class="hljs-string">"%c"</span>, &amp;single);</code></span></pre>


<p class="wp-block-paragraph">具体代码：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char single = <span class="hljs-number">0</span>;
    scanf(<span class="hljs-string">"%c"</span>, &amp;single);
    printf(<span class="hljs-string">"%c\n"</span>, single);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在这里 scanf 需要用到取地址符 <code>&amp;</code>，用于 single。因为 scanf 需要用到存储的变量的地址。</p>



<p class="wp-block-paragraph">然而，如果读入的是字符串，可以这样：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char multiple&#91;<span class="hljs-number">10</span>];
    scanf(<span class="hljs-string">"%s"</span>, &amp;multiple);
    printf(<span class="hljs-string">"%s\n"</span>, multiple);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">这里不需要使用 <code>&amp;</code> 运算符，而使用数组名称，就像指针一样。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char multiple&#91;<span class="hljs-number">10</span>];
    scanf(<span class="hljs-string">"%s"</span>, multiple); <span class="hljs-comment">//可以不需要取地址符 数组名本身就是地址</span>
    printf(<span class="hljs-string">"%s\n"</span>, multiple);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">如果以这种方式使用数组名称，而没有带索引值，它就引用数组的第一个元素的地址。</p>



<p class="wp-block-paragraph">但数组不是指针，它们有一个重要的区别：可以改变指针包含的地址，但不能改变数组名称引用的地址。</p>



<h4 class="wp-block-heading">指针算术与数组类型</h4>



<p class="wp-block-paragraph">我们前面知道 char 类型是占一个字节。</p>



<p class="wp-block-paragraph">所以当我们使用指针 <code>p + 1</code> 就去到下一个字节，下一个字节就读取下一个字节的字符。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char multiple&#91;<span class="hljs-number">10</span>];
    scanf(<span class="hljs-string">"%s"</span>, multiple); <span class="hljs-comment">//可以不需要取地址符 数组名本身就是地址</span>
    char *p = multiple; <span class="hljs-comment">//&amp;multiple&#91;0]</span>
    printf(<span class="hljs-string">"%c\n"</span>, *p);
    printf(<span class="hljs-string">"%c\n"</span>, *(p+<span class="hljs-number">1</span>));
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">但是如果是其他类型，比如 long 类型不是占用一个字节，而是四个字节。</p>



<p class="wp-block-paragraph">这时候，如果我们要读取下个元素，是否是 <code>p+4</code>？还是？</p>



<p class="wp-block-paragraph">大家思考一下这个问题。</p>



<p class="wp-block-paragraph">下面看这个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long multiple&#91;] = {<span class="hljs-number">15</span>L, <span class="hljs-number">25</span>L, <span class="hljs-number">35</span>L, <span class="hljs-number">45</span>L};
    long * p = multiple;

    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; sizeof(multiple)/sizeof(multiple&#91;<span class="hljs-number">0</span>]); i++)
    {
        printf(<span class="hljs-string">"\n地址 p+%d (&amp;multiple&#91;%d]): %d   *(p+%d) 值: %d"</span>,
               i, i, p+i, i, *(p+i));
    }

    printf(<span class="hljs-string">"\n    long类型占: %d bytes\n"</span>, sizeof(long));
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">上面代码，<code>p</code> 是 6422016，<code>p+1</code> 本来我们觉得应该是 6422017，但是它实际上是 6422020。</p>



<p class="wp-block-paragraph">所以 <code>p+1</code> 比 <code>p</code> 是大了 4，而不是 1。</p>



<p class="wp-block-paragraph">这里是编译器帮我们来计算，编译器根据指针类型 long，然后决定了是 4。</p>



<p class="wp-block-paragraph">就是因为我们的指针是 long 类型指针 <code>long * p</code>，所以当我们 <code>p+1</code> 的时候，编译器知道是 long 类型，然后知道它 4 个字节，所以虽然是 <code>p+1</code>，但是编译器自动跳转四个字节。</p>



<h4 class="wp-block-heading">多维数组与指针</h4>



<p class="wp-block-paragraph">前面我们讨论的是一维数组与指针的关系，二维或者多维数组是否相同？</p>



<p class="wp-block-paragraph">其实某种程度上是相同的。</p>



<p class="wp-block-paragraph">考虑之前的井字游戏中用到的数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
    {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
    {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
    {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
};</code></span></pre>


<p class="wp-block-paragraph">下面使用该数组来探讨一下：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    printf(<span class="hljs-string">"address of board        : %p\n"</span>, board);
    printf(<span class="hljs-string">"address of board&#91;0]&#91;0]  : %p\n"</span>, &amp;board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]);
    printf(<span class="hljs-string">"but what is in board&#91;0] : %p\n"</span>, board&#91;<span class="hljs-number">0</span>]);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">我们可以看到，以上三个值是相同的。</p>



<p class="wp-block-paragraph">声明一维数组 <code>x[n1]</code> 时，它告诉编译器它是一个有 n1 个元素的数组。</p>



<p class="wp-block-paragraph">声明二维数组 <code>y[n1][n2]</code>，编译器就会创建一个大小为 n1 的数组，它的每个元素是一个大小为 n2 的数组。</p>



<p class="wp-block-paragraph">声明二维数组时，就是创建一个数组的数组。</p>



<p class="wp-block-paragraph">因此使用数组名+一个索引值访问这个二维数组时，例如 <code>board[0]</code> 就是引用一个子数组的地址。</p>



<p class="wp-block-paragraph">仅使用二维数组名时，就是引用二维数组的开始地址。它也是第一个子数组的开始地址。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    printf(<span class="hljs-string">"value of board&#91;0]&#91;0] : %c\n"</span>, board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]);
    printf(<span class="hljs-string">"value of *board&#91;0]   : %c\n"</span>, *board&#91;<span class="hljs-number">0</span>]);
    printf(<span class="hljs-string">"value of **board     : %c\n"</span>, **board);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">使用 <code>board</code> 获取子数组的第一个元素需要两个间接运算符 <code>**board</code>。</p>



<p class="wp-block-paragraph">如果只使用一个 <code>*</code>，只会得到子数组的第一个元素，即 <code>board[0]</code> 引用的地址。</p>



<p class="wp-block-paragraph">也就是 <code>*board</code> 得到的是 <code>board[0]</code> 的地址。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] =
    {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>}, <span class="hljs-comment">//board&#91;0] char b&#91;] = {'1','2','3'}</span>
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>}, <span class="hljs-comment">//board&#91;1] char b1&#91;] = {'4','5','6'}</span>
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}  <span class="hljs-comment">//board&#91;2] char b2&#91;] = {'7','8','9'}</span>
    };
    <span class="hljs-comment">//b 就是1的地址  b在这里 等同于 board&#91;0]</span>
    <span class="hljs-comment">//在一维数组里面 b&#91;0]是1 *b 也是1  *(b+1) 就是b&#91;1]</span>
    <span class="hljs-comment">//把b替换为board&#91;0]  *board&#91;0] *(board&#91;0]+1)</span>
    printf(<span class="hljs-string">"address of board        : %p\n"</span>, board);
    printf(<span class="hljs-string">"address of board&#91;0]&#91;0]  : %p\n"</span>, &amp;board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]);
    printf(<span class="hljs-string">"but what is in board&#91;0] : %p\n"</span>, board&#91;<span class="hljs-number">0</span>]);

    printf(<span class="hljs-string">"value of board&#91;0]&#91;0] : %c\n"</span>, board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]);
    printf(<span class="hljs-string">"value of *board&#91;0]   : %c\n"</span>, *board&#91;<span class="hljs-number">0</span>]);
    printf(<span class="hljs-string">"value of **board     : %c\n"</span>, **board);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">下面例子用 for 循环进一步改进前一个例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    <span class="hljs-comment">/* List all elements of the array */</span>
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span>; i++)
        printf(<span class="hljs-string">" board: %c\n"</span>, *(*board + i));
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">程序的输出如下：</p>



<p class="wp-block-paragraph">可以看到，使用表达式 <code>*(*board + i)</code> 可以得到一个数组元素的值。</p>



<p class="wp-block-paragraph">括号中的表达式 <code>*board + i</code> 会得到数组中偏移量为 i 的元素的地址。</p>



<p class="wp-block-paragraph"><code>board</code> 其实是 <code>char**</code> 类型的地址值，取消对 <code>board</code> 的引用，也就是 <code>*board</code>，也就是 <code>char*</code>，也就是它还是一个指针，然后指针 <code>+n</code> 也就是获取后面的元素。比如 <code>*board + 2</code> 获取第三个元素的地址。</p>



<p class="wp-block-paragraph">如果去掉括号，也就是：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">printf(<span class="hljs-string">"board:%c\n"</span>, **board + i);</code></span></pre>


<p class="wp-block-paragraph">则会输出下面：</p>



<p class="wp-block-paragraph">虽然好像是一模一样，但是如果修改为如下：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'9'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'7'</span>},
        {<span class="hljs-string">'6'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'4'</span>},
        {<span class="hljs-string">'3'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'1'</span>}
    };

    <span class="hljs-comment">/* List all elements of the array */</span>
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span>; i++)
        printf(<span class="hljs-string">" board: %c\n"</span>, **board + i);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">以上代码 <code>**board</code> 就是 <code>'9'</code>，然后 <code>'9' + 1</code> 就是 ascii 表中的下一个字符。</p>



<p class="wp-block-paragraph">如果明白的同学可以回去复习一下 char 类型。</p>



<p class="wp-block-paragraph">另外，如果表达式写成 <code>**(board + 1)</code> 这时候可能会导致错误。</p>



<p class="wp-block-paragraph">因为 <code>**(board + 0)</code> 指向 <code>board[0][0]</code>，而 <code>**(board + 1)</code> 指向 <code>board[1][0]</code>，<code>**(board + 2)</code> 指向 <code>board[2][0]</code>。</p>



<p class="wp-block-paragraph">为什么 <code>board + 1</code> 是 <code>board[1][0]</code> 而不是 <code>board[0][1]</code>？</p>



<p class="wp-block-paragraph">原因是 <code>board</code> 是 <code>char**</code> 类型，它 <code>+1</code> 也就是一维数组 <code>char[]</code> 移动 1，而不是一个元素 <code>char</code> 移动 1。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'9'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'7'</span>},
        {<span class="hljs-string">'6'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'4'</span>},
        {<span class="hljs-string">'3'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'1'</span>}
    };

    <span class="hljs-comment">/* List all elements of the array */</span>
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span>; i++)
        printf(<span class="hljs-string">" board: %c\n"</span>, **(board + i));
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">三种写法记住：</p>



<ul class="wp-block-list">
<li><code>*(*board + i)</code>：<code>*board</code> 本身就是一个 <code>char</code> 类型指针 <code>char*</code>，<code>char</code> 类型刚好占一个字节，<code>+i</code> 就自动跳到下一个元素</li>



<li><code>**board + i</code>：这个很好理解，<code>**board</code> 就是 <code>'9'</code>，<code>+1</code> 就跳到下一个 ascii 码了</li>



<li><code>**(board + i)</code>：<code>board</code> 本身是一个 <code>char**</code> 类型，也就是一维数组的指针，<code>+i</code> 就是跳过一个一维数组的跨度</li>
</ul>



<p class="wp-block-paragraph"><code>*board</code> 就是一个 <code>char*</code> 类型：</p>


<pre class="wp-block-code"><span><code class="hljs">char *p = *board;
*(p+1)
*(p+2)
*(p+3)
*(p+4)</code></span></pre>


<p class="wp-block-paragraph">这里就回到前面章节的内容了。</p>



<p class="wp-block-paragraph">前面用指针的表示法用数组名称引用二维数组，现在学习使用声明为指针的变量。</p>



<p class="wp-block-paragraph">下面的例子使用多维数组和指针：</p>



<p class="wp-block-paragraph">指针+一个数组，看这个指针是什么类型，如果是 char 就是跳过一个字节，如果是 long 就是四个字节。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    char *pboard = *board;             <span class="hljs-comment">/* A pointer to char */</span>

    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span>; i++)
        printf(<span class="hljs-string">" board: %c\n"</span>, *(pboard + i));  <span class="hljs-comment">//pboard 是一个char*指针 +1 就是跳过一个字节</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">这里使用数组中第一个元素的地址初始化指针，然后用一般的指针算术运算遍历整个数组。</p>



<p class="wp-block-paragraph"><code>board</code> 是 <code>char**</code> 类型，也就是指针的指针，是子数组 <code>board[0]</code> 的地址，<code>board[0]</code> 本身是一个一维数组。</p>



<p class="wp-block-paragraph">所以当我们 <code>board + i</code> 就是跳过一个一维数组的字节长度。</p>



<p class="wp-block-paragraph"><code>**(board + i)</code> 而不是第一个元素的地址。它必须是 <code>char*</code> 类型。</p>



<p class="wp-block-paragraph">也可以用以下方式来初始化 <code>pboard</code>：</p>


<pre class="wp-block-code"><span><code class="hljs">char *pboard = &amp;board&#91;0]&#91;0];</code></span></pre>


<p class="wp-block-paragraph">如果下面的写法则会报错，编译器可能会警告：</p>


<pre class="wp-block-code"><span><code class="hljs">pboard = board;</code></span></pre>


<p class="wp-block-paragraph">因为 <code>board</code> 是两个 <code>*</code>，而 <code>pboard</code> 是一个 <code>*</code>。</p>



<p class="wp-block-paragraph">可以使用下面几种方式访问二维数组的元素：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
    {<span class="hljs-string">'9'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'7'</span>},
    {<span class="hljs-string">'6'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'4'</span>},
    {<span class="hljs-string">'3'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'1'</span>}
};</code></span></pre>


<p class="wp-block-paragraph"><code>board[0]</code> 就是 <code>{'9','8','7'}</code>，是一个一维数组。</p>



<p class="wp-block-paragraph">假如 <code>char b3[] = {'9','8','7'}</code>，这时候 <code>board[0]</code> 就是 <code>b3</code>。</p>



<p class="wp-block-paragraph">以前 <code>char* p = b3;</code>，这里 <code>p</code> 就是 <code>board[0]</code>。</p>



<p class="wp-block-paragraph">如果要访问 <code>'8'</code>，<code>*(b3+1)</code>。</p>



<p class="wp-block-paragraph">所以 <code>board[0]</code> 就是二维数组里面的第一个一维数组的第一个元素的地址。</p>



<p class="wp-block-paragraph">同样 <code>board[1]</code> 就是第二个一维数组的第一个元素的地址了，也就 <code>{'6','5','4'}</code> 的 6 的地址。</p>



<p class="wp-block-paragraph">然后 <code>board[2]</code> 就是 3 的地址。</p>



<h3 class="wp-block-heading">动态内存分配</h3>



<p class="wp-block-paragraph">指针是一个非常灵活且强大的编程工具，有非常广泛的应用。</p>



<p class="wp-block-paragraph">大多数 C 程序都在某种程度上使用了指针。</p>



<p class="wp-block-paragraph">C 语言还有一个功能：动态内存分配，它依赖指针的概念，为在代码中使用指针提供了很强的刺激机制，它允许在执行程序时动态分配内存。</p>



<p class="wp-block-paragraph">只有使用指针，才能动态分配内存。</p>



<p class="wp-block-paragraph">大多数产品程序都使用了动态内存分配。例如电子邮件客户端在检索电子邮件时，事先并不知道有多少封电子邮件，也不知道每封邮件需要多少内存。电子邮件客户端在运行期间会得到足够的内存，来管理电子邮件的数量和大小。</p>



<p class="wp-block-paragraph">前面我们见过一个程序计算一组学生的平均分，当时它处理 10 个学生。</p>



<p class="wp-block-paragraph">理想情况下，该程序应能处理任意多个学生，但事先不知道要处理多少个学生，所使用的内存也不会比指定的学生分数所需的内存多。</p>



<p class="wp-block-paragraph">动态内存分配就可以实现这个功能，可以在执行时创建足够以容纳所需数据量的数组。</p>



<p class="wp-block-paragraph">在程序的执行期间分配内存时，内存区域中的这个空间称为堆（heap）。</p>



<p class="wp-block-paragraph">还有另一个内存区域，称为栈（stack），其中的内存分配给函数的参数和本地变量。在执行完该函数后，存储参数和本地变量的内存空间就会释放。堆中的内存是由程序员控制的。</p>



<p class="wp-block-paragraph">如本章后面所述，在分配堆上的内存时，由程序员跟踪所分配的内存何时不再需要，并释放这些空间，以便可以重用它们。</p>



<p class="wp-block-paragraph">前面第五章，可以利用变量指定数组的维度，在运行期间创建数组。</p>



<p class="wp-block-paragraph">也可以在运行期间明确分配内存。</p>



<p class="wp-block-paragraph">在运行期间分配内存的最简单的标准函数是 <code>malloc</code> 函数。</p>



<p class="wp-block-paragraph">使用这个函数需要在程序中包含头文件 <code>stdlib.h</code>。<code>malloc</code> 函数需要指定要分配的内存字节数作为参数。</p>



<p class="wp-block-paragraph">这个函数返回所分配内存的第一个字节的地址。所以需要使用指针来存储该函数的返回值。</p>



<p class="wp-block-paragraph">例子：</p>


<pre class="wp-block-code"><span><code class="hljs">int *pNumber = (int*)malloc(100);</code></span></pre>


<p class="wp-block-paragraph">这条语句请求 100 个字节的内存，并把这个内存块的地址赋予 <code>pNumber</code>。只要不修改它，任何时间使用这个变量 <code>pNumber</code> 它都会指向所分配的 100 个字节的第一个 int 的位置。这个内存块能够保持 25 个 int 值，每个 int 占 4 个字节。</p>



<p class="wp-block-paragraph">上面语句 100 是假定 int 占 4 个字节。但是我们最好这样写，因为不是所有的系统 int 都是 4 个字节。</p>


<pre class="wp-block-code"><span><code class="hljs">int *pNumber = (int*)malloc(25 * sizeof(int));</code></span></pre>


<p class="wp-block-paragraph">这样就保证可以存储 25 个 int 值了。</p>



<p class="wp-block-paragraph">这里需要 <code>int*</code> 指针，所以需要强制类型转换。因为 <code>malloc</code> 可以为任何类型的数据分配内存。</p>



<p class="wp-block-paragraph">这个函数本身不知道是什么类型，所以它返回一个 <code>void</code> 类型的指针，写成 <code>void*</code>。</p>



<p class="wp-block-paragraph">类型 <code>void*</code> 可以指向任何类型的数据。然而不能去掉对 <code>void</code> 指针的引用，因为它指向未具体说明的对象。</p>



<p class="wp-block-paragraph">可以请求任意数量的字节，字节数受制于计算机未用的内存以及 <code>malloc</code> 的运用场合。如果因某种原因而不能分配请求的内存，<code>malloc</code> 会返回一个 <code>NULL</code> 指针。这个指针等于 0。</p>



<p class="wp-block-paragraph">所以我们最好先检查是否已分配，再使用它。</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">int *pNumber = (int*)malloc(<span class="hljs-number">25</span> * sizeof(int));
<span class="hljs-keyword">if</span>(!pNumber)
{
    <span class="hljs-comment">//其它操作</span>
}</code></span></pre>


<p class="wp-block-paragraph">在动态分配内存时，应该总是在不需要该内存时释放它们。堆上分配的内存会在程序结束时自动释放，但最好在使用完这些内存后立即释放，甚至是在退出程序之前，也应立即释放。在比较复杂的情况下，很容易出现内存泄漏。当动态分配了一些内存时，没有保留对它们的引用，就会出现内存泄漏，此时无法释放内存。这常常发生在循环内部，由于没有释放不再需要的内存，程序会在每次循环迭代时使用越来越多的内存，最终占用所有内存。</p>



<p class="wp-block-paragraph">当然，要释放动态分配的内存，必须能访问引用内存块的地址。要释放动态分配的内存，而该内存的地址存储在 <code>pNumber</code> 指针中，可以使用下面的语句：</p>


<pre class="wp-block-code"><span><code class="hljs language-php">free(pNumber);
pNumber = <span class="hljs-keyword">NULL</span>;</code></span></pre>


<p class="wp-block-paragraph"><code>free()</code> 函数的形参是 <code>void*</code> 类型，所有指针类型都可以自动转换为这个类型，所以可以把任意类型的指针作为参数传送给这个函数。只要 <code>pNumber</code> 包含分配内存时返回的地址，就会释放所分配的整个内存块，以备以后使用。在指针指向的内存释放后，应总是把指针设置为 <code>NULL</code>。</p>



<p class="wp-block-paragraph"><strong>警告</strong>：在释放指针指向的堆内存时，必须确保它不被另一个地址覆盖。</p>



<p class="wp-block-paragraph">如果给 <code>free()</code> 函数传送一个空指针，该函数就什么也不做。应避免两次释放相同的内存区域，因为在这种情况下，<code>free()</code> 函数的操作是不确定的，因此也就无法预料。如果多个指针变量引用已分配的内存，就有可能两次释放相同的内存，所以要特别小心。</p>



<h4 class="wp-block-heading">试试看：动态内存分配</h4>



<p class="wp-block-paragraph">下面使用指针来计算质数，将动态内存分配的概念应用于实践。质数是只能被 1 和这个数本身整除的整数。</p>



<p class="wp-block-paragraph">查找质数的过程非常简单。首先，由观察得知，2、3 和 5 是前三个质数，因为它们不能被除了 1 以外更小的数整除。其他质数必定都是奇数（否则它们可以被 2 整除），所以要找出下一个质数，可以从最后一个质数开始，给它加 2。检查完这个数后，再给它加 2，继续检查。</p>



<p class="wp-block-paragraph">检查一个数是否为质数，而不只是奇数，可以用这个数除以比它小的所有奇数。其实不需要这么麻烦。如果一个数不是质数，它必定能被比它小的质数整除。我们要按顺序查找质数，所以可以把已经找到的质数作为除数，确定所检查的数是否为质数。</p>



<p class="wp-block-paragraph">这个程序将使用指针和动态内存分配：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>
<span class="hljs-comment">#include &lt;stdbool.h&gt;</span>

int main(void)
{
    unsigned long *primes = <span class="hljs-keyword">NULL</span>;       <span class="hljs-comment">/* Pointer to primes storage area    */</span>
    unsigned long trial = <span class="hljs-number">0</span>;            <span class="hljs-comment">/* Integer to be tested              */</span>

    bool found = <span class="hljs-keyword">false</span>;                 <span class="hljs-comment">/* Indicates when we find a prime    */</span>
    size_t total = <span class="hljs-number">0</span>;                   <span class="hljs-comment">/* Number of primes required         */</span>
    size_t count = <span class="hljs-number">0</span>;                   <span class="hljs-comment">/* Number of primes found            */</span>

    printf(<span class="hljs-string">"How many primes would you like - you'll get at least 4?  "</span>);
    scanf(<span class="hljs-string">"%u"</span>, &amp;total);                <span class="hljs-comment">/* Total is how many we need to find */</span>
    total = total &lt; <span class="hljs-number">4</span>U ? <span class="hljs-number">4</span>U : total;    <span class="hljs-comment">/* Make sure it is at least 4        */</span>

    <span class="hljs-comment">/* Allocate sufficient memory to store the number of primes required */</span>
    primes = (unsigned long *)malloc(total * sizeof(unsigned long));
    <span class="hljs-keyword">if</span>(primes == <span class="hljs-keyword">NULL</span>)
    {
        printf(<span class="hljs-string">"\nNot enough memory. Hasta la Vista, baby.\n"</span>);
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }

    <span class="hljs-comment">/* We know the first three primes     */</span>
    <span class="hljs-comment">/* so let's give the program a start. */</span>
    *primes = <span class="hljs-number">2</span>UL;                      <span class="hljs-comment">/* First prime                   */</span>
    *(primes+<span class="hljs-number">1</span>) = <span class="hljs-number">3</span>UL;                  <span class="hljs-comment">/* Second prime                  */</span>
    *(primes+<span class="hljs-number">2</span>) = <span class="hljs-number">5</span>UL;                  <span class="hljs-comment">/* Third prime                   */</span>
    count = <span class="hljs-number">3</span>U;                         <span class="hljs-comment">/* Number of primes stored       */</span>
    trial = <span class="hljs-number">5</span>U;                         <span class="hljs-comment">/* Set to the last prime we have */</span>

    <span class="hljs-comment">/* Find all the primes required */</span>
    <span class="hljs-keyword">while</span>(count &lt; total)
    {
        trial += <span class="hljs-number">2</span>UL;                     <span class="hljs-comment">/* Next value for checking       */</span>

        <span class="hljs-comment">/* Try dividing by each of the primes we have       */</span>
        <span class="hljs-comment">/* If any divide exactly - the number is not prime  */</span>
        <span class="hljs-keyword">for</span>(size_t i = <span class="hljs-number">0</span>; i &lt; count; i++)
            <span class="hljs-keyword">if</span>(!(found = (trial % *(primes+i))))
                <span class="hljs-keyword">break</span>;                        <span class="hljs-comment">/* Exit if no remainder          */</span>

        <span class="hljs-keyword">if</span>(found)                        <span class="hljs-comment">/* we got one - if found is true */</span>
            *(primes+count++) = trial;     <span class="hljs-comment">/* Store it and increment count  */</span>
    }

    <span class="hljs-comment">/* Display primes 5-up */</span>
    <span class="hljs-keyword">for</span>(size_t i = <span class="hljs-number">0</span>; i &lt; total; i++)
    {
        <span class="hljs-keyword">if</span>(!(i % <span class="hljs-number">5</span>U))
            printf(<span class="hljs-string">"\n"</span>);                   <span class="hljs-comment">/* Newline after every 5         */</span>
        printf(<span class="hljs-string">"%12lu"</span>, *(primes+i));
    }
    printf(<span class="hljs-string">"\n"</span>);                       <span class="hljs-comment">/* Newline for any stragglers    */</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在 <code>&lt;stdlib.h&gt;</code> 头文件中声明的 <code>calloc()</code> 函数与 <code>malloc()</code> 函数相比有两个优点。</p>



<p class="wp-block-paragraph">第一，它把内存分配为给定大小的数组。</p>



<p class="wp-block-paragraph">第二，它初始化了所分配的内存，所有的位都是 0。</p>



<p class="wp-block-paragraph">函数需要两个参数：数组的元素个数和数组元素占用的字节数，这两个参数的类型都是 <code>size_t</code>。</p>



<p class="wp-block-paragraph">该函数也不知道数组元素的类型，所以所分配区域的地址返回为 <code>void*</code> 类型。</p>



<p class="wp-block-paragraph">下面的语句使用 <code>calloc()</code> 为包含 75 个 int 元素的数组分配内存：</p>


<pre class="wp-block-code"><span><code class="hljs">int *pNumber = (int*)calloc(75, sizeof(int));</code></span></pre>


<p class="wp-block-paragraph">如果不能分配所请求的内存，返回值是 <code>NULL</code>，也可以检查分配内存的结果，这非常类似于 <code>malloc()</code>，但 <code>calloc()</code> 分配的内存区域都会初始化为 0。当然，可以让编译器执行类型转换：</p>


<pre class="wp-block-code"><span><code class="hljs">int *pNumber = calloc(75, sizeof(int));</code></span></pre>


<p class="wp-block-paragraph">后面的代码省略了这个类型转换。</p>



<p class="wp-block-paragraph">将上面的程序改为使用 <code>calloc()</code> 代替 <code>malloc()</code> 来分配需要的内存，只需要修改一条语句。其他代码不变：</p>


<pre class="wp-block-code"><span><code class="hljs language-php">primes = calloc((size_t)total, sizeof(unsigned long));
<span class="hljs-keyword">if</span> (primes == <span class="hljs-keyword">NULL</span>)
{
    printf(<span class="hljs-string">"Not enough memory. It's the end I'm afraid.\n"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
}</code></span></pre>


<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e6%95%b0%e7%bb%84%e4%b8%8e%e6%8c%87%e9%92%88/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>指针</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e6%8c%87%e9%92%88/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e6%8c%87%e9%92%88/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:52:51 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13546</guid>

					<description><![CDATA[指针基础概念 指针本质上也是一个变量，它也有类型。 我们以前 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">指针基础概念</h3>



<p class="wp-block-paragraph">指针本质上也是一个变量，它也有类型。</p>



<p class="wp-block-paragraph">我们以前讲的变量。</p>


<pre class="wp-block-code"><span><code class="hljs">int age = 12;</code></span></pre>


<p class="wp-block-paragraph">这个变量存储一个整数，这个变量的名字叫 age。变量其实是内存中的一块小区域。通常是占 n 个字节。</p>



<p class="wp-block-paragraph">一个字节是 8 个位，8 bit。一个 bit 存储 0 或 1。</p>



<p class="wp-block-paragraph">指针是 C 语言中最强大的工具之一，它也是最容易令人困惑的主题，所以一定要在开始时正确理解其概念。</p>



<p class="wp-block-paragraph">在前面讨论内存时，谈到计算机如何为声明的变量分配一块内存。</p>



<p class="wp-block-paragraph">在程序中使用变量名引用这块内存，但是一旦编译执行程序，计算机就使用内存位置的地址来引用它。</p>



<p class="wp-block-paragraph">例如</p>


<pre class="wp-block-code"><span><code class="hljs">int number = 5;</code></span></pre>


<p class="wp-block-paragraph">这条语句会分配一块内存来存储一个整数，使用 number 名称可以访问这个整数。值 5 就存储在这块区域中。</p>



<p class="wp-block-paragraph">计算机用一个地址引用这块区域。存储这个数据的地址取决于所使用的计算机、操作系统和编译器。</p>



<p class="wp-block-paragraph">在源代码中，这个变量名是固定不变的，但是地址在不同的系统上是不同的。</p>



<p class="wp-block-paragraph">可以存储地址的变量称为指针。存储在指针中的地址通常是另一个变量。</p>



<p class="wp-block-paragraph">指针 pnumber 中的地址是 number 第一个字节的地址。</p>



<p class="wp-block-paragraph">变量 number 是一个值为 99 的整数变量。存储在 pnumber 中地址是 number 第一个字节的地址。</p>



<p class="wp-block-paragraph">知道变量 pnumber 是一个指针是不够的，更重要的是，编译器必须知道它所指的变量类型。没有这个信息，根本不可能知道它占用多少内存，或者如何处理它所指向的内存的内容。</p>



<p class="wp-block-paragraph">char 类型占一个字节，long 类型占四个字节，因此每个指针都和某个变量类型相关联，也就是用于指向该类型的变量。</p>



<p class="wp-block-paragraph">所以，如果指针的类型是 int，就是指向 int 类型的变量。</p>



<p class="wp-block-paragraph">float 类型的指针，就是指向 float 类型的变量。</p>



<p class="wp-block-paragraph">一般给类型的指针写成 type*</p>



<p class="wp-block-paragraph">类型名 void 表示没有指定类型，所以 void* 类型的指针可以包含任意类型的数据项地址。</p>



<p class="wp-block-paragraph">以下语句可以声明一个指向 int 类型变量的指针：</p>


<pre class="wp-block-code"><span><code class="hljs">int *pnumber;</code></span></pre>


<p class="wp-block-paragraph">pnumber 变量的类型是 int *，它可以存储任意 int 类型变量的地址。</p>



<p class="wp-block-paragraph">该语句还可以写作：</p>


<pre class="wp-block-code"><span><code class="hljs">int* pnumber;</code></span></pre>


<p class="wp-block-paragraph">这条语句创建了 pnumber 变量，但是没有初始化它，未初始化的指针是非常危险的。</p>



<p class="wp-block-paragraph">比未初始化的普通变量要危险很多，所以应总是在声明指针时对它进行初始化。</p>



<p class="wp-block-paragraph">如果不指向变量，可以设为 NULL。</p>


<pre class="wp-block-code"><span><code class="hljs language-php">int *pnumber = <span class="hljs-keyword">NULL</span>;</code></span></pre>


<p class="wp-block-paragraph">NULL 是在标准库中定义的一个常量，对于指针它表示 0。</p>



<p class="wp-block-paragraph">NULL 是一个不指向任何内存位置的值。</p>



<p class="wp-block-paragraph">这表示使用不指向任何对象的指针，不会意外覆盖内存。</p>



<p class="wp-block-paragraph">NULL 在头文件 stddef.h、stdlib.h、stdio.h、string.h、time.h、wchar.h 和 locale.h 中定义。</p>



<p class="wp-block-paragraph">只要编译器不能识别 NULL，就应在源文件中包含 stddef.h 头文件。</p>



<p class="wp-block-paragraph">如果用已声明的变量地址初始化 pointer 变量，可以使用寻址运算符 &amp;。</p>



<p class="wp-block-paragraph">例如：</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">int number = 99;
int *pnumber = <span class="hljs-symbol">&amp;number;</span></code></span></pre>


<p class="wp-block-paragraph">注意 number 的声明必须在 pnumber 之前。否则代码不能编译。编译器需要先分配好空间，才能使用 number 的地址初始化 pnumber 变量。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main(void)
{
    int number = <span class="hljs-number">99</span>;
    <span class="hljs-comment">//int *pNumber;//不安全</span>
    <span class="hljs-comment">//int *pNumber = NULL;//可以指向一个NULL</span>
    int *pNumber = &amp;number;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">指针的声明没有什么特别之处。可以用相同的语句声明一般的变量和指针。</p>



<p class="wp-block-paragraph">例如：</p>


<pre class="wp-block-code"><span><code class="hljs">double value, *pval, fnum;</code></span></pre>


<p class="wp-block-paragraph">要注意如下问题，很多人很容易犯错。</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">#include <span class="hljs-tag">&lt;<span class="hljs-name">stdio.h</span>&gt;</span>
#include <span class="hljs-tag">&lt;<span class="hljs-name">stdlib.h</span>&gt;</span>

int main(void)
{
    int number, *pNumber;
    pNumber = <span class="hljs-symbol">&amp;number;</span>
    int age = *pNumber;
    return 0;
}</code></span></pre>


<h3 class="wp-block-heading">间接运算符与指针访问</h3>



<p class="wp-block-paragraph">使用间接运算符 * 可以访问指针所指的变量值。</p>



<p class="wp-block-paragraph">这个运算符也称为取消引用运算符，因为它用于取消对指针的引用。</p>



<p class="wp-block-paragraph">假设声明以下的变量：</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">int number = 15;
int *pointer = <span class="hljs-symbol">&amp;number;</span>
int result = 0;</code></span></pre>


<p class="wp-block-paragraph">pointer 变量含有 number 变量的地址，所以可以在表达式中使用它计算 result 的新值。如下：</p>


<pre class="wp-block-code"><span><code class="hljs">result = *pointer + 5;</code></span></pre>


<p class="wp-block-paragraph">表达式 *pointer 等于存储在 pointer 中的地址的值。这是存储在 number 中的值 15。</p>



<p class="wp-block-paragraph">所以 result 是 15+5 等于 20。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main(void)
{
    int number = <span class="hljs-number">15</span>;
    int *pointer = &amp;number;
    int result = <span class="hljs-number">0</span>;
    <span class="hljs-comment">//result = number +5;</span>
    result = *pointer + <span class="hljs-number">5</span>;
    printf(<span class="hljs-string">"%d"</span>, result);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">以下例子将声明一个变量和一个指针，然后输出它们的地址和它们所含的值。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int number = <span class="hljs-number">0</span>;                 <span class="hljs-comment">/* A variable of type int initialized to  0 */</span>
    int *pointer = <span class="hljs-keyword">NULL</span>;            <span class="hljs-comment">/* A pointer that can point to type int     */</span>
    number = <span class="hljs-number">10</span>;
    printf(<span class="hljs-string">"\nnumber的地址: %p"</span>, &amp;number);            <span class="hljs-comment">/* Output the address */</span>
    printf(<span class="hljs-string">"\nnumber的值: %d\n\n"</span>, number);           <span class="hljs-comment">/* Output the value   */</span>

    pointer = &amp;number;              <span class="hljs-comment">/* Store the address of number in pointer   */</span>

    printf(<span class="hljs-string">"pointer的地址: %p"</span>, &amp;pointer);            <span class="hljs-comment">/* Output the address */</span>
    printf(<span class="hljs-string">"\npointer的大小: %d bytes"</span>, sizeof(pointer)); <span class="hljs-comment">/* Output the size   */</span>
    printf(<span class="hljs-string">"\npointer的值: %p"</span>, pointer);  <span class="hljs-comment">/* Output the value (an address) */</span>
    printf(<span class="hljs-string">"\n*pointer指向的值: %d\n"</span>, *pointer);       <span class="hljs-comment">/* Value at the address */</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<ul class="wp-block-list">
<li>同时也是乘法符号，但是编译器不会混淆，因为出现的位置是不一样的，而且编译器是可以理解的。</li>
</ul>



<p class="wp-block-paragraph">可以通过指针 pnumber 访问 number 的内容，所以可以在算术语句中使用取消引用的指针。</p>



<p class="wp-block-paragraph">例如：</p>


<pre class="wp-block-code"><span><code class="hljs">*pnumber += 25;</code></span></pre>


<p class="wp-block-paragraph">上述语句将变量 pnumber 所指向的地址中的值增加 25。星号 * 表示访问 pnumber 变量所指向的内容。这里它是变量 number 的内容。</p>



<p class="wp-block-paragraph">变量 pnumber 能存储任何 int 变量的地址。这表示可以用下面的语句改变 pnumber 的变量。</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">int value = 999;
pnumber = <span class="hljs-symbol">&amp;value;</span></code></span></pre>


<p class="wp-block-paragraph">重复之前的语句：</p>


<pre class="wp-block-code"><span><code class="hljs">*pnumber += 25;</code></span></pre>


<p class="wp-block-paragraph">该语句操作的新的变量 value。value 的新值是 1024。这表示指针可以包含同一类型的任意变量的地址。</p>



<p class="wp-block-paragraph">所以，可以使用一个指针变量可以改变其它任何变量的值，只要它们的类型和指针相同。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int value = <span class="hljs-number">900</span>;
    int *pnumber = <span class="hljs-keyword">NULL</span>;
    int number = <span class="hljs-number">90</span>;
    pnumber = &amp;number;
    printf(<span class="hljs-string">"%d\n"</span>, *pnumber); <span class="hljs-comment">//90</span>
    *pnumber += <span class="hljs-number">10</span>;
    printf(<span class="hljs-string">"%d\n"</span>, number); <span class="hljs-comment">//100</span>

    pnumber = &amp;value;
    *pnumber += <span class="hljs-number">10</span>;
    printf(<span class="hljs-string">"%d\n"</span>, value); <span class="hljs-comment">//110? 910?</span>
    printf(<span class="hljs-string">"%d\n"</span>, *pnumber); <span class="hljs-comment">//910</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">自己动手做一下下面的题目：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long num1 = <span class="hljs-number">0</span>;
    long num2 = <span class="hljs-number">0</span>;
    long *pnum = <span class="hljs-keyword">NULL</span>;

    pnum = &amp;num1; <span class="hljs-comment">//pnum的值是num1的地址</span>
    *pnum = <span class="hljs-number">2</span>;   <span class="hljs-comment">//num1：2</span>
    ++num2;   <span class="hljs-comment">//num2：1</span>
    num2 += *pnum;   <span class="hljs-comment">//num2：3</span>

    pnum = &amp;num2;  <span class="hljs-comment">//pnum的值是num2的地址</span>
    ++*pnum;   <span class="hljs-comment">//num2：4                                    /* Increment num2 indirectly */</span>

    printf(<span class="hljs-string">"\nnum1 = %ld  num2 = %ld  *pnum = %ld  *pnum + num2 = %ld\n"</span>,
           num1, num2, *pnum, *pnum + num2); <span class="hljs-comment">//2 4 4 8</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h3 class="wp-block-heading">指针与输入</h3>



<p class="wp-block-paragraph">下面例子演示指针如何用于键盘输入。</p>



<p class="wp-block-paragraph">前面使用 scanf() 输入数值。使用 &amp; 运算符获取接收输入的变量的地址，并用作传给函数的参数。有了一个含有地址的指针后，只需使用这个指针的名字作为参数。</p>



<p class="wp-block-paragraph">下面是以前的写法：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int value = <span class="hljs-number">0</span>;
    scanf(<span class="hljs-string">"%d"</span>, &amp;value);
    printf(<span class="hljs-string">"\n%d"</span>, value);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">看下面例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int value = <span class="hljs-number">0</span>;
    int *pvalue = <span class="hljs-keyword">NULL</span>;

    pvalue = &amp;value;                    <span class="hljs-comment">/* Set pointer to refer to value  */</span>

    printf(<span class="hljs-string">"Input an integer: "</span>);
    scanf(<span class="hljs-string">" %d"</span>, pvalue);              <span class="hljs-comment">/* Read into value via the pointer */</span>

    printf(<span class="hljs-string">"\nYou entered %d\n"</span>, value);      <span class="hljs-comment">/* Output the value entered */</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">pvalue 和 &amp;value 是相同的，用任何一个作为 scanf 的第二个参数都是可以的，它们都表示 value 的地址。</p>



<p class="wp-block-paragraph">我们的代码：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int value = <span class="hljs-number">0</span>;
    int *pValue = <span class="hljs-keyword">NULL</span>;
    pValue = &amp;value;
    scanf(<span class="hljs-string">"%d"</span>, pValue);
    printf(<span class="hljs-string">"\n%d"</span>, value);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">假定创建如下指针：</p>


<pre class="wp-block-code"><span><code class="hljs language-php">int *pvalue = <span class="hljs-keyword">NULL</span>;</code></span></pre>


<p class="wp-block-paragraph">如前面说的，NULL 是 C 语言中是特殊的常量。它相当于数字 0 的指针。</p>



<p class="wp-block-paragraph">NULL 常常定义为 ((void*)0)。</p>



<p class="wp-block-paragraph">给指针赋予 0 时，就等于将它设为 NULL。</p>



<p class="wp-block-paragraph">所以编写如下语句：</p>


<pre class="wp-block-code"><span><code class="hljs">int *pvalue = 0;</code></span></pre>


<p class="wp-block-paragraph">因为 NULL 等于 0，如果要测试指针 pvalue 是否是 NULL，可以编写如下语句：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">if</span> (!pvalue)
{
    <span class="hljs-comment">//指针为空</span>
}</code></span></pre>


<p class="wp-block-paragraph">当然也可以这样：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-keyword">if</span> (pvalue == <span class="hljs-keyword">NULL</span>)
{
    <span class="hljs-comment">//指针为空</span>
}</code></span></pre>


<p class="wp-block-paragraph">我们的代码：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int *pvalue = <span class="hljs-keyword">NULL</span>;
    int *pv = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (!pvalue)
    {
        <span class="hljs-comment">//空指针</span>
    }
    <span class="hljs-keyword">if</span> (pvalue == <span class="hljs-keyword">NULL</span>)
    {
        <span class="hljs-comment">//空指针</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h3 class="wp-block-heading">常量指针</h3>



<p class="wp-block-paragraph">声明指针时，可以使用 const 关键字指定，该指针指向的值不能改变。</p>



<p class="wp-block-paragraph">看下面例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">long value = 9999L;
const long *pvalue = <span class="hljs-symbol">&amp;value;</span></code></span></pre>


<p class="wp-block-paragraph">这时候 pvalue 所指向的值声明为 const，编译器就会检查语句有没有试图修改 pvalue 指向的值。所以下面语句是错误的：</p>


<pre class="wp-block-code"><span><code class="hljs">*pvalue = 8888L;</code></span></pre>


<p class="wp-block-paragraph">也就是不能通过 pvalue 的指针来修改它所指向的值。</p>



<p class="wp-block-paragraph">但是可以通过 value 来修改。</p>



<p class="wp-block-paragraph">下面语句是可以的：</p>


<pre class="wp-block-code"><span><code class="hljs">value = 7777L;</code></span></pre>


<p class="wp-block-paragraph">虽然不能通过 pvalue 来修改它所指向的值。</p>



<p class="wp-block-paragraph">但是 pvalue 本身保存的值（地址）是可以改变的。</p>



<p class="wp-block-paragraph">比如下面：</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">long number = 8888L;
pvalue = <span class="hljs-symbol">&amp;number;</span></code></span></pre>


<p class="wp-block-paragraph">这样 pvalue 的值又被改为了 number 的地址。仍然不能使用指针改变它指向的值。也就是如果希望：</p>


<pre class="wp-block-code"><span><code class="hljs">*pvalue = 8888L;</code></span></pre>


<p class="wp-block-paragraph">这样，那也是不行的。</p>



<p class="wp-block-paragraph">一句话总结：</p>



<p class="wp-block-paragraph">指向常量的指针，可以改变指针中的地址，但是不能改变地址指向的值。</p>



<p class="wp-block-paragraph">我们的代码：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long value = <span class="hljs-number">9999</span>L;
    value = <span class="hljs-number">123</span>L;
    <span class="hljs-keyword">const</span> long *pValue = &amp;value;
    *pValue = <span class="hljs-number">456</span>L; <span class="hljs-comment">//指针是const 不能通过它来修改指向的变量</span>
    printf(<span class="hljs-string">"%d"</span>, value);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">我们的例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long value = <span class="hljs-number">9999</span>L;
    value = <span class="hljs-number">123</span>L;
    <span class="hljs-keyword">const</span> long *pValue = &amp;value;
    <span class="hljs-comment">//*pValue = 456L;//指针是const 不能通过它来修改指向的变量</span>
    value = <span class="hljs-number">456</span>L;
    printf(<span class="hljs-string">"%d"</span>, value);

    long number = <span class="hljs-number">1000</span>L;
    pValue = &amp;number;
    <span class="hljs-comment">//*pValue = 456L;//虽然指针指向了number 但是也是不能通过它来修改</span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">当然，也可以使指针中存储的地址不能改变。</p>



<p class="wp-block-paragraph">此时，在指针声明中使用 const 关键字的方式，但是有点不同。</p>



<p class="wp-block-paragraph">下面语句可以使指针总是指向相同的对象：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">int count = <span class="hljs-number">43</span>;
int *<span class="hljs-keyword">const</span> pcount = &amp;count; <span class="hljs-comment">//定义一个常量指针</span></code></span></pre>


<p class="wp-block-paragraph">第二条语句声明并初始化了 pcount，指定该指针存储的地址不能改变。</p>



<p class="wp-block-paragraph">编译器会检查代码是否无意中把指针指向其他地方，所以下面语句会在编译时生成一条错误信息。</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">int item = 34;
pcount = <span class="hljs-symbol">&amp;item;</span> //错误 尝试改变指针存储的地址值</code></span></pre>


<p class="wp-block-paragraph">但是使用 pcount 仍可以改变 pcount 指向的值：</p>


<pre class="wp-block-code"><span><code class="hljs">*pcount = 235;</code></span></pre>


<p class="wp-block-paragraph">这条语句通过指针引用了存储在 count 中的值，并将其改为 235。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long value = <span class="hljs-number">9999</span>L;

    long * <span class="hljs-keyword">const</span> pValue = &amp;value;
    *pValue = <span class="hljs-number">100</span>L;
    printf(<span class="hljs-string">"%d"</span>, value);

    long number = <span class="hljs-number">12</span>L;
    pValue = &amp;number; <span class="hljs-comment">//出错 指针的值不能改变</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">当然还可以直接使用 count 来改变它的值。</p>



<p class="wp-block-paragraph">可以创建一个常量指针，它指向一个常量值。也就是结合上一节课的。</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">int item = <span class="hljs-number">25</span>;
<span class="hljs-keyword">const</span> int *<span class="hljs-keyword">const</span> pitem = &amp;item;</code></span></pre>


<p class="wp-block-paragraph">这时候 pitem 是一个指向常量的常量指针。所以所有的信息都固定不变。不能改变存储在 pitem 中的地址，也不能使用 pitem 改变它指向的内容。</p>



<p class="wp-block-paragraph">但仍可以直接修改 item 的值。</p>



<p class="wp-block-paragraph">如果希望所有的信息都固定不变，可以把 item 也指定为 const。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long value = <span class="hljs-number">9999</span>L;

    <span class="hljs-keyword">const</span> long * <span class="hljs-keyword">const</span> pValue = &amp;value;
    <span class="hljs-comment">//*pValue = 100L; //不能改变指针指向的变量的值</span>
    printf(<span class="hljs-string">"%d"</span>, value);

    long number = <span class="hljs-number">12</span>L;
    <span class="hljs-comment">//pValue = &amp;number; //出错 指针的值不能改变</span>

    printf(<span class="hljs-string">"\n%d"</span>, *pValue);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h3 class="wp-block-heading">指针命名规范</h3>



<p class="wp-block-paragraph">随着程序越来越大，就越难记住哪一个是一般变量，哪一个是指针，因此，最好使用 p 作为指针名的第一个字母。</p>



<p class="wp-block-paragraph">如果严格遵守这个命名方法，那就很容易记住了。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long value = <span class="hljs-number">9999</span>L;
    long * pValue = &amp;value;

    *pValue = <span class="hljs-number">100</span>L;
    printf(<span class="hljs-string">"%d"</span>, value);
    printf(<span class="hljs-string">"\n%d"</span>, *pValue);

    long number = <span class="hljs-number">111</span>L;
    pValue = &amp;number; <span class="hljs-comment">//看到p前缀的变量 就知道这是一个指针</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e6%8c%87%e9%92%88/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>字符串</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e5%ad%97%e7%ac%a6%e4%b8%b2-2/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e5%ad%97%e7%ac%a6%e4%b8%b2-2/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:43:55 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13540</guid>

					<description><![CDATA[字符串 字符串常量的例子非常常见。字符串常量是放在一对双引号 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">字符串</h3>



<p class="wp-block-paragraph">字符串常量的例子非常常见。字符串常量是放在一对双引号中的一串字符和符号。一对双引号之间的任何内容都会被编译器视为字符串，包括特殊字符和嵌入的空格。每次使用 printf 显示信息时，就将该信息定义成字符串常量了。以下是字符串的例子：</p>



<p class="wp-block-paragraph">第二个字符串中带有换行符。第三个字符串输出双引号和斜线。</p>



<p class="wp-block-paragraph">字符串的串就是一连串，所以字符串在内存中的存储是这样的：</p>



<p class="wp-block-paragraph">上图中每个字符串的末尾都添加了代码值 0 的特殊字符，这个字符称为空字符，写为 <code>\0</code>。C 中的字符串总是由 <code>\0</code> 字符结束。所以字符串的长度永远都比字符串中的字符数多 1。</p>



<p class="wp-block-paragraph">可以自己将 <code>\0</code> 字符添加到字符串的结尾，但是这样会使得字符串的末尾有两个 <code>\0</code> 字符。下面说明空字符 <code>\0</code> 是如何运作：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    printf(<span class="hljs-string">"The character \0 is used to terminate a string."</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">以上程序输出：</p>



<p class="wp-block-paragraph">这不是期望的结果，因为它仅仅显示了字符串的第一部分。这个程序显示了前两个字符串就结束输出。因为在字符串中有 <code>\0</code>，printf 函数遇到第一个空字符 <code>\0</code> 就会停止输出。即使末尾有另外一个 <code>\0</code> 也永远不会执行它。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    printf(<span class="hljs-string">"\\\\www.foxdevelop.com \\0\n\"Foxdevelop\""</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">C 语言对变量存储字符串的语法没有特殊规定，而且 C 根本就没有字符串变量，也没有处理字符串的特殊运算符。但这不成问题，因为标准库提供了许多函数来处理字符串。整数 int 这些类型 C 语言提供 <code>+ - *</code> 等运算符，但是字符串 C 语言没有提供类型也没有符号运算，不过标准库里面有人使用 C 语言写好了代码。比如假如希望 C 语言使用 <code>+ -</code>，其实可以使用其他方式去实现，不需要写到这门语言里面。</p>



<p class="wp-block-paragraph">之前说的 char 类型是用来存储字符的，字符串就是多个字符连起来，数组可以存储多个相同类型的数据。换个角度思考，就可以使用 char 类型的数组来保存字符串。这是字符串变量的最简单的方式：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">char</span> <span class="hljs-selector-tag">saying</span><span class="hljs-selector-attr">&#91;20]</span>;</code></span></pre>


<p class="wp-block-paragraph">这个变量可以存储一个至多包含 19 个字符的字符串，因为必须给终止字符提供一个数组元素，也就是需要一个 <code>\0</code>。当然也可以使用该数组存储 20 个字符，但这样就不是一个字符串了。</p>



<p class="wp-block-paragraph">也可以用以下的声明初始化前面的字符串变量：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char saying&#91;] = <span class="hljs-string">"this is a string."</span>;</code></span></pre>


<p class="wp-block-paragraph">这里没有明确定义数组的大小，编译器指定一个足以容纳这个字符串常量的数值。在这个例子中它是 18，其中 17 个元素用于存储字符串中的字符，再加上一个额外的终止字符 <code>\0</code>。当然可以指定数值，但要确保它一定正确。</p>



<p class="wp-block-paragraph">也可以用一个字符串初始化 char 类型数组的部分元素：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">char str&#91;<span class="hljs-number">40</span>] = <span class="hljs-string">"To be"</span>;</code></span></pre>


<p class="wp-block-paragraph">这里编译器会使用指定字符串的字符初始化 str[0] 到 str[4] 的前五个元素，而 str[5] 则是给 <code>\0</code>。数组的所有 40 个元素都会被分配空间，可以以任意方式使用。</p>



<p class="wp-block-paragraph">初始化一个 char 数组，将它声明为常量，是处理标准信息的好方法：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> char message&#91;] = <span class="hljs-string">"The end of the world is nigh."</span>;</code></span></pre>


<p class="wp-block-paragraph">将 message 声明为常量，它就不会在程序中被更改。只要试图更改它，编译器都会产生错误信息。当标准信息在程序中的许多地方使用时，这种定义方法特别有用，可以防止在程序的其他部分意外地修改这种常量。当然，如果必须改变这条信息，就不应将它指定为 const。</p>



<p class="wp-block-paragraph">要引用存储在数组中的字符串时，只需要使用数组名即可。例子：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">printf(<span class="hljs-string">"\n The message is：%s"</span>, message);</code></span></pre>


<p class="wp-block-paragraph">printf 会将第一个参数的 <code>%s</code> 的位置输出 message 数组中的连续的字符，直到遇到 <code>\0</code> 为止。这个例子将初始化两个字符串，然后确定每个字符串有多少个字符，不包含空字符：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str1&#91;] = <span class="hljs-string">"To be or not to be"</span>;
    char str2&#91;] = <span class="hljs-string">",that is the question"</span>;
    int count = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">while</span> (str1&#91;count] != <span class="hljs-string">'\0'</span>)
        count++;
    printf(<span class="hljs-string">"\n字符串 \"%s\" 的长度是 %d 个字符."</span>, str1, count);

    count = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">while</span> (str2&#91;count] != <span class="hljs-string">'\0'</span>)
        count++;
    printf(<span class="hljs-string">"\n字符串 \"%s\" 的长度是 %d 个字符.\n"</span>, str2, count);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>\0</code> 字符的 ASCII 码是 0，对应于布尔值的 false，其他 ASCII 码都不是 0。</p>



<p class="wp-block-paragraph">可以使用 char 类型的二维数组存储字符串，数组的每一行都用来存储一个字符串，就可以存储一整串字符串，通过一个变量名引用它们，例如：</p>



<p class="wp-block-paragraph">这个包含 3 行，每行 32 个字符。这样就相当于有三个字符串了。比如 <code>sayings[0]</code> 就是 &#8220;Manners maketh man.&#8221;，32 刚好是最长的字符串的长度包含 <code>\0</code>。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str1&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">32</span>] = {<span class="hljs-string">"To be or not to be"</span>,
                        <span class="hljs-string">"www.foxdevelop.com"</span>,
                        <span class="hljs-string">"www.baidu.com"</span>};
    printf(<span class="hljs-string">"%c\n"</span>, str1&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">3</span>]);
    printf(<span class="hljs-string">"%s\n"</span>, str1&#91;<span class="hljs-number">1</span>]);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">在字符串数组中，必须制定第二维的大小，也可以让编译器计算数组有多少个字符串。上面可以写成：</p>



<p class="wp-block-paragraph">可以用下面代码输出以上三个字符串：</p>



<p class="wp-block-paragraph">上面代码 <code>sizeof(str1)</code> 是整个二维数组的字节数，<code>sizeof(str1[0])</code> 则是表示里面的一个字符串的长度，因为这三个字符串都是固定长度 32，所以只需要用第一个字符串就可以：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str1&#91;]&#91;<span class="hljs-number">32</span>] = {<span class="hljs-string">"To be or not to be"</span>,
                       <span class="hljs-string">"www.foxdevelop.com"</span>,
                       <span class="hljs-string">"www.baidu.com"</span>,
                       <span class="hljs-string">"www.taobao.com"</span>};
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; sizeof(str1) / sizeof(str1&#91;<span class="hljs-number">0</span>]); i++)
    {
        printf(<span class="hljs-string">"%s\n"</span>, str1&#91;i]);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">更改前面的例子，确定二维数组中字符串个数和每个字符串的长度：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str&#91;]&#91;<span class="hljs-number">70</span>] = {
        <span class="hljs-string">"Computers do what you tell them to do,not what you want them to do."</span>,
        <span class="hljs-string">"When you put somthing in memory,remember where you put it."</span>,
        <span class="hljs-string">"Never test for a condition you don't know what to do with."</span>
    };
    unsigned int count = <span class="hljs-number">0</span>;
    unsigned int strCount = sizeof(str) / sizeof(str&#91;<span class="hljs-number">0</span>]);
    printf(<span class="hljs-string">"一共有%u个字符串。\n"</span>, strCount);

    <span class="hljs-keyword">for</span>(unsigned int i = <span class="hljs-number">0</span>; i &lt; strCount; i++)
    {
        count = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">while</span>(str&#91;i]&#91;count])
            ++count;
        printf(<span class="hljs-string">"字符串：\"%s\"占%u个字符\n"</span>, str&#91;i], count);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">前面说明了确定字符串长度的代码，但其实并不需要编写这样的代码。标准库提供了一个执行该操作的函，和许多处理字符串的其他函数。要使用他们，必须把 string.h 头文件包含在源文件中。</p>



<p class="wp-block-paragraph">标准库提供的字符串处理函数集合并不安全，他们使代码包含错误的可能性很大，有时这些错误很难查找。标准库提供了处理字符串函数的可选版本，他们更安全更不容易出错，因为会检查数组的维度，确保空间足够。这些可选函数是以 <code>_s</code> 结尾。</p>



<p class="wp-block-paragraph">很容易确定 C 编译器附带的标准库是否支持这些可选函数：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#define __STDC_WANT_LIB_EXT1__ 1</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main(void)
{
    <span class="hljs-comment">#if defined __STDC_LIB_EXT1__</span>
        printf(<span class="hljs-string">"可选函数有定义\n"</span>);
    <span class="hljs-comment">#else</span>
        printf(<span class="hljs-string">"可选函数没有有定义\n"</span>);
    <span class="hljs-comment">#endif</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">但是发现编译器不支持 C11。点击 Settings -&gt; Compiler，打开 Global compiler settings 界面，将 &#8220;Have g++ follow the C++11 ISO C++ language&#8221; 选项打上勾，最后点击 OK，可以设置编译器让它支持 C11。</p>



<p class="wp-block-paragraph"><code>strnlen</code> 或者 <code>strnlen_s</code> 函数返回字符串的长度，它需要两个参数，一个是字符串的地址另外一个是数组的大小。该函数把字符串的长度返回为一个 <code>size_t</code> 类型的整数值。如果第一个参数是 <code>NULL</code>，就返回 0。如果第二个参数值的元素个数中，第一个参数指定的数组不包括 <code>\0</code>，就返回第二个参数值作为字符串的长度。例如：</p>



<p class="wp-block-paragraph">以上是 <code>strnlen_s</code>，这是扩展方法但有些编译器不支持。这时候可以使用：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;string.h&gt;</span>
<span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str&#91;] = <span class="hljs-string">"foxdevelop.com"</span>;
    printf(<span class="hljs-string">"%zd"</span>, strlen(&amp;str));
}</code></span></pre>


<p class="wp-block-paragraph">以上没有使用扩展库，最后返回 14。</p>



<p class="wp-block-paragraph">扩展库中的 <code>strcpy_s</code> 函数用法如下，它把一个字符串变量的内容赋予另外一个字符串。<code>strcpy_s</code> 三个参数：第一个是复制的目标，第二个是一个整数指定第一个参数的大小，第三个是源字符串。指定目标字符串的长度可以使函数避免覆盖目标字符串最后一个字符后面的内存。如果源字符串比目标字符串长就会发生这种情形。如果一切正常该函数就返回 0 否则返回非 0。</p>



<p class="wp-block-paragraph">再看标准的复制函数 <code>strcpy()</code>，它会把第二个参数指定的字符串复制到第一个参数指定的位置上，不检查目标字符串的容量：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str&#91;] = <span class="hljs-string">"foxdevelop.com"</span>;
    char str2&#91;<span class="hljs-number">8</span>];
    strcpy(str2, str);
    printf(<span class="hljs-string">"%s"</span>, str2);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">连接是把一个字符串连接到另一个字符串的尾部，这是很常见的需求。例如把两个或多个字符串合成一条信息。<code>strcat_s()</code> 函数需要三个参数，字符串 <code>str1</code> 和 <code>str2</code> 连接在一起，<code>str2</code> 追加到 <code>str1</code> 上。<code>str1</code> 后面的 <code>\0</code> 会被覆盖，然后再在后面添加一个 <code>\0</code>。如果一切正常就返回 0，如果 <code>str1</code> 不够大不能追加 <code>str2</code> 则返回非 0。</p>



<p class="wp-block-paragraph">由于编译器不支持扩展库，所以只能使用 <code>strcat</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main(void)
{
    char name&#91;] = <span class="hljs-string">"Foxdevelop"</span>;
    char str&#91;<span class="hljs-number">20</span>] = <span class="hljs-string">"foxdevelop.com"</span>;
    strcat(&amp;str, &amp;name);
    printf(<span class="hljs-string">"%s"</span>, str);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">如果是数值，比较两个数很好理解，比如 11 &gt; 3。字符串库提供的函数还可以比较字符串，确定一个字符串是大于还是小于另外一个字符串。两个字符串的比较是基于它们的字符码。如果两个字符串相同则它们相等。要确定第一个字符串是小于还是大于第二个字符串，比较两个字符串中第一对不同的字符。例如如果第一个字符串中某字符的字符码小于第二个字符串中对应的字符，则第一个字符串就小于第二个字符串。</p>



<p class="wp-block-paragraph">比较字符串没有可选函数，使用的标准函数是 <code>strcmp(str1, str2)</code>，比较两个字符串，返回一个小于、等于或大于 0 的 int 值，分别对应 <code>str1</code> 小于、等于和大于 <code>str2</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str1&#91;] = <span class="hljs-string">"foxdevelop.cam"</span>;
    char str2&#91;] = <span class="hljs-string">"foxdevelop.cn"</span>;
    int res = strcmp(str1, str2);
    printf(<span class="hljs-string">"%d"</span>, res);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>strncmp</code> 函数用来比较两个字符串的前 n 个字符，它比 <code>strcmp</code> 多了第三个参数，第三个参数类型是 <code>size_t</code> 用来指定比较的字符数。如果要处理的字符串中表示零件号或序列号的前十个字符，就可以使用这个函数：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str1&#91;] = <span class="hljs-string">"foxdevelop.cam"</span>;
    char str2&#91;] = <span class="hljs-string">"foxdevelop.cn"</span>;
    int res = strncmp(str1, str2, <span class="hljs-number">6</span>);
    printf(<span class="hljs-string">"%d"</span>, res);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">头文件 string.h 声明了几个字符串搜索函数，但是在探讨它们之前，先了解一下下一章的主题——指针，这里需要这些基础知识以理解如何使用字符串搜索函数。</p>



<h3 class="wp-block-heading">指针的概念</h3>



<p class="wp-block-paragraph">C 提供一个非常有用的变量类型叫做指针。指针是含有地址的变量，它含有内存中另一个包含数值的位置的引用。内存有一个编号，每个字节有个编号从 0 开始。函数 scanf 就是使用了地址。下面的第二条语句就定义了指针 <code>pNumber</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">int <span class="hljs-built_in">Number</span> = <span class="hljs-number">25</span>;
int *pNumber = &amp;<span class="hljs-built_in">Number</span>;</code></span></pre>


<p class="wp-block-paragraph">然后就可以使用 <code>*pNumber</code> 来得到 Number 里面的值。<code>*</code> 是取消引用运算符，其作用是访问指针指定的地址中存储的数据：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int Number = <span class="hljs-number">25</span>;
    int *pNumber = &amp;Number;
    printf(<span class="hljs-string">"%d\n"</span>, Number);
    printf(<span class="hljs-string">"%d\n"</span>, *pNumber);
    printf(<span class="hljs-string">"%p\n"</span>, pNumber);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">函数 <code>strchr()</code> 在字符串中搜索给定的字符。它的第一个参数是要搜索的字符串，是 char 数组的地址。第二个参数是要查找的字符。这个函数会从字符串的开头开始搜索，返回在字符串中找到的第一个给定字符的地址。这是一个在内存中的地址，其类型是 <code>char *</code>。所以要存储这个返回值，必须创建一个能存储字符串地址的变量。如果没有找到给定的字符，函数就会返回 <code>NULL</code>。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str&#91;] = <span class="hljs-string">"foxdevelop.com"</span>;
    char ch = <span class="hljs-string">'m'</span>;
    char *pch = strchr(str, ch);
    <span class="hljs-keyword">if</span>(pch)
    {
        printf(<span class="hljs-string">"%p\n"</span>, pch);
        printf(<span class="hljs-string">"%c\n"</span>, *pch);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"no found"</span>);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">也可以写成：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str&#91;] = <span class="hljs-string">"foxdevelop.com"</span>;
    char ch = <span class="hljs-string">'m'</span>;
    char *pch = strchr(str, ch);
    <span class="hljs-keyword">if</span>(pch)
    {
        printf(<span class="hljs-string">"%s\n"</span>, pch);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"no found"</span>);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>NULL</code> 指针值转换为 bool 值是 false，非 <code>NULL</code> 是 true。所以可以使用 if 来判断是否找到字符。</p>



<p class="wp-block-paragraph"><code>strstr</code> 函数是所有搜索函数中最有用的函数，它查找一个字符串中的子字符串，返回找到的第一个子字符串的位置指针。同样如果找不到匹配的子字符串就返回 <code>NULL</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char text&#91;] = <span class="hljs-string">"foxdevelop.com"</span>;
    char word&#91;] = <span class="hljs-string">"mn"</span>;
    char *pFound = <span class="hljs-keyword">NULL</span>;
    pFound = strstr(text, word);
    printf(<span class="hljs-string">"%s"</span>, pFound);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;string.h&gt;</span>

int main(void)
{
    char str1&#91;] = <span class="hljs-string">"This string contains the holy grail."</span>;
    char str2&#91;] = <span class="hljs-string">"the holy grail"</span>;
    char str3&#91;] = <span class="hljs-string">"the holy grill"</span>;

    <span class="hljs-keyword">if</span>(strstr(str1, str2) == <span class="hljs-keyword">NULL</span>)
        printf(<span class="hljs-string">"\n\"%s\" was not found."</span>, str2);
    <span class="hljs-keyword">else</span>
        printf(<span class="hljs-string">"\n\"%s\" was found in \"%s\""</span>, str2, str1);

    <span class="hljs-keyword">if</span>(strstr(str1, str3) == <span class="hljs-keyword">NULL</span>)
        printf(<span class="hljs-string">"\n\"%s\" was not found."</span>, str3);
    <span class="hljs-keyword">else</span>
        printf(<span class="hljs-string">"\nWe shouldn't get to here!"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">C 库函数 <code>char *strtok(char *str, const char *delim)</code> 分解字符串 str 为一组字符串，delim 为分隔符。该函数返回被分解的第一个子字符串，如果没有可检索的字符串则返回一个空指针：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;string.h&gt;</span>
<span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    char str&#91;<span class="hljs-number">80</span>] = <span class="hljs-string">"This is - www.baidu.com - website"</span>;
    <span class="hljs-keyword">const</span> char s&#91;<span class="hljs-number">2</span>] = <span class="hljs-string">"-"</span>;
    char *token;

    token = strtok(str, s);

    <span class="hljs-keyword">while</span>(token != <span class="hljs-keyword">NULL</span>)
    {
        printf(<span class="hljs-string">"%s\n"</span>, token);
        token = strtok(<span class="hljs-keyword">NULL</span>, s);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">当 <code>strtok()</code> 在参数 s 的字符串中发现参数 delim 中包含的分割字符时，则会将该字符改为 <code>\0</code> 字符。在第一次调用时 <code>strtok()</code> 必需给予参数 s 字符串，往后的调用则将参数 s 设置成 <code>NULL</code>。每次调用成功则返回指向被分割出片段的指针。</p>



<p class="wp-block-paragraph">下面例子判断从键盘输入的一个字符串中有多少个数字、字母和标点符号：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>

int main(void)
{
    char buffer&#91;<span class="hljs-number">80</span>];
    int i = <span class="hljs-number">0</span>;
    int num_letters = <span class="hljs-number">0</span>;
    int num_digits = <span class="hljs-number">0</span>;

    printf(<span class="hljs-string">"\nEnter an interesting string of less than 80 characters:\n"</span>);
    gets(buffer);

    <span class="hljs-keyword">while</span>(buffer&#91;i] != <span class="hljs-string">'\0'</span>)
    {
        <span class="hljs-keyword">if</span>(isalpha(buffer&#91;i]))
            num_letters++;
        <span class="hljs-keyword">if</span>(isdigit(buffer&#91;i++]))
            num_digits++;
    }
    printf(<span class="hljs-string">"\nYour string contained %d letters and %d digits.\n"</span>,
           num_letters, num_digits);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">头文件 stdlib.h 声明了一些将字符串转换成数值的函数。这些函数会忽略前导空白：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main(void)
{
    char str&#91;] = <span class="hljs-string">"10"</span>;
    int num = atoi(str);
    printf(<span class="hljs-string">"%d"</span>, num * <span class="hljs-number">10</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e5%ad%97%e7%ac%a6%e4%b8%b2-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>练习题</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e7%bb%83%e4%b9%a0%e9%a2%98/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e7%bb%83%e4%b9%a0%e9%a2%98/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:43:16 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13539</guid>

					<description><![CDATA[练习题解答 练习 1：计算倒数及倒数总和 练习 2：数列求和 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">练习题解答</h3>



<h4 class="wp-block-heading">练习 1：计算倒数及倒数总和</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    double numbers&#91;<span class="hljs-number">5</span>] = {<span class="hljs-number">0.0</span>};
    double rnums&#91;<span class="hljs-number">5</span>] = {<span class="hljs-number">0.0</span>};
    double sum = <span class="hljs-number">0.0</span>;

    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++)
    {
        printf(<span class="hljs-string">"%d&gt;"</span>, i + <span class="hljs-number">1</span>);
        scanf(<span class="hljs-string">"%lf"</span>, &amp;numbers&#91;i]);
        rnums&#91;i] = <span class="hljs-number">1.0</span> / numbers&#91;i];
        sum += rnums&#91;i];
    }

    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++)
    {
        printf(<span class="hljs-string">"%lf\n"</span>, rnums&#91;i]);
    }
    printf(<span class="hljs-string">"倒数总和:%lf\n"</span>, sum);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h4 class="wp-block-heading">练习 2：数列求和</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    double numbers&#91;<span class="hljs-number">100</span>] = {<span class="hljs-number">0.0</span>};
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">2</span>; i &lt;= <span class="hljs-number">200</span>; i += <span class="hljs-number">2</span>)
    {
        numbers&#91;i / <span class="hljs-number">2</span> - <span class="hljs-number">1</span>] = <span class="hljs-number">1.0</span> / (i * (i + <span class="hljs-number">1</span>) * (i + <span class="hljs-number">2</span>));
    }

    double res = <span class="hljs-number">0.0</span>;
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++)
    {
        <span class="hljs-keyword">if</span>(i % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
        {
            res += numbers&#91;i];
        }
        <span class="hljs-keyword">else</span>
        {
            res -= numbers&#91;i];
        }
    }
    res = res * <span class="hljs-number">4.0</span> + <span class="hljs-number">3.0</span>;
    printf(<span class="hljs-string">"%lf\n"</span>, res);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h4 class="wp-block-heading">练习 3：二维数组计算并输出</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    double data&#91;<span class="hljs-number">11</span>]&#91;<span class="hljs-number">5</span>];

    <span class="hljs-comment">/* 初始化数组 */</span>
    int row = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span>(double d = <span class="hljs-number">2.0</span>; d &lt;= <span class="hljs-number">3.0</span>; d += <span class="hljs-number">0.1</span>)
    {
        data&#91;row]&#91;<span class="hljs-number">0</span>] = d;
        data&#91;row]&#91;<span class="hljs-number">1</span>] = <span class="hljs-number">1.0</span> / d;
        data&#91;row]&#91;<span class="hljs-number">2</span>] = d * d;
        data&#91;row]&#91;<span class="hljs-number">3</span>] = d * d * d;
        data&#91;row]&#91;<span class="hljs-number">4</span>] = d * d * d * d;
        row++;
    }

    <span class="hljs-comment">/* 输出标题 */</span>
    printf(<span class="hljs-string">"%-6s %-10s %-10s %-10s %-10s\n"</span>,
           <span class="hljs-string">"x"</span>, <span class="hljs-string">"1/x"</span>, <span class="hljs-string">"x^2"</span>, <span class="hljs-string">"x^3"</span>, <span class="hljs-string">"x^4"</span>);

    <span class="hljs-comment">/* 输出每一行 */</span>
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">11</span>; i++)
    {
        printf(<span class="hljs-string">"%-6.1f %-10.4f %-10.4f %-10.4f %-10.4f\n"</span>,
               data&#91;i]&#91;<span class="hljs-number">0</span>], data&#91;i]&#91;<span class="hljs-number">1</span>], data&#91;i]&#91;<span class="hljs-number">2</span>], data&#91;i]&#91;<span class="hljs-number">3</span>], data&#91;i]&#91;<span class="hljs-number">4</span>]);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h4 class="wp-block-heading">练习 4：计算多个班级学生的平均分</h4>



<p class="wp-block-paragraph">这个程序支持任意多个班级、任意多个学生。输入时先输入班级数，再依次输入每个班级的学生数，然后输入每个学生的成绩。程序会输出每个学生的平均分以及该班级的平均分。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int classCount = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"请输入班级数量: "</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;classCount);

    <span class="hljs-keyword">for</span>(int c = <span class="hljs-number">0</span>; c &lt; classCount; c++)
    {
        int studentCount = <span class="hljs-number">0</span>;
        printf(<span class="hljs-string">"\n请输入第 %d 个班级的学生数量: "</span>, c + <span class="hljs-number">1</span>);
        scanf(<span class="hljs-string">"%d"</span>, &amp;studentCount);

        double scores&#91;studentCount];
        double classSum = <span class="hljs-number">0.0</span>;

        printf(<span class="hljs-string">"请输入第 %d 个班级 %d 名学生的成绩:\n"</span>, c + <span class="hljs-number">1</span>, studentCount);
        <span class="hljs-keyword">for</span>(int s = <span class="hljs-number">0</span>; s &lt; studentCount; s++)
        {
            printf(<span class="hljs-string">"  学生 %d: "</span>, s + <span class="hljs-number">1</span>);
            scanf(<span class="hljs-string">"%lf"</span>, &amp;scores&#91;s]);
            classSum += scores&#91;s];
        }

        <span class="hljs-comment">/* 输出该班每个学生的成绩和平均分 */</span>
        printf(<span class="hljs-string">"\n第 %d 个班级学生成绩:\n"</span>, c + <span class="hljs-number">1</span>);
        <span class="hljs-keyword">for</span>(int s = <span class="hljs-number">0</span>; s &lt; studentCount; s++)
        {
            printf(<span class="hljs-string">"  学生 %d 成绩: %.1f, 个人平均分: %.1f\n"</span>,
                   s + <span class="hljs-number">1</span>, scores&#91;s], scores&#91;s]);
        }

        <span class="hljs-comment">/* 输出班级平均分 */</span>
        printf(<span class="hljs-string">"第 %d 个班级的平均分: %.2f\n\n"</span>, c + <span class="hljs-number">1</span>, classSum / studentCount);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">说明</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>练习</th><th>要点</th></tr></thead><tbody><tr><td>练习 1</td><td>一维数组存储原始值和倒数，注意 <code>1.0/x</code> 确保浮点除法</td></tr><tr><td>练习 2</td><td>数列公式 <code>1/(i*(i+1)*(i+2))</code>，交替加减后乘以4加3</td></tr><tr><td>练习 3</td><td>二维数组初始化，列标题对齐输出，步长 0.1</td></tr><tr><td>练习 4</td><td>变长数组（VLA），嵌套循环处理多班级多学生，分别计算个人和班级平均分</td></tr></tbody></table></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e7%bb%83%e4%b9%a0%e9%a2%98/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>井字游戏（Tic-Tac-Toe）</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e4%ba%95%e5%ad%97%e6%b8%b8%e6%88%8f%ef%bc%88tic-tac-toe%ef%bc%89/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e4%ba%95%e5%ad%97%e6%b8%b8%e6%88%8f%ef%bc%88tic-tac-toe%ef%bc%89/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:42:39 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13538</guid>

					<description><![CDATA[井字游戏（圈叉游戏） 下面我们来编写一个游戏，让两个人在计算 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">井字游戏（圈叉游戏）</h3>



<p class="wp-block-paragraph">下面我们来编写一个游戏，让两个人在计算机上玩井字游戏。</p>



<p class="wp-block-paragraph">游戏是一个 3×3 的方格，两个人轮流在方格中输入标记 X 或 O，谁先使 3 个标记连成水平、垂直或者对角线，谁就是赢家。</p>



<p class="wp-block-paragraph">实现思路：</p>



<ol class="wp-block-list">
<li>使用三行三列的二维数组存储标记</li>



<li>玩家标识为 1 和 2，编号 1 的玩家先玩，轮流输入</li>



<li>用 1~9 标记九个格子，玩家输入方格数字</li>



<li>从方格数字计算行列索引：行 = (choice &#8211; 1) / 3，列 = (choice &#8211; 1) % 3</li>



<li>每次轮完后检查是否有玩家获胜</li>



<li>游戏在有人获胜或轮完 9 次后结束</li>
</ol>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdbool.h&gt;</span>

int main(void)
{
    int board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {<span class="hljs-number">0</span>};               <span class="hljs-comment">/* 3x3棋盘，0表示空 */</span>
    int player = <span class="hljs-number">1</span>;                      <span class="hljs-comment">/* 当前玩家 1或2 */</span>
    int choice = <span class="hljs-number">0</span>;                      <span class="hljs-comment">/* 玩家选择 1-9 */</span>
    int row = <span class="hljs-number">0</span>, col = <span class="hljs-number">0</span>;                <span class="hljs-comment">/* 行列索引 */</span>
    int turns = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 已进行的回合数 */</span>
    int winner = <span class="hljs-number">0</span>;                      <span class="hljs-comment">/* 获胜者 0表示无 */</span>

    printf(<span class="hljs-string">"井字游戏 (Tic-Tac-Toe)\n"</span>);
    printf(<span class="hljs-string">"玩家1用 X，玩家2用 O\n"</span>);
    printf(<span class="hljs-string">"格子编号 1-9，布局如下：\n"</span>);
    printf(<span class="hljs-string">" 1 | 2 | 3 \n"</span>);
    printf(<span class="hljs-string">"---+---+---\n"</span>);
    printf(<span class="hljs-string">" 4 | 5 | 6 \n"</span>);
    printf(<span class="hljs-string">"---+---+---\n"</span>);
    printf(<span class="hljs-string">" 7 | 8 | 9 \n\n"</span>);

    <span class="hljs-keyword">while</span>(turns &lt; <span class="hljs-number">9</span> &amp;&amp; winner == <span class="hljs-number">0</span>)
    {
        <span class="hljs-comment">/* 显示当前棋盘 */</span>
        printf(<span class="hljs-string">"\n"</span>);
        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++)
        {
            <span class="hljs-keyword">for</span>(int j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">3</span>; j++)
            {
                <span class="hljs-keyword">if</span>(board&#91;i]&#91;j] == <span class="hljs-number">0</span>)
                    printf(<span class="hljs-string">"   "</span>);
                <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(board&#91;i]&#91;j] == <span class="hljs-number">1</span>)
                    printf(<span class="hljs-string">" X "</span>);
                <span class="hljs-keyword">else</span>
                    printf(<span class="hljs-string">" O "</span>);
                <span class="hljs-keyword">if</span>(j &lt; <span class="hljs-number">2</span>) printf(<span class="hljs-string">"|"</span>);
            }
            printf(<span class="hljs-string">"\n"</span>);
            <span class="hljs-keyword">if</span>(i &lt; <span class="hljs-number">2</span>) printf(<span class="hljs-string">"---+---+---\n"</span>);
        }

        <span class="hljs-comment">/* 当前玩家输入 */</span>
        printf(<span class="hljs-string">"\n玩家%d (%c) 请选择格子 (1-9): "</span>,
               player, player == <span class="hljs-number">1</span> ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>);
        scanf(<span class="hljs-string">"%d"</span>, &amp;choice);

        <span class="hljs-comment">/* 验证输入 */</span>
        <span class="hljs-keyword">if</span>(choice &lt; <span class="hljs-number">1</span> || choice &gt; <span class="hljs-number">9</span>)
        {
            printf(<span class="hljs-string">"无效选择，请选择1-9之间的数字！\n"</span>);
            <span class="hljs-keyword">continue</span>;
        }

        row = (choice - <span class="hljs-number">1</span>) / <span class="hljs-number">3</span>;
        col = (choice - <span class="hljs-number">1</span>) % <span class="hljs-number">3</span>;

        <span class="hljs-keyword">if</span>(board&#91;row]&#91;col] != <span class="hljs-number">0</span>)
        {
            printf(<span class="hljs-string">"该格子已被占用，请重新选择！\n"</span>);
            <span class="hljs-keyword">continue</span>;
        }

        <span class="hljs-comment">/* 放置标记 */</span>
        board&#91;row]&#91;col] = player;
        turns++;

        <span class="hljs-comment">/* 检查获胜 */</span>
        <span class="hljs-comment">/* 检查行 */</span>
        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++)
        {
            <span class="hljs-keyword">if</span>(board&#91;i]&#91;<span class="hljs-number">0</span>] == player &amp;&amp; board&#91;i]&#91;<span class="hljs-number">1</span>] == player &amp;&amp; board&#91;i]&#91;<span class="hljs-number">2</span>] == player)
                winner = player;
        }
        <span class="hljs-comment">/* 检查列 */</span>
        <span class="hljs-keyword">for</span>(int j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">3</span>; j++)
        {
            <span class="hljs-keyword">if</span>(board&#91;<span class="hljs-number">0</span>]&#91;j] == player &amp;&amp; board&#91;<span class="hljs-number">1</span>]&#91;j] == player &amp;&amp; board&#91;<span class="hljs-number">2</span>]&#91;j] == player)
                winner = player;
        }
        <span class="hljs-comment">/* 检查对角线 */</span>
        <span class="hljs-keyword">if</span>(board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>] == player &amp;&amp; board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] == player &amp;&amp; board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>] == player)
            winner = player;
        <span class="hljs-keyword">if</span>(board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>] == player &amp;&amp; board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] == player &amp;&amp; board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>] == player)
            winner = player;

        <span class="hljs-comment">/* 切换玩家 */</span>
        <span class="hljs-keyword">if</span>(winner == <span class="hljs-number">0</span>)
            player = (player == <span class="hljs-number">1</span>) ? <span class="hljs-number">2</span> : <span class="hljs-number">1</span>;
    }

    <span class="hljs-comment">/* 显示最终棋盘 */</span>
    printf(<span class="hljs-string">"\n最终棋盘：\n"</span>);
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++)
    {
        <span class="hljs-keyword">for</span>(int j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">3</span>; j++)
        {
            <span class="hljs-keyword">if</span>(board&#91;i]&#91;j] == <span class="hljs-number">0</span>)
                printf(<span class="hljs-string">"   "</span>);
            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(board&#91;i]&#91;j] == <span class="hljs-number">1</span>)
                printf(<span class="hljs-string">" X "</span>);
            <span class="hljs-keyword">else</span>
                printf(<span class="hljs-string">" O "</span>);
            <span class="hljs-keyword">if</span>(j &lt; <span class="hljs-number">2</span>) printf(<span class="hljs-string">"|"</span>);
        }
        printf(<span class="hljs-string">"\n"</span>);
        <span class="hljs-keyword">if</span>(i &lt; <span class="hljs-number">2</span>) printf(<span class="hljs-string">"---+---+---\n"</span>);
    }

    <span class="hljs-keyword">if</span>(winner != <span class="hljs-number">0</span>)
        printf(<span class="hljs-string">"\n恭喜玩家%d (%c) 获胜！\n"</span>, winner, winner == <span class="hljs-number">1</span> ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>);
    <span class="hljs-keyword">else</span>
        printf(<span class="hljs-string">"\n平局！\n"</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h3 class="wp-block-heading">井字游戏（Tic-Tac-Toe）</h3>



<h4 class="wp-block-heading">步骤 1：添加主游戏循环和显示棋盘</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int player = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 当前玩家号码 1或者2 */</span>
    int winner = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 赢了的玩家号码 */</span>
    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    <span class="hljs-comment">/* 至多需要输入九次 */</span>
    <span class="hljs-keyword">for</span>(unsigned int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span> &amp;&amp; winner == <span class="hljs-number">0</span>; i++)
    {
        printf(<span class="hljs-string">"\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>]);

        player = i % <span class="hljs-number">2</span> + <span class="hljs-number">1</span>;              <span class="hljs-comment">/* 切换玩家 */</span>
        <span class="hljs-comment">/* 玩家选择 */</span>
    }

    <span class="hljs-comment">/* 输出游戏结果 */</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">步骤 2：让玩家选择方格并验证有效性</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int player = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 当前玩家号码 1或者2 */</span>
    int winner = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 赢了的玩家号码 */</span>
    int choice = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 选择的方格标记 */</span>
    unsigned int row = <span class="hljs-number">0</span>;                 <span class="hljs-comment">/* 行的索引 */</span>
    unsigned int column = <span class="hljs-number">0</span>;              <span class="hljs-comment">/* 列的索引 */</span>

    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    <span class="hljs-comment">/* 至多需要输入九次 */</span>
    <span class="hljs-keyword">for</span>(unsigned int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span> &amp;&amp; winner == <span class="hljs-number">0</span>; i++)
    {
        printf(<span class="hljs-string">"\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>]);

        player = i % <span class="hljs-number">2</span> + <span class="hljs-number">1</span>;              <span class="hljs-comment">/* 切换玩家 */</span>

        <span class="hljs-keyword">do</span>
        {
            printf(<span class="hljs-string">"玩家%d,请选择要填写的有效标记，之后在该标记会填充%c："</span>, player, player == <span class="hljs-number">1</span> ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>);
            scanf(<span class="hljs-string">"%d"</span>, &amp;choice);
            row = --choice / <span class="hljs-number">3</span>;
            column = choice % <span class="hljs-number">3</span>;
        }
        <span class="hljs-keyword">while</span>(choice &lt; <span class="hljs-number">0</span> || choice &gt; <span class="hljs-number">8</span> || board&#91;row]&#91;column] &gt; <span class="hljs-string">'9'</span>); <span class="hljs-comment">/* board&#91;row]&#91;column]&gt;'9' 表示已经填充了X或者O */</span>

        board&#91;row]&#91;column] = (player == <span class="hljs-number">1</span>) ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>;
    }

    <span class="hljs-comment">/* 输出游戏结果 */</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">步骤 3：添加检查获胜逻辑</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int player = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 当前玩家号码 1或者2 */</span>
    int winner = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 赢了的玩家号码 */</span>
    int choice = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 选择的方格标记 */</span>
    unsigned int row = <span class="hljs-number">0</span>;                 <span class="hljs-comment">/* 行的索引 */</span>
    unsigned int column = <span class="hljs-number">0</span>;              <span class="hljs-comment">/* 列的索引 */</span>

    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] = {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    <span class="hljs-comment">/* 至多需要输入九次 */</span>
    <span class="hljs-keyword">for</span>(unsigned int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span> &amp;&amp; winner == <span class="hljs-number">0</span>; i++)
    {
        printf(<span class="hljs-string">"\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>]);

        player = i % <span class="hljs-number">2</span> + <span class="hljs-number">1</span>;              <span class="hljs-comment">/* 切换玩家 */</span>

        <span class="hljs-keyword">do</span>
        {
            printf(<span class="hljs-string">"玩家%d,请选择要填写的有效标记，之后在该标记会填充%c："</span>, player, player == <span class="hljs-number">1</span> ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>);
            scanf(<span class="hljs-string">"%d"</span>, &amp;choice);
            row = --choice / <span class="hljs-number">3</span>;
            column = choice % <span class="hljs-number">3</span>;
        }
        <span class="hljs-keyword">while</span>(choice &lt; <span class="hljs-number">0</span> || choice &gt; <span class="hljs-number">8</span> || board&#91;row]&#91;column] &gt; <span class="hljs-string">'9'</span>);

        board&#91;row]&#91;column] = (player == <span class="hljs-number">1</span>) ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>;

        <span class="hljs-comment">/* 检查有没有胜出 */</span>
        <span class="hljs-keyword">if</span>((board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>] == board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] &amp;&amp; board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] == board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>])
           ||
           (board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>] == board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] &amp;&amp; board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] == board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>]))
        {
            winner = player;
        }
        <span class="hljs-keyword">else</span>
        {
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">2</span>; i++)
            {
                <span class="hljs-keyword">if</span>((board&#91;i]&#91;<span class="hljs-number">0</span>] == board&#91;i]&#91;<span class="hljs-number">1</span>] &amp;&amp; board&#91;i]&#91;<span class="hljs-number">1</span>] == board&#91;i]&#91;<span class="hljs-number">2</span>])
                   ||
                   (board&#91;<span class="hljs-number">0</span>]&#91;i] == board&#91;<span class="hljs-number">1</span>]&#91;i] &amp;&amp; board&#91;<span class="hljs-number">2</span>]&#91;i] == board&#91;<span class="hljs-number">1</span>]&#91;i]))
                {
                    winner = player;
                    <span class="hljs-keyword">break</span>;
                }
            }
        }
    }

    <span class="hljs-comment">/* 输出游戏结果 */</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">步骤 4：显示最终棋盘和比赛结果</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main()
{
    int player = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 当前玩家号码 1或者2 */</span>
    int winner = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 赢了的玩家号码 */</span>
    int choice = <span class="hljs-number">0</span>;                       <span class="hljs-comment">/* 选择的方格标记 */</span>
    unsigned int row = <span class="hljs-number">0</span>;                 <span class="hljs-comment">/* 行的索引 */</span>
    unsigned int column = <span class="hljs-number">0</span>;              <span class="hljs-comment">/* 列的索引 */</span>

    char board&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>] =
    {
        {<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>},
        {<span class="hljs-string">'4'</span>,<span class="hljs-string">'5'</span>,<span class="hljs-string">'6'</span>},
        {<span class="hljs-string">'7'</span>,<span class="hljs-string">'8'</span>,<span class="hljs-string">'9'</span>}
    };

    <span class="hljs-comment">/* 至多需要输入九次 */</span>
    <span class="hljs-keyword">for</span>(unsigned int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span> &amp;&amp; winner == <span class="hljs-number">0</span>; i++)
    {
        printf(<span class="hljs-string">"\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">2</span>]);
        printf(<span class="hljs-string">"---+---+---\n"</span>);
        printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>]);

        player = i % <span class="hljs-number">2</span> + <span class="hljs-number">1</span>;              <span class="hljs-comment">/* 切换玩家 */</span>

        <span class="hljs-keyword">do</span>
        {
            printf(<span class="hljs-string">"玩家%d,请选择要填写的有效标记，之后在该标记会填充%c："</span>, player, player == <span class="hljs-number">1</span> ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>);
            scanf(<span class="hljs-string">"%d"</span>, &amp;choice);
            row = --choice / <span class="hljs-number">3</span>;
            column = choice % <span class="hljs-number">3</span>;
        }
        <span class="hljs-keyword">while</span>(choice &lt; <span class="hljs-number">0</span> || choice &gt; <span class="hljs-number">8</span> || board&#91;row]&#91;column] &gt; <span class="hljs-string">'9'</span>);

        board&#91;row]&#91;column] = (player == <span class="hljs-number">1</span>) ? <span class="hljs-string">'X'</span> : <span class="hljs-string">'O'</span>;

        <span class="hljs-comment">/* 检查有没有胜出 */</span>
        <span class="hljs-keyword">if</span>((board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>] == board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] &amp;&amp; board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] == board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>])
                ||
                (board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>] == board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] &amp;&amp; board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>] == board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>]))
        {
            winner = player;
        }
        <span class="hljs-keyword">else</span>
        {
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">2</span>; i++)
            {
                <span class="hljs-keyword">if</span>((board&#91;i]&#91;<span class="hljs-number">0</span>] == board&#91;i]&#91;<span class="hljs-number">1</span>] &amp;&amp; board&#91;i]&#91;<span class="hljs-number">1</span>] == board&#91;i]&#91;<span class="hljs-number">2</span>])
                        ||
                        (board&#91;<span class="hljs-number">0</span>]&#91;i] == board&#91;<span class="hljs-number">1</span>]&#91;i] &amp;&amp; board&#91;<span class="hljs-number">2</span>]&#91;i] == board&#91;<span class="hljs-number">1</span>]&#91;i]))
                {
                    winner = player;
                    <span class="hljs-keyword">break</span>;
                }
            }
        }
    }

    <span class="hljs-comment">/* 输出最终棋盘 */</span>
    printf(<span class="hljs-string">"\n"</span>);
    printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">2</span>]);
    printf(<span class="hljs-string">"---+---+---\n"</span>);
    printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">1</span>]&#91;<span class="hljs-number">2</span>]);
    printf(<span class="hljs-string">"---+---+---\n"</span>);
    printf(<span class="hljs-string">" %c | %c | %c \n"</span>, board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">0</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">1</span>], board&#91;<span class="hljs-number">2</span>]&#91;<span class="hljs-number">2</span>]);

    <span class="hljs-keyword">if</span>(winner &gt; <span class="hljs-number">0</span>)
    {
        printf(<span class="hljs-string">"玩家%d赢了"</span>, player);
    }
    <span class="hljs-keyword">else</span>
    {
        printf(<span class="hljs-string">"本局平手"</span>);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e4%ba%95%e5%ad%97%e6%b8%b8%e6%88%8f%ef%bc%88tic-tac-toe%ef%bc%89/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>数组</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e6%95%b0%e7%bb%84-2/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e6%95%b0%e7%bb%84-2/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:42:05 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13516</guid>

					<description><![CDATA[数组简介 我们经常需要在程序中存储某种类型的大量数据值。例如 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">数组简介</h3>



<p class="wp-block-paragraph">我们经常需要在程序中存储某种类型的大量数据值。例如编写一个程序，追踪一只篮球队的成绩，就要存储一个赛季各场分数和各个球员得分。我们可以使用前面学过的知识为每个分数使用不同的变量。然而，如果一个赛季有非常多的赛事，这会非常频繁，因为有球赛的每个球员都需要许多变量。这显然不理想。</p>



<p class="wp-block-paragraph">理想情况应该把这些变量集中在一个名称下面，这样就不需要定义多个变量了。</p>



<h4 class="wp-block-heading">计算平均分的问题</h4>



<p class="wp-block-paragraph">我们通过一个例子来了解数组。这个例子是计算某班学生的平均分数。假设该班有十个学生。计算一组数字的平均值，要将它们全加起来，再除以数字的个数。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int number = <span class="hljs-number">0</span>;                      <span class="hljs-comment">/* 存储输入的分数*/</span>
    int count = <span class="hljs-number">10</span>;                      <span class="hljs-comment">/* 学生的个数 */</span>
    long sum = <span class="hljs-number">0</span>L;                       <span class="hljs-comment">/* 总分          */</span>
    float average = <span class="hljs-number">0.0</span>f;                <span class="hljs-comment">/* 平均分*/</span>

    <span class="hljs-comment">/* 读十个数的平均数 */</span>
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; count; i ++)
    {
        printf(<span class="hljs-string">"输入一个学生的成绩: "</span>);
        scanf(<span class="hljs-string">"%d"</span>, &amp;number);              <span class="hljs-comment">/* 读取一个数 */</span>
        sum += number;                     <span class="hljs-comment">/* 累加到sum*/</span>
    }

    average = (float)sum / count;          <span class="hljs-comment">/* 计算平均数 */</span>

    printf(<span class="hljs-string">"\n输入的十个数字的平均值是: %f\n"</span>, average);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">这个程序只对平均值感兴趣，所以累加输入的数然后输出平均值。如果要将其开发为更复杂的程序，需要输入一些数值，再输出每个人的分数，最后输出平均分，上面的代码就无法实现了，因为 <code>number</code> 每次都被覆盖了，不能再次使用。</p>



<p class="wp-block-paragraph">如何存储所有的分数，可以声明十个整数，但是这样不能用 <code>for</code> 循环输入，而且必须添加代码逐个读入，太麻烦了。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int number0 = <span class="hljs-number">0</span>, number1 = <span class="hljs-number">0</span>, number2 = <span class="hljs-number">0</span>, number3 = <span class="hljs-number">0</span>, number4 = <span class="hljs-number">0</span>;
    int number5 = <span class="hljs-number">0</span>, number6 = <span class="hljs-number">0</span>, number7 = <span class="hljs-number">0</span>, number8 = <span class="hljs-number">0</span>, number9 = <span class="hljs-number">0</span>;

    long sum = <span class="hljs-number">0</span>L;          <span class="hljs-comment">/* Sum of the numbers     */</span>
    float average = <span class="hljs-number">0.0</span>f;   <span class="hljs-comment">/* Average of the numbers */</span>

    <span class="hljs-comment">/* Read the ten numbers to be averaged */</span>
    printf(<span class="hljs-string">"输入一到五个数字,\n"</span>);
    printf(<span class="hljs-string">"每个数字用空格隔开，输入完成按回车键.\n"</span>);
    scanf(<span class="hljs-string">"%d%d%d%d%d"</span>, &amp;number0, &amp;number1, &amp;number2, &amp;number3, &amp;number4);
    printf(<span class="hljs-string">"输入后面五个数字,\n"</span>);
    printf(<span class="hljs-string">"每个数字用空格隔开，输入完成按回车键.\n"</span>);
    scanf(<span class="hljs-string">"%d%d%d%d%d"</span>, &amp;number5, &amp;number6, &amp;number7, &amp;number8, &amp;number9);

    <span class="hljs-comment">/* Now we have the ten numbers, we can calculate the average */</span>
    sum = number0 + number1 + number2 + number3 + number4 +
          number5 + number6 + number7 + number8 + number9;
    average = (float)sum / <span class="hljs-number">10.0</span>f;

    printf(<span class="hljs-string">"\n平均数是: %f\n"</span>, average);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">数组的概念</h4>



<p class="wp-block-paragraph">数组是一组数目固定、类型相同的数据项，数组中的数据项称为元素。数组中的元素都是 <code>int</code>、<code>long</code> 或者其他类型。</p>



<p class="wp-block-paragraph">下面是数组声明，非常类似于声明一个含有单一数值的正常变量，但要在名称后面的方括号中放置一个数：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">long</span> <span class="hljs-selector-tag">numbers</span><span class="hljs-selector-attr">&#91;10]</span>;</code></span></pre>


<p class="wp-block-paragraph">方括号中的数字定义了要存放在数组中的元素个数，称为数组维。存储在数组中的每个数据项都用相同的名称访问，在这个例子中，该名称就是 <code>numbers</code>。要选择某个元素，可以在数组名称后的方括号内使用索引值。索引值从 0 开始，最后一个是 9。所以第一个元素就是 <code>numbers[0]</code>，第二个是 <code>numbers[1]</code>，最后一个是 <code>numbers[9]</code>。</p>



<p class="wp-block-paragraph">索引值从 0 开始，不是 1。这一点大家一定要牢记。很多初学者在这个地方犯错。</p>



<p class="wp-block-paragraph">如果访问的时候索引超过这个数组的合法范围，比如上面如果访问 <code>numbers[10]</code>，这个时候就可能程序不能正常运行。编译器检查不出这种错误，所以程序仍可以编译，但是执行有问题。有些时候甚至会覆盖重要信息，导致电脑锁死，需要重启计算机。所以大家要注意避免这个问题。</p>



<p class="wp-block-paragraph">此外，定义的时候 <code>long numbers[10]</code> 这个地方的 10 并不是索引的意思，而是表示这个数组有十个元素。这点与直接访问比如 <code>numbers[10]</code> 的 10 是不同的概念。<code>long numbers[10]</code> 是声明，<code>numbers[10]</code> 是操作某个元素，当然在这里会超出了范围。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    long numbers&#91;<span class="hljs-number">10</span>];
    printf(<span class="hljs-string">"%ld"</span>, numbers&#91;<span class="hljs-number">10</span>]); <span class="hljs-comment">//访问了第十一个元素 可能会访问到一些垃圾数据</span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">下面使用数组知识来解决平均分的问题：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int numbers&#91;<span class="hljs-number">10</span>];                     <span class="hljs-comment">/* 声明有十个元素的数组*/</span>
    int count = <span class="hljs-number">10</span>;                      <span class="hljs-comment">/* 读取数据数量 */</span>
    long sum = <span class="hljs-number">0</span>L;                       <span class="hljs-comment">/* 存储总数          */</span>
    float average = <span class="hljs-number">0.0</span>f;                <span class="hljs-comment">/* 平均数*/</span>

    printf(<span class="hljs-string">"\n输入十个数:\n"</span>);       <span class="hljs-comment">/* 提示输入 */</span>

    <span class="hljs-comment">/* 读取十个数 */</span>
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; count; i ++)
    {
        printf(<span class="hljs-string">"%2d&gt; "</span>, i + <span class="hljs-number">1</span>);
        scanf(<span class="hljs-string">"%d"</span>, &amp;numbers&#91;i]);          <span class="hljs-comment">/* 读取十个数到数组里的十个元素 */</span>
        sum += numbers&#91;i];                 <span class="hljs-comment">/* 累加 */</span>
    }

    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; count; i++)
    {
        printf(<span class="hljs-string">"\n序号：%d 分数：%d"</span>, i + <span class="hljs-number">1</span>, numbers&#91;i]);
    }

    average = (float)sum / count;          <span class="hljs-comment">/* 计算平均数*/</span>

    printf(<span class="hljs-string">"\n十个数的平均数是: %f\n"</span>, average);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">内存地址与寻址运算符</h4>



<p class="wp-block-paragraph">寻址运算符 <code>&amp;</code> 输出其操作数的内存地址。前面使用了寻址运算符 <code>&amp;</code>，它广泛用在 <code>scanf()</code> 函数。<code>&amp;</code> 放在变量前面，<code>scanf</code> 需要用到这个变量的地址，<code>scanf</code> 内部可以利用这个地址去修改对应的变量的值。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    <span class="hljs-comment">/* 定义一些整数变量 */</span>
    long a = <span class="hljs-number">1</span>L;
    long b = <span class="hljs-number">2</span>L;
    long c = <span class="hljs-number">3</span>L;

    <span class="hljs-comment">/* 声明一些浮点变量 */</span>
    double d = <span class="hljs-number">4.0</span>;
    double e = <span class="hljs-number">5.0</span>;
    double f = <span class="hljs-number">6.0</span>;

    printf(<span class="hljs-string">"long类型的变量占用%u个字节。"</span>, sizeof(long));
    printf(<span class="hljs-string">"\n这是一些long类型变量的地址:"</span>);
    printf(<span class="hljs-string">"\na的地址是：%p，\nb的地址是：%p"</span>, &amp;a, &amp;b);
    printf(<span class="hljs-string">"\nc的地址是：%p"</span>, &amp;c);
    printf(<span class="hljs-string">"\n\ndouble类型的变量占用%d字节。"</span>, sizeof(double));
    printf(<span class="hljs-string">"\n这是一些double类型变量的地址："</span>);
    printf(<span class="hljs-string">"\nd的地址是：%p，\ne的地址是：%p"</span>, &amp;d, &amp;e);
    printf(<span class="hljs-string">"\nf的地址是：%p\n"</span>, &amp;f);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph"><code>%u</code> 是显示 <code>sizeof</code> 生成的值，它是无符号的整数。<code>%p</code> 是一个新的格式说明符，用来输出一个内存地址，其值为十六进制。内存地址一般是 32 位或者 64 位，地址的大小取决于引用的最大内存量。</p>



<p class="wp-block-paragraph">声明一个包含 4 个元素的数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">long</span> <span class="hljs-selector-tag">number</span><span class="hljs-selector-attr">&#91;4]</span>;</code></span></pre>


<p class="wp-block-paragraph">获取数组元素地址的方式类似普通变量：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int value = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"\n%p"</span>, &amp;value);

    long number&#91;<span class="hljs-number">4</span>];
    printf(<span class="hljs-string">"\n%p\n"</span>, &amp;number&#91;<span class="hljs-number">2</span>]);

    int data&#91;<span class="hljs-number">5</span>];
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++)
    {
        data&#91;i] = <span class="hljs-number">12</span> * (i + <span class="hljs-number">1</span>);
        printf(<span class="hljs-string">"data&#91;%d] 地址是：%p 值是：%d\n"</span>, i, &amp;data&#91;i], data&#91;i]);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">数组初始化</h4>



<p class="wp-block-paragraph">为了安全起见，预先确定元素的初始值。可以使用大括号并且用逗号隔开，来给数组的元素初始化：</p>


<pre class="wp-block-code"><span><code class="hljs">double values&#91;5] = {1.5, 2.5, 3.5, 4.5, 5.5};</code></span></pre>


<p class="wp-block-paragraph">前三个元素的值就是 1.5、2.5、3.5，后面两个元素初始化值为 0。</p>



<p class="wp-block-paragraph">如果没有给元素提供初值，编译器会给它们提供初值 0，所以初值提供了一种把整个数组初始化为 0 的简单方式，只需要给一个元素提供 0：</p>


<pre class="wp-block-code"><span><code class="hljs">double values&#91;5] = {0.0};</code></span></pre>


<p class="wp-block-paragraph">这样整个数组都初始化为 0.0。</p>



<p class="wp-block-paragraph">如果初始值超过元素个数，有些编译器就会报错。</p>



<p class="wp-block-paragraph">可以不指定数组的大小，让编译器从该列值中推断出元素的个数：</p>


<pre class="wp-block-code"><span><code class="hljs">int primes&#91;] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};</code></span></pre>


<p class="wp-block-paragraph">以上数组的长度就是 10。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    double numbers&#91;] = {<span class="hljs-number">0.5</span>, <span class="hljs-number">1.5</span>, <span class="hljs-number">2.5</span>, <span class="hljs-number">3.5</span>, <span class="hljs-number">4.5</span>, <span class="hljs-number">5.5</span>, <span class="hljs-number">6.5</span>};
    printf(<span class="hljs-string">"%.2lf\n"</span>, numbers&#91;<span class="hljs-number">3</span>]);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">sizeof 运算符</h4>



<p class="wp-block-paragraph"><code>sizeof</code> 可以计算指定类型的变量所占的字节数：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">printf(<span class="hljs-string">"%zu"</span>, sizeof(long));</code></span></pre>


<p class="wp-block-paragraph"><code>sizeof</code> 也可以用于数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">double values&#91;<span class="hljs-number">5</span>] = {<span class="hljs-number">1.5</span>, <span class="hljs-number">2.5</span>, <span class="hljs-number">3.5</span>, <span class="hljs-number">4.5</span>, <span class="hljs-number">5.5</span>};
printf(<span class="hljs-string">"%zu"</span>, sizeof values);</code></span></pre>


<p class="wp-block-paragraph">也可以使用表达式 <code>sizeof values[0]</code> 来计算数组中一个元素所占的字节数。可以通过如下运算来求出数组中的元素的数目：</p>


<pre class="wp-block-code"><span><code class="hljs">size_t elementCount = sizeof values / sizeof values&#91;0];</code></span></pre>


<p class="wp-block-paragraph">在使用循环处理中的所有元素时，可以使用 <code>sizeof</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    printf(<span class="hljs-string">"%zu\n"</span>, sizeof(double));
    double numbers&#91;] = {<span class="hljs-number">0.5</span>, <span class="hljs-number">1.5</span>, <span class="hljs-number">2.5</span>, <span class="hljs-number">3.5</span>, <span class="hljs-number">4.5</span>, <span class="hljs-number">5.5</span>, <span class="hljs-number">6.5</span>};
    printf(<span class="hljs-string">"%zu\n"</span>, sizeof numbers);
    printf(<span class="hljs-string">"数组的元素个数：%u"</span>, sizeof numbers / sizeof(double));

    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; sizeof numbers / sizeof(double); i++)
    {
        printf(<span class="hljs-string">"\n%.1lf"</span>, numbers&#91;i]);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">多维数组</h4>



<p class="wp-block-paragraph">一个数组里面可以存储多个相同类型的数据，这个我们叫做一维数组。比如 <code>float arr[5]</code>。下面介绍二维数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">float</span> <span class="hljs-selector-tag">carrots</span><span class="hljs-selector-attr">&#91;25]</span><span class="hljs-selector-attr">&#91;50]</span>;
<span class="hljs-selector-tag">float</span> <span class="hljs-selector-tag">numbers</span><span class="hljs-selector-attr">&#91;3]</span><span class="hljs-selector-attr">&#91;5]</span>;</code></span></pre>


<p class="wp-block-paragraph">虽然在内存中存储实际上还是顺序存储在内存中，但是我们可以把它想象成三行五列的表格。</p>



<p class="wp-block-paragraph">二维数组的初始化类似于一维数组，区别是把每一行的初始值放在大括号中 <code>{}</code>，再把所有行放在一堆大括号中。如果指定的初始值少于一行的元素，这些值会从每行的第一个元素开始，依序赋予各个元素，剩下未指定初值的元素则初始化为 0。</p>


<pre class="wp-block-code"><span><code class="hljs">int numbers&#91;3]&#91;4] = {0};</code></span></pre>


<p class="wp-block-paragraph">三维数组可以理解为我们有四块地，每块地 10 行 20 列：</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">double</span> <span class="hljs-selector-tag">beans</span><span class="hljs-selector-attr">&#91;4]</span><span class="hljs-selector-attr">&#91;10]</span><span class="hljs-selector-attr">&#91;20]</span>;</code></span></pre>


<p class="wp-block-paragraph">要处理多维数组中的所有元素，需要一个嵌套循环，嵌套的层数就是数组的维数：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int numbers3&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">5</span>] =
    {
        {
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
        },
        {
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
        },
        {
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
        }
    };

    int sum = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++)
    {
        <span class="hljs-keyword">for</span>(int j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">3</span>; j++)
        {
            <span class="hljs-keyword">for</span>(int k = <span class="hljs-number">0</span>; k &lt; <span class="hljs-number">5</span>; k++)
            {
                sum += numbers3&#91;i]&#91;j]&#91;k];
            }
        }
    }

    printf(<span class="hljs-string">"%d"</span>, sum);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">使用 <code>sizeof</code> 可以确定多维数组中每一维的元素个数：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int numbers3&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">5</span>] =
    {
        {
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
        },
        {
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
        },
        {
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>},
            {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
        }
    };

    int sum = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">0</span>; i &lt; sizeof(numbers3) / sizeof(numbers3&#91;<span class="hljs-number">0</span>]); i++)
    {
        <span class="hljs-keyword">for</span>(int j = <span class="hljs-number">0</span>; j &lt; sizeof(numbers3&#91;<span class="hljs-number">0</span>]) / sizeof(numbers3&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]); j++)
        {
            <span class="hljs-keyword">for</span>(int k = <span class="hljs-number">0</span>; k &lt; sizeof(numbers3&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]) / sizeof(numbers3&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]&#91;<span class="hljs-number">0</span>]); k++)
            {
                sum += numbers3&#91;i]&#91;j]&#91;k];
            }
        }
    }

    printf(<span class="hljs-string">"%d"</span>, sum);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">变长数组</h4>



<p class="wp-block-paragraph">前面的所有数组都在代码中指定了固定的长度，也可以定义其长度在程序运行期间确定。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    size_t len = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"请输入数组长度:"</span>);
    scanf(<span class="hljs-string">"%zd"</span>, &amp;len);
    float numbers&#91;len];

    numbers&#91;<span class="hljs-number">3</span>] = <span class="hljs-number">1.2</span>f;
    printf(<span class="hljs-string">"%f"</span>, numbers&#91;<span class="hljs-number">3</span>]);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">也可以在执行期间确定二维或多维数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    size_t len = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"请输入数组长度:"</span>);
    scanf(<span class="hljs-string">"%zd"</span>, &amp;len);

    size_t len2 = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"请输入数组长度:"</span>);
    scanf(<span class="hljs-string">"%zd"</span>, &amp;len2);

    float numbers&#91;len]&#91;len2];

    numbers&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">2</span>] = <span class="hljs-number">1.2</span>f;
    printf(<span class="hljs-string">"%f"</span>, numbers&#91;<span class="hljs-number">3</span>]&#91;<span class="hljs-number">2</span>]);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">下面的代码可以检查编译器是否支持变长数组：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>

int main(void)
{
    <span class="hljs-comment">#ifdef __STDC_NO_VLA__</span>
        printf(<span class="hljs-string">"不支持"</span>);
        <span class="hljs-keyword">exit</span>(<span class="hljs-number">1</span>);
    <span class="hljs-comment">#endif</span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">使用变长数组计算平均分：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    size_t len = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"请输入学生个数:"</span>);
    scanf(<span class="hljs-string">"%zd"</span>, &amp;len);

    int grades&#91;len];
    long sum = <span class="hljs-number">0</span>L;
    float average = <span class="hljs-number">0.0</span>f;

    printf(<span class="hljs-string">"输入学生分数\n"</span>);

    <span class="hljs-keyword">for</span>(size_t i = <span class="hljs-number">0</span>; i &lt; len; ++i)
    {
        printf(<span class="hljs-string">"%2zd&gt;"</span>, i + <span class="hljs-number">1</span>);
        scanf(<span class="hljs-string">"%d"</span>, &amp;grades&#91;i]);
        sum += grades&#91;i];
    }

    printf(<span class="hljs-string">"分数\n"</span>);

    <span class="hljs-keyword">for</span>(size_t i = <span class="hljs-number">0</span>; i &lt; len; ++i)
    {
        printf(<span class="hljs-string">"grades&#91;%2zd]=%3d"</span>, i, grades&#91;i]);

        <span class="hljs-keyword">if</span>((i + <span class="hljs-number">1</span>) % <span class="hljs-number">5</span> == <span class="hljs-number">0</span>)
            printf(<span class="hljs-string">"\n"</span>);
    }

    average = (float)sum / len;
    printf(<span class="hljs-string">"\n %zd 个学生的平均分是 : %.2f\n"</span>, len, average);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<hr class="wp-block-separator has-alpha-channel-opacity"/>
]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e6%95%b0%e7%bb%84-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Simon 记忆测试游戏</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/simon-%e8%ae%b0%e5%bf%86%e6%b5%8b%e8%af%95%e6%b8%b8%e6%88%8f/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/simon-%e8%ae%b0%e5%bf%86%e6%b5%8b%e8%af%95%e6%b8%b8%e6%88%8f/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:40:27 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13526</guid>

					<description><![CDATA[Simon 记忆测试游戏 编写一个简单的 simon 游戏， ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">Simon 记忆测试游戏</h3>



<p class="wp-block-paragraph">编写一个简单的 simon 游戏，这是一个记忆测试游戏。计算机会在屏幕将一串数字显示很短时间，玩家必须在数字消失之前记住他们，然后输入这串数字。每次过关后，计算机会显示更长一串数字，让玩家继续玩下去，玩家尽可能使这个过程重复更多次数。</p>



<h4 class="wp-block-heading">分析</h4>



<p class="wp-block-paragraph">程序的逻辑很简单，程序必须产生一连串 0~9 的整数，使它们在屏幕上显示一秒钟，之后删除它们。</p>



<h4 class="wp-block-heading">解决方案</h4>



<h5 class="wp-block-heading">步骤 1：确定代码基本功能块，包括游戏的主循环</h5>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;                     /* 使用 input 和 output   */</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;                     /* 使用 toupper() function */</span>
<span class="hljs-comment">#include &lt;stdbool.h&gt;                   /* 使用 bool, true, false  */</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;                    /* 使用 rand() 和 srand() */</span>
<span class="hljs-comment">#include &lt;time.h&gt;                      /* 使用 time() 和 clock() */</span>

int main(void)
{
    <span class="hljs-comment">/* 记录是否要玩另一个游戏 */</span>
    char another_game = <span class="hljs-string">'Y'</span>;

    <span class="hljs-comment">/* 如果输入正确的序列，则为true，否则为false */</span>
    int correct = <span class="hljs-keyword">false</span>;

    <span class="hljs-comment">/* 成功输入的序列数          */</span>
    int counter = <span class="hljs-number">0</span>;

    int sequence_length = <span class="hljs-number">0</span>;     <span class="hljs-comment">/* 序列中的位数        */</span>
    time_t seed = <span class="hljs-number">0</span>;             <span class="hljs-comment">/* 随机数序列的种子值 */</span>
    int number = <span class="hljs-number">0</span>;              <span class="hljs-comment">/* 存储输入数字*/</span>

    time_t now = <span class="hljs-number">0</span>;            <span class="hljs-comment">/* 存储随机值的当前时间种子  */</span>
    int time_taken = <span class="hljs-number">0</span>;        <span class="hljs-comment">/* 游戏时间（秒） */</span>

    <span class="hljs-comment">/* 描述游戏是如何进行的 */</span>
    printf(<span class="hljs-string">"\n准备玩简单的Simon游戏, "</span>);
    printf(<span class="hljs-string">"观察屏幕上的数字序列."</span>);
    printf(<span class="hljs-string">"\n小心观察，因为数字只显示出来几秒"</span>);
    printf(<span class="hljs-string">"\n计算机将删除它们，然后提示您输入相同的序列."</span>);
    printf(<span class="hljs-string">"\n当你这样做时，你必须在数字之间加空格. \n"</span>);
    printf(<span class="hljs-string">"\n祝你好运！\n按回车键开始\n"</span>);
    scanf(<span class="hljs-string">"%c"</span>, &amp;another_game);

    <span class="hljs-comment">/* 一个外循环迭代就是一个游戏 */</span>
    <span class="hljs-keyword">do</span>
    {
        correct = <span class="hljs-keyword">true</span>;         <span class="hljs-comment">/* 默认情况下，表示输入的顺序正确 */</span>
        counter = <span class="hljs-number">0</span>;            <span class="hljs-comment">/* 初始化成功尝试次数的计数*/</span>
        sequence_length = <span class="hljs-number">2</span>;    <span class="hljs-comment">/* 数字序列的初始长度*/</span>
        time_taken = clock();  <span class="hljs-comment">/* 在游戏开始时记录当前时间*/</span>

        <span class="hljs-comment">/* 只要序列输入正确，内环就继续 */</span>
        <span class="hljs-keyword">while</span>(correct)
        {
            <span class="hljs-comment">/* 每三次成功尝试，增加序列长度 */</span>
            sequence_length += counter++ % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>;

            <span class="hljs-comment">/* 将seed设置为自1970年1月1日以来的秒数  */</span>
            seed = time(<span class="hljs-keyword">NULL</span>);

            now = clock();                  <span class="hljs-comment">/* 记录序列的开始时间  */</span>

            <span class="hljs-comment">/* 生成数字序列并显示数字 */</span>
            srand((unsigned int)seed);      <span class="hljs-comment">/* 初始化随机序列 */</span>
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= sequence_length; i++)
                printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);    <span class="hljs-comment">/* 输出随机数字          */</span>

            <span class="hljs-comment">/* 等一秒 */</span>
            <span class="hljs-keyword">for</span>( ; clock() - now &lt; CLOCKS_PER_SEC; );

            <span class="hljs-comment">/* 现在重写数字序列 */</span>
            printf(<span class="hljs-string">"\r"</span>);                   <span class="hljs-comment">/* 转到行首 */</span>
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= sequence_length; i++)
                printf(<span class="hljs-string">"  "</span>);                 <span class="hljs-comment">/* 输出空白 覆盖 */</span>

            <span class="hljs-keyword">if</span>(counter == <span class="hljs-number">1</span>)           <span class="hljs-comment">/* 只输出第一次尝试的消息 */</span>
                printf(<span class="hljs-string">"\n现在输入序列-不要忘记空格\n"</span>);
            <span class="hljs-keyword">else</span>
                printf(<span class="hljs-string">"\r"</span>);                <span class="hljs-comment">/* 回到行首 */</span>

            <span class="hljs-comment">/* 对照原始数字检查输入序列 */</span>
            srand((unsigned int)seed);     <span class="hljs-comment">/* 重新启动随机序列    */</span>
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= sequence_length; i++)
            {
                scanf(<span class="hljs-string">"%d"</span>, &amp;number);         <span class="hljs-comment">/* 读取输入数字         */</span>
                <span class="hljs-keyword">if</span>(number != rand() % <span class="hljs-number">10</span>)     <span class="hljs-comment">/* 与随机数比较 */</span>
                {
                    correct = <span class="hljs-keyword">false</span>;            <span class="hljs-comment">/* 输入错误             */</span>
                    <span class="hljs-keyword">break</span>;                      <span class="hljs-comment">/* 无需进一步检查... */</span>
                }
            }
            printf(<span class="hljs-string">"%s\n"</span>, correct ? <span class="hljs-string">"对的!"</span> : <span class="hljs-string">"错的!"</span>);
        }

        <span class="hljs-comment">/* 计算玩游戏的总时间（秒）*/</span>
        time_taken = (clock() - time_taken) / CLOCKS_PER_SEC;

        <span class="hljs-comment">/* 输出游戏分数 */</span>
        printf(<span class="hljs-string">"\n\n 你的分数是 %d"</span>, --counter * <span class="hljs-number">100</span> / time_taken);

        fflush(stdin);

        <span class="hljs-comment">/* 检查是否需要新游戏*/</span>
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;another_game);

    }
    <span class="hljs-keyword">while</span>(toupper(another_game) == <span class="hljs-string">'Y'</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h3 class="wp-block-heading">程序分解：游戏循环控制</h3>



<ol class="wp-block-list">
<li>首先完成游戏是否继续玩，输入 y 则继续，输入 n 则结束。</li>
</ol>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>

int main(void)
{
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    <span class="hljs-keyword">do</span>
    {
        printf(<span class="hljs-string">"\n玩了一次游戏"</span>);

        fflush(stdin); <span class="hljs-comment">//清空输入缓冲区，通常是为了确保不影响后面的数据读取</span>
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);
    printf(<span class="hljs-string">"\n游戏结束"</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h3 class="wp-block-heading">Code::Blocks 语法纠错功能（红色波浪线）</h3>



<p class="wp-block-paragraph">菜单栏 <code>Plugins</code>（插件）下拉找到 <code>Manage Plugins</code>，点开找到 <code>SpellChecker</code>，将它设置为 <code>Disable</code> 即可。</p>



<h3 class="wp-block-heading">程序分解：Simon 游戏逐步实现</h3>



<h4 class="wp-block-heading">1. 游戏循环控制</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>

int main(void)
{
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    <span class="hljs-keyword">do</span>
    {
        printf(<span class="hljs-string">"\n玩了一次游戏"</span>);

        fflush(stdin); <span class="hljs-comment">//清空输入缓冲区，通常是为了确保不影响后面的数据读取</span>
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);
    printf(<span class="hljs-string">"\n游戏结束"</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">2. 输出随机序列</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>

int main(void)
{
    time_t seed = <span class="hljs-number">0</span>; <span class="hljs-comment">//随机数序列的种子值</span>
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    int seqLength = <span class="hljs-number">2</span>; <span class="hljs-comment">//一开始数字序列长度为2 后面 根据猜对情况 每次递增1</span>
    <span class="hljs-keyword">do</span>
    {
        <span class="hljs-comment">//将seed设置为自1970年1月1日以来的秒数 存储起来后面有用</span>
        seed = time(<span class="hljs-keyword">NULL</span>);

        srand((unsigned int)seed); <span class="hljs-comment">//初始化随机序列</span>

        <span class="hljs-comment">//输出随机数字</span>
        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
        {
            printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>); <span class="hljs-comment">//只输出1到9</span>
        }

        fflush(stdin);
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">3. 显示一秒后隐藏序列</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>

int main(void)
{
    time_t seed = <span class="hljs-number">0</span>;
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    int seqLength = <span class="hljs-number">2</span>;
    time_t now = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">do</span>
    {
        seed = time(<span class="hljs-keyword">NULL</span>);
        srand((unsigned int)seed);
        now = clock();

        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
        {
            printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);
        }

        <span class="hljs-comment">//等一秒</span>
        <span class="hljs-keyword">for</span>( ; clock() - now &lt; CLOCKS_PER_SEC; );

        <span class="hljs-comment">//现在重写数字序列</span>
        printf(<span class="hljs-string">"\r"</span>);
        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
        {
            printf(<span class="hljs-string">"  "</span>);
        }

        fflush(stdin);
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">4. 随机数种子复用验证</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>

int main(void)
{
    time_t seed = time(<span class="hljs-keyword">NULL</span>);

    srand((unsigned int)seed);

    printf(<span class="hljs-string">"第一次输出\n"</span>);
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">5</span>; i++)
    {
        printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);
    }

    printf(<span class="hljs-string">"\n"</span>);

    srand((unsigned int)seed);
    printf(<span class="hljs-string">"第二次输出\n"</span>);
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">5</span>; i++)
    {
        printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);
    }
    printf(<span class="hljs-string">"\n"</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">5. 检查用户输入</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>
<span class="hljs-comment">#include &lt;stdbool.h&gt;</span>

int main(void)
{
    time_t seed = <span class="hljs-number">0</span>;
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    int seqLength = <span class="hljs-number">2</span>;
    time_t now = <span class="hljs-number">0</span>;
    int number = <span class="hljs-number">0</span>;
    int correct = <span class="hljs-keyword">true</span>;

    <span class="hljs-keyword">do</span>
    {
        seed = time(<span class="hljs-keyword">NULL</span>);
        srand((unsigned int)seed);
        now = clock();

        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
        {
            printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);
        }

        <span class="hljs-keyword">for</span>( ; clock() - now &lt; CLOCKS_PER_SEC; );

        printf(<span class="hljs-string">"\r"</span>);
        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
        {
            printf(<span class="hljs-string">"  "</span>);
        }
        printf(<span class="hljs-string">"\r"</span>);

        <span class="hljs-comment">//对照原始数字检查输入序列</span>
        srand((unsigned int)seed);
        <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
        {
            scanf(<span class="hljs-string">"%d"</span>, &amp;number);
            <span class="hljs-keyword">if</span>(number != rand() % <span class="hljs-number">10</span>)
            {
                correct = <span class="hljs-keyword">false</span>;
                <span class="hljs-keyword">break</span>;
            }
        }
        printf(<span class="hljs-string">"%s\n"</span>, correct ? <span class="hljs-string">"对的!"</span> : <span class="hljs-string">"错的!"</span>);

        fflush(stdin);
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">6. 加入内层循环，答错才退出</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>
<span class="hljs-comment">#include &lt;stdbool.h&gt;</span>

int main(void)
{
    time_t seed = <span class="hljs-number">0</span>;
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    int seqLength = <span class="hljs-number">2</span>;
    time_t now = <span class="hljs-number">0</span>;
    int number = <span class="hljs-number">0</span>;
    int correct = <span class="hljs-keyword">true</span>;

    <span class="hljs-keyword">do</span>
    {
        <span class="hljs-keyword">while</span>(correct)
        {
            seed = time(<span class="hljs-keyword">NULL</span>);
            srand((unsigned int)seed);
            now = clock();

            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);
            }

            <span class="hljs-keyword">for</span>( ; clock() - now &lt; CLOCKS_PER_SEC; );

            printf(<span class="hljs-string">"\r"</span>);
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                printf(<span class="hljs-string">"  "</span>);
            }
            printf(<span class="hljs-string">"\r"</span>);

            srand((unsigned int)seed);
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                scanf(<span class="hljs-string">"%d"</span>, &amp;number);
                <span class="hljs-keyword">if</span>(number != rand() % <span class="hljs-number">10</span>)
                {
                    correct = <span class="hljs-keyword">false</span>;
                    <span class="hljs-keyword">break</span>;
                }
            }
            printf(<span class="hljs-string">"%s\n"</span>, correct ? <span class="hljs-string">"对的!"</span> : <span class="hljs-string">"错的!"</span>);
        }

        fflush(stdin);
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">7. 每答对三次递增序列长度</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>
<span class="hljs-comment">#include &lt;stdbool.h&gt;</span>

int main(void)
{
    time_t seed = <span class="hljs-number">0</span>;
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    int seqLength = <span class="hljs-number">2</span>;
    time_t now = <span class="hljs-number">0</span>;
    int number = <span class="hljs-number">0</span>;
    int correct = <span class="hljs-keyword">true</span>;
    int counter = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">do</span>
    {
        <span class="hljs-keyword">while</span>(correct)
        {
            <span class="hljs-keyword">if</span>(counter &gt; <span class="hljs-number">0</span> &amp;&amp; counter % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>)
            {
                seqLength++;
            }

            seed = time(<span class="hljs-keyword">NULL</span>);
            srand((unsigned int)seed);
            now = clock();

            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);
            }

            <span class="hljs-keyword">for</span>( ; clock() - now &lt; CLOCKS_PER_SEC; );

            printf(<span class="hljs-string">"\r"</span>);
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                printf(<span class="hljs-string">"  "</span>);
            }
            printf(<span class="hljs-string">"\r"</span>);

            srand((unsigned int)seed);
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                scanf(<span class="hljs-string">"%d"</span>, &amp;number);
                <span class="hljs-keyword">if</span>(number != rand() % <span class="hljs-number">10</span>)
                {
                    correct = <span class="hljs-keyword">false</span>;
                    <span class="hljs-keyword">break</span>;
                }
            }
            printf(<span class="hljs-string">"%s\n"</span>, correct ? <span class="hljs-string">"对的!"</span> : <span class="hljs-string">"错的!"</span>);

            <span class="hljs-keyword">if</span>(correct)
            {
                counter++;
            }
        }

        fflush(stdin);
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">8. 计算分数</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>
<span class="hljs-comment">#include &lt;stdbool.h&gt;</span>

int main(void)
{
    time_t seed = <span class="hljs-number">0</span>;
    char isPlayAgain = <span class="hljs-string">'Y'</span>;
    time_t now = <span class="hljs-number">0</span>;
    int number = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">do</span>
    {
        int seqLength = <span class="hljs-number">2</span>;
        int correct = <span class="hljs-keyword">true</span>;
        int counter = <span class="hljs-number">0</span>;

        int timeStart = clock();
        <span class="hljs-keyword">while</span>(correct)
        {
            <span class="hljs-keyword">if</span>(counter &gt; <span class="hljs-number">0</span> &amp;&amp; counter % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>)
            {
                seqLength++;
            }

            seed = time(<span class="hljs-keyword">NULL</span>);
            srand((unsigned int)seed);
            now = clock();

            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                printf(<span class="hljs-string">"%d "</span>, rand() % <span class="hljs-number">10</span>);
            }

            <span class="hljs-keyword">for</span>( ; clock() - now &lt; CLOCKS_PER_SEC; );

            printf(<span class="hljs-string">"\r"</span>);
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                printf(<span class="hljs-string">"  "</span>);
            }
            printf(<span class="hljs-string">"\r"</span>);

            srand((unsigned int)seed);
            <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= seqLength; i++)
            {
                scanf(<span class="hljs-string">"%d"</span>, &amp;number);
                <span class="hljs-keyword">if</span>(number != rand() % <span class="hljs-number">10</span>)
                {
                    correct = <span class="hljs-keyword">false</span>;
                    <span class="hljs-keyword">break</span>;
                }
            }
            printf(<span class="hljs-string">"%s\n"</span>, correct ? <span class="hljs-string">"对的!"</span> : <span class="hljs-string">"错的!"</span>);

            <span class="hljs-keyword">if</span>(correct)
            {
                counter++;
            }
        }

        int timeSpan = (clock() - timeStart) / CLOCKS_PER_SEC;
        printf(<span class="hljs-string">"\n\n 你的分数是 %d"</span>, counter * <span class="hljs-number">100</span> / timeSpan);

        fflush(stdin);
        printf(<span class="hljs-string">"\n你想再玩一次吗 (y/n)? "</span>);
        scanf(<span class="hljs-string">"%c"</span>, &amp;isPlayAgain);
    }
    <span class="hljs-keyword">while</span>(tolower(isPlayAgain) == <span class="hljs-string">'y'</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">练习题</h3>



<h4 class="wp-block-heading">练习 1：乘法表</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int size = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"请输入乘法表的大小: "</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;size);

    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= size; i++)
    {
        <span class="hljs-keyword">for</span>(int j = <span class="hljs-number">1</span>; j &lt;= size; j++)
        {
            printf(<span class="hljs-string">"%d\t"</span>, i * j);
        }
        printf(<span class="hljs-string">"\n"</span>);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">练习 2：输出可打印字符（0~127）</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>

int main(void)
{
    <span class="hljs-keyword">for</span>(int code = <span class="hljs-number">0</span>; code &lt;= <span class="hljs-number">127</span>; code++)
    {
        <span class="hljs-keyword">if</span>(isgraph(code))
        {
            printf(<span class="hljs-string">"code: %3d  -&gt;  %c\n"</span>, code, (char)code);
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">练习 3：空白字符输出名称</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>

int main(void)
{
    <span class="hljs-keyword">for</span>(int code = <span class="hljs-number">0</span>; code &lt;= <span class="hljs-number">127</span>; code++)
    {
        <span class="hljs-keyword">if</span>(isgraph(code))
        {
            printf(<span class="hljs-string">"code: %3d  -&gt;  %c\n"</span>, code, (char)code);
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(code == <span class="hljs-string">'\n'</span>)
        {
            printf(<span class="hljs-string">"code: %3d  -&gt;  newline\n"</span>, code);
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(code == <span class="hljs-string">'\t'</span>)
        {
            printf(<span class="hljs-string">"code: %3d  -&gt;  tab\n"</span>, code);
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(code == <span class="hljs-string">' '</span>)
        {
            printf(<span class="hljs-string">"code: %3d  -&gt;  space\n"</span>, code);
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">练习 4：修改猜谜游戏（基于 rand 值域）</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>

int main(void)
{
    int chosen = <span class="hljs-number">0</span>;
    int guess = <span class="hljs-number">0</span>;
    int limit = RAND_MAX / <span class="hljs-number">100</span>; <span class="hljs-comment">//利用rand()整个值域来确定随机数值</span>

    srand(time(<span class="hljs-keyword">NULL</span>));
    chosen = rand() % limit + <span class="hljs-number">1</span>;

    printf(<span class="hljs-string">"猜一个 1 到 %d 之间的数字: "</span>, limit);
    <span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>)
    {
        scanf(<span class="hljs-string">"%d"</span>, &amp;guess);
        <span class="hljs-keyword">if</span>(guess == chosen)
        {
            printf(<span class="hljs-string">"猜中了!\n"</span>);
            <span class="hljs-keyword">break</span>;
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(guess &lt; chosen)
        {
            printf(<span class="hljs-string">"太小了，再试: "</span>);
        }
        <span class="hljs-keyword">else</span>
        {
            printf(<span class="hljs-string">"太大了，再试: "</span>);
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<h4 class="wp-block-heading">练习 5：猜谜游戏允许继续玩</h4>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>
<span class="hljs-comment">#include &lt;stdlib.h&gt;</span>
<span class="hljs-comment">#include &lt;time.h&gt;</span>
<span class="hljs-comment">#include &lt;ctype.h&gt;</span>

int main(void)
{
    char playAgain = <span class="hljs-string">'Y'</span>;

    <span class="hljs-keyword">while</span>(toupper(playAgain) == <span class="hljs-string">'Y'</span>)
    {
        int chosen = <span class="hljs-number">0</span>;
        int guess = <span class="hljs-number">0</span>;
        int limit = <span class="hljs-number">20</span>;

        srand(time(<span class="hljs-keyword">NULL</span>));
        chosen = rand() % limit + <span class="hljs-number">1</span>;

        printf(<span class="hljs-string">"\n猜一个 1 到 %d 之间的数字: "</span>, limit);
        <span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>)
        {
            scanf(<span class="hljs-string">"%d"</span>, &amp;guess);
            <span class="hljs-keyword">if</span>(guess == chosen)
            {
                printf(<span class="hljs-string">"猜中了!\n"</span>);
                <span class="hljs-keyword">break</span>;
            }
            <span class="hljs-keyword">else</span>
            {
                printf(<span class="hljs-string">"错了，再试一次 (输入0放弃本轮): "</span>);
                <span class="hljs-keyword">if</span>(guess == <span class="hljs-number">0</span>)
                {
                    printf(<span class="hljs-string">"正确答案是 %d\n"</span>, chosen);
                    <span class="hljs-keyword">break</span>;
                }
            }
        }

        printf(<span class="hljs-string">"继续玩下一轮? (Y/N): "</span>);
        scanf(<span class="hljs-string">" %c"</span>, &amp;playAgain);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/simon-%e8%ae%b0%e5%bf%86%e6%b5%8b%e8%af%95%e6%b8%b8%e6%88%8f/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>continue 语句</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/continue-%e8%af%ad%e5%8f%a5/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/continue-%e8%af%ad%e5%8f%a5/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:39:59 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13525</guid>

					<description><![CDATA[continue 语句 有时候不希望结束循环，但要跳出目前的 ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">continue 语句</h3>



<p class="wp-block-paragraph">有时候不希望结束循环，但要跳出目前的迭代，继续执行下一个迭代。循环体内的 <code>continue</code> 语句就有这个作用，它可以编写为：</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">continue</span>;</code></span></pre>


<p class="wp-block-paragraph">下面是 <code>continue</code> 的例子。</p>



<p class="wp-block-paragraph"><code>break</code> 会直接退出整个循环：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i++)
    {
        <span class="hljs-keyword">if</span>(i == <span class="hljs-number">5</span>)
        {
            <span class="hljs-keyword">break</span>;
        }
        printf(<span class="hljs-string">"%d\n"</span>, i);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">以上代码输出：1 2 3 4，当 <code>i</code> 等于 5 时执行 <code>break</code>，整个循环终止。</p>



<p class="wp-block-paragraph">如果是 <code>continue</code>：</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i++)
    {
        <span class="hljs-keyword">if</span>(i == <span class="hljs-number">5</span>)
        {
            <span class="hljs-keyword">continue</span>;
        }
        printf(<span class="hljs-string">"%d\n"</span>, i);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">以上代码输出：1 2 3 4 6 7 8 9 10，当 <code>i</code> 等于 5 时执行 <code>continue</code>，跳过本次迭代中 <code>continue</code> 后面的语句（即 <code>printf</code>），直接进入下一次循环。</p>



<p class="wp-block-paragraph"><code>continue</code> 是退出本次循环，然后进入到下一个循环；而 <code>break</code> 则是退出整个循环，后面的都不执行了。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/continue-%e8%af%ad%e5%8f%a5/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>使用 do-while 循环翻转正整数数字顺序</title>
		<link>https://www.foxdevelop.com/zh/2026/09/29/%e4%bd%bf%e7%94%a8-do-while-%e5%be%aa%e7%8e%af%e7%bf%bb%e8%bd%ac%e6%ad%a3%e6%95%b4%e6%95%b0%e6%95%b0%e5%ad%97%e9%a1%ba%e5%ba%8f/</link>
					<comments>https://www.foxdevelop.com/zh/2026/09/29/%e4%bd%bf%e7%94%a8-do-while-%e5%be%aa%e7%8e%af%e7%bf%bb%e8%bd%ac%e6%ad%a3%e6%95%b4%e6%95%b0%e6%95%b0%e5%ad%97%e9%a1%ba%e5%ba%8f/#respond</comments>
		
		<dc:creator><![CDATA[jack]]></dc:creator>
		<pubDate>Tue, 29 Sep 2026 03:39:26 +0000</pubDate>
				<category><![CDATA[C语言]]></category>
		<guid isPermaLink="false">https://www.foxdevelop.com/?p=13524</guid>

					<description><![CDATA[使用 do-while 循环翻转正整数数字顺序 比如原来是  ...]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">使用 do-while 循环翻转正整数数字顺序</h3>



<p class="wp-block-paragraph">比如原来是 12345，转换后是 54321。</p>



<p class="wp-block-paragraph">算法如下：</p>



<p class="wp-block-paragraph">把这个数 12345，设 <code>r = 0</code>。</p>



<ul class="wp-block-list">
<li>12345 % 10 得 1234 余 5，然后让 <code>r * 10 + 5</code> 保存到变量 <code>r</code></li>



<li>1234 % 10 得 123 余 4，然后让 <code>r * 10 + 4</code> 得 54 保存到 <code>r</code></li>



<li>123 % 10 得 12 余 3，然后让 <code>r * 10 + 3</code> 得 543</li>



<li>12 % 10 得 1 余 2，然后让 <code>r * 10 + 2</code> 得 5432</li>



<li>1 % 10 得 0 余 1，然后让 <code>r * 10 + 1</code> 得 54321</li>
</ul>



<p class="wp-block-paragraph">当商为 0 的时候就停止循环。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int number = <span class="hljs-number">0</span>;                      <span class="hljs-comment">/* The number to be reversed */</span>
    int rebmun = <span class="hljs-number">0</span>;                      <span class="hljs-comment">/* The reversed number       */</span>
    int temp = <span class="hljs-number">0</span>;                        <span class="hljs-comment">/* Working storage           */</span>

    <span class="hljs-comment">/* Get the value to be reversed */</span>
    printf(<span class="hljs-string">"\n输入一个正整数: "</span>);
    scanf(<span class="hljs-string">" %d"</span>, &amp;number);

    temp = number;                       <span class="hljs-comment">/* Copy to working storage  */</span>

    <span class="hljs-comment">/* Reverse the number stored in temp */</span>
    <span class="hljs-keyword">do</span>
    {
        rebmun = <span class="hljs-number">10</span> * rebmun + temp % <span class="hljs-number">10</span>;    <span class="hljs-comment">/* Add the rightmost digit    */</span>
        temp = temp / <span class="hljs-number">10</span>;                    <span class="hljs-comment">/* Remove the rightmost digit */</span>
    }
    <span class="hljs-keyword">while</span> (temp);                        <span class="hljs-comment">/* Continue while temp &gt; 0   */</span>

    printf(<span class="hljs-string">"\n这个数 %d 翻转后是 %d \n"</span>,
            number, rebmun );
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>


<p class="wp-block-paragraph">这个程序 <code>do-while</code> 是最适合的，因为任何数都至少有一位数字。用取模运算符 <code>%</code> 除以 10 的余数，可以得到最右边的数字。</p>



<p class="wp-block-paragraph">任何非零整数都会转换为 true，布尔值 false 对应 0。</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">#include &lt;stdio.h&gt;</span>

int main(void)
{
    int number = <span class="hljs-number">0</span>;
    printf(<span class="hljs-string">"\n输入一个正整数: "</span>);
    scanf(<span class="hljs-string">"%d"</span>, &amp;number);

    int r = <span class="hljs-number">0</span>;
    int s = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">do</span>
    {
        s = number / <span class="hljs-number">10</span>;
        r = r * <span class="hljs-number">10</span> + number % <span class="hljs-number">10</span>;
        number = s;
    } <span class="hljs-keyword">while</span>(number != <span class="hljs-number">0</span>);

    printf(<span class="hljs-string">"%d"</span>, r);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}</code></span></pre>]]></content:encoded>
					
					<wfw:commentRss>https://www.foxdevelop.com/zh/2026/09/29/%e4%bd%bf%e7%94%a8-do-while-%e5%be%aa%e7%8e%af%e7%bf%bb%e8%bd%ac%e6%ad%a3%e6%95%b4%e6%95%b0%e6%95%b0%e5%ad%97%e9%a1%ba%e5%ba%8f/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
