C print name with scanf

0

I have the following code, the problem is that it returns string2 as '(null)'. How do I solve it? and why does this happen?

#include <stdio.h>
int main()
{
    char *string;
    char *string2;

    printf("Primeiro nome: ");
    scanf("%s", string);

    printf("Ultimo sobrenome: ");
    scanf("%s", string2);

    printf("Ola senhor %s %s. Bem-vindo.\n", string, string2);

    return 0;


}
    
asked by anonymous 24.09.2014 / 11:39

1 answer

4

Experiment with arrays instead of pointers

#include <stdio.h>

int main(void)
{
    char string[1000];  // array em vez de ponteiro
    char string2[1000]; // array em vez de ponteiro

    printf("Primeiro nome: ");
    if (scanf("%999s", string) != 1) /* erro */;

    printf("Ultimo sobrenome: ");
    if (scanf("%999s", string2) != 1) /* erro */;

    printf("Ola senhor %s %s. Bem-vindo.\n", string, string2);

    return 0;
}

If you really want to use pointers, you have to allocate space for the strings, and release that space when it is no longer necessary:

#include <stdio.h>
#include <stdlib.h> /* malloc() and friends */

int main(void)
{
    char *string;
    char *string2;

    string = malloc(1000);            /* aloca espaco */
    if (string == NULL) /* erro */;
    string2 = malloc(1000);           /* aloca espaco */
    if (string2 == NULL) /* erro */;

    printf("Primeiro nome: ");
    if (scanf("%999s", string) != 1) /* erro */;

    printf("Ultimo sobrenome: ");
    if (scanf("%999s", string2) != 1) /* erro */;

    printf("Ola senhor %s %s. Bem-vindo.\n", string, string2);

    free(string);   /* liberta espaco */
    free(string2);  /* liberta espaco */

    return 0;
}
    
24.09.2014 / 11:50