問題在於你的int arr[]={};
的定義,它創建了一個沒有存儲空間的空數組。除非動態分配,否則最好總是定義最大數組大小。解決這個問題(以及初始化所有值)會解決這個問題。
以下是糾正問題的一種方法。它定義了128
的數組元素MAXVALUES
的最大數量。它也增加了提示定向用戶數據請求,和防止尾隨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
,防止發生#define
分配比需要更多的空間(這有點像這裏用大錘撲打一隻蒼蠅)。它只需要更多的工作。具體來說,在分配arr
之前,需要知道n
中有多少個數字,以便您可以分配不超過所需的內存。這裏,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;
}
'int arr [] = {};'這裏,你認爲'arr'的大小是多少? – 2014-11-23 06:41:20
我不知道,它取決於輸入,如果它是12345,那麼大小將會是5. – 2014-11-23 06:45:54
但是C不能這樣工作。數組不會根據需要增長,'int arr [] = {};'是非法的。 – 2014-11-23 06:54:25