Variadic function returns garbage value - c

I was testing variadic functions in C. The following was supposed to return the sum of all of the arguments but it keeps printing garbage values instead.
#include <stdio.h>
#include <stdarg.h>
int add(int x, int y, ...)
{
va_list add_list;
va_start(add_list, y);
int sum = 0;
for (int i = 0; i < y; i++)
sum += va_arg(add_list, int);
va_end(add_list);
return sum;
}
int main()
{
int result = add(5, 6, 7, 8, 9);
printf("%d\n", result);
return 0;
}
I thought it was going to return the sum of all of the arguments

The variadic function needs some way of knowing how many values you have passed to the function. Therefore, you should additionally pass this number as the first argument to the function:
#include <stdio.h>
#include <stdarg.h>
int add( int num_values, ... )
{
va_list add_list;
va_start( add_list, num_values );
int sum = 0;
for ( int i = 0; i < num_values; i++ )
sum += va_arg( add_list, int );
va_end(add_list);
return sum;
}
int main( void )
{
int result = add( 5, 5, 6, 7, 8, 9 );
printf( "%d\n", result );
return 0;
}
This program has the following output:
35

You say that you have y optional arguments, but actually you have only 3, instead of 6.
int result = add(5, 3, 7, 8, 9);
should work.
PS: Also, you do not use the first parameter x, so you can remove it.

Related

Find max, min and sum of an array using function

I want to create a programm to find maximum, minimum and summation for a given array, but when I take my code to compiler, it returned expressed expression before 'int' and too few arguments to all the functions.
And here is my code, please tell me why it doesn't work.
#include <stdio.h>
#include <stdlib.h>
void print_array(int array[], int len) {
// print array on screen
int b;
printf("Array: ");
for (b = 0; b < len - 1; b++) {
printf("%d, ", array[b]);
}
if (b >= len - 1) {
printf("%d\n", array[b]);
}
}
// function
int min(int *x, int len) {
int mintemp = x[0], i;
for (i = 1;i < len;i++) {
if(x[i] < mintemp) {
mintemp = x[i];
}
}
return mintemp;
}
int max(int *y, int len) {
int maxtemp = y[0], j;
for (j = 1;j < len;j++) {
if(y[j] > maxtemp) {
maxtemp = y[j];
}
}
return maxtemp;
}
int sum(int *z, int len) {
int sumtemp = 0, k;
for (k = 0;k < len;k++) {
sumtemp = sumtemp + z[k];
}
return sumtemp;
}
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(int *x, int len));
printf("Minimum: %d\n", min(int *y, int len));
printf("Summation: %d\n", sum(int *z, int len));
return 0;
}
The problem was with calling the functions. Function call in C is like this
function_name(argument 1, argument 2, argument 3, ......, argument n);
There is no need to specifying the data type along the parameters in the call like you were doing in your code.
Also you were passing pointers x, y and z that do not point to your array.
I have corrected the code as shown below.
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(array, len)); // pass array and len
printf("Minimum: %d\n", min(array, len));
printf("Summation: %d\n", sum(array, len));
return 0;
}
If you want to pass the array to functions via pointers you can do it like this.
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
int *x = array;
int *y = array;
int *z = array;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(x, len));
printf("Minimum: %d\n", min(y, len));
printf("Summation: %d\n", sum(z, len));
return 0;
}
Also there is no need to declare 3 different pointers and pass it to the functions, you can declare just one and reuse it with subsequent calls.
Hope this helps.!!

How to merge array elements with token merging ## operator???

I want to merge 3, 7, 1 to get 371. I want to know how to merge it???
#include <stdio.h>
int main(void)
{
int a[] ={3, 7, 1};
return(0);
}
I think rather than "merge", you want to convert array into an integer value, just like join operation that we see in Java variants. You can easily achieve this by iterating over the array :
#include <stdio.h>
int joinArray(int a[], int N) {
int i, res = 0;
for(i = 0; i < N; i++)
res = res*10 + a[i];
return res;
}
int main() {
int a[] = {3, 7, 1};
printf("merged res : %d\n", joinArray(a, 3));
return 0;
}
You could try something like this;
#include <stdio.h>
int main(void)
{
int a[] ={3, 7, 1};
int i, result = 0;
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
result += a[i] * pow(10, sizeof(a)/sizeof(a[0])-i-1);
printf("result %d\n", result);
return(0);
}

Print elements after place in array in c

So I tried to print elements of array after some point or place
but its print me another number of garbage. The code need to print 7,8,9,5.
I'm sure that the problem is in the line :
for (arr=x+1; arr < arr+ n; arr++)
but I don't understand what to write instead this line.
Please help me and use * or & instead [](use pointers). thanks!
#include <stdio.h>
#include <stdlib.h>
void printAfterX(int* arr, int n, int* x);
int main(void)
{
int arr[] = { 4, 8, 6, 2, 1, 3, 5, 7, 8, 9, 5 };
printAfterX(arr, 11, arr + 6);
system("PAUSE");
return 0;
}
void printAfterX(int* arr, int n, int* x)
{
if (n >= arr)
{
printf("not found");
}
else
{
for (arr=x+1; arr < arr+ n; arr++)
{
printf("%d ",*arr);
}
}
}
Why do you need to mix pointers and indices? You are right, in the line for (arr=x+1; arr < arr+n; arr++) there is a problem, because arr < arr + n is always true for positive n. So, this loop will never end.
Also it is not clear what does if (n >= arr) mean. Here you compare number of elements in the array and pointer on this array. It is useless. It seems that you need to compare x and arr.
I'd recommend you to use index of element to simplify your code. Try this:
void printAfterX(int* arr, int n, int x)
{
if (x < 0 || x+1 >= n)
{
printf("not found");
}
else
{
for (int i = x+1; i < n; i++)
{
printf("%d ", arr[i]);
}
}
}
And to call this function you need to change third parameter:
printAfterX(arr, 11, 6);
Also it is better to avoid using of system("pause") - read here: system("pause"); - Why is it wrong?
Update:
Ok, if you need to use pointers, try this:
void printAfterX(int* arr, int n, int* x)
{
if (x < arr || x+1 > arr+n)
{
printf("not found");
}
else
{
for (x = x+1; x < arr + n; x++)
{
printf("%d ", *x);
}
}
}
It is obvious that arr < arr + n always holds true unless it has an overflow, so the loop won't stop before that happens.
Furthermore, by writing n >= arr, you compare an int to an int *, which definitely make no sense. To check the array bound, you should also check whether it's less than the lower bound.
Finally, I think it's better to use a simple while loop.
Here is the refined code:
#include <stdio.h>
#include <stdlib.h>
void printAfterX(int *arr, int n, int *x);
int main(void)
{
int arr[] = { 4, 8, 6, 2, 1, 3, 5, 7, 8, 9, 5 };
printAfterX(arr, 11, arr + 6);
getchar();
return 0;
}
void printAfterX(int *arr, int n, int *x)
{
if (x < arr || x >= arr + n)
{
printf("No such element");
}
while(x < arr + n)
{
printf("%d ", *x);
x++;
}
}
The line for (arr=x+1; arr < arr+ n; arr++) is an infinite loop as arr < arr+ n is always true.
Also in line if (n >= arr) you are comparing a int with a pointer,which is not meaningful.
Modify your function like this:
void printAfterX(int* arr, int n, int* x)
{
if (n <= x-arr) //checking it doesn't exceeds the size
{
printf("not found");
}
else
{
for (x++; x < arr+ n; x++)
{
printf("%d ",*x);
}
}
}
You have to pass the number of elements as a parameter to the function to know when you have reached the end of the array.
You also can't compare a variable of type int to varibale of type int *.Try this version:
#include <stdio.h>
#include <stdlib.h>
void printAfterX(int* arr, size_t size, size_t offset);
int main(void)
{
int arr[] = { 4, 8, 6, 2, 1, 3, 5, 7, 8, 9, 5 };
printAfterX(arr, 11, 7);
system("PAUSE");
return 0;
}
void printAfterX(int* arr, size_t size, size_t offset)
{
if (offset >= size)
{
printf("not found");
return;
}
else
{
while(offset < size)
{
printf("%d ", *(arr + offset));
offset++;
}
}
}
Try it:
#include <stdio.h>
#include <stdlib.h>
void printAfterX(int[], int, int);
int main(void)
{
int arr[] = { 4, 8, 6, 2, 1, 3, 5, 7, 8, 9, 5 };
printAfterX(arr, 11, 6);
system("PAUSE");
return 0;
}
void printAfterX(int arr[], int n, int x)
{
if (n <= arr[x])
{
printf("not found");
}
else
{
for (i=x+1; i < n; i++)
{
printf("%d ",arr[i]);
}
}
}

Completing my addarray () formula

I apologize for my vagueness in advance-this is my first post and I can really use some help.
The assignment is as follows:
/* Write a function named addarray() that returns the sum of the
elements of an array of int values. Your functions should take two
parameters, the array and the number of elements in the array. Make
your function work with the following program; */
/* arraysum.c
*
* Synopsis - displays the value returned by the function addarray()
* with 2 different sets of parameters.
*
* Objective - To provide a test program for the addarray() function.
* Your answers should be 55 and 0.
*
*/
#include <stdio.h>
int addarray(int [], int, int);
void main() {
int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int array2[4] = {0, 0, 0, 0};
printf("The sum of array1 = %d\n", addarray(array1, 0, 10));
printf("The sum of array2 = %d\n", addarray(array2, 0, 4));
}
This is my solution aid:
int addarray(int s[], int i, int n) {
int sum = 0;
for (i = 0; i < n; i++) {
sum += s[i];
}
return sum;
}
I cant seem to figure out how to get the proper result. Any help would be appreciated.
This is what I have completed so far:
#include <stdio.h>
int addarray(int array1[], int num_elements);
void print_array(int array1[], int num_elements);
void main(void)
{
int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum;
printf("\nArray:\n");
print_array(array1, 10);
sum = addarray(array1, 10);
printf("The sum is %d\n .", sum);
}
int addarray(int array1[], int num_elements)
{
int i, sum=0;
for (i=0; i<num_elements; i++)
{
sum = sum + array1[i];
}
return(sum);
}
void print_array(int array1[], int num_elements)
{
int i;
for(i=0; i<num_elements; i++)
{
printf("%d ", array1[i]);
}
printf("\n");
}
I cant figure out how to get a second array to be summed up.
Such as Array2.
int is a reserved word.you can't give a variable the name int.besides,the assignment says the function should take two parameters,not 3.check this :
#include <stdio.h>
int addarray(int arr[],int size);
void main() {
int array1[10] = {1,2,3,4,5,6,7,8,9,10};
int array2[4] = {0,0,0,0};
printf("The sum of array1 = %d\n", addarray(array1,10));
printf("The sum of array2 = %d\n", addarray(array2,4));
}
int addarray(int arr[],int size)
{
int sum = 0 , n ;
for( n = 0 ; n < size ; n++ )
{
sum += arr[n];
}
return sum;
}

C recursive permutations

i have been trying to complete figure out this part of my assignment to no avail for the past day, and require some help or guidance to help understand the problem.
so far i have this:
swap(int A, int B){
int temp;
temp = A;
A = B;
B = temp;
}
int max_array(int array[], int arraySize)
{
int i, max=-32000;
for (i=0; i<arraySize; i++)
{
if (array[i]>max)
{
max=array[i];
}
}
printf("%d \n Max array: ", max)
return(max);
}
int nextPermutation(int array[], int arraySize){
int i;
n = max_array(array, arraySize);
if (int i; n == array[i] && i > 1; i++){
swap(array[i], array[i-1]);
}
else if(int i; n == array[i]; i++){
}
}
void main(){
int intArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//int intArray[10] = {1, 10, 3, 9, 8, 6, 7, 2, 4, 5};
nextPermutation(intArray, 10);
int i = 0;
for(i = 0; i < 10; i++){
printf("%d ",intArray[i]);
}
}
But the question that i'm struggling to understand is
"If a1,...,an is an arbitrary permutation (where a1,...,an are the numbers 1, 2, …, n in a probably different order) then the “next” permutation is produced by the
following procedure:
(i) If the maximal element of the array (which is n) is not the first element of the
array, say n=ai , where i>1 , then to produce the "next" permutation you
need to swap ai and ai−1 .
(ii) If the maximal element of the array is in the first position, i.e. n=a1 , then to
produce the “next” permutation to the permutation (a1,...,an)
, first find the “next” permutation to the (n-1)-element permutation (a2,...,an
), and then append a1 to the end of thus obtained array of (n-1) elements."
so it needs to permutate every single possible combination with the array of 1,2,3,4,5,6,7,8,9,10 and then finish when it reaches this point "(n, …, 2, 1). And this is
the only permutation that does not have the "next" permutation to it."
And the function int 'nextPermutation(int array[], int arraySize){' needs to stay the same.
Any help or tips will be excellent!
There are some errors in your program,
swap() function will not affect the program as it doesn't use pass by reference.
max_array() should find the index of the maximum value, not the maximum value itself.
There is no recursion in your program as far as I can see.
main() should return int.
The program fragement given below might give you an idea,
int ct=-1,n=10,temp[10]={0,0,0,0,0,0,0,0,0,0};
int intArray[10]={1,2,3,4,5,6,7,8,9,10};
permute(int k)
{
int i;
temp[k]=++ct;
if(ct==n-1)
{
for(i=0;i<n;i++)
{
printf("%d",intArray[temp[i]]);
}
printf("\n");
}
for(i=0;i<n;i++)
{
if(temp[i]==0)
{
permute(i);
}
}
ct--;
temp[k]=0;
}
int main()
{
permute(0);
}
for swap sample
#include <stdio.h>
void swap(int* A, int* B){
int wk;
wk = *A;
*A = *B;
*B = wk;
}
int main(void){
int array[] = { 1,2,3 };
swap(&array[0], &array[2]);
printf("array[0]=%d, array[2]=%d\n", array[0], array[2]);
return 0;
}

Resources