I am trying to make a program which accepts an input number from a user. This number will then be used as the variable in a 2-dimensional array grid.
What I am having problems with is after I compile I get a memory error. I am setting the values of the elements using a pointer to the array inside a function (have to for project). I assume it has to do with the memory manipulation with pointers but I just cannot work this out.
Good catch jmc, I stared at it for a few minutes and couldn't find that. Should have been x++ in the second for loop. That is a major problem!
Another issue that is not major but could be a problem later is the lack of initialization of the array. Since only some elements are updated in the for loops, the rest could contain garbage.
Oh man.. I am an idiot... lol.. Thanks alot for catching that, jmc and thanks for the suggestion kempofighter. I am not sure if not initializing the arrey will pose any kind of problem for the reason that those elements not initialize are not used.
Edit: Yeah that did the trick... (I really should examine my code harder before I ask for help)
Here is the completed code body, for the records..
//A program that uses pointers to output an array of numbers.
//By: Boon
//Include statements
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
//Function Prototypes
void display(int *addr, int num);
void create_symm(int *addr, int num);
//The Main Function
int main(int argc, char* argv[])
{
//Variable Declarations
int matrix, arey[10][10];
int *addy=0;
//Assigning Address to Pointer
addy=&arey[0][0];
//Getting User Input
printf("Enter matrix dimension (1-10) or 0 to quit==> ");
scanf("%i",&matrix);
printf("\n");
//Calling Function that uses pointer to sort out array
create_symm(addy, matrix);
//Calling Function to display array
display(addy, matrix);
//"Press any key to continue"
printf("\n");
system("PAUSE");
return 0;
}
//Definition for function which uses pointers to modify array
void create_symm(int *addr, int num)
{
//Variables for the "For Loops"
int i,x;
//Loop that controls the Columns
for(i=0; i<num;i++ )
{
//Loop that controls the Rows
for (x=0; x<num ; x++) {
//If statement which ensures that the correct number is subtracted from num
if (x>i) {
*addr=num-(x-i);
}
else *addr=num-(i-x);
addr++;
}
}
}
//Definition for function which outputs the array
void display(int *addr, int num)
{
//Variables for the "For Loops"
int i,x;
//Loop which controls the Columns
for(i=0; i<num;i++ )
{
//Loop which controls the Rows
for (x=0; x<num ; x++) {
//Prints the current number
printf("%i ", *addr);
//Moves the pointer up one memory address
addr++;
}
//New-Line for Column loop
printf("\n");
}
}