Pass the table to work with the pointer

advertisements

please help to fixed this program.I'm try to print array of pointer using pointer instead of array but i got this error:

enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault

this is the code:

#include <stdio.h>
#include <stdlib.h>

int *array;
int n;

void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);

int main (void) {
   int result;
   printf("enter number of element:");scanf("%d",&n);
   input(array,n);
   display(array,n);
   result=sum(array,n);
   printf("sum of array=%d",result);
   return 0;
}

void input(int *array,int n){
   int j;
   array=(int *)malloc(n*sizeof(int));
   for(j=0;j<n;j++){
        printf("array[%d]=",j);scanf("%d",array+j);
   }
}

void display(int *array,int n){
    int j;

    for(j=0;j<n;j++){
        printf("%d\t",*(array+j));
   }
    printf("\n");
}

 int sum(int *array,int n){
     int sum=0,j;

     for(j=0;j<n;j++){
       sum+=*array+j;
    }
    return sum;
}

how can i fixed this code? please somebody explain me what's wrong with that code


Variable array is a local variable in function input.

As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.

In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:

void input(int n)
{
    ...
    array = (int*)malloc(n*sizeof(int));
    ...
}

int main()
{
    ...
    input(n);
    ...
}

Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.