Function takes as parameter a string array

Asked

Viewed 7,425 times

2

I just started learning the C programming language and I’m having a hard time.

I declare a string vector, pass values to that vector and then pass that same vector as a function argument. The problem is here, when I run the program and the moment I pass the array of strings as argument, it simply stops working.

I leave here an example of code, to see how I’m doing:

#include <stdio.h>
#include <stdlib.h>
void MostraTodos(char memoria[]);

int main(int argc, char *argv[]) {
    char memoria[3][30];
    int i;
for(i=0;i<3;i++){
    printf("Introduza o seu nome\n");
    scanf("%s", &memoria[i]);
    }

MostraTodos(memoria);
return 0;
}


void MostraTodos(char memoria[]){
    int i;
    for(i=0; i<3; i++){
        printf("%s", memoria[i]);
    }

}

I’ve done a lot of research and I can’t find the answer, and I think it’s easy to solve.

  • Use as follows: scanf_s("%s", &memoria[i], 30);

1 answer

2


One of the reasons for the error is that they exist strings in C. There actually is array of char ended with a null. If conceptualize it correctly it is easier to understand. Then there are two errors, in fact, the same in two places.

One is that it is parameterizing the function to receive a vector of char, but what you want is a vector vector of 30 chars. So this is what you have to use in the parameter.

The other mistake is that it’s going to the scanf() a pointer to the vector element when you want to pass a pointer to the address where the vector of char of each element, so you have to pass element 0 of this vector.

#include <stdio.h>

void MostraTodos(char memoria[][30]) {
    for (int i = 0; i < 3; i++) printf("%s\n", memoria[i]);
}

int main() {
    char memoria[3][30];
    for (int i = 0; i < 3; i++) {
        printf("Introduza o seu nome\n");
        scanf("%s", &memoria[i][0]);
    }
    MostraTodos(memoria);
}

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

  • First of all, thank you for your reply. I think I understand what you said. However I was left with a doubt: Of the two changes you suggested, if I only make the first one (char memoria[][30]) the program apparently works correctly without giving any kind of error. Could you explain to me why this is happening? Thank you.

  • @Peixoto works on some compilers. That’s what I always say, working is different than being right. what works one day can stop working, the right is always right. So one of the biggest learnings that a programmer has to have is that he can’t trust what works, he has to make sure that he’s right. And for this it needs a lot of dedication and study. It can not do "on the thighs".

Browser other questions tagged

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