我有这份作业,它一直让我头疼,因为我找不到我做错了什么。
基本上,它应该读取一定数量的字符,即最后一个字符“x”并将它们存储到堆内存中。
之后,程序应使用 ASCII 表对其进行排序。
然后,它应该将每四个字符读取为一个 int。输入的字符数始终是四的倍数,因此每次都有效。
最后但并非最不重要的一点是,它应该打印整数。
我的问题是:程序以错误的顺序打印整数。
这里是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int cont = 1;
int i, j, tmp;
char c;
char *dados = NULL;
do
{
scanf("%s", &c);
dados = (char*)realloc(dados, sizeof(char)*cont);
dados[cont - 1] = c;
cont++;
}
while(c != 'x');
for (i = 0; i < (cont - 1); i++)
{
for (j = 0; j < (cont - i - 1); j++)
{
if (dados[j] > dados[j + 1])
{
tmp = dados[j];
dados[j] = dados[j + 1];
dados[j + 1] = tmp;
}
}
}
int *charInt = (int*)dados;
int aux = sizeof(int);
for(i = 1; i <= (cont - 1); i = i + aux)
{
printf("%d\n", *charInt);
++charInt;
}
return 0;
}
最佳答案
我做了一些修改。下面的代码应该可以工作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int cont = 0;
int i, j, tmp;
char c;
char *dados = NULL;
dados = malloc(sizeof(char));
do
{
scanf("%s", &c);
dados = (char*)realloc(dados, sizeof(char)*cont);
dados[cont] = c;
cont++;
}
while(c != 'x');
for (i = 0; i < (cont - 2); i++)
{
for (j = 0; j < (cont - i - 2); j++)
{
if (dados[j] > dados[j + 1])
{
tmp = dados[j];
dados[j] = dados[j + 1];
dados[j + 1] = tmp;
}
}
}
char *charInt = (char*)dados;
int aux = sizeof(char);
for(i = 0; i <= (cont - 2)*aux; i = i + aux)
{
printf("%d\n",*charInt);
++charInt;
}
return 0;
}
关于将字符数组转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29808605/