Passing pointers to an array as arguments to a function - c

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++)

Related

Finding the maximum of an array recursively

I am learning recursion. As an exercise I am trying to find the maximum of an array recursively.
int recursive (int *arr, int n, int largest) {
if(n==0)
return largest;
else {
if (*(arr+n)>largest) {
largest = *(arr+n);
recursive(arr, n-1, largest);
}
}
}
int main() {
int length = n-1;
int largest = v[0];
int z = recursive(arr, length, largest);
printf("\n%d", z);
}
I followed your suggestions, using pointers instead of arrays, and probably the program looks way better. But still it is not doing it's not showing the maximum correctly. I think the logic is correct.
First thing pay attention to compiler warnings, your recursive function doesn't return value when you enter the else part.
Now the second thing is please don't use things like *(arr+n) which is hard to read instead use arr[n], also while just a preference when using arrays as function arguments use int arr[] to call the function instead of int *arr (in the first version it's clear you should pass an array).
Third thing is to name your things instead of int recursive describe what the function is doing for example int maxElemRecursive
So your recursive function should be something like
int maxElemRecursive(int arr[],int n,int largest)
{
if(n==0) return largest;
if(arr[n] > largest) // No need for else because return largest; would've returned value;
{
largest = arr[n];
}
return maxElemRecursive(arr,n-1,largest); // You have to return the value of the function.
// You still pass the array with just arr.
}
In C usually you can't declare an array whose size is unknown at compile-time, hence int v[n] is dangerous code.
Depending on your compiler and the compiler's settings this could be a compile error or it could be a bug.
For such problems you need to learn about pointers and dynamic memory allocation.
Side-note: After C99 there are stuff like Variable Length Arrays but the rules are a little advanced.
Also to pass an array to a function you give the array a pointer as an argument:
int z = recursion(v, n, v[0]);
instead of:
int z = recursion(v[n], n, v[0]);

Passing array to function, to multiply every value of the array by 10

This program is to multiply every value of array by 10 using a function. I am getting a lot of errors.
Can I take size in for loop?
#include<stdio.h>
mult(int arr[])
{
int i;
for(i=0;i<size;i++)
{
arr*=10;
}
return arr;
}
int main()
{
int j[];
printf("enter the all ten values to multiply by 10");
for(j=0;j<size;j++)
scanf("%d");
j[] = mult(j);
printf("%d",&j);
return 0;
}
int j[]; You're creating an array wrongly (in this context). You have to specify its size. Eg.: int j[256];
for(j=0;j<size;j++) scanf("%d"); What's size? how can you increment an array?? You're using scanf wrongly. You should do for(int s=0;s<size;s++) scanf("%d",&j[s]);.
j[] = mult(j); is wrong again. You should create another array and copy values there.
printf("%d",&j); you don't need & here, remove it. You'd better use "%d\n" to print each number on its own line.
mult(int arr[]) function declared wrongly. You must specify a type your function returns. You may need to use int *mult(...) instead and return &arr[0];
arr*=10; what're you trying to achieve with this? Completely wrong, you're multiplying the address here.
Read the docs, please! Your code doesn't make any sense, please learn C first, then try to code.
Moreover, you'll need pointers here, pay attention to them. I'd advise you to write Hello World program first to just understand the basics. Mr. Kernighan and Mr. Ritchie will help you too.
Note: I may have missed some mistakes here as there are too many of them. Please correct me if so.
Here is a complete code learn the differences and correct your code:
#include<stdio.h>
void mult(int *arr,int size)
{
int i;
for(i=0;i<size;i++)
arr[i]*=10;
}
int main()
{
int size=10;
int j[size],i;
printf("enter the all ten values to multiply by 10\n");
for(i=0;i<size;i++)
scanf("%d",j+i);
mult(j,size);
for(i=0;i<size;i++)
printf("%d ",j[i]);
printf("\n");
return 0;
}
You must tell mult() what is the size of the array, and the array you are passing will be modified in mult() so you don't need to return a value.
mult(j, size);
and your mult() function
void mult(int *arr, size_t size)
{
int i;
for(i=0;i<size;i++)
{
arr[i] *= 10;
}
}

Array not being passed to Function Method

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.

C Send/Return array with functions

I came across this article http://www.eskimo.com/~scs/cclass/int/sx5.html
but this part confused me: what's the point of returning the array in send_array_3 if we're already modifying it using send_array or send_array_2 for example? We don't need to return it, right?
void send_array(int a[], int n) {
for (int i=0; i<n; i++)
a[i] = i*i;
}
void send_array_2(int* a, int n) {
for (int i=0; i<n; i++)
a[i] = i*i;
}
int* send_array_3(int a[], int n) {
for (int i=0; i<n; i++)
a[i] = i*i;
return a;
}
They say it's not that useful:
Another difference is that the return value of this latest version of
itoa isn't terribly useful. The pointer which this version of itoa
returns is always the same as the pointer you handed it. Even if this
version of itoa didn't return anything as its formal return value, you
could still get your hands on the string it created, since it would be
sitting right there in your own array (the one that you passed to
itoa). In the case of getline, we had a second thing to return as the
formal return value, namely the length of the line we'd just read.
generally you either allocate memory to a pointer and return the array in a function, you pass in the pointer to the array with memory already allocated, and use any return value for error handling, so you can wrap the function in an if statement or whatever.
You could even pass in the address of an array pointer as an int ** (for an int array) allocate the memory, and then not have to return it.
what you got there are just examples how you can handle the problem of "returning" arrays
three different methods are in here and all should work (i would preffer send_array_2)

All the array length methods in C don't work

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

Resources