I'm currently trying to pass an array of (values[3]) which it's first 3 values contain user input. However, I'm getting the error "expected int* but argument is type of int". I've tried to pass to method1, without the iteration of 'i', using the first three positions in the values array, but that's as far as I managed to attempt to fix it, any help would be much appreciated!
int main(void)
{
int i;
int values[3];
printf("Enter three consecutive numbers (With spaces between)");
scanf("%d %d %d",&values[0],&values[1],&values[2]);
for(i=0;i<3;i++)
method1(values[i]);
}
int method1(int values[3])
{
}
You cannot pass an array to a function as an array - it "decays" to a pointer. There are two issues with your code:
There is no forward declaration of method1 visible at the point of invocation, and
You are passing values[i], a scalar value in place of an array.
A forward declaration is necessary because otherwise the compiler would assume that method1 takes an returns an int, which is not true. Add this line before main
int method1(int values[]);
You could also move method1 above main to fix this without providing a forward declaration. Also, 3 inside square brackets is not necessary, because the array is passed like a pointer anyway.
If you want to pass the entire array, pass values. Of course, i becomes unnecessary:
int res = method1(values);
#include <stdio.h>
int main(void)
{
int i;
int values[3];
printf("Enter three consecutive numbers (With spaces between)");
scanf("%d %d %d",&values[0],&values[1],&values[2]);
method1(values, 3);
getchar();
getchar();
return 0;
}
int method1(int* values, int size)
{
int i;
for(i=0; i<size; i++){
printf("%d ", values[i]);
}
return 1;
}
In C, arrays are passed by reference, you can see method1's first argument is int* that refers first element of array, and second argument is size of this array.
Related
This question already has answers here:
Why do we need to specify the column size when passing a 2D array as a parameter?
(8 answers)
Closed 2 years ago.
I want to create an array that has that stores the multiplication values of any integer n. After that, I would like to pass that array into another function and print out the array. However, I get the following error:
My code:
This is my .c file:
#include "multiplication.h"
#include <stdio.h>
int main(){
int num;
int arr=multiplication(4);
printArray(arr);
}
int mulitpication(int num){
/* initialize array and build*/
int arr[num][num];
for(int i=0; i<num;i++){
printf("row number: %d ",i);
for(int j=0;j<num;j++){
printf("column number: %d", j);
arr[i][j]= (i+1)*(j+1);
}
}
return arr;
}
void printArray(int arr[][]){
int i;
for(i=0;i<sizeof(arr);i++){
for(int j=0;j<sizeof(arr);j++){
printf("%d ",arr[i][j]);
}
}
This is my header file:
void multiplication(int num);
void print(int arr[][]);
The Error:
multiplication.h:4:19: error: array has incomplete element type 'int []'
void print(int arr[][]);
^
First of all, you don't include the source files into one another, you compile and link them together to form the binary.
That said, the actual problem is in the code you did not show (multiplication.h file), but from the error message we can see
void print(int arr[][]);
is not a valid syntax. You can only leave the outer(-most) index as empty, all other index(es) must have a proper value. Something like
void print(int arr[ ][10]);
^^---------- inner index
^^^------------- outer index
or, for more dimensions
void print(int arr[ ][5][10][15]);
The analogy behind this is, for function declarators,
"A declaration of a parameter as ''array of type'' shall be adjusted to ''qualified pointer to type'',...."
So, to have that adjustment, the type should be known to compiler at compile-time.
In case of a declaration like
void print(int arr[][10]);
the type is int[10], but if a syntax like
void print(int arr[][]);
is allowed , the type cannot be known. Hence the error.
Other issues: You seem to have many other issues, like
The function definition is
int mulitpication(int num){ // returning an int
but actually you do
return arr; //where arr is an array of size int[num][num], defined locally
this is invalid because of two things
an int and an int[num][num] are not the same type.
the scope of a VLA i.e., arr is limited to the function block, you cannot have the array return the address to the caller and expect something meaningful as the returned address will not be valid anymore.
I believe, you're better off using allocated memory (malloc() and family) and keeping track of your index/ count of elements manually.
To fix the printArray function you will need to include the array dimensions. In C, arrays are simply a block of elements, there is no length stored anywhere. The programmer would need to keep track of the length by some method.
For example:
// header
void printArray(int num, int arr[num][num]);
// source file
void printArray(int num, int arr[num][num])
{
for(int i=0;i<num;i++){
for(int j=0;j<num;j++){
printf("%d ",arr[i][j]);
}
For the multiplication function you will need to do something similar, the caller should allocate the array (e.g. int arr[num][num];) and then the function should fill in the values for the array cells.
I'm new to programming and I don't really understand this question. Can some of you give me examples of what it means. How do I write a function where a is int values and n is the length?
I'm confused...
I'm not sure what your question is, as you haven't provided much information. However, a function in C is defined like this:
return_type function_name( parameter list ) {
body of the function
}
So, for this situation, we could say:
void arrayFunction( int a[], int n){
//do whatever you need to do with the function here
}
This may help you some.
Suppose you have an array of ints, as follows:
int arr[] = {2,3,4,5,6};
You can see that there are 5 elements inside above array arr. You can count them.
But it happens that when you pass the above arr to function, that function has no idea about how many elements arr contains. See below (incorrect) code snippet:
#include <stdio.h>
void display(int arr[]){
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr);
return 0;
}
The function named 'display()' has no idea about how many elements arr has
Therefore you you need to pass the extra argument (the extra argument called 'n') to tell that called function about the number of elements inside arr. You need to tell this separately - the length of arr.
Now this becomes - as you said in your question - arr is int values and n is the length
Below is the correct code:
#include <stdio.h>
void display(int a[], int n){
//Now display knows about lenth of elemnts in array 'a'
// Length is 5 in this case
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr, 5);
return 0;
}
Now, the function named 'display()' knows the length of array of int. This is the way you write code where you specify your array and its length.
More formally, this is because while passing array, it decays to a pointer and so the need arises to pass its length also alongwith it.
Here is my main function:
main(){
int *seats[50] = {0};
char x;
do{
printf("A-Add Reservation\tC-Cancel Reservation\n");
scanf("%c", &x);
} while(x != 'a' && x != 'c');
switch(x){
case 'a':
addRes(&seats);
break;
default:
break;
}
}
I am trying to pass seats[] into the addRes() function so I can modify it within addRes(). Here is the function:
void addRes(int **seats[]){
int s, i, scount=0, j=0, k=0, yourseats[]={0};
printf("How many seats do you require? ");
scanf("%i\n", &s);
for(i=0;i<=sizeof(*seats);i++){
if(*seats[i] == 0)
scount++;
}
if(scount >= s){
for(i=0;i<=s;){
if(*seats[i] == 0){
yourseats[j]=i;
*seats[i]=1;
i++; j++;
}
else i++;
}
printf("Your seat numbers are: \n");
while(k < j){
printf("%i\n", yourseats[k]);
k++;
}
}
else {
printf("Sorry, there are not enough seats available.\n");
}
}
It compiles with the warnings:
Line 15 (*seats[i]=1;) Assignment makes pointer from integer without a cast.
Line 53: (addRes(&seats);) Passing argument 1 of 'addRes' from incompatible pointer type.
Line 3: (void addRes(int ** seats[]){) Expected 'int ***' but argument is of type 'int *(*)[50]'.
On running the program it gets to
How many seats do you require?
and does nothing after entering a value.
Any help would be much appreciated!
Declaration int **seats[] in function parameter is == int ***seats, and this means type of *seats[i] is int* and you are assigning a number to it, that is incompatible type error:
*seats[i] = 1;
^ ^ int
|
int*
incompatible types
Next in addRes(&seats);
seats in array of pointer its type if int*[50] that &seat is pointer of array and type of &seat is int*(*)[50] Where as function argument type is int ***, so again type incompatible error.
Notice you are also getting a reasonable error message from compiler: Expected 'int ***' but argument is of type 'int * (*)[50]'.
Suggestion:
As I can see in your code, you don't allocate memory for seats[i] in your function addRes() and So as I understand you not need to declare seat[] array as array of pointers but you need simple array of int.
Change declaration in main():
int *seats[50] = {0};
should be just:
int seats[50] = {0};
// removed * before seats
Next just pass seats[] array's name to addRes() function where declaration of function should be
addRes(int* seats)
or addRes(int seats[])
it make your work pretty simple in function addRes() you can access its elements as seats[i] ( and it no need to use extra * operator).
Length of array:
One more conceptional problem in your code that you are using sizeof(*seats) to know the length of array. Its wrong! because in addRes() function seats is not more an array but a pointer so it will give you the size of address ( but not array length).
And yes to inform about size of seats[] in addRes() function send an extra parameter called length, so finally declare addRes() as follows (read comments):
void addRes(int seats[], int length){
// access seat as
// seat[i] = 10;
// where i < length
}
Call this function from main() as follows:
addRes(seats, 50);
// no need to use &
One more problem that presently you are not facing but you will encounter soon as you will run you code that scanf() need extra enter in function addRes(). To resolve it change: scanf("%i\n", &s); as scanf("%i", &s); no need of extra \n in format string in scanf().
int *seats[50] = {0};
This is an array of integer pointers, all you need is an actual array so drop the * resulting in int seats[50] = {0};.
Also your function signature for an array is wrong, void addRes(int seats[]) will do fine.
Finally, to pass an array to that new signature, you can pass the array directly without any unary address-of operators (arrays will decay to a pointer when passed as an argument to a function):
addRes(seats);
Also as pointed out, when assigning to an array element, you need to drop the *:
seats[i]=1;
Is more than enough. Same goes for the if statements and the like where you do a comparison against an array element.
Regarding your addRes function:
for(i=0;i<=sizeof(*seats);i++)
You will only get the size of the pointer this way, which on a 32bit machine is 4. This trick will not work on an array passed to a function. You will need to pass the array separately.
You can fix it in the following way:
Change the function signature of address to this:
void addRes(int seats[], int size)
Pass the size in one of the following ways in main:
Directly: addRes(seats, 50);
Indirectly: addRes(seats, sizeof(seats)/sizeof(int));
Note that the above only works on local to the scope of this function arrays, it won't work on an array you've obtained as an argument to a function (or dynamically allocated arrays).
Another issue is to do with scanf, you should drop the \n. Use scanf("%i", &s);
I am trying to implement INSERTION SORT here in C, which I think I've done successfully. However, I am having problems in passing arrays as arguments.
I want in place sorting, which means that the original array passed into the insertion_sort function should contain the elements in the sorted array itself.
#include<stdio.h>
int * insertion_sort(int *a,int length)
{
int j;
for(j=1;j<length;j++)
{
int i,key=a[j];
for(i=j-1;j>=0;j--)
{
if(a[i]<=key)
break;
a[i+1]=a[i];
}
a[i+1]=key;
}
return *a;
}
int main(void)
{
int a[]={10,12,7,6,9,8};
insertion_sort(a,6);
int i;
for(i=0; i<6; i++)
printf("%d\n", a[i]);
return 0;
}
EDIT
Nothing gets printed in the output screen.
Help me find the bug here. Thanks !!
1.You probably meant to use i in the inner loop:
Change:
for(i=j-1;j>=0;j--)
^^ ^^
to:
for(i=j-1;i>=0;i--)
2.You don't have to return anything as the original array gets modified (which is just as well since you ignore the returned value).
3.Array index starts from 0. Change outer loop to: for(j=0;j<length;j++)
I have tried (sizeof(array)/sizeof(array[0])). Didn't work.
I wrote a simple function:
int length(int array[]){
int i=0;
while(array[i]) i++;
return i;
}
Worked one minute, didn't work the next.
Someone please help! I'm using Xcode as an IDE
The length of an array is not part of the array in C, so when passing an array as a parameter to a function you should pass its length as a parameter too. Here's an example:
#define ARRLEN(a) (sizeof(a)/sizeof (a)[0]) /* a must be an array, not a pointer */
void printarray(int* a, int alen)
{
int i;
for (i = 0; i < alen; i++)
printf("%d\n", a[i]);
}
main()
{
int a[] = { 3, 4, 5 };
printarray(a, ARRLEN(a));
return 0;
}
However, if your array is defined in such a way as to always end with a sentinel that isn't normal data, then you can traverse the elements until you encounter the sentinel. e.g.,
void printstrings(char** a)
{
int i;
for (i = 0; a[i]; i++)
printf("%s\n", a[i]);
}
main()
{
char* a[] = { "This", "should", "work.", NULL };
printstrings(a);
return 0;
}
Passing an array into a function is the same as passing a pointer to the array.
So sizeof(array)/sizeof(array[0]) does not work.
You can define a global macro:
#define A_LEN(a) (sizeof(a)/sizeof(a[0]))
Try this
main()
{
int a[10] ;
printf("%d\n", sizeof(a)/sizeof(int) ) ;
}
output : 10
See Why doesn't sizeof properly report the size of an array when the array is a parameter to a function? from the comp.lang.c FAQ to understand why the sizeof method doesn't work. You probably should read the entire section on arrays.
Regarding your length function, your "simple" function can work only if your array happens to have the semantic that it is terminated with an element that has the value of 0. It will not work for an arbitrary array. When an array has decayed into a pointer in C, there is no way to recover the size of the array, and you must pass along the array length. (Even functions in the C standard library are not immune; gets does not take an argument that specifies the length of its destination buffer, and consequently it is notoriously unsafe. It is impossible for it to determine the size of the destination buffer, and it therefore cannot prevent buffer overflows.)
There are several methods to get the length of array inside a function (can be in the same file or in different source file)
pass the array length as a separate parameter.
make array length as global extern so that function can directly access global data