using #define in functions - c

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.

Related

ERROR C2371 Override, the default format is different. what is the error point?

#include <stdio.h>
int main(void) {
int list_size;
printf("size of the array:");
scanf("%d", &list_size);
int list[5];
for (int i = 0; i < list_size; i++) {
scanf("%d", &list[i]);
}
printArray(list, 5);
return 0;
}
void printArray(int list[], int list_size){
for (int j = 0; j < list_size; j++) {
printf("%d ", list[j]);
}
}
Error C2371 : 'printArray' : Override, the default format is different. How can I change the code?
Is the array declaration wrong?
I have to make function 'printArray', so I can't put code into main function.
For starters you are not using the variable list_size in the array declaration
scanf("%d", &list_size);
int list[5];
It seems you mean
int list[list_size];
Correspondingly the function printArray should be called like
printArray(list, list_size);
You have to declare the function printArray before its call for example before main
void printArray(int list[], int list_size);
int main( void )
{
//...
}
As the function does not change the passed array then the first parameter should be declared with the qualifier const.
void printArray(const int list[], int list_size);
int main( void )
{
//...
}
And the function can be defined like
void printArray( const int list[], int list_size ) {
for (int j = 0; j < list_size; j++) {
printf("%d ", list[j]);
}
putchar( '\n' );
}
Pay attention to that this declaration
int list[list_size];
declares a variable length array. You need to set a corresponding option of the compiler to compile your program according to the C99 Standard.
Otherwise you could define some large enough constant for the size of the array. For example
int main( void )
{
enum { N = 100 };
int list[N];
int list_size;
printf( "size of the array (not greater than %d): ", N );
if ( scanf( "%d", &list_size ) != 1 || N < list_size ) list_size = N;
//...
Like this
/* function declaration or prototype */
void printArray(int list[], int list_size);
int main(void) {
...
}
void printArray(int list[], int list_size) {
...
}
You have to declare functions before you use them. Function declarations are also called prototypes.
You should declarate the function after the headers files if you make the function after the principal program
#include <stdio.h>
void printArray(int list[], int list_size);
int main(void)
{
int list_size;
do
{
printf("size of the array:");
scanf("%d", &list_size);
}
int list[list_size];
for (int i = 0; i < list_size; i++)
{
scanf("%d", &list[i]);
}
printf("\nDisplay of array :\n");
for (int i = 0; i < list_size; i++)
{
printf("%d", list[i]);
}
printf("\n\n");
printArray(list, list_size);
return 0;
}
void printArray(int list[], int list_size)
{
printf("\nDisplay of array :\n");
for (int j = 0; j < list_size; j++)
{
printf("%d ", list[j]);
}
}
This code print 2 time the output of array,if you want to display the array 1 time you should remove this foor loop :
printf("\nDisplay of array :\n");
for (int i = 0; i < list_size; i++)
{
printf("%d", list[i]);
}
C is parsed without looking ahead. You could write a single-pass C compiler (not the most useful thing, but the language was designed with this in mind). When the compiler sees the call to printArray, i.e. the line printArray(list, 5);, it doesn't know yet what printArray's real declaration is - it hasn't read it yet. But it has to do something with that call, and instead it makes a guess: the compiler implicitly declares, at that moment, the function as-if you had the following declaration:
int printArray();
In C, this declaration really means
int printArray(...);
And thus, the call to printArray is generated with such an implicit declaration - the function is called as if it was a variadic function. But it isn't a variadic function. You later attempt to define it in an incompatible way, as:
void printArray(int [], int);
This is not allowed and triggers an error: in C, all the declarations must agree with the definition. C allows multiple declarations - they are not an error, as long as they all agree. In your case they didn't: the implicit one didn't match the explicit one that came later.
There are two ways of fixing this error:
Declare void printArray(int list[], int size); before the point of use, e.g. before main. You can still define it later - after main.
Change the signature of printArray to match what the compiler implied, i.e. printArray(...) { ... }. The only problem is: such a signature would be useless. You can pass whatever arguments you want into that function, but there's no way to actually use them from inside the function. That variadic argument mechanism of C requires at least one named argument. So no luck there. A minimum viable printArray function with variadic arguments could look as follows - and of course then it's not defined as printArray(...) anymore, so the compiler would raise the error you see due to the mismatch of implicit declaration and definition, and you're back to square one.
void printArray(int list[], ...)
{
va_list args;
va_start(args, list);
int count = va_arg(args, int);
for (int i = 0; i < count; ++i) printf("%d ", list[i]);
printf("\n");
va_end(args);
}
The problem is in va_start: you have to pass it the first named argument to the function. With a signature like printArray(...), there are no named arguments, and thus you can't use va_start, and there's no way of accessing any arguments passed to such function from the inside of it - not while depending on Standard (portable) C. On various architectures there are non-portable "hacks" to bypass this issue, but they are not recommended at all.
Note: If you want to declare a function with no arguments in C, it should be declared as:
int myFunction(void); /* <- like this, not like -> */ int myFunction();
To add to the potential confusion, C++ sees things differently: there, the int foo(void) is redundant, since it interprets int foo() as a function taking no parameters, and not as int foo(...) like C would.
You could've declared your function before the main() one. As for the rest, I don't see the problem with your function.
#include <stdio.h>
void printArray(int list[], int list_size)
{
for (int j = 0; j < list_size; j++)
{
printf("%d ", list[j]);
}
}
int main(void)
{
int list_size;
printf("size of the array:");
scanf("%d", &list_size);
int list[list_size];
for (int i = 0; i < list_size; i++)
{
scanf("%d", &list[i]);
}
printArray(list, list_size);
return 0;
}

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;
}

Sum of array in C

I'm working on a small program for school and can't get my array of doubles to sum properly. The specific error I'm getting is
warning C4244: 'return': conversion from 'double' to 'int', possible loss of data
on the line where sum is returned. And the sum displayed is gibberish.
The code is intended to:
fill an array of doubles with user input,
print the doubles on the screen in a column,
add up all the doubles in the array, and
print the sum onto the screen.
Code
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAX_SIZE 15
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
SumArray(double a[], int *i);
int main()
{
double input[15];
int input_size;
double sum;
FillArray(input, &input_size);
PrintArray(input, input_size);
sum = SumArray(input, &input_size);
printf("The sum is %f\n", sum);
return 0;
}
void FillArray(double a[], int *i)
{
int k;
printf("Filling an array of doubles\n");
printf("How many doubles do you want to enter (<15)\n");
scanf(" %d", i);
for (k = 0; k <*i; k++)
{
printf("Enter double:\n");
scanf("%lf", &a[k]);
}
}
void PrintArray(double a[], int i)
{
int k;
printf("Printing an array of integers:\n");
for (k = 0; k<i; k++)
{
printf("%f\n", a[k]);
}
printf("\n");
}
SumArray(double a[], int *i)
{
int k;
double sum = 0;
for (k = 0; k<*i; k++);
{
sum +=a[k];
}
return (sum) ;
}
You need to specify double SumArray(...) instead of merely SumArray(...) where you declare and define the function. If you do not specify a return type, int is assumed. Specifically:
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
double SumArray(double a[], int *i);
/*^^^^^^-- add return type*/
int main()
and
double SumArray(double a[], const int numElements)
/*^^^^^^- same deal*/ /* also ^^^^^ ^^^^^^^^^^^ */
{
int k;
double sum = 0.0; /* Edit 3: 0.0 rather than 0 for clarity */
for (k = 0; k < numElements; ++k) /* no ; here! --- Edit 3: ++k for speed and good practice */
{ /* ^^^^^^^^^^^ */
sum +=a[k];
}
return (sum) ;
}
Edit Also, you can use const int numElements instead of int *i in SumArray. You don't need to modify the value inside SumArray, so you don't need the * and you can specify const. And it's a good practice to give your variables descriptive names, e.g., numElements instead of i. That will help you understand your own code when you have to maintain it later! (Ask me how I know. ;) )
To use this, you also need to change the call in main to remove the &:
sum = SumArray(input, input_size);
/* ^ no & here */
Edit 2 As #BLUEPIXY pointed out, the trailing ; on the for loop was misplaced. As a result, the {} block ran once, after the loop had completed. That would be a significant cause of the "gibberish" you saw: the effect was to set k=numElements and then set sum=a[numElements], which was a non-existent element. So the sum was being set to whatever random memory contents happened to be after a.

Passing array to function using pointer

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].

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