scanf only reads first field












0















I want to read in two strings with scanf and store them in two variables. How ever only the first one seems to be read properly, the second one just returns (null), but I'm not sure why though.



int main(int argc, char **argv) {
char *c, *p;

printf("Enter a command with a parameter: ");
scanf("%s%s", c, p);
...
}


Somebody got an idea, what's going wrong? I don't find any errors and for my understanding it should work.










share|improve this question























  • When I enter ls -l it only reads the ls properly, that's what i don't understand. scanf should read the white space between them and store the -l in p, but i doesn't.

    – anonymoose
    Nov 19 '18 at 15:39








  • 3





    You've not initialized either c or p to point to anywhere, so you have undefined behaviour.

    – Jonathan Leffler
    Nov 19 '18 at 15:42











  • It’s undefined behavior you didn’t initialize the char * variables.

    – danglingpointer
    Nov 19 '18 at 15:42











  • You don't look at the return value of scanf. How do you know how many fields were parsed?

    – Gerhardh
    Nov 19 '18 at 15:50











  • FYI: There's a Q&A How to prevent scanf() causing buffer overflow in C?

    – Jonathan Leffler
    Nov 19 '18 at 15:54
















0















I want to read in two strings with scanf and store them in two variables. How ever only the first one seems to be read properly, the second one just returns (null), but I'm not sure why though.



int main(int argc, char **argv) {
char *c, *p;

printf("Enter a command with a parameter: ");
scanf("%s%s", c, p);
...
}


Somebody got an idea, what's going wrong? I don't find any errors and for my understanding it should work.










share|improve this question























  • When I enter ls -l it only reads the ls properly, that's what i don't understand. scanf should read the white space between them and store the -l in p, but i doesn't.

    – anonymoose
    Nov 19 '18 at 15:39








  • 3





    You've not initialized either c or p to point to anywhere, so you have undefined behaviour.

    – Jonathan Leffler
    Nov 19 '18 at 15:42











  • It’s undefined behavior you didn’t initialize the char * variables.

    – danglingpointer
    Nov 19 '18 at 15:42











  • You don't look at the return value of scanf. How do you know how many fields were parsed?

    – Gerhardh
    Nov 19 '18 at 15:50











  • FYI: There's a Q&A How to prevent scanf() causing buffer overflow in C?

    – Jonathan Leffler
    Nov 19 '18 at 15:54














0












0








0








I want to read in two strings with scanf and store them in two variables. How ever only the first one seems to be read properly, the second one just returns (null), but I'm not sure why though.



int main(int argc, char **argv) {
char *c, *p;

printf("Enter a command with a parameter: ");
scanf("%s%s", c, p);
...
}


Somebody got an idea, what's going wrong? I don't find any errors and for my understanding it should work.










share|improve this question














I want to read in two strings with scanf and store them in two variables. How ever only the first one seems to be read properly, the second one just returns (null), but I'm not sure why though.



int main(int argc, char **argv) {
char *c, *p;

printf("Enter a command with a parameter: ");
scanf("%s%s", c, p);
...
}


Somebody got an idea, what's going wrong? I don't find any errors and for my understanding it should work.







c scanf stdio






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 '18 at 15:34









anonymooseanonymoose

335




335













  • When I enter ls -l it only reads the ls properly, that's what i don't understand. scanf should read the white space between them and store the -l in p, but i doesn't.

    – anonymoose
    Nov 19 '18 at 15:39








  • 3





    You've not initialized either c or p to point to anywhere, so you have undefined behaviour.

    – Jonathan Leffler
    Nov 19 '18 at 15:42











  • It’s undefined behavior you didn’t initialize the char * variables.

    – danglingpointer
    Nov 19 '18 at 15:42











  • You don't look at the return value of scanf. How do you know how many fields were parsed?

    – Gerhardh
    Nov 19 '18 at 15:50











  • FYI: There's a Q&A How to prevent scanf() causing buffer overflow in C?

    – Jonathan Leffler
    Nov 19 '18 at 15:54



















  • When I enter ls -l it only reads the ls properly, that's what i don't understand. scanf should read the white space between them and store the -l in p, but i doesn't.

    – anonymoose
    Nov 19 '18 at 15:39








  • 3





    You've not initialized either c or p to point to anywhere, so you have undefined behaviour.

    – Jonathan Leffler
    Nov 19 '18 at 15:42











  • It’s undefined behavior you didn’t initialize the char * variables.

    – danglingpointer
    Nov 19 '18 at 15:42











  • You don't look at the return value of scanf. How do you know how many fields were parsed?

    – Gerhardh
    Nov 19 '18 at 15:50











  • FYI: There's a Q&A How to prevent scanf() causing buffer overflow in C?

    – Jonathan Leffler
    Nov 19 '18 at 15:54

















When I enter ls -l it only reads the ls properly, that's what i don't understand. scanf should read the white space between them and store the -l in p, but i doesn't.

– anonymoose
Nov 19 '18 at 15:39







When I enter ls -l it only reads the ls properly, that's what i don't understand. scanf should read the white space between them and store the -l in p, but i doesn't.

– anonymoose
Nov 19 '18 at 15:39






3




3





You've not initialized either c or p to point to anywhere, so you have undefined behaviour.

– Jonathan Leffler
Nov 19 '18 at 15:42





You've not initialized either c or p to point to anywhere, so you have undefined behaviour.

– Jonathan Leffler
Nov 19 '18 at 15:42













It’s undefined behavior you didn’t initialize the char * variables.

– danglingpointer
Nov 19 '18 at 15:42





It’s undefined behavior you didn’t initialize the char * variables.

– danglingpointer
Nov 19 '18 at 15:42













You don't look at the return value of scanf. How do you know how many fields were parsed?

– Gerhardh
Nov 19 '18 at 15:50





You don't look at the return value of scanf. How do you know how many fields were parsed?

– Gerhardh
Nov 19 '18 at 15:50













FYI: There's a Q&A How to prevent scanf() causing buffer overflow in C?

– Jonathan Leffler
Nov 19 '18 at 15:54





FYI: There's a Q&A How to prevent scanf() causing buffer overflow in C?

– Jonathan Leffler
Nov 19 '18 at 15:54












3 Answers
3






active

oldest

votes


















6














char *c, *p;


These are just pointers without any memory behind them. Moreover, they are uninitialized, so reading or assigning they value or reading from or assigning to the memory they point to would be undefined behavior and will spawn nasal demons.



In order to read input from user, you need a place to save the memory to.



char c[20], p[20];


Will allocate 20 characters for c and 20 character for p. c and p are not pointers, but arrays char[20]. However arrays handlers "decay" (read: magically change) into pointers in most contexts.



scanf for "%s" scanf modifier expects a pointer to char char* with enough memory to hold the inputted string.



I would do:



int main(int argc, char **argv) {
char c[20], p[20];

printf("Enter a command with a parameter: ");
scanf("%19s%19s", c, p);
}


The 19 in the %19s limits scanf so that it does not reads input into memory region that is out of bounds in c and/or p pointers, which will lead to undefined behaviour too.






share|improve this answer





















  • 1





    Thanks a lot, i didn't even knew about the limitation stuff.

    – anonymoose
    Nov 19 '18 at 15:49













  • @JonathanLeffler Or just remove the comment, since it's no longer needed. :)

    – Broman
    Nov 19 '18 at 15:51



















4














This is undefined behavior. You have not initialized your pointers. Your compiler should tell you about this.



k.c:8:17: warning: variable 'c' is uninitialized when used here [-Wuninitialized]
scanf("%s%s", c, p);


What you need to do is to initialize your pointers. Using malloc is one way of doing it.



char *c=malloc(SIZE);
char *p=malloc(SIZE);


You want to avoid undefined behavior at ALL COST because it means that the behavior can be ANYTHING, including working the way you want. It can make debugging a nightmare.



But as Swordfish mentioned in the comments, it is suicidal to do this without specifying a max length for your string, because you will have no control over if you write past your buffer, which also is undefined behavior.






share|improve this answer

































    0














    you can also use %ms instead of %s because it allocate memory itself and there is no need of allocation memory manually by programmer.



    int main(int argc, char **argv) {
    char *c, *p;

    printf("Enter a command with a parameter: ");
    scanf("%ms%ms", &c, &p); //no need of allocating memory manually
    ...
    }





    share|improve this answer



















    • 1





      "%ms" is a useful idea with libraries that employ this non-standard enhancement. difference between %ms and %s scanf. Note that code still should later free(c), free(p)

      – chux
      Nov 19 '18 at 18:47













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53377940%2fscanf-only-reads-first-field%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6














    char *c, *p;


    These are just pointers without any memory behind them. Moreover, they are uninitialized, so reading or assigning they value or reading from or assigning to the memory they point to would be undefined behavior and will spawn nasal demons.



    In order to read input from user, you need a place to save the memory to.



    char c[20], p[20];


    Will allocate 20 characters for c and 20 character for p. c and p are not pointers, but arrays char[20]. However arrays handlers "decay" (read: magically change) into pointers in most contexts.



    scanf for "%s" scanf modifier expects a pointer to char char* with enough memory to hold the inputted string.



    I would do:



    int main(int argc, char **argv) {
    char c[20], p[20];

    printf("Enter a command with a parameter: ");
    scanf("%19s%19s", c, p);
    }


    The 19 in the %19s limits scanf so that it does not reads input into memory region that is out of bounds in c and/or p pointers, which will lead to undefined behaviour too.






    share|improve this answer





















    • 1





      Thanks a lot, i didn't even knew about the limitation stuff.

      – anonymoose
      Nov 19 '18 at 15:49













    • @JonathanLeffler Or just remove the comment, since it's no longer needed. :)

      – Broman
      Nov 19 '18 at 15:51
















    6














    char *c, *p;


    These are just pointers without any memory behind them. Moreover, they are uninitialized, so reading or assigning they value or reading from or assigning to the memory they point to would be undefined behavior and will spawn nasal demons.



    In order to read input from user, you need a place to save the memory to.



    char c[20], p[20];


    Will allocate 20 characters for c and 20 character for p. c and p are not pointers, but arrays char[20]. However arrays handlers "decay" (read: magically change) into pointers in most contexts.



    scanf for "%s" scanf modifier expects a pointer to char char* with enough memory to hold the inputted string.



    I would do:



    int main(int argc, char **argv) {
    char c[20], p[20];

    printf("Enter a command with a parameter: ");
    scanf("%19s%19s", c, p);
    }


    The 19 in the %19s limits scanf so that it does not reads input into memory region that is out of bounds in c and/or p pointers, which will lead to undefined behaviour too.






    share|improve this answer





















    • 1





      Thanks a lot, i didn't even knew about the limitation stuff.

      – anonymoose
      Nov 19 '18 at 15:49













    • @JonathanLeffler Or just remove the comment, since it's no longer needed. :)

      – Broman
      Nov 19 '18 at 15:51














    6












    6








    6







    char *c, *p;


    These are just pointers without any memory behind them. Moreover, they are uninitialized, so reading or assigning they value or reading from or assigning to the memory they point to would be undefined behavior and will spawn nasal demons.



    In order to read input from user, you need a place to save the memory to.



    char c[20], p[20];


    Will allocate 20 characters for c and 20 character for p. c and p are not pointers, but arrays char[20]. However arrays handlers "decay" (read: magically change) into pointers in most contexts.



    scanf for "%s" scanf modifier expects a pointer to char char* with enough memory to hold the inputted string.



    I would do:



    int main(int argc, char **argv) {
    char c[20], p[20];

    printf("Enter a command with a parameter: ");
    scanf("%19s%19s", c, p);
    }


    The 19 in the %19s limits scanf so that it does not reads input into memory region that is out of bounds in c and/or p pointers, which will lead to undefined behaviour too.






    share|improve this answer















    char *c, *p;


    These are just pointers without any memory behind them. Moreover, they are uninitialized, so reading or assigning they value or reading from or assigning to the memory they point to would be undefined behavior and will spawn nasal demons.



    In order to read input from user, you need a place to save the memory to.



    char c[20], p[20];


    Will allocate 20 characters for c and 20 character for p. c and p are not pointers, but arrays char[20]. However arrays handlers "decay" (read: magically change) into pointers in most contexts.



    scanf for "%s" scanf modifier expects a pointer to char char* with enough memory to hold the inputted string.



    I would do:



    int main(int argc, char **argv) {
    char c[20], p[20];

    printf("Enter a command with a parameter: ");
    scanf("%19s%19s", c, p);
    }


    The 19 in the %19s limits scanf so that it does not reads input into memory region that is out of bounds in c and/or p pointers, which will lead to undefined behaviour too.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 19 '18 at 15:49

























    answered Nov 19 '18 at 15:43









    Kamil CukKamil Cuk

    9,9611527




    9,9611527








    • 1





      Thanks a lot, i didn't even knew about the limitation stuff.

      – anonymoose
      Nov 19 '18 at 15:49













    • @JonathanLeffler Or just remove the comment, since it's no longer needed. :)

      – Broman
      Nov 19 '18 at 15:51














    • 1





      Thanks a lot, i didn't even knew about the limitation stuff.

      – anonymoose
      Nov 19 '18 at 15:49













    • @JonathanLeffler Or just remove the comment, since it's no longer needed. :)

      – Broman
      Nov 19 '18 at 15:51








    1




    1





    Thanks a lot, i didn't even knew about the limitation stuff.

    – anonymoose
    Nov 19 '18 at 15:49







    Thanks a lot, i didn't even knew about the limitation stuff.

    – anonymoose
    Nov 19 '18 at 15:49















    @JonathanLeffler Or just remove the comment, since it's no longer needed. :)

    – Broman
    Nov 19 '18 at 15:51





    @JonathanLeffler Or just remove the comment, since it's no longer needed. :)

    – Broman
    Nov 19 '18 at 15:51













    4














    This is undefined behavior. You have not initialized your pointers. Your compiler should tell you about this.



    k.c:8:17: warning: variable 'c' is uninitialized when used here [-Wuninitialized]
    scanf("%s%s", c, p);


    What you need to do is to initialize your pointers. Using malloc is one way of doing it.



    char *c=malloc(SIZE);
    char *p=malloc(SIZE);


    You want to avoid undefined behavior at ALL COST because it means that the behavior can be ANYTHING, including working the way you want. It can make debugging a nightmare.



    But as Swordfish mentioned in the comments, it is suicidal to do this without specifying a max length for your string, because you will have no control over if you write past your buffer, which also is undefined behavior.






    share|improve this answer






























      4














      This is undefined behavior. You have not initialized your pointers. Your compiler should tell you about this.



      k.c:8:17: warning: variable 'c' is uninitialized when used here [-Wuninitialized]
      scanf("%s%s", c, p);


      What you need to do is to initialize your pointers. Using malloc is one way of doing it.



      char *c=malloc(SIZE);
      char *p=malloc(SIZE);


      You want to avoid undefined behavior at ALL COST because it means that the behavior can be ANYTHING, including working the way you want. It can make debugging a nightmare.



      But as Swordfish mentioned in the comments, it is suicidal to do this without specifying a max length for your string, because you will have no control over if you write past your buffer, which also is undefined behavior.






      share|improve this answer




























        4












        4








        4







        This is undefined behavior. You have not initialized your pointers. Your compiler should tell you about this.



        k.c:8:17: warning: variable 'c' is uninitialized when used here [-Wuninitialized]
        scanf("%s%s", c, p);


        What you need to do is to initialize your pointers. Using malloc is one way of doing it.



        char *c=malloc(SIZE);
        char *p=malloc(SIZE);


        You want to avoid undefined behavior at ALL COST because it means that the behavior can be ANYTHING, including working the way you want. It can make debugging a nightmare.



        But as Swordfish mentioned in the comments, it is suicidal to do this without specifying a max length for your string, because you will have no control over if you write past your buffer, which also is undefined behavior.






        share|improve this answer















        This is undefined behavior. You have not initialized your pointers. Your compiler should tell you about this.



        k.c:8:17: warning: variable 'c' is uninitialized when used here [-Wuninitialized]
        scanf("%s%s", c, p);


        What you need to do is to initialize your pointers. Using malloc is one way of doing it.



        char *c=malloc(SIZE);
        char *p=malloc(SIZE);


        You want to avoid undefined behavior at ALL COST because it means that the behavior can be ANYTHING, including working the way you want. It can make debugging a nightmare.



        But as Swordfish mentioned in the comments, it is suicidal to do this without specifying a max length for your string, because you will have no control over if you write past your buffer, which also is undefined behavior.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 19 '18 at 15:46

























        answered Nov 19 '18 at 15:41









        BromanBroman

        6,256112241




        6,256112241























            0














            you can also use %ms instead of %s because it allocate memory itself and there is no need of allocation memory manually by programmer.



            int main(int argc, char **argv) {
            char *c, *p;

            printf("Enter a command with a parameter: ");
            scanf("%ms%ms", &c, &p); //no need of allocating memory manually
            ...
            }





            share|improve this answer



















            • 1





              "%ms" is a useful idea with libraries that employ this non-standard enhancement. difference between %ms and %s scanf. Note that code still should later free(c), free(p)

              – chux
              Nov 19 '18 at 18:47


















            0














            you can also use %ms instead of %s because it allocate memory itself and there is no need of allocation memory manually by programmer.



            int main(int argc, char **argv) {
            char *c, *p;

            printf("Enter a command with a parameter: ");
            scanf("%ms%ms", &c, &p); //no need of allocating memory manually
            ...
            }





            share|improve this answer



















            • 1





              "%ms" is a useful idea with libraries that employ this non-standard enhancement. difference between %ms and %s scanf. Note that code still should later free(c), free(p)

              – chux
              Nov 19 '18 at 18:47
















            0












            0








            0







            you can also use %ms instead of %s because it allocate memory itself and there is no need of allocation memory manually by programmer.



            int main(int argc, char **argv) {
            char *c, *p;

            printf("Enter a command with a parameter: ");
            scanf("%ms%ms", &c, &p); //no need of allocating memory manually
            ...
            }





            share|improve this answer













            you can also use %ms instead of %s because it allocate memory itself and there is no need of allocation memory manually by programmer.



            int main(int argc, char **argv) {
            char *c, *p;

            printf("Enter a command with a parameter: ");
            scanf("%ms%ms", &c, &p); //no need of allocating memory manually
            ...
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 19 '18 at 16:51









            Susheel DwivediSusheel Dwivedi

            554




            554








            • 1





              "%ms" is a useful idea with libraries that employ this non-standard enhancement. difference between %ms and %s scanf. Note that code still should later free(c), free(p)

              – chux
              Nov 19 '18 at 18:47
















            • 1





              "%ms" is a useful idea with libraries that employ this non-standard enhancement. difference between %ms and %s scanf. Note that code still should later free(c), free(p)

              – chux
              Nov 19 '18 at 18:47










            1




            1





            "%ms" is a useful idea with libraries that employ this non-standard enhancement. difference between %ms and %s scanf. Note that code still should later free(c), free(p)

            – chux
            Nov 19 '18 at 18:47







            "%ms" is a useful idea with libraries that employ this non-standard enhancement. difference between %ms and %s scanf. Note that code still should later free(c), free(p)

            – chux
            Nov 19 '18 at 18:47




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53377940%2fscanf-only-reads-first-field%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to change which sound is reproduced for terminal bell?

            Can I use Tabulator js library in my java Spring + Thymeleaf project?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents