I am taking an algorithm class and haven't coded in c in around 5 years and realized I have forgotten alot. I tried to use atoi, i know there is a better function but for what I'm using it for and my lack of knowledge now it is simpler, for a program that scans users input and prints out a string as an int until the user types stop. It compiles right but when I run it in putty there is a segmentation fault. Hopefully can steer me in the right direction to do this with atoi so that I can implement this in another program that pushes and pulls numbers in an array. I'm just trying to get the general idea on how atoi works so that I can implement it right in the other program. Thanks.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main(){
        int chartoint;
        char * answer = NULL;
        do
        {
        scanf(" %s", &answer);
        chartoint = atoi(*answer);
        printf("%d\n\n\n", chartoint);
        }while ((strcmp("stop",answer)));
        return 0;
}

Recommended Answers

All 4 Replies

You haven't allocated/assigned any memory for answer...

and I assume that involves malloc or calloc, where is a good site to relearn those key concepts again?

atoi is used with string and not chars. This link explain the function along with some sample code

just google for malloc/ calloc you will find tons of documentation and examples

and I assume that involves malloc or calloc, where is a good site to relearn those key concepts again?

No, it involves creating space: char answer[20]; Also, see this series on scanf(). You are using it dangerously.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.