首页 > 解决方案 > Visual Studio 2019 中的 C 语言

问题描述

嗨,我尝试从函数 array2struct 返回一个结构,我成功地将信息从数组移动到 num 和 frac,但是当我尝试将它们放入 numer 时出现错误,谢谢你的帮助,如果有人可以如果退货也有问题,请帮我更改

在此处输入图像描述

#include <stdio.h>
#include<stdlib.h>
#define point '.'
#define CRT_SECURE_NO_WARNINGS
struct real* array2struct(char* arr);
char* struct2array(struct real* s);
struct real {
    int num;
    int frac;
};
int main()
{

    int num = 27;
    int frac = 31;
    struct real number;
    number.num = num;
    number.frac = frac;
    char* ch;
    ch=struct2array(&number);
    struct real* number2;
    number2=array2struct(ch);
    free(ch);
    return 0;
}
char* struct2array(struct real* s)
{
    int size = 2;//one for'\0' and one for the point
    unsigned int num = s->num;
    unsigned int reverse_num = 0;
    unsigned int remain=s->frac;
    unsigned int reverse_remain = 0 ;
    int index;
    if (remain == 0)
        size++;//we need to put zero after the point
    if (num == 0)
        size++;//we need to put zero befor the point
    while (num != 0)//count the size we have to used for num
    {
        size++;
        num = num / 10;
    }
    num = s->num;
    while (remain != 0)//count the size we have to use for franction
    {
        remain = remain / 10;
        size++;
    }
    remain = s->frac;
    char* number = malloc(sizeof(char) * size);//build string in the correct length
    size = 0;
    while (num != 0)//swich the digits in num
    {
        size++;//count the size of num
        reverse_num += num % 10;
        num /= 10;
        if (num != 0)
            reverse_num *= 10;
    }
    for (int i = 0; i < size; i++)//put the number in the string
    {
        number[i] ='0'+ (reverse_num % 10);
        reverse_num /= 10;
    }
    number[size] = point;//after the number is in the string put point
    index = size+1;//the next index after the point
    size = 0;
    while (remain != 0)//swich the digits in the remain and count the size of the franction part
    {
        size++;
        reverse_remain += remain % 10;
        remain /= 10;
        if (remain != 0)
            reverse_remain *= 10;
    }
    for (int i = 0; i < size; i++)//put the number in the string
    {
        number[index] = '0' + (reverse_remain % 10);
        reverse_remain /= 10;
        index++;
    }
    number[index] = '\0';//close the string
    return number;
}
struct real* array2struct(char* arr)
{
    int num=0;
    int frac=0;
    int index = 0;
    for (; arr[index] != point; index++)
    {
        num *= 10;
        num += (int)(arr[index] - '0');
    }
    index++;//pass the point index
    while (arr[index] != '\0')
    {
        frac *= 10;
        frac += (int)(arr[index] - '0');
        index++;
    }
    struct real* number;
    number->num = num;
    number->frac = frac;
    return number;
}

标签: arrayscstruct

解决方案


推荐阅读