Passing array to function using pointer - c

I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
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.

To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}

Try this input():
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);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).

this should do..make sure you understand what the others have said..
#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= 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)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}

What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].

Related

How to print a 2D array?

I have two functions. One that creates a multiplication table of a given number and the other function prints the array out. Below is my code:
Here's the error (Line 18):
expression must be a pointer to a complete object type
How do I fix this error and print the array? Also, I don't know how to print a new line after every row.
#include "multiplication.h"
#include <stdio.h>
int arr[][];
void mulitpication(int num){
/* initialize array and build*/
int arr[num][num];
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int arr[][]){
/* print the arr*/
int i;
for(i=0;i<sizeof(arr);i++){
for(int j=0;j<sizeof(arr);j++){
printf("%d ",arr[i][j])**(line 18)**;
}
}
}
If using C99 or later with VLA support, pass into the print function the dimensions needed.
// void print(int arr[][]){
void print(size_t rows, size_t cols, int arr[row][col]){
size_t r,c;
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) {
printf("%d ",arr[r][c]);
}
printf("\n");
}
}
You need to declare the array in main(), so it can be passed to both functions.
When an array is passed as a function parameter, it just passes a pointer. You need to pass the array dimensions, they can't be determined using sizeof.
To get each row of the table on a new line, put printf("\n"); after the loop that prints a row.
#include <stdio.h>
void multiplication(int num, arr[num][num]){
/* initialize array and build*/
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int num, int arr[num][num]){
/* print the arr*/
int i;
for(i=0;i<num;i++){
for(int j=0;j<num;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main(void) {
int size;
printf("How big is the multiplication table? ");
scanf("%d", &size);
int arr[size][size];
multiplication(size, arr);
print(size, arr);
return 0;
}

Using pointers as a dynamically allocated array

I'm trying to write a program that dynamically allocates memory for an array, which the user then fills with integer values and the program sorts said integer values. However, it seems that my array isn't working as intended. I have managed to get the program working with a static array, but the dynamic allocation is causing me a lot of problems with incorrect values and whatnot. Here's what I have so far for the dynamically allocated version (if it would help you guys, I can also provide the version that uses a static array):
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
void sortArray (int *numbers, int i2);
int indexMax (int *numbers, int low, int high);
void swap (int *num1, int *num2);
int getArray (int *numbers);
void displayArray (int *numbers, int i2);
main()
{
int *numbers, i2;
i2=getArray(numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
}
int getArray (int *numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
i2=GetInteger();
numbers=(int *)malloc(i2*sizeof(int));
for(i=0;i<i2;i++, numbers++)
{
printf("Enter next integer: ");
*numbers=GetInteger();
printf("\n");
}
return(i2);
}
void displayArray (int *numbers, int i2)
{
int i;
printf ("\nThe sorted list is: \n\n");
for (i=0;i<i2;i++, numbers++)printf ("%d\n", *numbers);
}
void sortArray (int *numbers, int i2)
{
int i, minInd;
for(i=0;i<i2;i++)
{
minInd=indexMax(numbers, i, i2-1);
swap(&numbers[i], &numbers[minInd]);
}
}
int indexMax (int *numbers, int low, int high)
{
int i, maxInd;
maxInd=high;
for (i=high;i>=low;i--)
{
if(*(numbers+i)>*(numbers+maxInd)) maxInd=i;
}
return (maxInd);
}
void swap (int *num1, int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
}
Here is a working solution:
#include <stdio.h>
#include <stdlib.h>
void sortArray (int *numbers, int i2);
int indexMax (int *numbers, int low, int high);
void swap (int *num1, int *num2);
int getArray (int **numbers);
void displayArray (int *numbers, int i2);
main()
{
int *numbers, i2;
i2=getArray(&numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
}
int getArray (int **numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
scanf("%d", &i2);
(*numbers) = malloc(i2 * sizeof(int));
int *temp = *numbers;
for(i = 0; i < i2; i++)
{
printf("Enter next integer: ");
scanf("%d", &temp[i]);
printf("\n");
}
return(i2);
}
void displayArray (int *numbers, int i2)
{
int i;
printf ("\nThe sorted list is: \n\n");
for (i=0;i<i2;i++, numbers++)printf ("%d\n", *numbers);
}
void sortArray (int *numbers, int i2)
{
int i, minInd;
for(i=0;i<i2;i++)
{
minInd=indexMax(numbers, i, i2-1);
swap(&numbers[i], &numbers[minInd]);
}
}
int indexMax (int *numbers, int low, int high)
{
int i, maxInd;
maxInd=high;
for (i=high;i>=low;i--)
{
if(*(numbers+i)>*(numbers+maxInd)) maxInd=i;
}
return (maxInd);
}
void swap (int *num1, int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
}
The thing is in your main when you are declaring int *numbers , numbers pointer is pointing to some junk memory location as local variables can have any garbage value, so while you are passing this numbers pointer to getArray() function you are passing its value, Suppose numbers is pointing to some random value = 1234 and suppose address of numbers is = 9999. Now when you call getArray(numbers) you tell taht whatever is there in numbers pass it to getArray's numbers variable that we are letting is 1234.
Then when you allocate memory to numbers that is local variable of getArray() function not main's and it might have address suppose = 0x8888. Then malloc allocates some address space as specified and stores the start address of that allocated address space(suppose i.e. = 0x7777) into location 0x8888 not 0x9999 which is the adress of main's numbers variable.
Thus when the getArray function ends and next time you call sortArray you pass it value present in numbers variable of main which is still junk 1234. and the actual value you should be passing is present at address 0x8888.
Try this:
int main(void)
{
int *numbers, i2;
i2 = getArray(&numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
return 0;
}
int getArray (int **numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
i2 = GetInteger();
*numbers = malloc(i2 * sizeof int);
etc...
You simply need one more level of indirection to make int getArray(int**) return a pointer to an allocated array.
As an aside, you can use the C library function qsort() to do the sorting work for you. Here is an example:
int main(void)
{
int a[]={4,7,9,1,34,90,66,12};
qsort(a, sizeof(a)/sizeof(a[0]), sizeof(int), compare);
return 0;
}
int compare(const void *a, const void *b){
const int *x = a, *y = b;
if(*x > *y)
return 1;
else
return(*x < *y) ? -1: 0;
}
Works just as well with dynamically allocated int arrays, or char arrays

using #define in functions

How do i make it so that i can use #define variables in my functions? I need to create a program that calls upon functions with this code. Basically my functions at the bottom can change but my main function cannot change from this kind of format, so however i write my functions i have to pass the variable a and variable SIZE through the functions. But current it seems that SIZE is not actually recognized as an int variable.
#include <stdio.h>
#define SIZE 9
int i, position, tmp;
void readArray(int a[]);
void printArray(int a[]);
void sortArray(int a[]);
int main(void)
{
int a[SIZE];
readArray(a);
printArray(a);
sortArray(a);
printf("After sorting:\n");
printArray(a);
return 0;
}
//Functions//
void readArray(int a[]){
printf("Please enter %d integers: ", SIZE);
for (i=0; i<SIZE; i++) {
scanf("%d", &a[i]);
}
}
void printArray(int a[]){
for (i=0;i<SIZE;i++) {
printf("a[%d] = %3d\n", i, a[i]);
}
}
void sortArray(int a[]){
for (i=0; i<SIZE; i++) {
// In each iteration, the i-th largest number becomes the i-th array element.
// Find the largest number in the unsorted portion of the array and
// swap it with the number in the i-th place.
for (position=i; position<SIZE; position++) {
if (a[i] < a[position]) {
tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
}
}
}
Writing
#define SIZE 9
will tell the preprocessor to replace each appearance of SIZE with 9.
meaning, the following line -
void sortArray(int a[], int SIZE)
will be replaced with -
void sortArray(int a[], int 9)
I assume you understand this is illegal.
You should just delete the second function parameter.
You should rename the C variables to something other than SIZE. This is already used by the preprocessor. Also, watch out because you've written Int instead of int.

Passing an array as an argument to a function pointer in C

I'm currently studying pointers to functions and have been practicing on sort array functions.
The point is I input a sequence of numbers into the function and the program will re arrange it in ascending order. It worked just fine when I do a call by value function (I think that's how you call it). However when I try to assign a pointer to function and try to use that pointer instead of the function itself, it returns a bunch of errors. I'm sure the problem is due to the fact that I'm passing an array as an argument to the function POINTER. Here is my code:
#include<stdio.h>
#define SIZE 10
void sort(int a[], int size);
void swap(int *elt1, int *elt2);
main()
{
int i; int array[SIZE]= {1,9,3,2,4,100,43,23,32,12};
void (*fptr)(int array, int SIZE);
fptr = &sort;
(*fptr)(array,SIZE);
/*sort(array, SIZE);*/
for(i=0;i<SIZE;i++)
{
printf("%d\n", array[i]);
}
return 0;
}
void sort(int a[], int size)
{
int pass, j;
for(pass = 0; pass<size;pass++)
{
for(j=0;j<size;j++)
{
if(a[j]>a[j+1])
{
swap(&a[j], &a[j+1]);
}
}
}
}
void swap(int *elt1, int *elt2)
{
int hold;
hold = *elt1;
*elt1 = *elt2;
*elt2 = hold;
}
The first argument of the function is a pointer to int (that is, int *), and not int.
void (*fptr)(int array, int SIZE);
should be
void (*fptr)(int *array, int SIZE);

Print 2d array by calling a function print_array with argument the 2d array

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define length 100
void print_array();
int main()
{
int m,n,i,j;
int A[length][length];
printf("Give dimensions of array (up to 100x100):\ni:\n");
scanf("%d",&i);
printf("j:\n");
scanf("%d",&j);
srand(time(NULL));
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
print_array(i,j,A);
return 0;
}
void print_array(int i,int j,int A[][j])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
Hello. I am trying to print a 2d array by calling a function print but when I run the program I get:
For the first printf() the correct values:
A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=4
A[1,1]=17
A[1,2]=43
A[2,0]=7
A[2,1]=37
A[2,2]=20
But when with the 2nd printf() within the function call of print_array I get:
A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=0
A[1,1]=0
A[1,2]=0
A[2,0]=0
A[2,1]=0
A[2,2]=0
Seems like I miss something with pointers... Thanks.
This is C99, right?
The problem is that you're confusing the array size.
The main program has int A[length][length], but then you call the function with a dynamic size for the final dimension, A[][j]. If j != length, then the function will index the array incorrectly.
I would recommend representing the array in the function call as a bare pointer to the first element, and doing the indexing manually:
void print_array(const int *A, size_t width, size_t height)
{
for(size_t i = 0; i < height; ++i)
{
for(size_t j = 0; j < width; ++j)
printf("A[%zu][%zu] = %d\n", i, j, A[i * width + j]);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <time.h>
#define length 100
void print_array(int i,int j,int A[length][length]);
int main()
{
int m,n,i,j;
int A[length][length];
printf("Give dimensions of array (up to 100x100):\ni:\n");
scanf("%d",&i);
printf("j:\n");
scanf("%d",&j);
srand(time(NULL));
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
print_array(i,j,A);
return 0;
}
void print_array(int i,int j,int A[length][length])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
Apart from the above, you need to do some input validation for the dimension (i and j). They should not exceed the length. If it exceeds the length then you will run into problems.
void print_array(int i,int j,int A[][j])
should be
void print_array(int i,int j,int A[][length])
When you tell the compiler that the actual array has different dimensions than what you earlier specified, it accesses the wrong elements. A is always 100x100, you just don't fill all of it.
You need to define the size of the array int A[][] in the function signature. Use this function instead :
void print_array(int i,int j,int A[length][length])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
First you should forward declare your function with the correct prototype
void print_array(int n,int m, int A[n][m]);
And then use it with the correct dimensions
print_array(length, length, A);
Other than that:
use size_t for sizes instead of int
usual naming conventions have i and j as indices and n and m
as sizes. Sticking to such conventions makes code easier to read for others.
You've declared A as int A[length][length], But in the print_array function you've declare it as A[][j] which means in your function A have a different number of colones which leads to this error.
change this line
void print_array(int i,int j,int A[][j])
with this one
void print_array(int i,int j,int A[][length])
http://www.cplusplus.com/doc/tutorial/arrays/
array and matrix printing functions are little similar but tricky..
but i have worked on it and found out some thing and i think it will be useful for all
here is a simple C code for Function for printing matrix
#include<stdio.h>
void printmatrix(int l,int x,int y,int *p_arr);
void putvalue(int l,int x,int y,int *r_arr);
/* ******** Function to insert some random value in to a Matrix ************ */
void putvalue(int l,int x,int y,int *r_arr)
{
int i,j;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
r_arr[(l*i)+j]=i+j+10;
}
}
}
/* *********Function to Print any Matrix ********** */
void printmatrix(int l,int x, int y,int *p_arr)
{
int i,j;
printf("\n");
for(i=0;i<x;i++)
{
printf("\n");
for(j=0;j<y;j++)
{
printf(" %d",p_arr[(l*i)+j]);
}
}
}
/* ****** Main ****** */
void main()
{
int i,j,l;
int Big_arr[80][100],Small_arr[20][40];
// ****** I have taken two different size arrays *****
int x,y;
clrscr();
printf("\n Enter x and y values under 20X40:"); // Because of screen size of Output
scanf("%d %d",&x,&y);
if((x!=0)&&(y!=0))
{
printf("\n %dX%d",x,y);
l=sizeof(Big_arr[0])/sizeof(Big_arr[0][0]); // **** l is the length of a single row of matrix
putvalue(l,x,y,(int*)Big_arr);
printf("\n Printing Big_arr");
printmatrix(l,x,y,(int*)Big_arr);
l=sizeof(Small_arr[0])/sizeof(Small_arr[0][0]);
putvalue(l,x,y,(int*)Small_arr);
printf("\n Printing Small_arr");
printmatrix(l,x,y,(int*)Small_arr);
}
else
printf("\n ***** Enter valied x and y values *****");
getch();
}
hope u like it.

Resources