program outputs exit phrase instead of words stored in Cstrcmp not working for fgets file read input stringReversing words in a sentence using pointers using cCode does not output entire string but instead only a part of itReading Both Individual Characters of Strings and the Strings themselves Pointed to by a String ArrayHow to count Integer array elements like char based strlen() in C?C how to store words in a char pointer from the user inputCreating an array of strings using malloc in Cstrcpy(char*,char a[]) is giving incorrect output. (Reversing a string word by word)printf char array segment fault CStoring a string of words in a data structure

Were Alexander the Great and Hephaestion lovers?

What to do when surprise and a high initiative roll conflict with the narrative?

How can I get an unreasonable manager to approve time off?

Thread Pool C++ Implementation

Is it possible to have a wealthy country without a middle class?

Second (easy access) account in case my bank screws up

How to tell your grandparent to not come to fetch you with their car?

Certain search in list

Compiling C files on Ubuntu and using the executable on Windows

1980s live-action movie where individually-coloured nations on clouds fight

Can Rydberg constant be in joules?

Commas in clist_map_inline:nn split values in undesired places

Are there any important biographies of nobodies?

Overlapping String-Blocks

What speaks against investing in precious metals?

What is the actual quality of machine translations?

Did Milano or Benatar approve or comment on their namesake MCU ships?

How can I end combat quickly when the outcome is inevitable?

Is it possible to have the age of the universe be unknown?

How did old MS-DOS games utilize various graphic cards?

What's up with this leaf?

Wooden cooking layout

Paying more mana for a Flashed creature

What ways have you found to get edits from non-LaTeX users?



program outputs exit phrase instead of words stored in C


strcmp not working for fgets file read input stringReversing words in a sentence using pointers using cCode does not output entire string but instead only a part of itReading Both Individual Characters of Strings and the Strings themselves Pointed to by a String ArrayHow to count Integer array elements like char based strlen() in C?C how to store words in a char pointer from the user inputCreating an array of strings using malloc in Cstrcpy(char*,char a[]) is giving incorrect output. (Reversing a string word by word)printf char array segment fault CStoring a string of words in a data structure






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















So I was working on an assignment for school, and had written up a variation of this code:



#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100

// This program takes an input of strings and prints them out with a new line separating each one.

int main()
char *WordArray[MAX]; //initializing variables
int i = 0;
int count = 0;

printf("enter up to 100 words, that are 20 characters maximum n");

for (i = 0; i <100; i++) //runs while there's less than 100 inputs
char Array[1];
scanf("%s",Array); //stores string in the array
if (strcmp(Array, "STOP") == 0) //compares the string with stop, and if it is, it breaks out of the loop
break;

WordArray[i]=Array; //stores the string in the pointer array


printf("The output isn");
for (count = 0; count<i; count++) //counts up to the amount of words stored
printf("%sn",WordArray[count]); //outputs each pointer string




and I noticed that the output was printing "STOP" instead of the values stored. Anyone have any answers to why and/or how to fix it? I know one of the methods is to switch to a 2D array instead of using pointers, but I'm still baffled as to why a program like this wouldn't work.










share|improve this question






























    0















    So I was working on an assignment for school, and had written up a variation of this code:



    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    #define MAX 100

    // This program takes an input of strings and prints them out with a new line separating each one.

    int main()
    char *WordArray[MAX]; //initializing variables
    int i = 0;
    int count = 0;

    printf("enter up to 100 words, that are 20 characters maximum n");

    for (i = 0; i <100; i++) //runs while there's less than 100 inputs
    char Array[1];
    scanf("%s",Array); //stores string in the array
    if (strcmp(Array, "STOP") == 0) //compares the string with stop, and if it is, it breaks out of the loop
    break;

    WordArray[i]=Array; //stores the string in the pointer array


    printf("The output isn");
    for (count = 0; count<i; count++) //counts up to the amount of words stored
    printf("%sn",WordArray[count]); //outputs each pointer string




    and I noticed that the output was printing "STOP" instead of the values stored. Anyone have any answers to why and/or how to fix it? I know one of the methods is to switch to a 2D array instead of using pointers, but I'm still baffled as to why a program like this wouldn't work.










    share|improve this question


























      0












      0








      0








      So I was working on an assignment for school, and had written up a variation of this code:



      #include <stdio.h>
      #include <ctype.h>
      #include <string.h>
      #define MAX 100

      // This program takes an input of strings and prints them out with a new line separating each one.

      int main()
      char *WordArray[MAX]; //initializing variables
      int i = 0;
      int count = 0;

      printf("enter up to 100 words, that are 20 characters maximum n");

      for (i = 0; i <100; i++) //runs while there's less than 100 inputs
      char Array[1];
      scanf("%s",Array); //stores string in the array
      if (strcmp(Array, "STOP") == 0) //compares the string with stop, and if it is, it breaks out of the loop
      break;

      WordArray[i]=Array; //stores the string in the pointer array


      printf("The output isn");
      for (count = 0; count<i; count++) //counts up to the amount of words stored
      printf("%sn",WordArray[count]); //outputs each pointer string




      and I noticed that the output was printing "STOP" instead of the values stored. Anyone have any answers to why and/or how to fix it? I know one of the methods is to switch to a 2D array instead of using pointers, but I'm still baffled as to why a program like this wouldn't work.










      share|improve this question
















      So I was working on an assignment for school, and had written up a variation of this code:



      #include <stdio.h>
      #include <ctype.h>
      #include <string.h>
      #define MAX 100

      // This program takes an input of strings and prints them out with a new line separating each one.

      int main()
      char *WordArray[MAX]; //initializing variables
      int i = 0;
      int count = 0;

      printf("enter up to 100 words, that are 20 characters maximum n");

      for (i = 0; i <100; i++) //runs while there's less than 100 inputs
      char Array[1];
      scanf("%s",Array); //stores string in the array
      if (strcmp(Array, "STOP") == 0) //compares the string with stop, and if it is, it breaks out of the loop
      break;

      WordArray[i]=Array; //stores the string in the pointer array


      printf("The output isn");
      for (count = 0; count<i; count++) //counts up to the amount of words stored
      printf("%sn",WordArray[count]); //outputs each pointer string




      and I noticed that the output was printing "STOP" instead of the values stored. Anyone have any answers to why and/or how to fix it? I know one of the methods is to switch to a 2D array instead of using pointers, but I'm still baffled as to why a program like this wouldn't work.







      c






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 18:05









      Weather Vane

      27.7k52139




      27.7k52139










      asked Mar 24 at 18:01









      Jessy SiaJessy Sia

      853




      853






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Your char Array[1]; isn't large enough to store any but an empty string. Also, when it works, every pointer will point to the same string, which will be the last entry you made. This makes some corrections where commented.



          #include <stdio.h>
          #include <stdlib.h> // instead of ctype.h
          #include <string.h>

          #define MAX 100

          // This program takes an input of strings and prints them out with a new line separating each one.

          int main()
          char *WordArray[MAX];
          int i = 0;
          int count = 0;

          printf("enter up to 100 words, that are 20 characters maximum n");

          for (i = 0; i <100; i++)
          char Array[21]; // increase size of array
          scanf("%20s",Array); // limit entry length
          if (strcmp(Array, "STOP") == 0)
          break;

          WordArray[i] = strdup(Array); // allocate memory for and copy string


          printf("The output isn");
          for (count = 0; count<i; count++)
          printf("%sn",WordArray[count]);


          // free each string's memory
          for (count = 0; count<i; count++)
          free(WordArray[count]);




          Program output:



          enter up to 100 words, that are 20 characters maximum
          one two three STOP
          The output is
          one
          two
          three


          Edit: note that your code contains another undefined behaviour besides the too-short string char Array[1] which is that you dereference the pointer you stored in char *WordArray[MAX];. The scope of Array is inside the for loop, and theoretically ceases to exist after the loop completes, so the pointer you store is invalid. Here, the word entered is duplicated with strdup so that doesn't apply.




          share|improve this answer

























            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%2f55326827%2fprogram-outputs-exit-phrase-instead-of-words-stored-in-c%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Your char Array[1]; isn't large enough to store any but an empty string. Also, when it works, every pointer will point to the same string, which will be the last entry you made. This makes some corrections where commented.



            #include <stdio.h>
            #include <stdlib.h> // instead of ctype.h
            #include <string.h>

            #define MAX 100

            // This program takes an input of strings and prints them out with a new line separating each one.

            int main()
            char *WordArray[MAX];
            int i = 0;
            int count = 0;

            printf("enter up to 100 words, that are 20 characters maximum n");

            for (i = 0; i <100; i++)
            char Array[21]; // increase size of array
            scanf("%20s",Array); // limit entry length
            if (strcmp(Array, "STOP") == 0)
            break;

            WordArray[i] = strdup(Array); // allocate memory for and copy string


            printf("The output isn");
            for (count = 0; count<i; count++)
            printf("%sn",WordArray[count]);


            // free each string's memory
            for (count = 0; count<i; count++)
            free(WordArray[count]);




            Program output:



            enter up to 100 words, that are 20 characters maximum
            one two three STOP
            The output is
            one
            two
            three


            Edit: note that your code contains another undefined behaviour besides the too-short string char Array[1] which is that you dereference the pointer you stored in char *WordArray[MAX];. The scope of Array is inside the for loop, and theoretically ceases to exist after the loop completes, so the pointer you store is invalid. Here, the word entered is duplicated with strdup so that doesn't apply.




            share|improve this answer





























              1














              Your char Array[1]; isn't large enough to store any but an empty string. Also, when it works, every pointer will point to the same string, which will be the last entry you made. This makes some corrections where commented.



              #include <stdio.h>
              #include <stdlib.h> // instead of ctype.h
              #include <string.h>

              #define MAX 100

              // This program takes an input of strings and prints them out with a new line separating each one.

              int main()
              char *WordArray[MAX];
              int i = 0;
              int count = 0;

              printf("enter up to 100 words, that are 20 characters maximum n");

              for (i = 0; i <100; i++)
              char Array[21]; // increase size of array
              scanf("%20s",Array); // limit entry length
              if (strcmp(Array, "STOP") == 0)
              break;

              WordArray[i] = strdup(Array); // allocate memory for and copy string


              printf("The output isn");
              for (count = 0; count<i; count++)
              printf("%sn",WordArray[count]);


              // free each string's memory
              for (count = 0; count<i; count++)
              free(WordArray[count]);




              Program output:



              enter up to 100 words, that are 20 characters maximum
              one two three STOP
              The output is
              one
              two
              three


              Edit: note that your code contains another undefined behaviour besides the too-short string char Array[1] which is that you dereference the pointer you stored in char *WordArray[MAX];. The scope of Array is inside the for loop, and theoretically ceases to exist after the loop completes, so the pointer you store is invalid. Here, the word entered is duplicated with strdup so that doesn't apply.




              share|improve this answer



























                1












                1








                1







                Your char Array[1]; isn't large enough to store any but an empty string. Also, when it works, every pointer will point to the same string, which will be the last entry you made. This makes some corrections where commented.



                #include <stdio.h>
                #include <stdlib.h> // instead of ctype.h
                #include <string.h>

                #define MAX 100

                // This program takes an input of strings and prints them out with a new line separating each one.

                int main()
                char *WordArray[MAX];
                int i = 0;
                int count = 0;

                printf("enter up to 100 words, that are 20 characters maximum n");

                for (i = 0; i <100; i++)
                char Array[21]; // increase size of array
                scanf("%20s",Array); // limit entry length
                if (strcmp(Array, "STOP") == 0)
                break;

                WordArray[i] = strdup(Array); // allocate memory for and copy string


                printf("The output isn");
                for (count = 0; count<i; count++)
                printf("%sn",WordArray[count]);


                // free each string's memory
                for (count = 0; count<i; count++)
                free(WordArray[count]);




                Program output:



                enter up to 100 words, that are 20 characters maximum
                one two three STOP
                The output is
                one
                two
                three


                Edit: note that your code contains another undefined behaviour besides the too-short string char Array[1] which is that you dereference the pointer you stored in char *WordArray[MAX];. The scope of Array is inside the for loop, and theoretically ceases to exist after the loop completes, so the pointer you store is invalid. Here, the word entered is duplicated with strdup so that doesn't apply.




                share|improve this answer















                Your char Array[1]; isn't large enough to store any but an empty string. Also, when it works, every pointer will point to the same string, which will be the last entry you made. This makes some corrections where commented.



                #include <stdio.h>
                #include <stdlib.h> // instead of ctype.h
                #include <string.h>

                #define MAX 100

                // This program takes an input of strings and prints them out with a new line separating each one.

                int main()
                char *WordArray[MAX];
                int i = 0;
                int count = 0;

                printf("enter up to 100 words, that are 20 characters maximum n");

                for (i = 0; i <100; i++)
                char Array[21]; // increase size of array
                scanf("%20s",Array); // limit entry length
                if (strcmp(Array, "STOP") == 0)
                break;

                WordArray[i] = strdup(Array); // allocate memory for and copy string


                printf("The output isn");
                for (count = 0; count<i; count++)
                printf("%sn",WordArray[count]);


                // free each string's memory
                for (count = 0; count<i; count++)
                free(WordArray[count]);




                Program output:



                enter up to 100 words, that are 20 characters maximum
                one two three STOP
                The output is
                one
                two
                three


                Edit: note that your code contains another undefined behaviour besides the too-short string char Array[1] which is that you dereference the pointer you stored in char *WordArray[MAX];. The scope of Array is inside the for loop, and theoretically ceases to exist after the loop completes, so the pointer you store is invalid. Here, the word entered is duplicated with strdup so that doesn't apply.





                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 24 at 18:39

























                answered Mar 24 at 18:13









                Weather VaneWeather Vane

                27.7k52139




                27.7k52139





























                    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%2f55326827%2fprogram-outputs-exit-phrase-instead-of-words-stored-in-c%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

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해