I am trying to compile the following code on Ubuntu (64-bit), with Dev-C++ 5.9.2
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Afficher les nombres parfaits inférieurs ou égaux à un entier donné
void parfaitInf(int n)
{
int i, j, somme;
for(i=2;i<=n;i++)
{
somme=1;
for(j=2;j<=i/2;j++)
{
if(i%j==0) somme+=j;
}
if(somme==i) printf("%d\n",i);
}
}
// Tester si un entier est un nombre d'Armstong
void armstrong(int n)
{
int somme=0,m=n;
do
{
somme+=pow(m%10,3);
m/=10;
}
while(m!=0);
if(somme==n) printf("%d est Armstrong.\n",n);
else printf("%d n\'est pas Armstrong !\n",n);
}
// Calculer la racine carrée d'un nombre entier
void racineCarree(int n)
{
printf("La racine carr%ce de %d est %f",130,n,sqrt(n));
}
void menuPrincipale(int *choix)
{
do
{
printf("\t\tMenu\n");
printf("[1] Afficher les nombres parfaits inf%rieurs ou %cgaux %c un entier donn%ce\n",130,130,133,130);
printf("[2] Tester si un entier est un nombre d\'Armstrong\n");
printf("[3] Calculer la racine carr%ce d\'un nombre entier\n\n",130);
printf("Votre choix ? ");
scanf("%d",&choix);
}
while(&choix<1 || &choix>3);
}
int main()
{
int n,choix;
menuPrincipale(choix); //compilation error here
printf("%d",&choix);
// Not Continued
return 0;
}
On line 51, my compiler gives me the error "ISO C++ forbids comparison between pointer and integer [-fpermissive]".
On line 57, my compiler gives me the error "[Error] invalid conversion from 'int' to 'int*' [-fpermissive]"
Why doesn't this work? I want to understand the current problem.
basic of pointers
int i = 1;
int *p = &i; // p is a memory address of where i is stored. & is address of variable.
int j = *p; // j is the value pointed to by p. * resolves the reference and returns the value to which the pointer addresses.
int **dp = &p; // dp is the address of the pointer that itself is an address to a value. dp->p->i
cout << i; // 1
cout << p; // 0x.... some random memory address
cout << j; // 1
cout << dp; // 0x... some random memory address that is where the p variable is stored
so as your your issue, as others said in menuPrincipale() your incorrectly using pointers.
Related
I was tasked to do a program to read the name of one student, 4 of their subjects and their respective grades. I have worked with for and while loops, also with if statements and here is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main() {
printf("Este programa captura el nombre de un alumno \n");
printf ("y cuatro de sus materias y sus respectivas notas\n");
printf ("Nota: El programa solo toma en cuenta los dos primeros\n");
printf ("decimales de la notas expresada.\n\n");
char alumno[40] = {'\0'};
char mat[4][20] = {'\0', '\0', '\0', '\0'};
float calif[4] = {-1, -1, -1, -1};
int i;
while (alumno[0] == '\0') {
printf("Ingresa el nombre del alumno: ");
gets(alumno);
if (alumno[0] == '\0') {
printf("\nError. El alumno debe de llevar un nombre.");
printf ("\nTrata nuevamente\n\n");
};
};
for (i = 0; i < 4; ++i) {
while (mat[i][0] == '\0') {
printf("Ingresa el nombre de la materia %d: ", i+1);
gets(mat[i]);
if (mat[i][0] == '\0') {
printf("\nError. Las materias deben ser declaradas.");
printf ("\nTrata nuevamente.\n\n");
};
};
while (calif[i] < 0 || calif[i] > 10) {
printf("Ingrese la nota correspondiente a esta materia (0-10): ");
scanf("%2.2f", calif[i]);
if (calif[i] < 0 || calif[i] > 10) {
printf("\nError. Debe ingresar una nota válidad entre 0 y 10.");
printf ("\nTrata nuevamente.\n\n");
};
};
};
return 0;
};
The program seems to be working fine until it gets to the point to ask the grade of the first subject. Any grade I put it causes an infinite loop. I have searched about this problem to no avail. So please, let me know what I am doing wrong here.
There are multiple problems in your code:
[major] you read the mark with scanf("%2.2f", calif[i]): the format string is incorrect, the first 2 means read at most 2 bytes and the .2 is an error as scanf() does not support the precision syntax at all. It should just be "%f" and you should pass the address of the destination variable &calif[i] instead of its value. Furthermore, you should test the return value to check for invalid or missing input.
the prototype for main is int main(), int main(void) or int main(int argc, char *argv[]), the missing return type is an obsolete syntax.
reading input with gets() is risky as there is no way to prevent buffer overflow with sufficiently long input strings. You should instead use scanf("%39s", alumno) or fgets(alumno, sizeof alumno, stdin) and test the return value to detect premature end of input stream. Same remark for the second instance of gets().
This question already has answers here:
When should I use ampersand with scanf()
(3 answers)
Closed 4 years ago.
That's the code: I don't understand why we put the "&" in the scanf with ageAmis while ageAmis is a pointer?
NB "This code works"
int main(int argc, char *argv[]){
int nombreDAmis = 0, i = 0;
int* ageAmis = NULL; // Ce pointeur va servir de tableau après l'appel du malloc
// On demande le nombre d'amis à l'utilisateur
printf("Combien d'amis avez-vous ? ");
scanf("%d", &nombreDAmis);
ageAmis = malloc(nombreDAmis * sizeof(int)); // On alloue de la mémoire pour le tableau
// On demande l'âge des amis un à un
for (i = 0 ; i < nombreDAmis ; i++)
{
printf("Quel age a l'ami numero %d ? ", i + 1);
scanf("%d", &ageAmis[i]); //why the "&"
}
// On affiche les âges stockés un à un
printf("\n\nVos amis ont les ages suivants :\n");
for (i = 0 ; i < nombreDAmis ; i++)
{
printf("%d ans\n", ageAmis[i]);
}
// On libère la mémoire allouée avec malloc, on n'en a plus besoin
free(ageAmis);
}
return 0;
}
You are right that ageAmis is a pointer. However, that's not what you pass to scanf().
ageAmis[i] has type int because you are dereferencing i location from ageAmis base address. It's equivalent to *(ageAmis + i). That's you can't pass ageAmis[i] to scanf as it expects an argument of type int* for the format %d. So & is required here.
You could alternatively just pass ageAmis + i as well:
scanf("%d", ageAmis + i);
which is equivalent to:
scanf("%d", &ageAmis[i]);
Note that:
*(ageAmis + i) == *(i + ageAmis) == ageAmis[i]
I need to pass a matrix to a function as a parameter but when checking if it is happening or not I try to print the value of the matrix [1][1] and it does not work
int Cabe_proceso(int pag, int cel,int pal,char Memoria_fisica[1][pal-1]){
printf("[%s]\n",Memoria_fisica[1][1]);
}
int main(void){
int palabras, celdas;
printf("Ingrese la cantidad de palabras soportadas por la memoria principal\n");
scanf("%i",&palabras);
printf("Ingrese la cantidad de palabras que define el tamano de un marco de paginas\n");
scanf("%i",&celdas);
int marcos =palabras/celdas;
int i,j,aux=celdas,m=1;
if(palabras%celdas ==0){
marcos= marcos;
}else{
marcos++;
}
char *Memoria_fisica[1][palabras-1];
for(i=0;i<1;i++){
for(j=0;j<palabras;j++){
Memoria_fisica[i][j]= "0";
}
}
for(i=0;i<1;i++){
for(j=0;j<palabras;j++){
printf("[%s]\n",Memoria_fisica[i][j]);
if(j==aux-1){
printf("--------------marco %i\n", m);
aux=aux+celdas;
m++;
}
}
if(palabras%celdas!=0){
printf("------------------marco %i\n",marcos);
}
}
printf("%i\n",celdas);
Cabe_proceso(1,celdas,palabras,Memoria_fisica);
return 0;
}
I included the bookstores stdio.h , stdlib.h, strings.h
Here is the code, basically I gotta do the ceasar cipher in C using arrays and chars only, here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
main ()
{
char alfabeto[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int a=0;
int b=0;
int m=0;
int c=0;
//char letra;
int cont=0;
char k[]={};
printf("Introduzca un primer numero 'a':\n");
scanf(" %i", &a);
printf("Introduzca un segundo numero 'b':\n");
scanf(" %i", &b);
printf("Introduzca una palabra clave entre 4 y 10 letras (cuando termine presione '.'):\n");
//Falta una validacion para la palabra.
for (int j=0;j<10;j++)
{
scanf(" %c",&k[j]);
cont=j; //cuenta la cantidad de elementos
if (k[j]=='.')
{
j=10;
}
}
for(int j=0;j<cont;j++) //Error in this bit I think.
{
for (int i=0;i<26;i++)
{
if (alfabeto[i]==k[j])
{
m=i;
i=26;
}
}
c = ( (a * m) + b );
printf("%c es: %i \t",k[j],c);
}
}
It uses a formula where c=(a*m+b).
m being the position of the original letter for example: A=0 then m=0.
a being a number you choose as well as b.
In my case I chose a=1 and b=3 and the word CESAR as the key word.
According to the formula the output number of each letter should be c.
The output should be:
C es: 5 E es: 7 S es: 21 A es: 3 R es: 20
Yet it is this:
WrongOutput
UPDATE:
I had to correct this:
char k[]={};
Into this:
char k[10]={'\0'};
Now I get the right output:
Right Output
I have problems getting the right value for cociente; every time I run it, cociente is printed as 1 but that is not the value I want to assign it, this is the code where I print:
printf("\nEl valor del cociente es: %d",(polinomio_->polinomio->cociente));.
This is my code:
#include<stdio.h>
#include<stdlib.h>
typedef struct termino
{
int exponente;
float cociente;
} termino;
typedef struct polinomio
{
termino* polinomio;
int size;
} polinomio;
void multiplicarEscalar(int escalar, termino* term){
term->cociente = (term->cociente)*(float)escalar;
}
main()
{
int size_;
termino* terminos;
int cociente_temporal;
polinomio *polinomio_;
//polinomio_ = malloc(sizeof(polinomio));
//printf("%d",(sizeof(polinomio_)*2));
printf("Bienvenido al cálculo de operaciones usando 1 polinomio.\n");
printf("Ingrese la cantidad de términos que tendrá el polinomio.");
scanf("%d",&size_);
terminos =(termino*) malloc(sizeof(termino) * size_);
polinomio_ = (polinomio*) malloc(sizeof(polinomio) );
polinomio_->polinomio = terminos;
polinomio_->size = size_;
printf("Ingrese el cociente 0:\n");
scanf("%d",&cociente_temporal);
polinomio_->polinomio->cociente = cociente_temporal;
//multiplicarEscalar(2,polinomio_->polinomio);
printf("\nEl valor del cociente es: %d",(polinomio_->polinomio->cociente));
free(polinomio_);
}
You are using "%d" to print a float. That leads to undefined behavior.
Instead of
printf("\nEl valor del cociente es: %d",(polinomio_->polinomio->cociente));
use
printf("\nEl valor del cociente es: %f",(polinomio_->polinomio->cociente));
// ^^^