-3

I want the user to enter 3 names, and right after the program prints these 3 names can someone tell me why is not printing anything??? I tried everything if someone could explain it..... there is no error, it simply exits after inserting the strings

#include <stdio.h>
#include <stdlib.h>
int main(){
int i, a, componentes;
char *nome;
componentes = 3;
nome = (char*) malloc(sizeof(char)*100);
printf("\n");
for(i = 0; i < componentes; i++){
// printf("String %d: ", i+1);
scanf("%s", &nome[i]);     
}

printf("\n");
for(a = 0; a < componentes; a++){       
printf("%s\n", nome[i]);
}
return 0;
} 
  • 1
    `scanf("%s", &nome[i]);` You only have a buffer for *one* string not 3. `&nom[i]` points to somewhere in the same buffer every iteration. Similarly `printf("%s\n", nome[i]);` is completely wrong and the compiler should give you a warning for that. `nom[i]` is a single `char` not a string. – kaylum Mar 12 '21 at 02:44
  • 1
    If you want to scan multiple strings you need to allocate a 2D array. Do a search. e.g.: [dynamic memory for 2D char array](https://stackoverflow.com/questions/2614249/dynamic-memory-for-2d-char-array) – kaylum Mar 12 '21 at 02:47
  • Consider using fgets() instead of scanf(). The latter is subject to buffer overflow for strings. use a #define instead of a variable for components. Also get familiar with the const keyword. It will help you. – Allan Wind Mar 12 '21 at 03:11

1 Answers1

0

I fixed the issues raised (plus free'ing the memory):

#include <stdio.h>
#include <stdlib.h>

#define N 3
#define LEN 100

int main() {
    char *components[N];
    for(int i = 0; i < N; i++) {
        components[i] = malloc(LEN);
        fgets(components[i], LEN, stdin);
    }
    for(int i = 0; i < N; i++) {
        printf("%s", components[i]);
        free(components[i]);
    }
    return 0;
}

You could also allocate the 300 bytes for the 3 strings via local variable on the stack, either with char components[N][LEN]; or as a single string that you index just to show you a different way:

#include <stdio.h>
#include <stdlib.h>

#define N 3
#define LEN 100

int main() {
    char components[N * LEN];
    for(int i = 0; i < N; i++) {
        fgets(components + i * LEN, LEN, stdin);
    }
    for(int i = 0; i < N; i++) {
        printf("%s", components + i * LEN);
    }
    return 0;
}
Allan Wind
  • 11,844
  • 4
  • 24
  • 32