Function receives as parameter a vector of strings

1

I started learning the C programming language a little while ago and I'm having a hard time.

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

Here's an example 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 researched a lot and I can not find the answer, but I think it's easy to solve.

    
asked by anonymous 03.12.2017 / 00:45

1 answer

1

One of the reasons for the error is to think that there are strings in C. In fact there is array of char terminated with a null. Conceptualizing this correctly makes it easier to understand. So there are two errors, actually the same in two places.

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

The other error is that you are passing% po_de% a pointer to the vector element when you want to pass a pointer to the address where the char vector of each element begins, 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 no Coding Ground . Also I put it in GitHub for future reference .

    
03.12.2017 / 01:25