Using Functions with Arrays? Code doesn't work - c

Why this code isn't work? I know there are other ways to do this but it must be this way. How can I fix this problem?
#include <stdio.h>
#include <stdlib.h>
int total(int arr[3], int size_of_array){
int i=0;
int total=0;
for(i=0;i<size_of_array;i++){
total+=arr[i];
}
return total;
}
int main(){
int array2[3]= {0,1,8};
int total(array2, 3);
}

int main(){
int array2[3]= {0,1,8};
int theAnswer; // Make an integer for the result.
theAnswer = total(array2, 3); // Call the function, and store the result.
printf("The answer is %d\n", theAnswer); // Show the result to the user
return 0; // main has to return 0 to indicate "success"
}

Related

Why is my solution to the k subarray product problem not working?

I implemented a solution that uses xor to know if a product has been computed before. It recursively gets all the possible products. Here's the code:
#include <stdio.h>
int driver(int *arr, int k, int n){
int counter=0;
int sbc=0;
while(counter++<n){
d_recursive(arr,k,n,1,0,arr[counter],&sbc);
}
return sbc;
}
void d_recursive(int *arr, int k, int n, int p, int prvc, int currc, int *sbc){
int counter=0;
while(counter++<n){
if(currc^arr[counter]*p!=prvc&&arr[counter]*p<k){
*sbc++;
d_recursive(arr,k,n,arr[counter]*p,currc,currc^arr[counter]*p,sbc);
}
}
}
int main(int argc, char **argv){
if(argc<3){
printf("Usage: %s [array of numbers] [value of k]\n",argv[0]);
return 1;
}
puts("Converting string arguments to integers(and adding them to a set).");
int i_arr[argc-2];
int prev_cache=0;
int curr_cache=atoi(argv[1]);
int counter=2;
while(counter++<argc-1){
if(curr_cache^atoi(argv[counter])!=prev_cache){
i_arr[counter]=atoi(argv[counter]);
prev_cache=curr_cache;
curr_cache^=i_arr[counter];
}
}
puts("Finished conversion.");
puts("Passing values to function.");
int output=driver(i_arr,atoi(argv[argc-1]),argc-2);
printf("Finished. Output is %d.",output);
return 0;
}
I tried printing a character every time d_recursive is called. It was called many times. The weird thing is, it takes the same time to segfault when input array size is 3 and 7. Why?

Selection Sort algorithm in C doesn't print the entire sorted array

#include <stdio.h>
#include <stdlib.h>
int smallest(int [],int);
int select_sort(int[],int);
int smallest(int arr[],int len){
int small_index=0;
int small=arr[0];
for(int i=0;i<len;i++){
if(arr[i]<small){small=arr[i];
small_index=i;
}
}
return small_index;
}
int select_sort(int arra[],int len){
int new_arra[100];
for(int i=0;i<len;i++){
int small=smallest(arra,len);
new_arra[i]=arra[small];
printf("%d",new_arra[i]);
}
return new_arra;
}
int main()
{
int arr[100]={6,1,0,-2,18};
select_sort(arr,5);
return 0;
}
I wrote this code for the selection sorting program and i know ideally i should be using the dynamic allocation for arrays in the select_sort function, but i was attempting it without it. It is supposed to print the array in an ascending order and I think I am messing up variable assignment somewhere, because when i run the program it only prints the smallest integer of the input array len number of times and not the rest of them.
If you don't mind messing up with your initial array, you can do:
int select_sort(int arra[],int len)
{
int maxValue = Integer.Max_Value;
int new_arra[100];
for(int i=0;i<len;i++){
int small=smallest(arra,len);
new_arra[i]=arra[small];
arra[small]= maxValue;
printf("%d",new_arra[i]);
}
return new_arra;
bear in mind that this is highly unefficient

Why does this function only assign the first collected value to the pointer but not the rest? [duplicate]

I am making this program in which my main function calls a function which returns an array after the calculation. I checked already that calculation is right inside the local function. But when I return that array to 'main' function then I only can print the correct value one time and it prints wrong value all other times.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int* getJoinedPipes(int input1_size, int* input1,int* output_size){
int i,j,temp;
int op1[input1_size-1];
*output_size = input1_size - 1;
for(i=0; i<input1_size; i++){
for(j=i+1; j<input1_size; j++){
if(input1[i] > input1[j]){
temp = input1[i];
input1[i] = input1[j];
input1[j] = temp;
}
}
}
op1[0]=input1[0] + input1[1];
for(i=1;i<input1_size-1;i++){
op1[i] = op1[i-1]+input1[i+1];
}
//printf("%d\n",op1[2]);
return op1;
}
int main() {
int output_size;
int* output;
int ip1_size = 0;
int ip1_i;
scanf("%d\n", &ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
int ip1_item;
scanf("%d", &ip1_item);
ip1[ip1_i] = ip1_item;
}
output = getJoinedPipes(ip1_size,ip1,&output_size);
printf("a==%d\n",output[0]);
printf("a==%d\n",output[0]);
printf("a==%d\n",output[0]);
int output_i;
for(output_i=0; output_i < output_size; output_i++) {
printf("%d\n", output[output_i]);
}
return 0;
}
Output should be
5
9
15
But in the console, it's showing the following (after dry run).
a==5
a==1943372821
a==1943372821
1943372821
17
6356632
You can see first time its giving correct value (5) and later for same print its giving garbage values.
op1 is an automatic array. You cannot return it and use it outside its scope.
op1 exists only within getJoinedPipes, if you return it, the result is Undefined Behaviour.
To fix it you can either:
pass op1 as a parameter to getJoinedPiped
allocate op1 on the heap dynamically. You you do that, you can safely return op1 but you have to remember to free it when you don't need it.
You are returning pointer to a local variable object whose lifetime has ended yet when you are trying to get its values -> horrible mistake and undefined behaviour.
If you want to return an array from function, allocate it dynamically via malloc, and dont forget to free it after you are done with that array. You should also check return value of malloc if you got memory you asked for.
Correct
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int* getJoinedPipes(int input1_size, int* input1,int* output_size){
int i,j,temp;
int * op1 = (int *)malloc(sizeof(int) * (input1_size-1));
*output_size = input1_size - 1;
for(i=0; i<input1_size; i++){
for(j=i+1; j<input1_size; j++){
if(input1[i] > input1[j]){
temp = input1[i];
input1[i] = input1[j];
input1[j] = temp;
}
}
}
op1[0]=input1[0] + input1[1];
for(i=1;i<input1_size-1;i++){
op1[i] = op1[i-1]+input1[i+1];
}
//printf("%d\n",op1[2]);
return op1;
}
int main() {
int output_size;
int* output;
int ip1_size = 0;
int ip1_i;
scanf("%d\n", &ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
int ip1_item;
scanf("%d", &ip1_item);
ip1[ip1_i] = ip1_item;
}
output = getJoinedPipes(ip1_size,ip1,&output_size);
printf("a==%d\n",output[0]);
printf("a==%d\n",output[0]);
printf("a==%d\n",output[0]);
int output_i;
for(output_i=0; output_i < output_size; output_i++) {
printf("%d\n", output[output_i]);
}
free(output);
return 0;
}
You should check your indentation... apart from that, I guess the problem could arise because the array you output in your function is created on the function stack. So what you get as an output array is a reference on the stack of your joinedPipes-function. Try to pass your array as an argument to the function and not create it as a return value.
Hope that does the trick...

Sum of array using pointers

#include <stdio.h>
int arrsum(int *, int *);
int main(void){
int a[]={1,2,3,4,5,6,7,8,9,10};
printf("\nSum: %d\n", arrsum(a,a+9));
return 0;
}
int arrsum(int *p, int *q){
int sum;
for(;p<=q;++p){
sum+=*p;
}
return sum;
}
I want to print the sum of elements of array using pointers because I am learning pointers.
When I run this code, I am getting 32811 as output which is wrong.
Please help.
Replace:
int sum;
with
int sum = 0;
Every statement is write
Just initialise Sum to any number because a complier assinged a garbage value to Sum .

Using variables

I have a problem with this simple program because it doesnt give me the true outcome. I just want to sum two arguments in the first function and then use the outcome in the second one. It will be nice to have overall outcome in the main function. Also I would like to ask the same question with arrays.
#include <stdio.h>
#include <stdlib.h>
int sum()
{
int a=2;
int b=3;
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int s)
{
int c=5;
int d=c+s;
}
int main(int s,int d)
{
sum();
printf("sum=%d\n",s);
printf("sum2=%d\n",d);
getchar();
return 0;
}
There are many problems with this code:
int main(int s, int d) won't do what you think. Command-line arguments to your program come in string format. So you would need to use int main(int argc, char *argv[]).
The variables s and d in main() are completely independent to the variables in sum() and sum2(). So changing their values in those functions will not affect the original variables.
You're not even calling the second function!
You can do things like this:
int sum(int a, int b)
{
return a+b;
}
int sum2(int c)
{
return c+5;
}
int main(void)
{
int x = 2;
int y = 3;
int z = sum(x,y);
int w = sum2(z);
printf("z = %d\n", z);
printf("w = %d\n", w);
}
First of all, s is a local variable inside sum( ). Hence it cannot be available outside the function.
int sum() {
// ..
int s = a+b; // local variable, hence local scope
// ..
}
Also, secondly, int main(int s,int d) won't work since in command line arguments come in String format. So can't use a int there
I won't tell you the answer (lol but others have) but I'll give you these clues to figuring it out.
Ask your self which functions are returning data and which ones aren't.
Clue: the function needs a return to return some data.
Then ask yourself which functions' returns are actually being used.
Clue: to collect the data returned from a function you need to assign the result to a variable like so
int i;
i = somefunct();
You can't access the value of variable 's' outside the function sum() since it is out of scope. You'll have to return the value to your main() function. Also your main function parameters are incorrect. You need something more like this:
#include <stdio.h>
#include <stdlib.h>
int sum(int a, int b)
{
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int c, int sum)
{
return c+sum;
}
int main(int argc, char *argv[])
{
int val1 = sum(2, 3);
printf("sum=%d\n",val1);
int val2 = sum2(5, val1);
printf("sum2=%d\n", val2);
getchar();
return 0;
}

Resources