Question about arrays and pointer

0
#include <stdio.h>
#include <locale.h>

int main () {

    setlocale (LC_ALL,"Portuguese"); // Formatação.

    int notas1[50],notas2[50],notas3[50],soma[50]; // Declaração.

    for (int i = 1; i < 50; i++){ // Dados.
        printf("\nInforme a primeira nota do aluno %i: ",i);
        scanf("%i",&notas1[i]);
        printf("\nInforme a segunda nota do aluno %i: ",i);
        scanf("%i",&notas2[i]);
        printf("\nInforme a terceira nota do aluno %i: ",i);
        scanf("%i",&notas3[i]); }

    for (int h = 1; h < 50; h++){ // Soma e divisão dos vetores 1,2 e 3 para cada nota.
        soma[h] = (notas1[h] + notas2 [h] + notas3 [h])/3; }

    for (int j = 1; j < 50; j++){ // Imprimindo.
        printf ("\nA nota do aluno %i é: %i",j,soma[j]); }

    return 0;
}

My doubts are: How would I ask for the number of vectors to be created for the user and then save in the variable to continue the program (without doing with pointer)? How would the extremely simplified code look like, or better what would that code look like if it was done with a pointer (I tried but did not give it).

    
asked by anonymous 09.06.2016 / 04:41

1 answer

1

Because in C you can declare variables anywhere in the code, you can request the value and then declare your vectors. Example:

int vec_len;
scanf("%d", &vec_len);

int notas1[vec_len],notas2[vec_len],notas3[vec_len],soma[vec_len];

But to simplify the code, it would be better to put all the notes in an array

int notas[vec_len][4]; // a quarta posição de notas serve para a soma das notas

Now for the use of pointers, it only changes the part of having to allocate from deallocation.

int vec_len;
scanf("%d", &vec_len);

int *notas1 = malloc(vec_len*sizeof(int));
int *notas2 = malloc(vec_len*sizeof(int));
int *notas3 = malloc(vec_len*sizeof(int));
int *soma = malloc(vec_len*sizeof(int));

The sizeof(int) is to allocate the exact size compatible with integer values.

And the simplification.

int **notas = malloc(vec_len*sizeof(int*)); // matriz ou ponteiro duplo
int x;
for(x=0;x<vec_len;x++)
    notas[x] = malloc(4*sizeof(int));

In **notas has sizeof(int*) because it is taking the size of int* to allocate, and notas[x] represents int* and stores int .

If you are going to use vectors, you do not have to make changes to the values. If it is to use array it gets notas[x][y] .

To deallocate the pointers just do.

//Caso seja uma matriz
//...
free(notas[x]);
//...
free(notas);
//Caso seja vetor
free(notas1);
free(notas2);
free(notas3);
free(soma);
    
09.06.2016 / 04:59