I have trouble printing the output of a string array

Asked

Viewed 56 times

2

Code:

#include <stdio.h>
#include <string.h>

int main() {
    int i, j, k;
    char nomes[10][99];

    for (j = 0; j < 2; j++) {
        printf("\nTurma %d:\n", j+1);
        for (i = 0; i < 10; i++) {
            printf("Aluno: ");
            scanf("%s", &nomes[i][j]);
        }
    }

    printf("\nTurma 1:\tTurma 2:\n");

    for (i = 0; i < 10; i++) {
        for (j = 0; j < 2; j++) {
            printf("%s\t", &nomes[i][j]);
        }
        printf("\n");
    }
}

The output of the second column is perfect (as far as possible), but the first column prints only the first letter of the string and concatenates with the respective string of the second column. I do not understand why this happens, I wanted to know what part of the code causes this problem. I will link an input image and an output image of the program to make everything clearer.

entrada

saída

1 answer

4


The biggest problem is that space is not reserved for the string, only to the matrix, then corrupts all memory.

I put a constant to facilitate since probably want to change the size of classes and students and the value is used in various places. I’m avoiding magic number, although I left in the size in the student’s name.

The number of the reserved size does not match the one of the loop, so it is quite wrong, but it seems that it is inverted in relation to what you want, only increases the problem already mentioned before, the memory is all corrupted.

I also protected the student name entry with the maximum allowed size.

The same would be right to print the header of the classes in a loop, I left this to do.

The alignment has some possible solutions, the one I thought was easier was to use the formatter that indicates the size that should occupy. There might be a better way, but what I thought now was to make an exception for the first column to not have the spacing. Then maybe I’ll see how to make it more linear.

#include <stdio.h>
#include <string.h>
#define TURMAS 2
#define ALUNOS 10

int main() {
    char nomes[ALUNOS][TURMAS][31];
    for (int j = 0; j < TURMAS; j++) {
        printf("\nTurma %d:\n", j + 1);
        for (int i = 0; i < ALUNOS; i++) {
            printf("Aluno: ");
            scanf("%30s", nomes[i][j]);
        }
    }
    printf("\nTurma 1:                      Turma 2:\n");
    for (int i = 0; i < ALUNOS; i++) {
        printf("%s", nomes[i][0]);
        for (int j = 1; j < TURMAS; j++) printf("%30s", nomes[i][j]);
        printf("\n");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you so much for the answer! I am new in C and do not know much, helped me too :).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.