954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Number tally in an array

Writting a program which involves tallying generated numbers. I'm having problems with the tallying part. It takes a number, and finds it in the second row of an array, and tallies (add 1) to the same position in the first row. Here's my extracted code:

#include <stdio.h>

void tally(int number, int output[][2]);  /* variable length */

int main() {
  int array[4][2];
  array[0][1] = 4;
  array[1][1] = 3;
  array[2][1] = 2;
  array[3][1] = 1;
  
  tally(2, array);
  tally(2, array);
  tally(1, array);
  tally(4, array);

  printf("%d, %d, %d, %d\n", array[0][0], array[1][0], array[2][0],
                             array[3][0]);
  
  return 0;
}

void tally(int number, int output[][2]) {
/* This function will find a number on the second row, and tally (add 1) to its equivalent place on the first row. */
   
  int count = 0;

  while(1) {
    if(output[count][1] == number) {
      output[count][0]++;
      return;
    }
    count++;
  }
}

Yes I know it has no security yet, so don't pass a number which isn't in the array.
The program seems to print out either random memory locations, or random pointers:

-1074781680, -1074781672, -1074781664, -1074781656

Any Idea's? Thanks.:confused:

Hiroshe
Posting Whiz in Training
256 posts since Jun 2008
Reputation Points: 431
Solved Threads: 17
 

Your 1st half of the array array[x][0] is never initialized to zero so the values start out with garbage.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

When you set a pointer and don't always use every "point" in it(especially while dealing with user input), you need memset() to set a default value.

MosaicFuneral
Posting Virtuoso
1,691 posts since Nov 2008
Reputation Points: 888
Solved Threads: 116
 
you need memset() to set a default value.


memset() is not needed. You can do it without calling a function by using an initializer for the array:

int array[4][2] = {0}; /* init all elements to 0 */
Tom Gunn
Master Poster
733 posts since Jun 2009
Reputation Points: 1,446
Solved Threads: 135
 

Thanks guy's. Works like a charm. :)

Hiroshe
Posting Whiz in Training
256 posts since Jun 2008
Reputation Points: 431
Solved Threads: 17
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You