User entry array being filled with garbage - c

im trying to make this function work but the array keeps getting filled with trash. The cicle is running properly, I just cant seem to find the error.
int CargaArregloEnteros(int a[], int dim, int v);
void MostrarArreglo(int n[], int v);
int main()
{ int notas[100], validos=0;
validos = CargaArregloEnteros(notas, 100, validos);
printf("\nLos validos son %d\n", validos);
MostrarArreglo(notas, validos);
return 0;
}
int CargaArregloEnteros(int a[], int dim, int v)
{
char opcion=0;
while(v<dim && opcion !=27)
{
printf("\n Ingrese una nota a cargar ");
fflush(stdin);
scanf("&d", &a[v]);
printf("\n Presione ESCAPE para salir\n");
fflush(stdin);
opcion=getch();
system("cls");
v++;
}
return v;
}
void MostrarArreglo(int n[], int v)
{
for(int i=0;i<v;i++)
{
printf("%d | ", n[i]);
}
}

You need to change
scanf("&d", &a[v]);
to
scanf("%d", &a[v]);
so that it constitutes a valid conversion specifier syntax.
Also, a good lesson on why it's best to check the return value of scanf() and other library functions.

Related

C program, where I should print array of a SECTION in an array

I built a program in C that is printing average of whole array with pointers and function. I need to make the function print a average of user selected section of an array, for example I put these number in an array: 9,8,2,3,6,4 and I want to make a average from just 2-4-. I am stucked, can you help me please? Thanks.
Code:
#include <stdio.h>
int priemer(int *pole,int n);
int main()
{
int a[100],*pole,n,i;
printf("Zadaj pocet prvkov pola (1-100)");
scanf("%d",&n);
while (n > 100 || n < 1)
{
printf("Chyba! Cislo musi byt v rozmedzi od 1 po 100.\n");
printf("Zadaj pocet prvkov znova: ");
scanf("%d", &n);
}
for(i=0;i<n;i++){
printf("Zadaj %d. prvok - ",i+1);
scanf("%d",&a[i]);
}
pole=a;
priemer(pole,n);
return 0;
}
int priemer(int *pole,int n)
{
int i,c=0;
float p;
for(i=0;i<n;i++)
{
c+=*(pole+i);
}
p=(float)c/n;
printf("Priemer vsetkych prvkov v poli je: %.3f\n",p);
return p;
}

My function that returns first and last index of a chosen real number in an array executes but doesn't always work

I'm trying to define a function prem_dern that returns the first index and last index of an input real number ( by the user ). When executing, the intitializing part works fine but not the prem_dern function ( program exits right after compiling. The program doesn't return any errors when compiling.Here is what I did :
#include <stdio.h>
#include <stdlib.h>
void prem_dern(float t[], int n, float r)
{
int i,j;
printf("donner le reel pour savoir les positions ");
scanf("%f",&r);
for(i=0;i<n;i++)
{
if (t[i]==r)printf("la premiere position %d:",i);
break;
}
for (j=n-1;j>0;j--)
{
if(t[j]==r) printf("la derniere position %d:",j);
break;
}
}
int main()
{ int i,n;
float r;
float t[100];
printf("donner le nombre des elements : \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("donner un element :");
scanf("%f",&t[i]);
}
prem_dern(t,n,r);
return 0;
}
A couple of observations that may be contributing to the problem:
This function prototype:
void prem_dern(float t[], int n, float r)
includes no way to return results to the caller. i.e. it is void, and none of the arguments include the address of something to be changed. This is legal, but would be more useful with the ability to do work, then pass its results.
Additionally, the size of the array float t[] is not passed, so the function has no way to know how many elements it contains.
It seems that the declaration of float t[100]; should be moved and changed from:
float r;
float t[100];
To:
scanf("%d",&n);
float t[n];//creating a variable length array that ties array size to n
for(i=0;i<n;i++)
{
printf("donner un element :");
scanf("%f",&t[i]);
}
This then provides an explicit tie between the array, and its size:
void prem_dern(float t[], int n, float r)
^^^^^
Next, for execution flow to see the break statement, change the following:
if (t[i]==r) printf("la premiere position %d:",i);
break;
To:
if (t[i]==r)
{
printf("la premiere position %d:",i)
break;
}
Edit to address OP main question
To create ability to return first and last indices of number entered by user modify the struct to return either a pointer to array, or a pointer to struct, or via a function parameter. Here is an adaptation of your function to return via function a struct * parameter:
Given for example this struct definition:
typedef struct {
int first;
int last;
float r;
}index_s;
Here is the adaptation of your function, that will return the float value entered (in the function), and the index of the array that contains same value.
void prem_dern(float t[], int n, index_s *val)
{
int i,j;
int *array = malloc(2*sizeof(*array));
if(array)
{
printf("donner le reel pour savoir les positions ");
scanf("%f",&val->r);
for(i=0;i<n;i++)
{
if (t[i]==val->r)
{
printf("la premiere position %d:",i);
break;
}
}
for (j=n-1;j>0;j--)
{
if(t[j]==val->r)
{
printf("la derniere position %d:",j);
break;
}
}
val->first = i;
val->last = j;
}
}
Calling example:
int main()
{
index_s val;//create instance of struct typedef
//all your other relevant code
...
scanf("%d",&n);
float t[n];//creating a variable length array that ties array size to n
for(i=0;i<n;i++)
{
printf("donner un element :");
scanf("%f",&t[i]);
}
...
prem_dern(t, n, &val);//pass struct as pointer (&)
val.first; //contains first index
val.last; //contains last index
val.r; //contains float val searched for
return 0;
}

How do i Fill in correctly My Struct Table without my Program Crashing?

I dont understand why my program crashs when tryign to fill in some DATA to my struct table declared in main ...
I know that a table is itself a pointer right ?
So basically i dont realy need to pass the address using &var when using scanf ... but thats when it crashes for me ..
when i tried to pass inputs by scanf("expression",&T[i].var) .. that worked but when showing my content i found out :
As you can see I couldnt event put something for my stat and values totally diffrent from the inputs .. probably cuz taking memory adresses .. but why the Id actually worked and also Lieu is null ?
so weird .
struct ChDep
{
int id;
int mins;
char nom[10];
char lieu[10];
double prix;
char stat;
};
//Function Fill some content to my Table
void RemplireHCD(int n, struct ChDep *T)
{
for (int i = 0; i < n; i++)
{
printf("Mission Numero : %d\n", i);
printf("ID = ");
scanf("%d", &T[i].id);
printf("\nDuree = ");
scanf("%d", &T[i].mins);
printf("\nNom = ");
scanf("%s", &T[i].nom);
printf("\nLieu = ");
scanf("%s", &T[i].lieu);
printf("\nPrix = ");
scanf("%lf", &T[i].prix);
printf("\nStatut = ");
scanf("%c", &T[i].stat);
system("cls");
}
}
//Function to show my Struct Table Content
void AfficherHCD(int n, struct ChDep *T)
{
system("cls");
for (int i = 0; i < n; i++)
{
printf("%d > [ ID: %d - Duree : %d - Libelee : %s - Lieu : %s - Prix : %lf - Statut : %c ]\n",
T[i].id, T[i].mins, T[i].nom, T[i].lieu, T[i].prix, T[i].stat);
}
}
int main(int argc, char *argv[])
{
struct ChDep HCD[20];
int n;
printf("SVP donnez Le Nombre de Mission A remplire : \n");
scanf("%d", &n);
system("cls");
RemplireHCD(n, HCD);
AfficherHCD(n, HCD);
getchar();
return 0;
}

Call and Return function using pointers locally in c

Hello there I am learning pointers so I created a calculator.
I managed to return the value and the pointers from a function but by declaring them globally. How can I declare them locally?
#include <stdio.h>
#include <stdlib.h>
Declaration of all functions
int Addition();
int Subtraction();
int Devision();
int Multiplication();
Declaration of Global Variables, which I would like to declare them locally
int p;
int n;
int *r=&n;
int *b=&p;
Start of main Function
int main()
{
int g,s;
while (1)
{
printf("Please choose the Arithmetic operation: \n");
printf("Addition-> 1 \nSubtraction-> 2 \nDevision-> 3 \nMultiplication-> 4 \nExit-> 0\n ");
scanf("%d",&g);
The user chooses an Arithmetic operation (function) by inputting one number(1,2,3,4 or 0 for Exit)
if (g==1)
{
s=Addition(r,b);
printf("The addition result is %d+%d=%d",*r, *b, s);
}
else if (g==2)
{
s=Subtraction(r,b);
printf("The Subtraction result is %d-%d=%d",*r, *b, s);
}
else if (g==3)
{
s=Devision(r,b);
printf("The Devision result is %d/%d=%d",*r, *b, s);
}
else if (g==4)
{
Multiplication(r,b);
printf("The Multiplication result is %d/%d=%d",*r, *b, s);
}
else
{
break;
}
return 0;
}
}
End of main function.
Below are all the other functions
Addition()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n+p;
return x;
}
Subtraction()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n-p;
return x;
}
Devision()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n / p;
return x;
}
Multiplication()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n * p;
return x;
}
1) Refresh the knowledge about pointers and pass parameters via pointers if you want to.
The indirection or dereference operator * gives the contents of an object pointed to by a pointer.
The unary or monadic operator & gives the address of a variable.
2) Avoid global variables declare them locally after main.
3) Use switch instead of if-else chains
#include <stdio.h>
#include <stdlib.h>
int Addition(int* n, int* p)
{
int x;
printf("Ennter first nr: ");
scanf("%d",n);
printf("Ennter second nr: ");
scanf("%d",p);
x = *n + *p;
return x;
}
int Subtraction(int* n, int* p)
{
int x;
printf("Ennter first nr: ");
scanf("%d",n);
printf("Ennter second nr: ");
scanf("%d",p);
x = *n - *p;
return x;
}
int main(void)
{
int n1 = 0;
int n2 = 0;
int *r = &n1;
int *b = &n2;
int g,s;
while (1)
{
printf("Please choose the Arithmetic operation: \n");
printf("Addition-> 1 \nSubtraction-> 2 \nDevision-> 3 \nMultiplication-> 4 \nExit-> 0\n ");
scanf("%d",&g);
switch(g)
{
case 0:
printf("END\n");
return 0;
break;
case 1:
s = Addition(r, b);
printf("The addition result is: %d+%d=%d\n\n",n1, n2, s);
break;
case 2:
s = Subtraction(r ,b);
printf("The Subtraction result is: %d-%d=%d\n\n",*r, *b, s);
break;
}
}
return 0;
}
Test:
Please choose the Arithmetic operation:
Addition-> 1
Subtraction-> 2
Devision-> 3
Multiplication-> 4
Exit-> 0
2
Ennter first nr: 5
Ennter second nr: 3
The Subtraction result is: 5-3=2
Please choose the Arithmetic operation:
Addition-> 1
Subtraction-> 2
Devision-> 3
Multiplication-> 4
Exit-> 0
0
END
I used them Globally because it was easier for me to call and read them. That is why I want to learn how can I declare them locally.
Very simply, just declare them locally, as shown: (without your user input code to focus on your primary question)
int main(void)
{ // locally declared
double a = 4.5;
double b = 10.8;
double result_1, result_2, result_3, result_4;
result_1 = add(a, b);
result_2 = sub(a, b);
result_3 = mul(a, b);
result_4 = div(a, b);
return 0;
}
// example function (the others will be of similar form,
// a single return line with the appropriate math operator.
double add(double a, double b)//no pointers necessary
{
return a + b;
}
If you really want to use a pointer, then you can implement the function to return the result via an argument:
void add(double a, double b, double *result)
{
*result = a + b;
}
Usage: (call from main for example)
add(a, b, &result_1);// passing the address of result_1
// to allow the value at that address
// to be modified.
Well, not sure if this is what you are asking for, but let me suggest you this code:
#include <stdio.h>
#include <stdlib.h>
int Addition(int* n, int* p)
{
int x;
printf("Ennter first nr: ");
scanf("%d",n);
printf("Ennter second nr: ");
scanf("%d",p);
x=*n+*p;
return x;
}
int main()
{
int n1=0;
int n2=0;
int *r=&n1;
int *b=&n2;
int g,s;
while (1)
{
printf("Please choose the Arithmetic operation: \n");
printf("Addition-> 1 \nSubtraction-> 2 \nDevision-> 3 \nMultiplication-> 4 \nExit-> 0\n ");
scanf("%d",&g);
if (g==1)
{
s=Addition(r,b);
printf("The addition result is %d+%d=%d",*r, *b, s);
}
return 0;
}
}
As you can see, we are using pointers to store the value of the number written by the user, so you can keep them after calling the function.

given N numbers show those above the average of the numbers themselves. C( how can i print output in main())

I want to know how can i print output in main().
User gives n number after I declare the array, and after I pass it by address to load it, then I pass it again address for elaboration but I don't know to print the output in the main function.
The output is in void elaborazionedati(int num,int vet[])
My Code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Prototipo
void caricamentovettore(int num,int vet[]);
void elaborazionedati(int num,int vet[]);
//fine
int main()
{
//Dichiarazione variabili
int n;
int scelta;
do
{
//how many numbers do u want to give?
printf("---------------------\nQunati numeri vuole inserire \n");
scanf("%d",&n);
//dichiaro il vettore
int vet[n];
caricamentovettore(n,vet);//array load
elaborazionedati(n,vet);// data elaboration
// this you can skip
printf("Per fare un'altro calcalcolo inserire :1\naltrimenti per uscire premere qualsiasi tasto\n");
scanf("%d",&scelta);
} while(scelta==1);
system("pause");
return 0;
}
//Inzio subroutine CARICAMENTO VETTORE
void caricamentovettore(int num,int vet[])
{ //dicgiarazione variabili
int i,z=1;
for(i=0;i<num;i++){
printf("Inserireil : %d numero\n",z++);
scanf("%d",&vet[i]);
}
}
//fine subroutine
//here is output
//Inzio subroutine ELABORAZIONE
void elaborazionedati(int num,int vet[])
{
int totale,media,i;
for(i=0;i<num;i++){
totale+=vet[i];
}
media=totale/num;
for(i=0;i<num;i++){
if(vet[i]>media){
printf("\nI numeri maggiore alla media%d\n",vet[i])//<--------how i can print this in main?
}
}
}
//fine subroutine
so i want to know how can i print output in main()
Do the following changes in your code,
1 void caricamentovettore(int num,int vet[]); change this to int caricamentovettore(int num,int vet[]);
2 remove elaborazionedati(n,vet); from your main function.And change caricamentovettore(n,vet); to int avg = caricamentovettore(n,vet);
3 change caricamentovettore function to,
void caricamentovettore(int num,int vet[])
{ //dicgiarazione variabili
int i,media = 0;
for(i=0;i<num;i++){
printf("Inserireil : %d numero\n",z++);
scanf("%d",&vet[i]);
media += vet[i];
}
return media/i;
}
4 Add this after caricamentovettore function call add below code,
for(int i=0;i<num;i++){
if(vet[i]>avg){
printf("\nI numeri maggiore alla media%d\n",vet[i])//<--------how i can print this in main?
}
}

Resources