Here is the problem:write in saparate function without using global variable
1/(function input)enter N in the range [0,20], then enter N numbers
2/(function display)Display N numbers in 2 columns
Here is my source code

#include<stdio.h>
#include<conio.h>
void Input(int *p,int n)
{
    int i;
    do
    {
     printf("Enter N numbers u want to input: ");
     scanf("%d",&n); 
    }while ( (n<0) || (n>20) );
    p =(int *)malloc(n*sizeof(int));
    printf("Ennter %d numbers: ",n);
    for( i=0; i<n; i++)
    {
         printf("\nNumber%: ",i);
         scanf("%d",p+i);
    }
    
}

void Display(int *p, int n)
{
     int i;
     printf("test");
     for( i=0; i<n; i++)
     {
        printf(" %d",p[i]);  
     }
}

int main()
{
  int *a, *N;
  Input(a,&N);
  Display(a,&N);
  getch();
  return 0;
}

I don't know how can I use the variable N in function input for the next function.

Recommended Answers

All 3 Replies

int main()
{
  int *a, *N;
  Input(a,&N);
  Display(a,&N);
  getch();
  return 0;
}

&N really means "the address of the pointer N". Your code shouldn't even compile because Input() expects an int for the second parameter. So what if Input() returns the value of N?

Oh, now I have one solution for that:

#include<stdio.h>
#include<conio.h>
#define MAX 20

int Input_N(int n)
{
    do
    {
     printf("Plz enter N in the range [0,20]");
     printf("Enter N numbers u want to input: ");
     scanf("%d",&n); 
    }while ( (n<0) || (n>20) );
     return n;
}

int (*input_n)(int) = Input_N;

void Get_N(int p[], int n)
{
    int i;
    printf("Ennter %d numbers: ",n); 
    for( i=0; i<n; i++)
    {
         printf("\nNumber%: ",i);
         scanf("%d",&p[i]);
    }
    for( i=0; i<n; i++)
    {
        printf(" %d",p[i]);  
    }
}

int main()
{
  int a[MAX],N;
  Get_N(a,input_n(N));
  getch();
  return 0;
}

My apologies, my advice was not very good. Your original solution is very close but with a few minor tweaks.

Your main should include this (note that N is no longer defined as a pointer and you are not passing in it's address to Display).

int *a, N;
Input(a,&N);
Display(a,N);

Now Input() has to accept a pointer N as one parameter. Inside the function, you need to set the actual value that N points to. Pointers can be confusing at first, lets see what you come up with.

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.