typedef struct Int40
{
int *digits;
} Int40;
Int40 *parseString(char *str)
{
Int40 *p;
int i;
int *intPtr;
printf(\"%s\\n\", str);
p->di
It looks like you are confused about a few things.
1) Memory allocation
p->digits = malloc(sizeof(str) + 1);
This is allocation for string but p->digits
is a pointer of int
type.
2) The function atoi
int atoi(const char *str);
Returns int
value.
Maximum value for a variable of type int
is 2147483647
Check: limits.h.
If you use long long int
it can give you 19
digits.
Do you need more digits than long long int
can give you?
3) Remember to allocate memory for the structure and also remember to release it.
Check the following program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct LLint19
{
long long int *digits;
} LLInt19;
long long int sg7_atoi(const char *c)
{
long long int value = 0;
int sign = 1;
if( *c == '+' || *c == '-' )
{
if( *c == '-' ) sign = -1;
c++;
}
while (*c >= '0' && *c <= '9') // to detect digit == isdigit(*c))
{
value *= 10;
value += (int) (*c-'0');
c++;
}
return (value * sign);
}
LLInt19 *parseString(char *str)
{
LLInt19 *p;
long long int *value;
printf("Input str: %s\n", str);
value = malloc (sizeof(long long int) ); // allocate memory for long long int value
p = malloc( sizeof(LLInt19) ); // allocate memory for the structure
*value = sg7_atoi(str); // do a conversion string to long long int
p->digits = value;
return p;
}
int main(int argc, char *argv[])
{
LLInt19 *p;
char test1[] = "1234567890123456789";
p = parseString(test1);
printf("Output str: %lld \n", *p->digits);
free(p->digits);
free(p);
return 0;
}
Output:
Input str: 1234567890123456789
Output str: 1234567890123456789