C print name with scanf

Asked

Viewed 719 times

0

I have the following code, the problem is that it returns string2 as '(null)'. How do I fix? 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;


}
  • string and string2 are pointers. But they point nowhere concrete.

  • But str1 comes to print

  • It was bad luck! If the program had burst (or printed "null") it wouldn’t have led you to think that this part was fine.

  • inputs: str1 = foo, str2 = bar... You are printing "Ola senhor foo (null). Welcome.". Okay then how do I fix it? I didn’t want to have to define a limited number ('char[99]')

  • Tried with gets instead of scanf and puts instead of printf?

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 to the strings, and release that space when it is no longer needed:

#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;
}
  • Thank you, that’s right. A question: We really have to set a limit of bytes(chars) in advance (malloc)?

  • The number of bytes to allocate pde to be determined by the program; does not need to be set by the programmer.

Browser other questions tagged

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