Do I need to match a string array to another array, how do I?

1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 3
#define LEN 80
char texto[MAX][LEN];
int main(){
    char string[MAX][LEN];
    int i, j, k;
    for(i=0;i<MAX;i++){
        printf("Inf. uma string: ");
        gets(texto[i]);
    }
    printf("\n\nstrings digitadas foram\n\n");
    for(i=0;i<3;i++){
        printf("%s \n",texto[i]);
    }
    printf("\n\n");

    for(i=0;i<3;i++){
        for(k=0;texto[i][k];k++){
            if(i==2){
                string[i][k]=texto[i][k];
                printf("String 2: %s\n",string[i][k]);
            }
        }
    }
    system("pause");
    return 0;
}
    
asked by anonymous 25.10.2017 / 17:30

1 answer

1

You can use the strcpy() function of the standard string.h library to copy each of the strings contained between the two-dimensional arrays texto[][] and string[][] .

Never use the gets() function! It was considered% of% due to the deprecated risk it represents. Use buffer overflow or scanf() of the default library fgets() .

Here is a tested code with the correct fixes:

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

#define MAX 3
#define LEN 80

char texto[MAX][LEN];

int main(){
    char string[MAX][LEN];
    int i;

    for( i = 0; i < MAX; i++ ){
        printf("Informe string %d: ", i );
        scanf( "%s", texto[i] );
    }

    printf("\nStrings digitadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, texto[i] );

    for( i = 0; i < MAX; i++ )
        strcpy( string[i], texto[i] );

    printf("\nStrings copiadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, string[i] );

    return 0;
}

However, if the challenge is not to use the stdio.h function, you can try something like:

#include <stdio.h>

#define MAX 3
#define LEN 80

char texto[MAX][LEN];

int main(){
    char string[MAX][LEN];
    int i, j;

    for( i = 0; i < MAX; i++ ){
        printf("Informe string %d: ", i );
        scanf( "%s", texto[i] );
    }

    printf("\nStrings digitadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, texto[i] );

    for( i = 0; i < MAX; i++ )
        for( j = 0; j < LEN; j++ )
            string[i][j] = texto[i][j];

    printf("\nStrings copiadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, string[i] );

    return 0;
}

Output:

Informe string 0: aeiou
Informe string 1: abcdefghijklmnopqrstuvwxyz
Informe string 2: 1234567890

Strings digitadas foram:
[0] aeiou 
[1] abcdefghijklmnopqrstuvwxyz 
[2] 1234567890 

Strings copiadas foram:
[0] aeiou 
[1] abcdefghijklmnopqrstuvwxyz 
[2] 1234567890 
    
25.10.2017 / 17:51