Reputation: 33
Here is the code, which fills an array with input numbers and outputs it. All these previous functions are executed with pointers, but the last function, which is supposed to print the numbers in a certain row, has some kind of a bug. It doesn't print the last row of the array, since array become 3x3 sort. What is the problem and how could I fix it? And what can you say about code itself. Is it flex, maintainable and useful or vice versa?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int** MAC_ROS(int str,int col);
int* task(int strm,int colm);
int* getNumber(int *p,int colm);
void GET_NUMBER(int *pointer,int col,int rowDestination);
void OUT(int *p,int str,int col);
int *point=NULL;
int arr[20][20];
int main(void){
int col,str,rowDestination;
printf("Input columns="); scanf("%d",&col);
printf("Input strings="); scanf("%d",&str);
point=task(str,col);
printf("rowDestination="); scanf("%d",&rowDestination);
GET_NUMBER(point,col,rowDestination);
}
int* task(int strm,int colm)
{
int *MAS_POINT;
MAS_POINT=(int*)MAC_ROS(strm,colm);
OUT(MAS_POINT,strm,colm);
return MAS_POINT;
}
int** MAC_ROS(int str,int col)
{
int a=0;
int *point,**el;
point=(int*)malloc(col*str*sizeof(int));
el=(int**)point;
for(int i=0;i<str;i++)
{
point=point+str*i;
for(int j=0;j<col;j++)
{
scanf("%d",&a);
*(point+j)=a;
}
}
return el;
}
void OUT(int *p,int str,int col)
{
for(int i=0;i<str;i++)
{
p=p+str*i;
for(int j=0;j<col;j++)
{
printf("%d ",*(p+j));
}
printf("\n");
}
}
void GET_NUMBER(int *pointer,int col,int rowDestination)
{
pointer=pointer+((rowDestination-1)*col);
for(int t=0;t<col;t++)
{
printf("%d ",*(pointer+t));
}
}
Upvotes: 0
Views: 60
Reputation: 182865
Your code in OUT
is:
void OUT(int *p,int str,int col)
{
for(int i=0;i<str;i++)
{
p=p+str*i;
for(int j=0;j<col;j++)
{
printf("%d ",*(p+j));
}
printf("\n");
}
}
To get to the next row, you can either add one row to the previous pointer or you can add an increasing number of rows to the original pointer. You, however, add an increasing number of rows to the original pointer, which won't work.
To get to the next row, you need to add on the number of columns. If the array has 8 columns, then to get to the next row, you need to 8 to the previous row to skip over each of the 8 columns in that row.
Possible fixes:
void OUT(int *op,int str,int col)
{
for(int i=0;i<str;i++)
{
int *p = op + col * i;
for(int j=0;j<col;j++)
{
printf("%d ",*(p+j));
}
printf("\n");
}
}
Or:
void OUT(int *p,int str,int col)
{
for(int i=0;i<str;i++)
{
for(int j=0;j<col;j++)
{
printf("%d ",*(p+j));
}
printf("\n");
p=p+col;
}
}
Or even:
void OUT(int *p,int str,int col)
{
for(int i=0;i<str;i++)
{
for(int j=0;j<col;j++)
{
printf("%d ",*p);
p++;
}
printf("\n");
}
}
Upvotes: 1