I've been lurking around here for a while, but this is my first post. I've been having trouble passing a pointer of a multidimensional array to a function. I think I got it, but i'd like to post it here to see if it's right. Here's the problem we were given:
Write a complete program and function for the following. You must use a #define for the size of the array. The program will prompt and let the user fill up a 4 x 4 array of integers. Then call a function called TWOES that will be passed a pointer to the array. Using this pointer you must traverse all memory locations in the array and count the element that are not evenly divisible by 2. The function will return this number of elements that not are divisible by 2. Back in main, the program will print out the value that is returned from the function.
note that the prototype for the function will look like this:
int TWOES( int * );
This is what I got:
Code:
#include <stdio.h>
#define ROW 4
#define COL 4
int numbers[ROW][COL]; /* Initialize the array */
int TWOES(int *); /* function prototype */
int main()
{
int rownum, colnum;
int count;
for (rownum = 0; rownum < ROW; rownum++)
{
for (colnum = 0; colnum < COL; colnum++)
{
printf("Please enter an integer:");
scanf ("%d", &numbers[rownum][colnum]); /* user input into array */
}
}
int *ptr;
ptr = &numbers[0][0];
count = TWOES(&ptr[0]); /*call the function */
printf("%d of your numbers are NOT divisible by 2\n",count); /* print value obtained from function */
return 0;
}
int TWOES(int *tempptr) /* function */
{
int r,c;
int count = 0;
for(r=0;r<ROW;r++)
{
for(c=0;c<COL;c++)
{
if(*tempptr % 2 != 0) /* running through the array and testing values */
{
count++;
}
tempptr++; /* Increasing by 4 bytes in memory through loop */
}
}
return (count); /* returning calculation to main() */
}
It works. I tested the values passed with printf functions, and they are passing the correct values, but is this right?