Several problems here
char *recepcao() {
char *receber;
scanf("%s", receber);
return receber;
}
has 2 errors: receber
is an uninitialized pointer, it's pointing to nowhere in
particular, so passing to scanf
is an undefined behaviour.
Also receber
is a local variable of recepcao
and it ceases to exists when
recepcao
returns, so you are returning a pointer to invalid memory location.
It would be better that you declare an array in main
and pass that array (with its size) to the functions. I also would use fgets
instead of scanf
, it easier to control fgets
.
You can use strlen(string)
instead of
for(i=0; string[i]!='\0'; ++i) {
continue;
}
but that's ok if you are not allowed to use strlen
in your assignment.
Also using pow
is overkill here, there is no need to include floating point
arithmetic (pow
returns a double
) when you could use a variable exp
initialized to 1 and multiply
it by 10 in every loop (see my code below).
Also
int *var;
...
for(j=0; j<i-1; ++j) {
var[j]=(string[j]-'0');
...
is not going to work because var
is not initialized. There is no need to use a
pointer here anyway, not even an array, you are not doing anything with the
saved values. It would be better to use a single char
variable:
char var;
...
for(j=0; j<i-1; ++j) {
var = string[j] - '0';
...
So you can rewrite your program with this information like this:
#include <ctype.h>
char *recepcao(char *receber, size_t len) {
if(fgets(receber, len, stdin) == NULL)
{
fprintf(stderr, "Could not read from user\n");
return NULL;
}
// removing newline
receber[strcspn(receber, "\n")] = 0;
return receber;
}
int conversao(const char *string) {
if(string == NULL)
return 0;
size_t len = strlen(string);
int res = 0, pow = 1;
for(size_t i = len - 1; i >= 0; --i)
{
if(isdigit(string[i]))
{
res += (string[i] - '0') * pow;
pow *= 10;
} else {
fprintf(stderr, "'%s' contains non-digits\n", string);
return 0;
}
}
return res;
}
int main(void)
{
char line[100];
if(recepcao(line, sizeof line) == NULL)
return 1;
printf("%d\n", conversao(line));
return 0;
}