为什么未序列化的数组元素在C中不总是0

  • 本文关键字:数组元素 序列化 arrays c
  • 更新时间 :
  • 英文 :


我输入4566371,发现未初始化的数组元素不是我们文本中所说的0


#include <stdio.h>
#define MAX 10
// Function to print the digit of
// number N
void printDigit(long long int N)
{
// To store the digit
// of the number N
int array_unsorted[MAX];//array_unsorteday for storing the digits
int i = 0;//initializing the loop for the first element of array_unsorted[]
int j, r;
// Till N becomes 0,we will MOD the Number N
while (N != 0) {
// Extract the right-most digit of N
r = N % 10;
// Put the digit in array_unsorted's i th element
array_unsorted[i] = r;
i++;
// Update N to N/10 to extract
// next last digit
N = N / 10;
}
// Print the digit of N by traversing
// array_unsorted[] reverse
for (j =MAX; j >=0; j--)
{
printf("%d ", array_unsorted[j]);
}
}
// Driver Code
int main()
{
long long int N;
printf("Enter your number:");
scanf("%lld",&N);
printDigit(N);
return 0;
}

输出:输入您的号码:456637177 0 8 32765 4 5 6 3 7 1
进程返回0(0x0(执行时间:2.406 s
按任意键继续
其他值应该为o,对吗?为什么是77,032765?为什么不都是0?比如0 0 0 4 5 6 3 7 1?

函数内部声明的整数数组如果未初始化,则其值不确定如果在全局范围内,在所有函数之外声明了类似的数组,则默认情况下,它将用零初始化。

要使数组始终初始化为零,请执行以下操作:

int array_unsorted[MAX] = {0};

这是因为在C中,= {0}将用零初始化所有值。如果说= {10, 20},它将初始化写入的前两个元素,并将其余元素初始化为零。

您已经为数组array_sunsorted正确地保留了内存空间,但在使用之前尚未清理内存。这个保留的内存可能在你之前被另一个函数或变量使用了!这就是为什么它已经有了一些值。在开始使用它之前,你应该手动将它设置为0。

如其他答案中所述,您可能需要初始化整数数组。无论您是否这样做,您都可能希望替换以下的for循环语句条件:

for (j =MAX; j >=0; j--)

带有:

for (j = i - 1; j >=0; j--) /* Start at the place the digit storage ended */

这样,就不会转移到函数的数字存储部分中未使用的数组元素中。

谨致问候。

最新更新