Return pointer in Main function - C
Jan 25, 2021 at 11:55am UTC
Hello,
How can I fix it? I want to back "12" in the main function with the result pointer and then print it.
The function is worked fine but I have a problem when I want to back result to main a print.
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include<stdio.h>
#include <string.h>
void strstrX(char * number1, char * number2, char * result)
{
int c1 = 0;
int first = 0;
while (number1[c1] != '\0' )
{
c1++;
}
int c2 = 0;
while (number2[c2] != '\0' )
{
c2++;
}
int num1 = 0;
for (int i = 0; i < c1; i++)
{
num1 = num1 * 10 + (number1[i] - '0' );
}
int num2 = 0;
for (int i = 0; i < c2; i++)
{
num2 = num2 * 10 + (number2[i] - '0' );
}
int r = num1 / num2;
int c3 = 0;
int rr = r;
while (r > 0)
{
r /= 10;
c3++;
}
result = (char *)malloc(c3 * sizeof (char ));
for (int i = c3 -1; i >= 0; i--)
{
result[i] = (rr % 10) + '0' ;
rr /= 10;
}
result[c3] = '\0' ;
}
int main()
{
char Str1[50] = "123" ;
char str2[50] = "10" ;
char res[50];
strstrX(Str1, str2, res);
printf_s("%s" ,res); // HERE A PROBLEM
return 0;
}
Last edited on Jan 25, 2021 at 12:05pm UTC
Jan 25, 2021 at 12:07pm UTC
result = (char *)malloc(c3 * sizeof (char ));
This line isn't needed as result is the array passed in main().
If this line is removed, then it prints 12
The code can also be somewhat simplified. Consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <stdio.h>
#include <string.h>
void strstrX(const char * number1, const char * number2, char * result)
{
int num1 = 0, num2 = 0;
for (; *number1; ++number1)
num1 = num1 * 10 + (*number1 - '0' );
for (; *number2; ++number2)
num2 = num2 * 10 + (*number2 - '0' );
int r = num1 / num2;
int rr = r;
int c3 = 0;
for (; r > 0; ++c3)
r /= 10;
for (int i = c3 - 1; i >= 0; i--, rr /= 10)
result[i] = (rr % 10) + '0' ;
result[c3] = '\0' ;
}
int main()
{
const char Str1[50] = "123" ;
const char str2[50] = "10" ;
char res[50];
strstrX(Str1, str2, res);
printf_s("%s" , res);
return 0;
}
Last edited on Jan 25, 2021 at 12:45pm UTC
Jan 25, 2021 at 1:51pm UTC
* use meaningful names
* use functions
1 2 3 4 5 6
void integer_division(const char * number1, const char * number2, char * result){
int num1 = str2int(number1);
int num2 = str2int(number2);
int r = num1/num2;
int2str(r, result);
}
Jan 25, 2021 at 5:23pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h>
#include <stdlib.h>
void strstrX(const char * number1, const char * number2, char result[50])
{
snprintf(result, 50, "%i" , atoi(number1) / atoi(number2));
}
int main()
{
const char Str1[50] = "123" ;
const char str2[50] = "10" ;
char res[50];
strstrX(Str1, str2, res);
printf_s("%s" , res);
return 0;
}
Topic archived. No new replies allowed.