Passing array into function in c - c

I'm getting gcc errors when I compile my code. The errors are about "passing argument 1 of ‘print_path’ makes pointer from integer without a cast".
Here is my function prototype:
void print_path(int previous[], int desired_node_index);
Here is my function:
void print_path(int previous[], int desired_node_index)
{
if( previous[desired_node_index] != -1 )
print_path( previous[desired_node_index] );
printf("-> %d ", previous[desired_node_index]);
}
and here is where I call my function:
print_path(previous, dest_index);
I'm obviously passing it in wrong, or else I'm doing something incorrectly about how to pass an array into a function. Any help?
Thanks guys!

This is obviously a recursive function. Note that print_path() takes 2 parameters: the first is an int array, and the second is an index to a position inside that array.
Calling it:
print_path( previous[desired_node_index] );
is absolutely wrong (unless you have overloaded this function), because it expects 2 parameters and you are only passing it one. What you should be doing is:
print_path( previous, desired_node_index );
What you seem to be missing in this function is an operation to increase/decrease the index variable, else you will always be printing the same position in the array.
Without knowing what is exactly that you are trying to do, there's the possibility that you wanted to do this:
print_path( previous, previous[desired_node_index] );

An obvious error is:
print_path( previous[desired_node_index] );
I'm not sure what you're trying to do, but I guess you want something like:
#include <stdio.h>
void print_path(int *previous, int desired_node_index);
int main(void) {
int dest_index = 2;
int previous[5] = { -1, 0, 1, 2, 3};
print_path(previous, dest_index);
return 0;
}
void print_path(int *previous, int desired_node_index) {
if( previous[desired_node_index] != -1 )
print_path( previous, previous[desired_node_index]);
printf("-> %d ", previous[desired_node_index]);
}

void receive_array(int *temp_arr)
{
int i=0;
do
{
temp_arr[i]=temp_arr[i]+1;
i++;
}
while((char)temp_arr[i]!='\0');
}

here I have made some modifications. The array temp_arr2[] is a buffer array. In my actual program, I printed the array from the main(). Here, for doing the same thing, one need to store back the end result of some computation into temp_arr[].MAX can be a macro or a global variable. In the previous one, I just forgot to edit the lines: temp_arr[i]=temp_arr[i]+1; (my demo sample code) :)
void receive_array(int *temp_arr)
{
int i=0;
int temp_arr2[MAX];
do
{
temp_arr2[i]=temp_arr[i];
i++;
}
while((char)temp_arr[i]!='\0');
}

If you want to pass array to function and return after changing the elements from the function you can see the following example:
You may find the solution at: https://github.com/krishnabhat81/Send-and-return-array-from-function-in-C
#include <stdio.h>
/*
If you want to return a single-dimension array from a function, you would have to
declare a function returning a pointer as in the following example:
*/
int *getRandom(int arr[])
{
static int r[10];
/*Second point to remember is that C does not advocate to return the address of a
local variable to outside of the function so you would have to define the
local variable as static variable.*/
int i;
for ( i = 0; i < 10; ++i)
{
r[i] = arr[i]+1;//rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main ()
{
/* a pointer to an int */
int *p;
int i;
int arris[10] = {110,22,33,44,5,6,7,8,9,20};
p = getRandom(arris);
for ( i = 0; i < 10; i++ )
{
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
return 0;
}

Related

pointers in functions don't return what I want

I have two functions, I need one to add a value to a variable and the other to print it, but the output is incorrect to what I expect.
What I do is define a function, passing a sum pointer as a parameter, in another function I create the variable that I will pass as a parameter and I invoke the new function passing that variable as an address, but when printing it it fails.
#include <stdio.h>
void test() {
int sum;
test2(&sum);
printf("%d",sum);
}
void test2(int *sumador) {
int i;
for(i = 0; i < 10; i++) {
sumador += i;
}
}
int main() {
test();
}
The problem is that you should dereference the pointer before summing with "i", like this:
*sumador += i;
This happens because "sumador" is a pointer and the content of the pointer is a memory address. In your original code you are adding "i" to the address stored in "sumador", what you actually want is to sum "i" with the content contained in the memory address stored in the pointer, which is the process we called dereferencing.
Another problem is that in function test make sure to initialize
the value of the variable sum.
int sum = 0;
Also, because test2 is called inside test, you should declare the function test2 above the function test, not below it, like this:
#include <stdio.h>
void test2(int *sumador) {
int i;
for(i = 0; i < 10; i++) {
*sumador += i;
}
}
void test() {
int sum = 0;
test2(&sum);
printf("%d",sum);
}
int main() {
test();
}
I hope I was able to help you,
have a nice day!

How to edit an array in another function than the main function in c programming?

I'd like to increase each element in the array by one in another function than the main function. Then, I'd like to call this function and print in the main function.
#include <stdio.h>
int function(int array2[5]) {
int i;
while(i<4) {
array2[i]=array2[i]+1;
i++;
}
return array2[5];
}
int main() {
int array[5]={1,2,3,4,5};
int answer;
answer[5]=function(array[5]);
int j;
while(j<4) {
printf("%d \n",answer[j]);
j++;
}
return 0;
}
Some important things to know:
When you pass an array in C, you don't make a copy. It is the same array, so modifying the array that is passed in modifies the original.
The [] are operators and not part of the variable name.
The [] work differently in declaring a type than when used in an expression. array[5] gives you the 6th element in array, but int array[5] declares an array with 5 elements.
Accessing an element beyond the end of the allocated array has undefined behavior, but usually will crash.
If you declare a variable int answer it is not an array, and cannot become an array. It is just one int
If you want to make a copy of an array, you need to explicitly copy. There are standard libraries that might do it, but you should learn to copy each element, one by one, to the new array.
The return type int of the function does not make a sense.
int function(int array2[5]) {
And moreover you are trying to return the non-existent 6-th element of an array with only 5 elements.
return array2[5];
Within the function you are using uninitialized variable i
int function(int array2[5]) {
int i;
while(i<4) {
//...
that results in undefined behavior. Also the used magic number 4 does not make a sense at least because you are trying to pass to the function an array with 5 elements.
The function should be declared with a second parameter that specifiers the number of elements in the passed array. This function declaration
int function(int array2[5]);
does not mean that the passed to the function array has exactly 5 elements. The compiler will adjust the parameter declaration of the function to pointer to the array element type like
int function(int *array2);
In this statement in main
int answer;
answer[5]=function(array[5]);
you are using the subscript operator with an object of the scalar type int. So the compiler shall issue an error message.
Here is a demonstrative program that shows how the function can be defined.
#include <stdio.h>
void function( int a[], size_t n )
{
for ( ; n--; ++a )
{
++*a;
}
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
function( a, N );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
return 0;
}
The program output is
1 2 3 4 5
2 3 4 5 6
There you go. I suppose this is what you want:
#include <stdio.h>
// Since the array named parameters are scoped only within its function,
// they are apart from your array in the main.
void function(int array[], int len) {
int i = 0;
while(i<len) {
array[i]=array[i]+1;
i++;
}
}
// Or alternatively you can process the array using a pointer
void functionWithPointer(int *array, int len) {
int i = 0;
while(i<len) {
*(array+i) = *(array+i)+1;
i++;
}
}
int main() {
int array[]={1,2,3,4,5};
// int answer; // Not necessary
int length = sizeof(array) / sizeof(int); // !!!ATTENTION
function(array, length);
// The array values updated by 1
printf("Array values after 1st update\n");
for(int k=0; k<length; k++) {
printf("%d \n",array[k]);
}
functionWithPointer(array, length);
// The array values updated by 1 again
printf("Array values after 2nd update\n");
int j;
while(j<length) {
printf("%d \n",array[j]);
j++;
}
return 0;
}
Here is the output:
Array values after 1st update
2
3
4
5
6
Array values after 2nd update
3
4
5
6
7

Element values show incorrect when print out from an array

I am just learning C and have my program print out incorrect values but I don't know how to fix it therefore I'd like to have your help.
Here is the codes . The test function stores integer numbers (from 0 to 20) in an array and return it. That array is copied to a new array (p[20]) in the main function and I try to print every element of that array out using for loop however the value is not correct, for example i = 0 then p[0] should be 0 but it shows -443987883 ,....
#include <stdio.h>
int test();
int main ()
{
int p[20];
strcpy(p , test);
int i;
int N = 20;
for (i=0; i < N; i++) {
printf ("%i,%i\n", i , p[i]);
}
}
int test (int i , char o[])
{
int N = 20;
for (i = 0; i < N; i++) {
o[i] = i;
}
return o;
}
Your code contains a lot of errors. I am going to point them out and explain to you how to fix it.
First of all, you should definitely forget the statement :
strcpy(p , test);
as by this you try to copy a function to an array! If you think that this statement calls test function and passes p as an argument to this, this is not true.
If you want another function, other than main, to fill your array, the best way would be to dynamically allocate a pointer to int and pass it by reference to the function. You can read more about passing by reference or by value here.
Let's see how you can do this. First of all, define N as a constant value outside your program :
#define N 20
Then, your main function should be modified like this :
int main ()
{
int *p;
int i;
//Dynamically allocate a pointer to ints
p = malloc(N*sizeof(int));
if (p == NULL)
printf ("Error in allocating memory\n");
//Now call your function
p = test(&p); //pass the pointer by reference
for (i = 0; i < N; i++)
printf ("%d, %d\n", i , p[i]);
}
and finally your test function should be modified accordingly like this :
int* test (int** p)
{
for (i = 0; i < N; i++)
*p[i] = i;
return *p;
}
So the prototype of your test function should change from :
int test();
to :
int* test(int**);

Is this the right way to pass an array back from the function to main

The program is running without errors, but it stops after it runs this function since it seems that the array is not being passed back. Is this the right way to pass the array back to the function? I've included only the essential code below. Please could you point out where I might be wrong.
int matchedNumbersfunc(int lotoNumbers[],int ticketNumbers[], int *numbersRight);
int main()
{
int lotoNumbers[7];
int ticketNumbers[7];
int matchedNumbers[7];
int numbersRight = 0;
matchedNumbers[7] = matchedNumbersfunc(ticketNumbers, lotoNumbers, &numbersRight);
return 0;
}
int matchedNumbersfunc(int lotoNumbers[],int ticketNumbers[], int *numbersRight)
{
int matchedNumbers[7];
int i, k ,j;
*numbersRight = 0;
for(k=0;k<7;k++)
{
matchedNumbers[k] = 0;
}
for(i=0;i<7;i++)
{
for(j=0;j<7;j++)
{
if(ticketNumbers[i] == lotoNumbers[j])
{
matchedNumbers[i] = ticketNumbers[i];
}
}
if(matchedNumbers[i] != 0)
{
printf("You have a winning number: %d\n", matchedNumbers[i]);
*numbersRight = *numbersRight + 1;
if(matchedNumbers[6] != 0)
{
*numbersRight = *numbersRight - 1;
}
}
}
return matchedNumbers[7];
}
So, you are returning a single value rather than an array. And as it happens, you are returning a value off the end of the array, and assigning to a value off the end of another array. Your arrays have 7 elements, indexed 0 to 6.
What you need to do is pass an array to the function and let the function populate it. A simple example:
void foo(int array[], size_t count)
{
for (size_t i = 0; i < count; i++)
array[i] = i;
}
Which you would call like this:
int myArray[7];
foo(myArray, 7);
Another solution is to allocate a new array dynamically in your function and return a pointer to that array with this prototype:
int* matchedNumbersfunc(int lotoNumbers[],int ticketNumbers[], int *numbersRight);
Your revised function would start like this:
int* matchedNumbers;
int i, k ,j;
*numbersRight = 0;
matchedNumbers = (int*) calloc (7, sizeof(int));
if (matchedNumbers==NULL)
return NULL;
for(k=0;k<7;k++)
...
return (matchedNumbers);
In the main() you do not need to allocate the table, but just a pointer:
...
int *matchedNumbers;
...
matchedNumbers = matchedNumbersfunc(...);
if (matchedNumbers==NULL)
{ /* not enough memory - some kind of error processing */ }
free (matchedNumbers); // once you don't need the result anymore
return 0;
For your simple programme dynamic allocation could be overkill. But for more complex processing, this approach could be useful as well.

Function pointer question in C

#include <stdlib.h>
int int_sorter( const void *first_arg, const void *second_arg )
{
int first = *(int*)first_arg;
int second = *(int*)second_arg;
if ( first < second )
{
return -1;
}
else if ( first == second )
{
return 0;
}
else
{
return 1;
}
}
int main()
{
int array[10];
int i;
/* fill array */
for ( i = 0; i < 10; ++i )
{
array[ i ] = 10 - i;
}
qsort( array, 10 , sizeof( int ), int_sorter );
for ( i = 0; i < 10; ++i )
{
printf ( "%d\n" ,array[ i ] );
}
}
I don't understand this line :
int first = *(int*)first_arg;
could anyone help me? explain it? thank you very much!!!
Is this a casting? explicit cast, from void* to int? but why we need ampersand outside ()?
You are first casting the void pointer to an int pointer:
(int*)first_arg
And then dereferencing the pointer: *(int*)first_arg to get the integer it points to. This is then assigned to an integer variable.
int first = *(int*)first_arg;
is the same as:
int* ptrToFirst = (int*)first_arg;
This is an explicit cast from const void* to int.
int first = *ptrToFirst;
Here the * is the dereferencing operator. This is pronounced 'star'.
This is an 'ampersand': '&'.
Why are we doing this? qsort() needs to have the callback determine the ordering. By passing the values indirectly as const void pointers, the arguments to the callback have fixed size even though the values could be any size. That is why the values need cast back in the callback.

Resources