How do I point (with a pointer, of course) to a string, so that I can then start it?

0

I'll give you an example of how I'm doing but it's wrong and I wanted someone to help me fix it.

    #include <stdio.h>
    void main() {

        char *p;
        char nome[21], outronome[21];

        scanf("%s", nome);

        * p = nome;
        scanf("%s", outronome);

        * p = outronome;

        printf("%s", *p);
     }
    
asked by anonymous 10.06.2018 / 01:16

2 answers

4

If you want to point to a string (array of characters) with a pointer, just do:

ponteiro = string;

So in your code the assignments:

* p = nome;
* p = outronome;

They are not right. Note that *p means the value pointed to by p . If p is a pointer of char then points to a char , but both nome and outronome are not chars and yes strings (chars arrays).

Soon to be correct it would have to be:

p = nome;
p = outronome;

As an aside, p is only used at the end of the program, so the first assignment is not even used.

In the show part, you have the same error here:

printf("%s", *p);

*p , that is, that indicated by p is of type char logo can not be applied with %s and yes %c . To be with %s you must pass a pointer to the first character of the string, which is p only:

printf("%s", p);

See this example working on Ideone

Complete code corrected for reference:

#include <stdio.h>
void main() {

    char *p;
    char nome[21], outronome[21];

    scanf("%s", nome);

    p = nome; //sem *
    scanf("%s", outronome);

    p = outronome; //sem *

    printf("%s", p); //sem *
}
    
10.06.2018 / 05:00
2
*p = nome; // INCORRETA ATRIBUICAO

In this section you are assigning a string to a variable of type char (* p is the memory address of the first char of the string) The right thing would be:

p = (char*) malloc(sizeof(nome)); // aloca memória necessaria para o nome
memcpy(p, nome, sizeof(nome)); // copia nome para p

There is also an error in printf:

printf("%s", *p);

As I said earlier, * p is the first char of the string, ie you are not printing a string but a char!

printf("%s", p); // agora vai imprimir a string

Anyway, I advise you to study strings and pointers, these errors could be avoided.

    
10.06.2018 / 01:55