I fairly new to C and am currently trying to use some parameters from one function in another function.
Essentially from function1 (which asks the user to input an array and return its size) I need to pass the whole array and its size as parameters to function2 which will then print them out to screen/file in the format shown in this image.
How can I create another separate function that uses the array and size of function1 in order to give me the desired output as described above.
For reference, this is the code for function1:
(I made use of a header as these two functions will later on be implemented into a menu)
#include <stdio.h>
#include "function1.h"
//Main
int main(void) // Without the explicit "void" argument list, this isn't a full function definition
{
int size;
printf("The size of list: ");
if (scanf("%d", &size) != 1 || size < 1) { // You should ALWAYS check the return value of a scanf call
printf("Invalid size input.\n");
return 1;
}
int marks[size]; // Need to specify the size and note that you cannot initialize a VLA
if (size >= 200) {
printf(" Limit exceeded.\n");
return 2;
}
intarray(marks,size);
return 0;
}
And the header file for function1 is:
#ifndef FUNCTION1_H
#define FUNCTION1_H
int intarray(int ar[], int size){
printf("Please enter %d values:\n"); // You need to give "size" as an argument
for (int i = 0; i < size; i++) {
scanf("%d", &ar[i]); // You should add a check for valid input here, as I have done in main
}
printf("Elements in array are: ");
for (int i = 0; i < size; i++) {
printf("%d, ", ar[i]);
}
printf("\n");
printf("Size of array is: %d", size);
}
#endif //FUNCTION1_H
Related
This algorithm is a linear search algorithm that finds the desired value. But when I compile this code, gives the segmentation fault in if(dizi[i]==aranan) this line. How can I solve this ?
#include <stdio.h>
int N,i,aranan;
int ArrayBastir(int *dizi,int N)
{
printf("My numbers\n");
for(int i =0; i<N;i++)
{
printf("%d\n", dizi[i]);
}
}
int findValue()
{
printf("The value you want to search");
scanf("%d",&aranan);
}
int Output(int *dizi,int N,int aranan)
{
for(int i =0; i<N;i++)
{
if(dizi[i]==aranan)
{
printf("%d number %d. found in queue \n", aranan,i+1);
}
}
}
int main() {
int N;
int aranan;
printf("Please enter how many numbers you want to enter");
scanf("%d", &N);
int dizi[N];
for(int i =0; i<N;i++)
{
scanf("%d", &dizi[i]);
}
ArrayBastir( dizi, N);
findValue(aranan);
Output(*dizi,N,aranan);
return 1;
}
Linear Search algorithm
You have two objects defined as:
int aranan;
Once is defined at file scope (a global), and one is defined within the scope of main.
When findValue(aranan) is called, a copy of the uninitialized value of aranan within the scope of main is passed to findValue. findValue is lacking a prototype, having not declared its arguments, so this is ignored.
findValue scans a value into the file scope aranan, but when Output(*dizi, N, aranan) is called it uses the value of aranan defined within main. aranan within main was never initialized, and thus this causes Output to search for an indeterminate value.
Additionally, *dizi is an int, when Output expects an int * as its first argument.
ArrayBastir and Output are also defined as each returning an int, which they do not do.
You should not ignore the return value of scanf, as it indicates the number of successful conversions, or a negative value on failure (EOF). In a program this small, you can get away with writing a simple wrapper function for reading integers, that just exits the program if the user enters something invalid.
main returning nonzero generally indicates your program failed. main is special - it is the only non-void function where you can omit a return statement. If main reaches the end of execution without an explicit return, it is treated as though it returned 0.
The issues above can be mitigated by avoiding the use of global variables, and by turning up your compilers warning level to catch obvious type mismatches.
For GCC or Clang, use -Wall -Wextra, and possibly -Werror.
For MSVC, use /Wall, and possibly /Wx.
Minimally refactored:
#include <stdio.h>
#include <stdlib.h>
int get_int(void)
{
int x;
if (1 != scanf("%d", &x)) {
fprintf(stderr, "Invalid input.\n");
exit(EXIT_FAILURE);
}
return x;
}
void ArrayBastir(int *dizi, int N)
{
printf("My numbers\n");
for (int i = 0; i < N; i++) {
printf("%d\n", dizi[i]);
}
}
void Output(int *dizi, int N, int aranan)
{
for (int i = 0; i < N; i++) {
if (dizi[i] == aranan) {
printf("Found <%d> at position %d.\n", aranan, i);
}
}
}
int main(void)
{
printf("Please enter how many numbers you want to enter: ");
int N = get_int();
int dizi[N];
for (int i = 0; i < N; i++) {
dizi[i] = get_int();
}
ArrayBastir(dizi, N);
printf("Enter the value you want to search for: ");
int aranan = get_int();
Output(dizi, N, aranan);
}
I am writing a program to check whether a set is a proper subset of a set or not. I am dynamically allocating memory for both of the sets(arrays) but after I provide one element the program stops executing.
#include <stdio.h>
int setID(int arr[],int arr2[],int size,int size2)
{
int counter =0;
for (int i=0; i<size2;i++)
{
if (arr2[i] == arr[i])
{
counter++;
}
}
if (counter == (size2))
{
return 1;
}
else
return 0;
}
int main ()
{
printf("We are going to check if set A is a proper subset of B or not\n");
printf("Please provide the cardinal number of set A \n");
int a=0,b=0;
scanf("%d",&a);
int *p;
p =(int*) malloc(a*sizeof(int));
printf("Please provide the elements of Set A\n");
for (int i=0;i<a;i++)
{
scanf("%d",p[i]);
}
printf("Please provide cardinal number for set B\n");
scanf("%d",&b);
int *p1;
p1= (int*) malloc(b*sizeof(int));
for (int i=0;i<b;i++)
{
scanf("%d",&p1[i]);
}
printf("Please note that 0 is false and 1 is true\n");
printf("%d\n",setID(p,p1,a,b));
return 0;
}
**Also have I passed the arguments correctly in the function: printf("%d\n",setID(p,p1,a,b)); **
There is one error here
scanf("%d",p[i]);
which should be
scanf("%d", &p[i]);
and which is correct a few lines further down when you did this with p1. You say the program stops after providing one element and this is consistent with the error.
There may be other errors too as posted by others.
in setID :
for (int i=0; i<size2;i++)
{
if (arr2[i] == arr[i])
{
counter++;
}
...
you suppose the size of arr is >= the size of arr2, but this is not mandatory because you read their size rather than to use the same when you allocate the arrays and read their values
if size < size2 (a < b in main) you go out of arr (p in main), the behavior is undefined
I'm trying to create a program which randomly decides how many cards you have, then randomly allocates a value to each of those cards.
I have managed to randomise the amount of cards, and I know how to randomise their values using an array and a for loop, but the problem is that this method only works when I manually choose a value for the number of elements in the array, but I want the number of elements to be the random amount of cards.
How do I go about this?
Here's my code so far to show what I mean. And yes, I'm aware the code probably could be done better but this is my first C assignment and I'm a complete beginner.
Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(void)
{
system("cls"); /* Clears output to start */
srand(time(NULL)); /* Sets seed for random number generator */
int player1_amount = rand() %9 + 2; /*Generates random number for player 1's amount of cards */
int player2_amount = rand() %9 + 2; /*Generates random number for player 2's amount of cards */
int a = 1; /* For loop purposes */
while(a <= 1) /* While loop to print out each player's amount of cards once */
{
printf("Player 1 you have %d cards! \n", player1_amount);
Sleep(500);
printf("Player 2 you have %d cards! \n", player2_amount);
a++;
}
Sleep(1000); /* Delays for 1 second before printing card values */
int values[3]; /* Creates an array with 3 elements, but I want the number of elements to be player1_amount from above */
int b; /* Random variable for the loop */
int size = sizeof(values) / sizeof(values[0]); /* Gets length of array */
for (b = 0; b < size; b++) /* For loop randomises 3 values and then stops */
{
values[b] = rand() % 10 +1;
}
printf("Player 1 your cards are"); /* For loop to print out the values one after the other */
for(b = 0; b < size; b++)
{
printf(" %d, ", values[b]);
}
getch();
return 0;
}
I believe you will want to use malloc or calloc for that with a pointer.
int *values = (int *)calloc(player1_amount, sizeof(int));
Just make sure you free your allocation when done:
free(values);
C allows you to declare variable sized array. If you are not interested in using functions like malloc or calloc you can simply use variable to declare array as I've done here :
#include <stdio.h>
void main()
{
int x;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
int array[x];
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
This program runs correctly without any error. So your problem is solved here itself without using malloc or calloc. But just make sure you declare your array after scanning or giving value to your variable which will represent the size of your array(here : x is the variable) and in your case I guess : player1_amount.
But still if you want to use malloc then here it goes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int x , i;
int * array;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
array = (int *) malloc(x * sizeof(int));
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
Both the codes will give you same output.
A little explanation ...
Malloc will take input parameter as the amount of memory you wish to allocate to given variable(like 'array' in our case) in bytes and will output the pointer to that block of memory.
Since here we are working with integer array the return type is cast as : (int *), had it been a character array we would type cast it as : (char *).
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 5 years ago.
I'm trying to create a function that creates an array in size n with random numbers stored inside, I've been trying several option but once i use the array in main, only the first number shows up correctly.
I'm using CodeBlock by the way.
static int *arr;
int i, num;
printf("enter the length of the array: ");
scanf("%d/n", &num);
arr = get_random_arr(num);
for(i=0;i<num;i++)
{
printf("outside the function: %d\n", *(arr+i));
}
return 0;
int *get_random_arr(int num)
{
int temp_arr[num];
int i;
srand((unsigned)time(NULL));
for (i=0;i<num;i++)
{
temp_arr[i] = rand() % 1001 ;
printf("inside the function: %d\n",temp_arr[i]);
}
return temp_arr;
}
and this is the code that compiles:
enter the length of the array: 3
inside the function: 224
inside the function: 774
inside the function: 60
outside the function: 224
outside the function: 2686648
outside the function: 1977872892
Thank's to "coderredoc" his answer was the solution i was looking for
scanf("%d/n", &num);
You have to enter the number followed by / and n. This is not what you want. You wanted this
scanf("%d\n", &num);
But here the scanf reads the number in num but then the reading continues until nonwhitespace character followed by \n is found. You don't need the \n here.
Also returning return temp_arr; and using it outside it's scope is UB.
The array temp_arr has automatic storage duration meaning its lifetime will end after the function ends. Accessing it outside its scope is undefined behavior which is precisely what you did.
Something like this
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *get_random_arr(int num)
{
if( num <= 0){
fprintf(stderr, "%s\n", "Error in the number: num >= 1");
exit(1);
}
int *temp_arr = (int*)malloc( sizeof *temp_arr *num);
if( !temp_arr ){
fprintf(stderr, "%s\n", "Error in malloc");
exit(1);
}
srand((unsigned)time(NULL));
for(size_t i=0;i<num;i++)
{
temp_arr[i] = rand() % 1001 ;
printf("inside the function: %d\n",temp_arr[i]);
}
return temp_arr;
}
int main(){
static int *arr;
int num;
printf("enter the length of the array: ");
if( scanf("%d", &num) != 1){
fprintf(stderr, "%s\n","Error in input" );
exit(1);
}
arr = get_random_arr(num);
for(size_t i=0;i<num;i++)
{
printf("outside the function: %d\n", *(arr+i));
}
free(arr);
return 0;
}
The code tries to show a possible way to achieve what you wanted. Dynamically allocated memories lifetimes extends beyond the scope of the function. That's why it works. Note the free() - which is used to free the dynamically allocated memory.
The first and foremost, in your code, temp_arr is local to the function get_random_arr(). Once the function finishes, the returned address is not valid anymore!
The moment you try to use the returned value, it causes undefined behavior, as the accessed memory is invalid in the context of the caller.
That said, not checking the return value of scanf() also posses a problem. In case scanf() fails, you'll be end up using an unitialized value.
I have been asked to write a lottery program in c++ not sure if i am using function correctly please help
//function prototypes
int myNumbers();
void displayNums();
#include <stdio.h>
#define NUMS 6
#define WIN 7
// function myNumbers takes input from user
int myNumbers(int numbers[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
return (numbers);
}//end function myNumbers
Each of your functions declares a new array, rather than using the array passed to it as an argument.
void displayNums(int print[])
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n", output);
}
Note that nowhere is the print argument used, and you're using int numbers[NUMS] instead. Remove that declaration and use print. (Also please consider naming your argument something other than print; this name is confusing and does not accurately describe what the variable stores.)
you are not using arrays properly to communicate the numbers, see the function
int myNumbers(int userPick[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i);
return (numbers);
}//end function myNumbers
it reads the number to a local array and returns *(input+i) which will be a random number since your read array is from input+0 to input+i-1. you should pass array or pointer to global array.
Even in case of display() function you are passing one array and using some other array inside display() function.
you should use a common array to communicate values. you can create a array in global scope and use it in all functions or create a array in main() and pass pointer to it to other functions and use the same array in other functions. learn how to pass arrays between functions and use arrays
Your functions looks erroneous:
int myNumbers(int userPick[]) // 1. userPick is not used anywhere
{
int i;
int numbers; // 2. initialize this variable to 1 first
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i); // 3. is this suppose to be inside the loop ?
return (numbers);
}//end function myNumbers
And in
void displayNums(int print[])//implement function
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n",output);
}//end function displayNums
You don't use print but create a new array numbers
Most of your code is erroneous. It won't compile. Here's some sample code. Work with it to implement the rest
#include <stdio.h>
#define NUMS 6
void displayNums(int nums[])
{
int i;
printf("Your numbers are:\n");
for(i = 0; i < NUMS; i++)
printf("%d ", nums[i]);
printf("\n");
}
void myNumbers(int nums[])
{
printf("Please Enter your lucky numbers\n");
int i;
for(i = 0; i < NUMS; i++)
scanf("%d", &nums[i]);
}
int main()
{
int numbers[6];
myNumbers(numbers);
displaynums(numbers);
//do the rest of the stuff here
return 0;
}
Going through a C tutorial might be helpful? Check out http://c.learncodethehardway.org/book/ for a nice intro to the language.