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:

Recommended Answers

All 4 Replies

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

commented: Yes, that's the solution :) +10
commented: thanks +2

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.

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 */
commented: thanks +2

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.