Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

c - scanf dynamic allocation

For whatever reason the following code prints (null):

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

int main(void)
{
    char *foo; 
    scanf("%ms", &foo);
    printf("%s", foo);
    free(foo);
}

I'm trying to allocate memory for a string dynamically but as I said earlier my program simply outputs (null). I worked around this by making a function using getche and realloc but it seems almost pointless due to the fact that I also had to program what would happen if the user entered backspace, tab, etc.. But as I said that is just a work around and I would rather know why the above code is not working...

Additional Information:

I am using the Pelles C IDE v7.00 and compiling with the C11 standard

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am not seeing %m in section 7.21.6.2 of the Draft C11 standard (the section on fscanf). I suggest that you avoid it and call malloc() as you would in C99.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...