This question already has answers here:
Manipulate multidimensional array in a function
(4 answers)
Closed 8 years ago.
Could anyone explain why this doesn't print correctly?
This is basic program with functions to read and print an array. All seems to be according to what I read...
I'm new and can't seem to make pointers work.
Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#define SIZE 2
void readArray(int *a);
void printArray(int *a);
int main (int argc, char *argv[])
{
int array[SIZE][SIZE];
readArray(&array[SIZE][SIZE]);
printf("Array [1][2] = %d.\n\n\n", array[1][2]);
printArray(&array[SIZE][SIZE]);
system ("PAUSE");
return 0;
}
void readArray(int *a)
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
printf("Array [%d] [%d]: ", i, j + 1);
scanf("%d \n",&a);
}
}
}
void printArray(int *a)
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
printf("Array [%d] [%d]: ", i, j + 1);
printf("%d \n",*a);
}
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[2][2];
printf("Enter array\n");
for(i=0;i<2;i++) //take condition i<2 because of your default size
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Printing array\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
getch();
}
try this code
Related
I can't figure out how to print array elements from my function into the main program so if some can examine this code and help me fix it I would appreciate it. The program is supposed to take the length of the array from user input and then ask for its elements and print them out afterward.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int arrayN(int N) {
printf("Input array lenght: ");
scanf("%d",&N);
if(N>2) {
return N;
} else {
return 0;
}
}
int arrayelements(int array[], int array_length) {
int loop, i, N;
array_length = arrayN(N);
printf("Enter elements of the array: \n");
for(int i = 0; i < array_length; ++i) {
scanf("%d", &array[i]);
}
for(loop = 0; loop < array_length; loop++) {
printf("%d ", array[loop]);
}
}
int main() {
int N, array[], array_length;
int b = arrayelements(array[], array_length);
int a = arrayN(N);
printf("Array length is: %d \n", a);
printf("Elements of array are: %d \n", b);
return 0;
}
I reworked your example code. Hope it is what you want.
Focus lied on fixing the array declaration issues, memory allocation and
user input.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
int userinput_integer(const char *fmt, ...){
int N, rv = 0;
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
while(1){
rv = scanf("%d", &N);
if (1 == rv) break;
printf("Input error! The input >>");
do{
rv = fgetc(stdin);
if (isprint(rv)) putchar(rv);
}while(rv != EOF && rv != '\n');
printf("<< is not a valid integer.\nPlease try again: ");
}
va_end(va);
return N;
}
int userinput_arraylength(void) {
int N;
N = userinput_integer("Input array lenght: ");
if(N>2) {
return N;
} else {
printf("Invalid length\n");
return 0;
}
}
int userinput_arrayelements(int *array, int N) {
printf("Enter elements of the array: \n");
for(int i = 0; i < N; ++i) {
array[i] = userinput_integer("%d: ", i);
}
return N;
}
void print_arrayelements(int *array, int N){
for(int i = 0; i < N; ++i) {
printf("%d ", array[i]);
}
}
int main() {
int N, *array;
N = userinput_arraylength();
array = malloc(N * sizeof(*array));
if (NULL == array){
printf("Allocation error!\n");
exit(-1);
}
N = userinput_arrayelements(array, N);
printf("Array length is: %d \n", N);
printf("Elements of array are:\n");
print_arrayelements(array, N);
free(array);
return 0;
}
Fistly, declaration of array is not correct.
It should be array[] = {0}
Secondly, you cannot call your array elements function before arrayN function, the size of array should be entered first
And in the array elements() there is no need to call the size function you can directly pass the size of array when calling the array elements ()
Here's the code:
#include <stdio.h>
#include<malloc.h>
int *getarray()
{
int size;
printf("Enter the size of the array : ");
scanf("%d",&size);
int *p= malloc(sizeof(size));
printf("\nEnter the elements in an array");
for(int i=0;i<size;i++)
{
scanf("%d",&p[i]);
}
return p;
}
int main()
{
int *ptr;
ptr=getarray();
int length=sizeof(*ptr);
printf("Elements that you have entered are : ");
for(int i=0;ptr[i]!='\0';i++)
{
printf("%d ", ptr[i]);
}
return 0;
}
C program for bubble sort using a minimum of 4 functions.(input,output,compute,main)
No global variables allowed.
No printf or scanf in compute.
No printf or scanf in main
Input should not call compute.
compute should not call output.
I haven't really understood pointers and functions.
#include <stdio.h>
void input(int* size, int* arr[])
{
printf("Enter the size of the array: ");
scanf("%d",size);
printf("Enter the elements of the array\n");
for(int i = 0;i < *size; i++)
{
scanf("%d", arr[i]);
}
}
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubble_sort(int arr[100],int size)
{
for(int i = 0;i < size - 1;i++)
{
for(int j = 0;j < size - 1 - i;j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}
void output(int size,int* arr)
{
printf("Sorted array\n");
for(int i = 0;i < size;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int* input_values[50];
int size;
input(&size, input_values);
bubble_sort(size,*input_values);
output(size, *input_values);
return 0;
}
No errors but showing segmentation fault.How do I solve this?
So your problem is here :
scanf(" %d", arr[i]);
You have to change this to :
scanf(" %d", &arr[i]);
This is the main problem, but there are a lot of others.
Also you have to change the order of parameters in
bubble_sort(size,*input_values);
to
bubble_sort(input_values,size);
and
output(size, *input_values);
to
output(size, input_values);
Also in order this to work at all i have changed the
scanf("%d", &arr[i]);
to
scanf(" %d", &arr[i]);
Actually your code is full of mistakes like the usage of scanf and the usage of pointers and arrays, the following is a workable version of you code see and compare:
#include <stdio.h>
void input(int* size, int arr[])
{
char chr;
printf("Enter the size of the array: ");
scanf( "%d%c", size, &chr );
printf("Enter the elements of the array\n");
for(int i = 0;i < *size; i++)
{
scanf("%d%c", &arr[i], &chr);
}
}
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubble_sort(int* size,int arr[])
{
for(int i = 0;i < *size - 1;i++)
{
for(int j = 0;j < *size - 1 - i;j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}
void output(int* size,int arr[])
{
printf("Sorted array\n");
for(int i = 0;i < *size;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int input_values[50];
int s = 0;
int* size = &s;
input(size, input_values);
bubble_sort(size,input_values);
output(size, input_values);
return 0;
}
I have an array
arr[]={7,5,-8,3,4};
And I have to update the same array to
arr[]={7,12,4,7,11};
my code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int sumArr(int *arr, int size);
void main()
{
int arr[] = { 7,5,-8,3,4 };
int i, size, res = 0;
printf("Enter Size Of The Array:");
scanf("%d", &size);
res = sumArr(arr, size);
for (i = 0; i < size; i++)
{
printf("%d\n", res);
}
}
int sumArr(int *arr, int size)
{
int i;
for (i = 0; i < size; i++)
{
arr[i+1]+= arr[i];
printf(" %d \n", arr[i + 1]);
}
return arr[i+1];
}
The output should be: 7,12,4,7,11
But in my code, the output is: 12,4,7,11,-858993449,58196502,58196502,58196502,58196502,58196502
Any hints?
I can use auxiliary functions for input and output arrays, will it help?
You have several mistakes in your code:
You need to stop the summing loop once i+1 reaches the end of the array
Your code knows the size; there is no need to read it from end-user
You need to print the value of res once, rather than printing it in a loop
You should consider moving the printing portion of the program into main from sumArray.
The modifications are very straightforward:
int sumArr(int *arr, int size) {
// Stop when i+1 reaches size; no printing
for (int i = 0; i+1 < size; i++) {
arr[i+1]+= arr[i];
}
return arr[size-1];
}
Printing in the main:
printf("sum=%d\n", res);
for (int i = 0; i < size; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
Demo.
I feel like I've attempted every combination I know of to get this to work and can't figure it out. How can I scanf() into an int** passed as a pointer to a function? I tried searching but couldn't find this, if it's a duplicate please let me know and I'll delete. It begins to run and after entering a few values it segfaults.
Here's my code, I think it's messing up on the scanf() line of the setMatrix() function:
#include <stdio.h>
#include <stdlib.h>
// create zero initialized matrix
int** callocMatrix(int rmax, int colmax) {
int **mat = calloc(rmax, sizeof(int*));
for(int i = 0; i < rmax; i++) mat[i] = calloc(colmax, sizeof(int));
return mat;
}
// fill matrix
void setMatrix(int ***mat, int r, int c){
printf("Insert the elements of your matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("Insert element [%d][%d]: ", i, j);
scanf("%d", mat[i][j]); // problem here??
printf("matrix[%d][%d]: %d\n", i, j, (*mat)[i][j]);
}
}
return;
}
// print matrix
void printMatrix(int ***mat, int r, int c){
for (int i=0; i<r;i++){
for (int j=0; j<c;j++) {
printf("%d ", (*mat)[i][j]);
}
printf("\n");
}
}
int main(int argc, char *argv[]) {
int r = 3, c = 3;
int **mat = callocMatrix(r, c);
setMatrix(&mat, r, c);
printMatrix(&mat, r, c);
}
There is no need to use triple pointer ***. Passing two-dimensional array will work as is. Here is the code:
#include <stdio.h>
#include <stdlib.h>
// create zero initialized matrix
int** callocMatrix(int rmax, int colmax) {
int **mat = calloc(rmax, sizeof(int*));
for(int i = 0; i < rmax; i++) mat[i] = calloc(colmax, sizeof(int));
return mat;
}
// fill matrix
void setMatrix(int **mat, int r, int c){
printf("Insert the elements of your matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("Insert element [%d][%d]: ", i, j);
scanf("%d", &mat[i][j]); // no problem here
printf("matrix[%d][%d]: %d\n", i, j, mat[i][j]);
}
}
}
// print matrix
void printMatrix(int **mat, int r, int c){
for (int i=0; i<r;i++){
for (int j=0; j<c;j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
int main(int argc, char *argv[]) {
int r = 3, c = 3;
int **mat = callocMatrix(r, c);
setMatrix(mat, r, c);
printMatrix(mat, r, c);
}
Should be:
scanf("%d", &(*mat)[i][j]);
You're passing a pointer to you matrix object, so you need to dereference it (with *) just as you do with printf. scanf then needs the address of the element to write into, so you need the &
I have an issue passing a matrix to a function in C. There is the function I want to create:
void ins (int *matrix, int row, int column);
but I noticed that in contrast to the vectors, matrix give me an error. How can I pass my matrix to a function so?
EDIT --> there is the code:
// Matrix
#include <stdio.h>
#define SIZE 100
void ins (int *matrix, int row, int column);
void print (int *matrix, int row, int column);
int main ()
{
int mat[SIZE][SIZE];
int row, col;
printf("Input rows: ");
scanf ("%d", &row);
printf("Input columns: ");
scanf ("%d", &col);
printf ("Input data: \n");
ins(mat, row, col);
printf ("You entered: ");
print(mat, row, col);
return 0;
}
void ins (int *matrix, int row, int column);
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
printf ("Row %d column %d: ", i+1, j+1);
scanf ("%d", &matrix[i][j]);
}
}
}
void print (int *matrix, int row, int column)
{
int i;
int j;
for(i=0; i<row; i++)
{
for(j=0; j<column; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
You need to pass a pointer with as much levels of indirection (*) as the number of dimensions of your matrix.
For example, if your matrix is 2D (e.g. 10 by 100), then:
void ins (int **matrix, int row, int column);
If you have a fixed dimension (e.g. 100), you can also do:
void ins (int (*matrix)[100], int row, int column);
or in your case:
void ins (int (*matrix)[SIZE], int row, int column);
If both your dimensions are fixed:
void ins (int matrix[10][100], int row, int column);
or in your case:
void ins (int matrix[SIZE][SIZE], int row, int column);
If you have a modern C compiler you can do the following for 2D matrices of any sizes
void ins (size_t rows, size_t columns, int matrix[rows][columns]);
Important is that the sizes come before the matrix, such that they are known, there.
Inside your function you then can access the elements easily as matrix[i][j] and the compiler is doing all the index calculations for you.
it would also possible to leave the first dimension empty, the same as (*matrix):
void ins (int matrix[][100], int row, int column);
Much better way to use malloc function and create dynamically allocated array and do whatever you want to do using 2d array:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
void fun(int **arr,int m,int n)
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &arr[i][j]);
}
}
}
int main()
{
int i,j,m,n;
printf("enter order of matrix(m*n)");
scanf("%d*%d",&m,&n);
int **a=(int **)malloc(m*sizeof(int));
for(i=0;i<n;i++)
a[i]=(int *)malloc(n*sizeof(int));
fun(a,m,n);
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
output:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
void fun(int **arr,int m,int n)
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &arr[i][j]);
}
}
}
int main()
{
int i,j,m,n;
printf("enter order of matrix(m*n)");
scanf("%d*%d",&m,&n);
int **a=(int **)malloc(m*sizeof(int));
for(i=0;i<n;i++)
a[i]=(int *)malloc(n*sizeof(int));
fun(a,m,n);
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
You can try this as well:
void inputmat(int r,int c,int arr[r * sizeof(int)][c * sizeof(int)])