1
When I run the code below, it gives the following error:
'daluno' was not declared in this Scope
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Aluno{
int matricula;
float p1;
float p2;
float p3;
float t1;
float t2;
};
void aloca(int N){
int *pAluno = &daluno;
pAluno = (int*)malloc(sizeof(daluno)*N);
if (pAluno==NULL){
printf("Memoria INSUFICIENTE");
exit(0);
}
int i;
for(i=0; i<N; i++) {
printf(" Digite a matricula do aluno %d: ",i);
scanf("%d", &daluno[i].matricula);
printf(" Digite a nota da prova 1 do aluno %d: ",i);
scanf("%d%*c", &daluno[i].p1);
printf("\n Digite a nota da prova 2 do aluno %d: ",i);
scanf("%f%*c", &daluno[i].p2);
printf("\n Digite a nota da prova 3 do aluno %d: ",i);
scanf("%f%*c", &daluno[i].p3);
printf("\n Digite a nota do trabalho 1 do aluno %d: ",i);
scanf("%f%*c", &daluno[i].t1);
printf("\n Digite a nota do trabalho 2 do aluno %d: ",i);
scanf("%f%*c", &daluno[i].t2);
}
for(i=0; i<N; i++) {
printf("matricula: %d prova 1: %f prova 2: %f prova 3: %f trabalho 1: %f trabalho 2: %f\n\n", daluno[i].matricula, daluno[i].p1, daluno[i].p2, daluno[i].p3, daluno[i].t1, daluno[i].t2);
}
free(pAluno);
}
int main (){
struct Aluno daluno;
int N;
printf("Digite a quantidade de N alunos: ");
scanf("%d",&N);
aloca (N);
return 0;
}
Yes, because it is only visible in the main function
– Wictor Chaves
So for me to allocate a vector dynamically I have to create a function?
– Bruno Gomes
It is declared in main, so can only be accessed in main.
– G. Bittencourt
You have to put it out of any function, so it becomes a global variable
– Wictor Chaves
As you created the variable 'daluno' in the main method, only the same has access to it. To access on a global level, you must initialize the variable outside the main method.
– Luiz Foli
The main is a function, and any variable declared within a function has the scope limited to function, if you want this variable to be accessed anywhere, you have to declare it globally, in case outside any function.
– Wictor Chaves
I don’t know if it fits, but you could pass the reference (pointer) of this variable by parameter to be accessed by the function, and thus you would change the variable without declaring it globally. Ps: if I’m wrong I withdraw the comment....
– Will