3

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?

2
  • Note: strtonum is a 'safe-robust' version of atoi/atol Commented Jan 29, 2012 at 16:12
  • Note: main() returns int, and takes (void) or (int, char **). Commented Jan 29, 2012 at 16:46

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3
    int value = atoi(ptr);

No need to dereference, atoi() expects a const char*, not a char.

    printf("%d",value);

And you print an integer using %d or %i. %s is for string only.


BTW, maybe you would like to use strtol instead

char buf[]="1853 was the year";
char* next;
long year = strtol(buf, &next, 10);

printf("'%ld' ~ '%s'\n", year, next);
// 'year' is 1853
// 'next' is " was the year"

1 Comment

8 seconds after me, but a fuller answer.
0

Use:

int value = atoi(ptr);

atoi should get a character pointer, which is what ptr is. *ptr is the first character - 1 in this case, and anyway isn't a pointer, so it's unusable for atoi.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.