以下只是一个代码的一部分。
t是测试用例编号,然后每个t都有整数n。
我想将整数分解为数字并存储在数组中,然后打印数组的每个元素。
输入
1
45
预期产量
5
4
实际产量
32767
0
码
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,n1,tmp,in,len,j;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int arr[]={};
n1=n;
in=0;
len=0;
while(n1>0)
{
tmp=n1%10;
arr[in]=tmp;
len++;
n1=n1/10;
in++;
}
for(j=0;j<len;j++)
{
printf("%d\n",arr[j]);
}
}
}
最佳答案
问题在于您对int arr[]={};
的定义,该定义创建一个没有存储空间的空数组。最好始终定义最大数组大小,除非动态分配。解决该问题(以及初始化所有值)将解决此问题。
以下只是纠正问题的一种方法。它定义了MAXVALUES
个数组元素128
的最大数量。它还会添加提示以使用户适应所请求的数据,并防止将第一次使用newline
的结尾scanf
读取为'n'
的输入:
#include <stdio.h>
#include <stdlib.h>
#define MAXVALUES 128
int main () {
int t = 0;
int n = 0;
int n1 = 0;
int tmp = 0;
int in = 0;
int len = 0;
int j = 0;
printf ("\n Enter the number of numbers to convert: ");
scanf ("%d%*c", &t);
while (t--) {
printf ("\n Enter the number 'n' : ");
scanf ("%d%*c", &n);
int arr[MAXVALUES] = {0};
in = 0;
len = 0;
n1 = n;
while (n1 > 0) {
tmp = n1 % 10;
arr[in] = tmp;
len++;
n1 = n1 / 10;
in++;
}
for (j = 0; j < len; j++) {
printf ("%d\n", arr[j]);
}
}
return 0;
}
输出:
$ ./bin/arrayval
Enter the number of numbers to convert: 2
Enter the number 'n' : 12345
5
4
3
2
1
Enter the number 'n' : 56789
9
8
7
6
5
根据
arr
中的数字动态分配n
您可以动态分配
arr
来防止#define
分配超过所需空间的空间(这有点像使用大锤在此处拍打苍蝇)。这只需要一点点工作。具体来说,在分配n
之前需要知道arr
中有多少位,以便您分配的内存不超过需要的数量。此处,n
中的位数由函数szitoa
计算,然后分配arr
。这是该类型解决方案的一种方法:#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* determine number of chars required for string of int i,
does NOT include space for null char (like strlen) */
size_t
szitoa (int val)
{
int it = 0;
int sz = (val > 0) ? 0 : 1; /* provide space of '-' */
val = (val > 0) ? val : -val; /* absolute value */
for (it = 1; it < INT_MAX; it*=10) {
sz++;
if (val >= it && val < (it*10))
break;
}
return sz;
}
int main () {
int t = 0;
int n = 0;
int n1 = 0;
int tmp = 0;
int in = 0;
int len = 0;
int j = 0;
printf ("\n Enter the number of numbers to covert: ");
scanf ("%d%*c", &t);
while (t--) {
printf ("\n Enter the number 'n' : ");
scanf ("%d%*c", &n);
/* dynamically allocate arr and validate */
int *arr = calloc (szitoa (n), sizeof (int));
if (!arr) {
fprintf (stderr, "error: arr allocation failed\n");
exit (EXIT_FAILURE);
}
in = 0;
len = 0;
n1 = n;
while (n1 > 0) {
tmp = n1 % 10;
arr[in] = tmp;
len++;
n1 = n1 / 10;
in++;
}
for (j = 0; j < len; j++) {
printf ("%d\n", arr[j]);
}
if (arr) free (arr); /* free memory allocated to arr */
}
return 0;
}