How to receive a char pointer via keyboard in C/C++?

Asked

Viewed 4,833 times

2

How do I receive a pointer from char keyboard?

2 answers

4


Basically the same way as other types of data. I know you’ve learned in another question how to use the scanf(). There are two differences to read a whole you already know.

scanf("%s", texto);

The first argument indicates that you are trying to read a string. The second is to pass the variable that will receive this data. Note that you do not use the operator & in this case because the variable is already a pointer.

#include <stdio.h>
#include <stdlib.h>
int main(){
   char *texto; //declara a variável da forma como você sugeriu
   texto = malloc(31); //reserva o espaço em memória para 30 caracteres
   scanf("%s30", texto); //Lê caracteres pelo teclado e guarda os primeiros 30 em texto
   printf("%s", texto); //imprime o que foi entrado.
   free(texto); //libera a memória alocada
   return 0;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You can also use the notation of array that neither C in most is another way to work with pointers. This way it becomes easier to make memory allocation. This case the allocation will normally occur in the stack and not in heap as is done with the malloc(). For simple examples it is easier. See Guilherme Bernal’s answer to an example with array. I used the pointer because that’s the term you used.

It is possible to allocate memory to an object pointed by a variable as done above in the stack also, as is done with array. This practice is not very recommended. The code below is equal to the malloc but instead of allocating dynamic memory (in heap), it allocates memory considered static (which does not need to be released later, read more to understand this in the link I passed above):

char * texto = alloca(31);

Never make too large memory allocation in stack. Do not use this area of memory to return the value of one function to another, directly or indirectly. If you need to do this you would have to copy the data in the return since the termination of a function would potentially make the data allocated in the stack for that function to be lost.

I won’t go into detail since it looks like you’re getting started. When you have specific questions about this, you can open another question, if it does not already exist on the site.

Anyway it is common to use pointer for dynamic allocations in heap and use array for allocation when you know it is best to use the stack. There’s no need to make up too much.

  • Thank you very much bigown for the help! One more question, which is the most usual form and in terms of performance of the program is better to use, through the array shown by Guilherme Bernal or through char pointer as illustrated by vc?

  • 2

    @Life here will depend a lot on the size of the entrance and what you want to do with it later. If it is for immediate processing, it is valid to use a local array. But to save the value and use later, it is already preferable to allocate dynamic memory as shown here. (bigown, forgot free! (not that it makes any difference in this example))

  • 1

    The shape of array is more syntactic, internally everything is pointer in C. In this case it will not make any big difference (I’ll even complement the answers on this). One or the other is usually chosen for the semantics one wants to give. You are working with something that is clearly one array? Goes with it, otherwise it goes pointer. The thing is a little more complicated than this, but it does not give p/ reply all in a comment. It is common for inexperienced programmers to use more often the array, it is slightly easier. @Guilhermebernal the program will already finish and release everything :P

  • Um got it... now it’s clearer to me... I’m starting to learn a little more about pointers now, so a lot of questions are coming to me.. I am performing string exercises in the online URI Java for marathon workouts, so I came up with a string exercise that gave me this question... thank you so much for the @bigown explanation! Your reply was very well explained! Thank you very much! Grateful, Eduardo.

2

You can read a string directly from the standard console entry using the command scanf. Thus:

#include <stdio.h>

int main() {
    printf("Digite uma frase: ");
    char frase[300];
    scanf("%s", frase);
    pritnf("Voce digitou '%s'", frase);
    return 0;
}

Note, however, that there is a risk of the user typing more than 299 characters. (plus the null terminator that the entire string has, totaling 300). If it does so there will be "buffer overflow" and your program will probably experience a crash. To avoid can use so:

scanf("%299s", frase);

Any amount of letters after the first 299 will not be read.

  • Now I understand Guilherme Bernal! Thank you very much for the reply!

Browser other questions tagged

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