Tom
Tom

Reputation: 9663

pointer of char array to integer in c

This is my code:

char str[] ="";
scanf("%s",&str);
char * pch;
pch = strtok (str,"#");
printf ("%s\n",pch);
return 0;

I need to render an input of "1#2#3" to three integers first, second and third. My code above tackles only the first variable and prints the first string "1" but i want to save it to an int variable.

I tried:

int first = atoi(&pch)

But 'first' get's the value 0 instead of 1. How can i parse a pointer of an array char to int?

Upvotes: 2

Views: 1572

Answers (4)

Manik Sidana
Manik Sidana

Reputation: 2163

You have declared str as char str[] ="";. This would allocate only one byte to str. Is it working correctly. I hope I am not missing something here.
As for strtok, you need to use it in a while loop
pch = strtok (str,"#");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, "#");
}

Upvotes: 0

hmjd
hmjd

Reputation: 122011

The code has undefined behaviour as str is not large enough to handle any input. str can hold at most 1 char and scanf() will append a null terminator when it reads in a string. If the user enters a single character and hits return then scanf() will write beyond the bounds the array str.

To correct, decide the maximum length of string that is acceptable and prevent scanf() by reading more:

char str[1024];
if (1 == scanf("%1023s", str))
{
}

Note that atoi() produces a result of 0 for invalid input or for "0", which is not helpful. Use strtol() instead or see the answer from dasblinkenlight for a simpler solution.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

If you know the precise layout of the input, and the exact number of ints, you can simplify this greatly:

scanf("%d#%d#%d", &a, &b, &c);

Here is a link to a demo on ideone.

Upvotes: 4

jonvuri
jonvuri

Reputation: 5940

You pass a char* to atoi(), not a char**. Just call it as atoi(pch)

Upvotes: 1

Related Questions