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;
}
string
andstring2
are pointers. But they point nowhere concrete.– pmg
But str1 comes to print
– Miguel
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.
– pmg
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]')
– Miguel
Tried with
gets
instead ofscanf
andputs
instead ofprintf
?– Franchesco