Passing arrays to a void function - c

I am trying to print out the contents of array1 times 10 if the integer inside is positive, if it is negative , the number should be left as it is in an another array. My code doesn't give me any result, I'm not that good in programming so I'm pretty sure I'm making a stupid mistake but I can't make out what it is, can someone point out the problem
void
tenfold (int array2[], int size )
{
int i, array1[size];
for (i=0;i<size;i++)
{
if (array1[i]>0)
array2[i]= 10 * array1[i];
else
array2[i]= array1[i];
}
}
int main()
{
int i,array1[9]= {3, 4, 5, 6, 7, -8, -9, 1, 2};
int size = 9;
tenfold(array1, size);
return 0;
}

tenfold should take array1 as input and array2 as local, other wise your are correct,
added a printf in tenfold to see the output.
#include<stdio.h>
void tenfold (int array1[], int size )
{
int i, array2[size];
for (i=0;i<size;i++)
{
if (array1[i]>0)
array2[i]= 10 * array1[i];
else
array2[i]= array1[i];
}
for(i=0;i<size;i++)
printf("(orignal) array1[%d]=%d, (new) array2[%d]=%d\n", i, array1[i], i, array2[i]);
}
int main()
{
int i,array1[9]= {3, 4, 5, 6, 7, -8, -9, 1, 2};
int size = 9;
tenfold(array1, size);
return 0;
}
Output:
(orignal) array1[0]=3, (new) array2[0]=30
(orignal) array1[1]=4, (new) array2[1]=40
(orignal) array1[2]=5, (new) array2[2]=50
(orignal) array1[3]=6, (new) array2[3]=60
(orignal) array1[4]=7, (new) array2[4]=70
(orignal) array1[5]=-8, (new) array2[5]=-8
(orignal) array1[6]=-9, (new) array2[6]=-9
(orignal) array1[7]=1, (new) array2[7]=10
(orignal) array1[8]=2, (new) array2[8]=20

You have changed the names of array in the function, update code to
//------------v array1
tenfold (int array1[], int size )
{
int i, array2[size]; //here array2
//your code
}
With your code, array1[] is never initialized and has random values, so if will not work as expected.

You should first start by trying to printf the values in tenfold(). :-)
You don't need to create array1 in tenfold().
Also, you may be able to get away from using a size variable and just use sizeof(array)/sizeof(array[0]).

tenfold doesn't print anything. There is no need to create another array if all you want if for that function to print. Be sure to add #include
#include <stdio.h>
void tenfold (int array[], int size)
{
int i;
for (i=0;i<size;i++)
{
if (array[i]>0)
printf("%d ", (10 * array[i]));
else
printf("%d ", array[i]);
}
}
output:
30 40 50 60 70 -8 -9 10 20

Related

I have to reverse the array [1,2,3,4,5,6,7] and i am stuck

#include <stdio.h>
int reverse(int *prr, int i)
{
for (i = 6; i; i--)
{
printf("%d is reverse \n", *prr + i);
}
}
int main()
{
int arrr[] = {1, 2, 3, 4, 5, 6, 7};
int *ptr = arrr;
reverse(ptr, 6);
return 0;
}
The output I am getting is
7 is reverse
6 is reverse
5 is reverse
4 is reverse
3 is reverse
2 is reverse
but not 1!
The loop condition i is equivalent to i != 0 (and for your specific use-case i > 0).
That is, the loop will end when the i reaches 0, so that index will not be printed.
To be able to print the last element, you need to include it in the loop with a condition like i >= 0.
While the off-by-1 question has been answered already, a slightly more idiomatic C way to write it would be to pass the array count as an argument (instead of count-1), and use pointer arithmetic (instead of indexing).
void reverse(int *prr, int i)
{
for (prr += i; i--; )
{ printf("%d is reverse \n", *--prr); }
}
int main()
{
int arrr[] = {1, 2, 3, 4, 5, 6, 7};
reverse(arrr, sizeof(arrr) / sizeof(arrr[0]));
return 0;
}
You have a couple of different ways to write the function. Though as #dxiv pointed out in your comments you want *(prr + i) instead of *prr + i (which by happy mistake just happened to output the same numbers corresponding the elements 1 - 7)
When you want to access a specific element from an array, you options are *(ptr + index) which is equivalent to ptr[index] (or for that matter index[ptr]).
Whenever you need to loop a certain number of times, you can simply decrement the counter, e.g.
#include <stdio.h>
void reverse (int *prr, size_t nelem)
{
while (nelem--)
printf ("%d is reverse\n", *(prr + nelem));
}
int main()
{
int arrr[] = {1, 2, 3, 4, 5, 6, 7};
reverse (arrr, sizeof arrr/sizeof *arrr);
}
Another approach for reversal is a recursive function, e.g.
void reverse (int *prr, size_t nelem)
{
if (nelem) {
printf ("%d is reverse\n", *(prr + nelem - 1));
reverse (prr, nelem - 1);
}
}
or even
void reverse (int *prr, size_t nelem)
{
printf ("%d is reverse\n", *(prr + --nelem));
if (nelem)
reverse (prr, nelem);
}
Example Use/Output
The output of all are equivalent, e.g.:
$ ./bin/reverse_arr_fn
7 is reverse
6 is reverse
5 is reverse
4 is reverse
3 is reverse
2 is reverse
1 is reverse

Array gets modified not int when called in a function

When I run this program-
#include <stdio.h>
void inc( int num[], int n)
{
int i;
n++;
for(i=0;i<10;i++)
num[i]++;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int a=2;
inc (arr, a);
int i;
for(i=0;i<10;i++)
printf("%d ", arr[i]);
printf("\n%d ", a);
return 0;
}
I get the output-
2 3 4 5 6 7 8 9 10 1
2
I understand why the int is unchanged but I don't understand why the array is getting changed since I have not used pointers to call the array. I know that the function will make a different copy of n and assign n=a and all changes will happen to n only and a will be unchanged. Why the array is getting changed?
In C, except for a few cases, an array name decays (=gets implicitly converted) to a pointer to its first element.
This
void inc(int num[], int n)
is exactly same as this:
void inc(int *num, int n)

Pass in part of an array as function argument

I have an array int arr[5] = {10, 2, 3, 5, 1}, and I want to pass in the last 4 elements (basically from index 1 to index4) into an argument as an array (so: [2, 3, 5, 1]). Is there a way to do this very simply (like how in Ruby you would be able to do arr[1..4]), or would I have to use a for loop?
You can manually increment the pointer by 1:
your_function(arr + 1)
Pointer arithmetic in C implicitly accounts for the size of the elements, so adding 1 will actually add 1 * sizeof(int)
For a closer analogue to array slicing from other languages, try this function:
int *slice_array(int *array, int start, int end) {
int numElements = (end - start + 1)
int numBytes = sizeof(int) * numElements;
int *slice = malloc(numBytes);
memcpy(slice, array + start, numBytes)
return slice;
}
It makes a slice of the array between the given start and end indices. Remember to free() the slice once you're done with it!
Answer
Given you current code:
int arr[5] = {10, 2, 3, 5, 1};
You can duplicate the range 1..4 by:
int arr_dup[4];
memcpy(arr_dup,arr+1,sizeof(int)*4);
Remember that your function definition should be a pointer, example:
void a_function(int *arr_arg); //Call via a_function(arr_dup);
Explanation
Arrays in c implemented as pointers (aka variables that hold memory addresses).
If you do arithmetic on the pointer, it will advance to the respective element. Example:
ptr + 1 //Next Element
ptr - 1 //Previous Element
#include <stdio.h>
#include <stdlib.h>
void my_function(int arr_size, int *arr)
{
int i;
for(i=0; i < arr_size; i++)
{
printf("[%d]:%d\n", i, arr[i]);
}
}
int main(int argc, char **argv)
{
int arr[] = { 10, 2, 3, 5, 1 };
(void)my_function(4, &arr[1]); /* TODO > use more flexible indexing */
return EXIT_SUCCESS;
}
I think you can use memcpy,memcpy can copy data byte to byte.In memmory,our data is binary,so even int is 4 bytes,we can copy it byte to byte.
int dst[4];
memcpy(dst,&arr[1],size(int) * 4);

How to determine number of elements that are in a array in C

i'm new learning the C Languange.
I want to know the number of elements that are in a array for example
int MyArray[80] = {50, 845, 584};
n = sizeof(MyArray)/sizeof(MyArray[0]); // This will give me 80.
But I only want the number of elements that are inside of {}, As i initialized above it has 3 elements (50, 845, 584), so how do i count them by code?
Another question:
How do i create an empty array so i can add elements by myself and print all elements with a for loop, I've tried this:
int i;
int MyArray[80] = {};
MyArray[0] = 50;
MyArray[1] = 584;
MyArray[2] = 784;
for(i=0; i<=sizeof(MyArray); i++){
printf("Array Element[%d] is: %d", i, MyArray[i]);
}
But this doesn't seem to work, any help? Thanks
EDIT: i fixed it by doing the following code found in another post:
#include <stdio.h>
#define NUM_ELEMS(a) (sizeof(a)/sizeof 0[a])
main() { int i; int numbers[] = {2, 3, 5, 7, 11, 13, 17, 19, 85};
int AllElements = NUM_ELEMS(numbers);
for(i=0; i<AllElements; i++){
printf("Element[%d] in array is: %d \n", i, numbers[i]);
}
}
If you initialize an array with fewer elements than the array is declared to hold, the remaining elements will be default-initialized. For integers, this means that they will be zeroed.
Assuming you have no zeroes in your initialization list, then, you can check how long the initialization list was by checking for the first zero in the array (up to the length of the array).
Alternately, if the array size should just be constant, you should specify the size as [], which makes it exactly as long as the initialization list and no longer.
I only want the number of elements that are inside of {}
Try
size_t n = sizeof (int[]){50, 845, 584} / sizeof (int);
An ugly way using the preprocessor:
#include <stdio.h>
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)
#define init_array(arr, ...) NARGS(__VA_ARGS__); arr = {__VA_ARGS__}
int main(void)
{
int n = init_array(int my_array[80], 50, 845, 584);
printf("%d\n", n);
return 0;
}
Is expanded to:
int main(void)
{
int n = 3; int my_array[80] = {50, 845, 584};
printf("%d\n", n);
return 0;
}
Output:
3
Note that this version is limited to N elements in the initializer.

Printing Arrays in separate Function in C

I'm trying to print all of the values in the four arrays by sending them to a separate function. But, the problem is I can't get the function to print the all of the integers in the array because I'm not sure what I could set the condition statement in the for loop to, that would be universal to any array of any size.
Right now the function only prints the first 11 numbers. I assume that's because the first number in that array is 11.
#include <stdio.h>
void print_array(int a[]);
void find_max(int b[]);
void find_min(int c[]);
void search(int d[]);
void SORT(int e[]);
int main(void)
{
int first[11] = {7,7,7,7,7,7,7,7,7,7,7};
int second[14] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2};
int third[16] = {-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int fourth[23] = {-3, 4, 33, 22, 9, -100, 2, 56, 57, 55, 2, 90, 2234, 32, 8, 123, 2, 33, 22, 22, 33, -1, -3};
print_array(&second[0]);
return(0);
}
void print_array(int a[])
{
int i;
for(i=0;i<*a;i++)
{
printf("%d ",a[i]);
}
}
Pass a second argument to your function that takes the length of the array. For example:
print_array(int *array, int length)
{
for (int i = 0; i < length; i++) { /* whatever */ }
}
The function has no way of knowing when the array ends. This piece of data simply does not exist unless you pass it manually. The array is just a sequence of bytes in the memory, it has no end delimiter. So you should add a parameter to the function telling it the length of the array.
Yep, this is how it works in C.
Change the function to:
void print_array(int a[], size_t a_size) {
int i;
for(i=0; i< a_size;i++)
// ...
And change the calling of the function to pass in the size:
print_array(second, sizeof(second)/sizeof(second[0]));
Which will calculate the memory size of the array (for a 4 int array on a 32 bit system it'll be 16) and divide it by the size of an int (on a 32 bit system, it's 4 bytes).
in C you can make it with a function and macro:
void printArray_(int *a, int len) {
for (int i = 0; i < len; i++) printf("%d ", a[i]);
}
#define printArray(arr) printArray_((arr), sizeof(arr)/sizeof(arr[0]))
int main(int argc, _TCHAR* argv[])
{
int data[] = { 1,2,3,4 };
printArray(data);
return 0;
}
output:
1 2 3 4
Change this line
print_array(&second[0]);
To
print_array(&second);
Because,
&second[0] just passes the reference to the element at 0th position,which will not be able to traverse the array.
And we cannot traverse the array passed by reference without the size.As there are arrays of varied size, we can compute the size of the array by,
int array_length = sizeof(array)/sizeof(array[0]);
Change the line
void print_array(int a[])
To
void print_array(int *a,int array_length)
And the function of array printing will be as,
void print_array(int *a,int array_length){
int i;
for(i=0;i<array_length;i++){
printf("%d ",*a);
a++; //for incrementing the position of array.
}
}

Resources