Jump to content
  • Advertisement
Sign in to follow this  
drjulio2002

Trying to store numbers in an array of Integers!

This topic is 4830 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello Everyone! I was woundering why is the following code returning me a memory address of the variable interger instead of storing the number itself in the array of integers?
      int c, i, length_word, number_word;
      int length_of_word[]={0};
      
      c = length_word = number_word = 0;
      while((c = getchar()) != EOF)
      {
               if(c != ' ' && c != '\n')
               {
                 length_word++;    
               }
               
               if(c == '\n' || c == ' ')
               {
                    number_word++;
                    length_of_word[number_word] = length_word;
                    printf("%d",length_of_word[number_word]);
                    length_word=0;
               } 
       }

Share this post


Link to post
Share on other sites
Advertisement
Quote:
int length_of_word[]={0};


Your array contains only enough room for a single element. Writing past the end of the array is a serious error: the program may be using these memory locations for other variables.

Share this post


Link to post
Share on other sites
Yes, set the length of the array to a larger number. e.g. int length_of_word[80]

Alternatively look up dynamic arrays.

Share this post


Link to post
Share on other sites
the problem is with this line:
int length_of_word[]={0};

Because you left no number between [ and ], it automatically fills in the size of the array as 1 because you only initiliazed 1 member, the 0. It's the same as:
int length_of_word[1]={0};

Put something like:

int length_of_word[100]={0};

And you won't have many problems. I also agree, go look up dynamic arrays.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!