Why do I get Segmentation fault?

My code is that:

int main(int argc, char *argv[])
{

int a, b ,c;
char numc[15];
int numi[15];

(Getting String from the user and putting it inside numc)
(I checked that the chars inside the array are digits)

a = atoi(numc[0]);
b = atoi(numc[1]);
c = atoi(numc[2]);

When I try to run it I get Segmentation fault.
Do you know why?
Thanks.
Can you post the rest of your code?
The complete code:
int main(int argc, char *argv[])
{

int a, b ,c, size, i,;
char numc[15];
int numi[15];

while ( (scanf("%s", &numc) ) != EOF )
{
boly = 0;
for (i=0; i<strlen(numc); i++)
{
if (isdigit(numc[i]) == 0)
{
boly = 1;
}
}
if (boly == 1)
{
printf("Invalid value\n");
} else
a = atoi(numc[0]);
b = atoi(numc[1]);
c = atoi(numc[2]);

}


return 0;




}
where's the declaration for boly?

edit: and your libraries?
Last edited on
Also have an extra , after your declaration of i.
Anyway, I'd consider not using atoi on the array, but rather casting them as ints. It won't even let me compile the code you have there. atoi expects a string, not a single char.
I would suggest you read through http://www.cplusplus.com/forum/articles/6046/ on how to take user input and convert between types in C++ style.

The style you have used in C, and have used it incorrectly. You have failed to null your arrays prior to use, so leaving them in an undefined state. I don't remember if scanf auto null-terminates, but I wouldn't be surprised if it doesn't.

Not to mention, you can just use scanf("%i", myInt); without having to read chars and cast/convert across.

Alternatively, your convering from 1 char to an int. atoi is not required as single chars are interchangable with int's anyways. int i = c; should be perfectly valid.
Probably the wrong place to post this, but shouldn't we have a sticky that explains how to use the # button?
I could cut and paste and do the indentation myself, but it seems that every other post is the same way, and I don't have enough experience to 'see' the code when everything is left justified.

Topic archived. No new replies allowed.