How do I save a variable read in a function in C? - c

Let's say I have this function:
void read() {
int num;
scanf("%d", &num);
}
and I want to use the num variable in another function like this:
void func() {
for (i = 0; i < num; i++)
printf("%d ", i);
}
But when trying to compile it says the variable is uninitialized. I know that it most likely requires pointers, but I can't get a hang of it.

There are two ways to go about doing this:
Return the variable that you read to a caller, or
Have the caller provide space for your variable, and store it there.
The first approach requires you to change the return type to int:
int read() {
int num;
scanf("%d", &num);
return num;
}
void func() {
int num = read();
for (i = 0; i < num; i++)
printf("%d ", i);
}
The second approach requires you to take an int* pointer:
void read(int* p) {
scanf("%d", p);
}
void func() {
int num;
read(&num);
for (i = 0; i < num; i++)
printf("%d ", i);
}

You func should be,
void func(int num) {
for (i = 0; i < num; i++)
printf("%d ", i);
}
And you also need to pass value like,
void read() {
int num;
scanf("%d", &num);
func(num);
}

You don't always need pointers - you can simply return the value and then use it.
int read() {
int num;
scanf("%d", &num);
return num;
}
You can now store the value returned from the function for future sue, e.g.
void func() {
int num = read();
for (i = 0; i < num; i++)
printf("%d ", i);
}

You can make the variable global and inside the function:
void func() {
int i;
for(i=0;i<num;i++)
printf("%d ", i);
}

Related

why does the printf not showing

I need help. It doesnt display the printf in the mean function. I am doing a dynamic allocation in c and the add function works but the mean function does not display. There is no problem to the add function it works but the max does not. I am sorry I know this problem is simple but still cant get the answer. I am also getting a warning to the add function during the call in main.
This is my code:
typedef int* Statistician;
void add(Statistician answer, int *count, int *SIZE, int item);
|
[Note] expected 'Statistician' {aka 'int *'} but argument is of type 'int **'
int main() {
int SIZE;
Statistician *answer;
int count;
int item;
add(answer, count, SIZE, item);
|
//[Warning] passing argument 1 of 'add' from incompatible pointer type [-Wincompatible-pointer-types]
printf("\nThe mean is: %.2f", mean(answer, SIZE));
return 0;
}
This is the add function:
void add(Statistician answer, int *count, int *SIZE, int item) {
int i;
printf("Enter n: ");
scanf("%d", &item);
answer = (int*)malloc(item * sizeof(int));
if(item == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
for(i = 0; i < item; ++i) {
scanf("%d", &answer[i]);
}
printf("Elements of array are: ");
for(i = 0; i < item; i++) {
printf("%d ", answer[i]);
}
if(item == 10) {
int m;
printf("\nAppend array: ");
scanf("%d", &m);
answer = realloc(answer, m * sizeof(int));
for(i = item; i < item + m; i++) {
scanf("%d", &answer[i]);
}
item = item + m;
int temp, j;
for(i = 0; i < item; i++) {
for(j = 0; j <= i; j++) {
if(*(answer + i) < *(answer + j)) {
temp = *(answer + i);
*(answer + i) = *(answer + j);
*(answer + j) = temp;
}
}
}
printf("Final array: \n");
for(i = 0; i < item; ++i) {
printf("%d ", answer[i]);
}
}
}
}
This is the max function that doesnt display:
float mean(Statistician answer, int count) {
int mean =0;
int cnt = 0;
for(int i=0;i<count;i++){
mean = mean + answer[i];
cnt++;
}
mean = mean / cnt;
return mean;
}
I fully expected to find a duplicate but I didn't.
The first argument to add is declared to be int ** (via typedef) and you passed it a paramter of type int *. The compiler will let you do this with a warning, but it's almost always wrong. Don't do it.
If you're running 64 bit code, anything can happen after you stomp memory. 32 bit code is slightly more predictable but it's still going to end badly.
From your code, it looks like you want void add(Statistician *answer, Statistician answer; and add(&answer.
The deep learning of pointers is here. The thing you need to modify in the calling function is the thing whose address is passed to the called function. Allocating arrays with malloc almost always ends up being double pointers.

Using the same function multiple times even though the vectors are different

In the below code, I am saving and printing two vectors. This means I have created each function —scanf() and printf()— twice even though they are the same apart from the vector name they operate. How could I have only one scanf() and printf() functions, and still save and print as many vectors as I want? N.b. In this case, I am only working with static vectors.
#include <stdio.h>
int scanning_first_vector(int *vector1);
int printing_first_vector(int *vector1);
int scanning_first_vector(int *vector2);
int printing_first_vector(int *vector2);
int main()
{
int vector1[5], vector2[5];
printf("Please enter the first vector.\n");
scanning_first_vector(vector1);
printing_first_vector(vector1);
printf("\nPlease enter the second vector.\n");
scanning_first_vector(vector2);
printing_first_vector(vector2);
return 0;
}
int scanning_first_vector(int *vector1)
{
int i;
for (i = 0; i < 5; ++i)
{
scanf("%d", &vector1[i]);
}
return 0;
}
int printing_first_vector(int *vector1)
{
int i;
for (i = 0; i < 5; ++i)
{
printf(" %d ", vector1[i]);
}
return 0;
}
int scanning_second_vector(int *vector2)
{
int i;
for (i = 0; i < 5; ++i)
{
scanf("%d", &vector2[i]);
}
return 0;
}
int printing_second_vector(int *vector2)
{
int i;
for (i = 0; i < 5; ++i)
{
printf(" %d \n", vector2[i]);
}
return 0;
}
I think I just did below the leaner version of the code after reading the comments — thank you, guys! :-) I understand now that I can use the same function & I only need to make sure I give distinctive names to the vectors in the main() function. It works well, but it would also be awesome to get confirmation that the way the code is done here is as lean & good as it can get :-) Thank you!
#include <stdio.h>
int scanning_vector(int *vector);
int printing_vector(int *vector);
int main()
{
int vector1[5], vector2[5];
printf("Please enter the first vector:\n");
scanning_vector(vector1);
printing_vector(vector1);
printf("\nPlease enter the second vector:\n");
scanning_vector(vector2);
printing_vector(vector2);
return 0;
}
int scanning_vector(int *vector)
{
int i;
for (i = 0; i < 5; ++i)
{
scanf("%d", &vector[i]);
}
return 0;
}
int printing_vector(int *vector)
{
int i;
for (i = 0; i < 5; ++i)
{
printf(" %d ", vector[i]);
}
return 0;
}

undefined reference to 'WinMain' [Error] ld returned 1 exit status, passing matrix as a parameter in function

I'm starting to learn programming in C, and I have this task where I have to write a program with part of the code on another file. But I'm having problems with that last part because I'm using matrices.
Here's the main body:
#include <stdio.h>
#include "otsenkatry.c"
int main()
{
int i, j;
int a[i];
int s, gru;
char A, B, C, D, E;
printf("Introduce the number os students ", &s);
fflush(stdout);
scanf("%d", &s);
printf("Introduce their grades\n");
fflush(stdout);
for (i = 0; i<s; i++)
{
printf("a[%d] = ", i);
fflush(stdout);
scanf("%d", &a[i]);
printf("Grade: %d %d \n", a, otsenkatry(a));
fflush(stdout);//}
}
return 0;
}
And that's the part with the problem:
int otsenkatry (int* a)
{
int i;
int gru;
if (a[i]<51)
{
gru=2;
}
if (a[i]>50 && a[i]<69)
{
gru=3;
}
if (a[i]>69 && a[i]<=85)
{
gru=4;
}
if (a[i]>85 && a[i]<=100)
{
gru=5;
}
return gru;
}
I figured, that it has to do with the pointers, but I don't know how to alter it.
Your matrix has undefined size:
int i, j;
int a[i];
To declare matrix a[] properly you need to pass the size - the value of i variable. Unfortunately, the i variable is declared one line above without initialization with any value.
There are a few problems with your code:
array a not properly declared
printing array a instead of integer
argument of otsenkatry is array, but should be an int
including a .c file
using undefined i value as array index in otsenkatry
the argument &s in the first printf is invalid
the otsenkatry function can be simplified
the variables j, gru, A, B, C, D, E are defined in main but never used
Here is a corrected implementation:
#include <stdio.h>
int otsenkatry (int v) {
if (v<51)
return 2;
if (v<69)
return 3;
if (v<=85)
return 4;
if (v<=100)
return 5;
return 0;
}
int main(){
int i, a[100], s;
printf("Introduce the number of students ");
fflush(stdout);
scanf("%d", &s);
if (s > 100)
s = 100;
printf("Introduce their grades\n");
fflush(stdout);
for (i = 0; i<s; i++) {
printf("a[%d] = ", i);
fflush(stdout);
scanf("%d", &a[i]);
printf("Grade %d: %d \n", a[i], otsenkatry(a[i]));
fflush(stdout);
}
return 0;
}

How to add a counter of a for loop and pass it across functions in C

I am relatively new to programming. I have been working on a project that takes the users input passes it to a function that finds the factors of the number, stores them in an array (only for 100 factors max) and then returns the array to the main program. Once I call the array to the main program, then print it using a for loop i run into an issue. I need a counter to figure out the size of the array to figure out how many times to run the for loop.
So far I have tried to use a pointer to count the first loop and send it to the main function with no luck. The only thing that works is a global variable, but for obvious reasons I would prefer not to do that.
#include <stdio.h>
#define MAX_SIZE 100
int* get_factors(int number)
{
int x;
int z;
int y = 0;
static int arr[MAX_SIZE];
for(x=1; x <= number; ++x)
{
if (number%x == 0)
{
arr[y] = x;
y++;
}
}
return arr;
}
int main(void)
{
int *num;
int temp;
int z = 0;
printf("Enter a number: ");
scanf("%d",&temp);
printf("Factors of %d: ", temp);
num = get_factors(temp);
for(z=0; z<=20; z++) //This is the loop that i need to figure out a
counter for
{
printf("%d ", num[z]);
}
return 0;
}
#include <stdio.h>
#define MAX_SIZE 100
struct myObject {
int arr[MAX_SIZE];
int index;
};
struct myObject
get_factors (int number)
{
int x;
struct myObject holder;
holder.index = 0;
for (x = 1; x <= number; ++x)
{
if (number % x == 0)
{
holder.arr[holder.index] = x;
holder.index++;
}
}
return holder;
}
int
main (void)
{
struct myObject num;
int temp;
int z;
printf ("Enter a number: ");
scanf ("%d", &temp);
printf ("Factors of %d: ", temp);
num = get_factors (temp);
for (z = 0; z < num.index; z++) //This is the loop that i need to figure out a
//counter for
{
printf ("%d ", num.arr[z]);
}
return 0;
}
If you change your function interface design, it could be easier to pass that information.
The idiomatic way to pass array in C function is via parameter, where the first paramenter is the array itself, and the second parameter is it maximun length.
In this way your function is not more responsible for allocating or deallocating the array. In other words, it does not own it anymore.
In your case, you can use the function return to pass the amount of slots used in this array and, on error, just a negative number.
In this way, your program can be something like that:
int get_factors(int number, int number[], size_t length)
{
int x;
int z;
int y = 0;
if ( number > length ) return -1;
for(x=1; x <= number; ++x)
{
if (number%x == 0)
{
arr[y] = x;
y++;
}
}
return y;
}
and at call site:
int main(void) {
int num[MAX_SIZE];
int temp;
int z = 0;
printf("Enter a number: ");
scanf("%d",&temp);
printf("Factors of %d: ", temp);
int slots = get_factors(temp, num, MAX_SIZE);
for(z=0; z<=slots; z++) //This is the loop that i need to figure out a
printf("%d ", num[z]);
return 0;
}

exercise about vector and function

Thanks a lot, with you help I understood all my mistakes (:
This is my first time using this website so I'm not sure if it is in the right format.
Basically I have to make a function that fills a vector, but it isn't working at all.
English isn't my first language so this is probably really confusing, but I'd appreciate if
somebody helped me. Thanks a lot.
#include <stdio.h>
#include <stdlib.h>
void le_vet(int v[1000], int n, int i)
{
for (i = 0; i < n; i++) {
printf("Type the number %d: ", i+1);
scanf("%d", &v[i]);
}
}
int main()
{
int v[1000], n;
printf("Type the syze of the vector: ");
scanf("%d", &n);
void le_vet(n);
system ("pause");
return 0;
}
You are not calling le_vet in your main function, you are rather doing something more along the lines of creating a function pointer called "le_vet" that takes an int (by default, as no type is specified) and returns a void. I'm pretty sure this is not what's intended.
Instead, change void le_vet(n) to le_vet(v, n) and change this:
void le_vet(int v[1000], int n, int i)
{
for (i = 0; i < n; i++) {
printf("Type the number %d: ", i+1);
scanf("%d", &v[i]);
}
}
to this:
void le_vet(int v[], int n)
{
int i;
for (i = 0; i < n; i++) {
printf("Type the number %d: ", i+1);
scanf("%d", &v[i]);
}
}
Since you're not needing to pass i in from outside the function, there's no need to include it in the arguments to the function. The first element in a for loop is executed once right as the loop is entered, therefore it is often used to declare the iteration variable for the loop, as I did here.
EDIT: Whoops. Can't do that in C. I'm to used to C++ that I made a goof here. Declare i just above the loop, as #Over Flowz suggests. Updating my revised code, but leaving this record as evidence that it's time to stop working and go eat dinner :)
You are only passing one argument to le_vet(), when it requires three arguments. You also need to remove the void, since you are calling on a function.
Maybe this will work.
void le_vet(int n)
{
static int v[1000];
for (int i = 0; i < n; i++) {
printf("Type the number %d: ", i+1);
scanf("%d", &v[i]);
}
}
You don't need the int i passed as a parameter, since you are creating another one in the for loop.
int i = 0;
while (i < n)
{
i++;
}
is the same as
for (int i = 0; i < n; i++)
When you invoke like this:
...
scanf("%d", &n);
void le_vet(n); //you are declaring a function. You need to remove the void keyword
system ("pause");
...
You should invoke like this:
...
scanf("%d", &n);
le_vet(n);
system ("pause");
...
Then you will see the real errors, like the number of parameters
try:
#include <stdio.h>
#include <stdlib.h>
void le_vet(char v[], int n)
{
int i = 0;
for(i = 0; i < n; i++)
{
printf("Type the number %d: ", i+1);
scanf("%s", &v[i]); //Read string, not decimal for output.
}
}
int main()
{
char v[1000] = {0}, n;
printf("Type size of the vector: ");
scanf("%d", &n);
le_vet(v, n);
printf("%s", v);
system("pause");
return 0;
}
Hope it helps.

Resources