Hi I tried to return a struct from the function array2struct, I succeeded to move the information from the array to num and frac as well, but when I tried to put them in numer somthing gets wrong, Thanks for help i would like if someone can help me to change it if the return is also get problem
#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;
}