对于我的 C 书中的一项作业,我必须找到一种将字符视为整数的方法。因此,我编写了一个程序,它采用代表整数的字符数组,将它们相加,然后输出结果。在下面的程序中,我尝试“添加”字符串“123”和“321”,这应该会产生“444”。
为此,我首先分别找到“3”、“2”和“1”与“0”的距离。例如,“3”在 ASCII 中是 51,“0”是 48,因此差异(或距离)是 3 ASCII 代码,转换为 ETX。请参阅下表。
以下是实现。包含打印语句用于调试目的:
#include <stdio.h>
int main (int argc, char *argv[]) {
char *num1 = "123";
char *num2 = "321";
const char Z = 48; //value of zero
char from_z = 0;
char total[] = { 0 };
int i = 0;
//main for loop
for (i = 0; num1[i] != '\0' || num2[i] != '\0'; i++) {
from_z = num2[i] - Z; //distance from '0'
total[i] = num1[i] + from_z;
//print out contents of current index and previous
//to compare
printf("i total[%d]: %c\n", i, total[i]);
printf("i - 1: total[%d]: %c\n", i-1, total[i-1]);
}
printf("i: %d\n", i);
total[i] = '\0';
return 0;
}
错误: 当我分配并打印新分配的索引和先前分配的索引时,在第二次迭代期间,
total[1]
的值从“4”更改为“\x01”。然而,total[0]
和total[2]
仍然包含“4”。检查下面的输出。 (当然'\x01'不会打印任何内容)
i total[0]: 4
i - 1: total[-1]:
i total[1]: 4
i - 1: total[0]: 4
i total[2]: 4
i - 1: total[1]:
i: 3
可以看到,total[1]先是‘4’,然后随机变成空白。使用调试器,我可以看出
total[1]
的内容是 \x01
。
修复了什么:
有一个静态数组,我将总计定义为具有 4 个索引,如下所示:
char total[4] = { 0 };
,问题已解决。但我仍然想知道为什么它不适用于动态数组。
char total[] = { 0 };
是不是动态数组——它是具有单个元素的固定大小数组。写入
total[0]
以外的任何元素都是在数组边界之外写入并调用未定义的行为。
C 没有“动态”数组,当您向其中写入新元素时会自动增长。如果需要可调整大小的数组,则需要使用
malloc
或 calloc
: 分配内存
size_t totalSize = 1;
char *total = calloc( totalSize, sizeof *total );
然后根据需要使用
realloc
: 手动调整其大小
if ( i == totalSize )
{
char *tmp = realloc( total, sizeof *total * (totalSize * 2) );
if ( tmp )
{
total = tmp;
totalSize *= 2;
}
}
完成后请务必自行清理:
free( total );