将字符数组转换为整数数组

标签 c arrays char integer

我有这份作业,它一直让我头疼,因为我找不到我做错了什么。

基本上,它应该读取一定数量的字符,即最后一个字符“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/

相关文章:

c - Pi 的数值评估

c - 是否有任何 linux 函数调用可以通过传递线程 ID 来获取特定线程的 CPU 使用率?

c - 编写 C 语句,清除两位而不干扰其他位

c++ - 将空字符串文字初始化或分配给 C 中的 char 指针或 C++ 中的 const char 指针的原因是什么?

java - 将字符保存到文件时出现问题

c++ - 查找给定数字组中数字的频率

arrays - 如何在 Robo3T 中将结果从一个查询传递到另一个查询

PHP/MySQL : Recreate multidimensional array from existing array

javascript - 将对象数组分组为特定格式

c 字符 * 问题