英文:
I want to convert integer into an array in C and this is my code and it kind of works
问题
我正在学习C,我遇到了一个问题,我想将整数转换为数组,我的代码可以工作,但问题是我在开始时声明了数组的大小,我希望能够使其适用于任何整数。
英文:
Im learning C right now and I've got this problem I want to convert the integer into an array my code works but the problem is that I declare the size of an array in the beginning and I want to make it so that it works for every integer basically.
#include<stdio.h>
int main()
{
int x,i,temp;
int arr1[6];
scanf("%d",&x);
for (i=5;i>=0;i--){
temp=x%10;
arr1[i]=temp;
x/=10;
}
for (i=0;i<=5;i++){
printf("%d",arr1[i]);
}
return 0;
}
Can you please help me?
I'm trying to find solution for the problem.
答案1
得分: 0
以下是翻译好的部分:
"For starters your code does not take into account that the user can enter a negative number."
- 首先,您的代码没有考虑用户可能输入负数。
"If you are not going to deal with negative values then declare the variable x
as having an unsigned integer type as for example unsigned int
."
- 如果您不打算处理负值,那么可以将变量
x
声明为无符号整数类型,例如unsigned int
。
"As for your problem then you can use a variable length array."
- 至于您的问题,您可以使用可变长度数组。
"For example"
- 例如,
如果您的编译器不支持可变长度数组,那么您可以使用标准函数 malloc
在头文件 <stdlib.h>
中动态分配一个数组,如下所示:
"unsigned int *a = malloc( n * sizeof( *a ) );"
unsigned int *a = malloc( n * sizeof( *a ) );
英文:
For starters your code does not take into account that the user can enter a negative number.
If you are not going to deal with negative values then declare the variable x
as having an unsigned integer type as for example unsigned int
.
As for your problem then you can use a variable length array.
For example
#include <stdio.h>
int main( void )
{
unsigned int x;
if ( scanf( "%u", &x ) == 1 )
{
size_t n = 0;
unsigned int tmp = x;
do
{
++n;
} while ( tmp /= 10 );
unsigned int a[n];
for ( size_t i = n; i != 0; x /= 10 )
{
a[--i] = x % 10;
}
for ( size_t i = 0; i < n; i++ )
{
printf( "%u ", a[i] );
}
putchar( '\n' );
}
}
If your compiler does not support variable length arrays then you can allocate an array dynamically using standard function malloc
declared in header <stdlib.h>
as for example
unsigned int *a = malloc( n * sizeof( *a ) );
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论