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

Asked

Viewed 51 times

0

I’ll give you an example of how I’m doing but it’s wrong and I’d like someone to help me fix that mistake.

    #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);
     }

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’re not right. Remember that *p means the value pointed by p. If p is a pointer of char then points to a char, but so much nome as outronome are not chars and yes strings (arrays of chars).

Soon to be correct it would have to be:

p = nome;
p = outronome;

As an aside, the p is only used at the end of the programme, so that the first allocation is not even used.

In the show part, there’s the same mistake, here:

printf("%s", *p);

*p, that is, the pointed by p is the type char so can not be applied with %s and yes %c. To be with %s has to pass a pointer to the first character of the string, which is the 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 *
}

2

*p = nome; // INCORRETA ATRIBUICAO

In this snippet you are assigning a string to a char variable (*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 the 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 to give a studied in strings and pointers, these errors could be avoided.

  • Yes, I forgot that, I updated my answer

Browser other questions tagged

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