Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atoi from string to Integer using char pointer

Tags:

c

pointers

Here is the code I have written which splits a string in c and then I want to return the first integer value pointed by the char pointer.

#include<stdio.h>
void main(){
    int month[12]={0};
    char buf[]="1853 was the year";
        char *ptr;
        ptr = strtok(buf," ");
        printf("%s\n",ptr);
        int value = atoi(*ptr);
        printf("%s",value);
} 

EDIT:It gives me segmentation fault.

The problem is it is printing 1853 as the year, But I want to convert this into integer format.How can i retrieve that value as an integer using the pointer?

like image 230
Abhishek Avatar asked Mar 16 '26 05:03

Abhishek


1 Answers

you are here trying to use an integer as a string:

    printf("%s",value);

you should do

    printf("%d",value);

Edit: yes, and also do int value = atoi(ptr); as added in another answer.

main should also be int, not void.

Also, what compiler are you using? With gcc 4.6 I got these errors and warnings when trying to compile your code (after adding some includes):

ptrbla.C:5:11: error: ‘::main’ must return ‘int’
ptrbla.C: In function ‘int main()’:
ptrbla.C:11:30: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
/usr/include/stdlib.h:148:12: error:   initializing argument 1 of ‘int atoi(const char*)’ [-fpermissive]
ptrbla.C:12:26: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’ [-Wformat]

I'd think you could get at least some of these from most compilers.

like image 133
Johan Lundberg Avatar answered Mar 17 '26 19:03

Johan Lundberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!