Create an account or log in

Keep learning for free! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
1 Hrs
5 Min
30 Seg

Usando punteros

3/16
Resources

How to implement pointers in C++ to manipulate character variables?

Pointers are a powerful tool in C++ that allow you to work directly with memory, facilitating dynamic operations. If you have ever wondered how to start using pointers effectively, and in particular in the context of character variables, this is the place for you. Below, we will explore how to create and manipulate pointers for character variables in C++ step by step.

How do you create and use a pointer for a character variable?

To start, let's assume that we want to work with a char variable named letter, which stores the character 'a'.

To do this, we first declare our character variable:

char letter = 'a';

Now, we proceed to create a pointer pointing to letter:

char* pointer = &letter;

Here, pointer is a pointer type variable that stores the memory address of letter. The & symbol is essential to get the address of a variable.

How do we print the value and memory address of a variable?

To display the value stored in the variable letter, we simply use the standard output cout:

std::cout << letter << std::endl;

For the memory address of letter, we employ:

std::cout << &letter << std::endl;

It is important to note that the memory address is sometimes represented by a series of characters that may look strange if treated as characters because of how the pointers are interpreted.

How to convert the memory address to a more understandable representation?

We can convert the memory address to integer format for clearer display using static conversion:

std::cout << static_cast<void*>(static_cast<int*>(reinterpret_cast<void*>(&letter)))) << std::endl;

Converting to an integer allows you to display the memory address in a hexadecimal format, commonly starting with 0x, followed by a numeric value.

How to access the variable value through a pointer?

One of the most fascinating capabilities of pointers is their ability to access the original value of the variable they point to. To do this, we use the * operator, which is known as the dereference operator:

std::cout << *pointer << std::endl;

When we execute this, the system prints the value stored at the address to which our pointer points. In this case, it would be the character 'a'.

What are the advantages of using pointers in dynamic memory operations?

The use of pointers opens the door to dynamic memory, allowing you to efficiently manage resources in your program. Using pointers, you can:

  • Manipulate data structures with greater flexibility.
  • Manage memory directly to optimize application performance.
  • Perform dynamic memory allocation operations, very useful in complex applications such as those requiring custom data structures.

Maintain a curious and experimental approach. Pointers not only allow you to manipulate basic variables, but also enable you to create and implement efficient and powerful data structures. Keep practicing and, over time, you will discover how to exploit the full potential of pointers in C++.

Contributions 12

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Les dejo el c贸digo de la clase 馃槂

#include <iostream>

using namespace std;

int main() {
  char character = 'A';
  char *pointer = &character;
  cout << (int *)&character << endl;
  cout << (int *)pointer << endl;
  cout << *pointer << endl;
}

Tambien les dejo mi repositorio con todo el c贸digo y notas del curso: UltiRequiem/oop-cpp-platzi

Lo interesante de los punteros es que puedes cambiar el valor de una variable del Main desde una funci贸n sin usar el return. Tengo entendido que esto no es muy buena pr谩ctica. Un breve ejemplo:

#include <iostream>
using namespace std;

void cambio(char *c){
    cout<< "El caracter recibido es: "<<*c<<endl;
    *c='q';
    cout<< "El caracter actual es: "<<*c<<endl;
}

int main(){
    
    char caracter = 'a';
    cambio(&caracter);
    cout<< "El caracter final es: "<< caracter;
    
    return 0;

} 

basicamente, si usas el * obtienes el valor de la variable pero si esta cambia no se actualiza el valor que te entregan, pero si usas el & pasas la direccion de memoria y entonces si se actualiza el valor de variable que te entregan

C贸digo de la clase: 馃槂

#include <iostream>
using namespace std;

int main(){
  char letra = 'A';
  char *puntero = &letra;
  cout << (int *) &letra << endl;
  cout << (int *) puntero << endl;
  cout << *puntero;
}

Otra cosa interesante es la aritm茅tica de punteros.

Un arreglo es en realidad un puntero que, valga la redundancia, apunta hacia la primera direcci贸n de memoria del arreglo. Sabiendo que un int pesa 4 bytes y dicho arreglo se defini贸 con una longitud de 3 espacios, entonces se sabe que avanzando 4 celdas en memoria se obtendr谩 el siguiente elemento, es decir, 1 salto equivale a 4 celdas para este caso.

int arreglo[] = { 10, -99, 4 };

Sabiendo que la siguiente expresi贸n representa a la direcci贸n en memoria del primer elemento:

cout << "Dir. hexadecimal del arreglo: " << arreglo << endl;

La siguiente expresi贸n avanzar谩 +1 y +2 saltos en memoria partiendo desde dicha direcci贸n:

cout << "Dir. hexadecimal del arreglo en index 1: " << arreglo + 1 << endl;
cout << "Dir. hexadecimal del arreglo en index 2: " << arreglo + 2 << endl;

Para obtener el valor de este salto en memoria se recurre al operador de indirecci贸n (*puntero):

cout << "Contenido de index 0: " << *(arreglo + 0) << endl;
cout << "Contenido de index 2: " << *(arreglo + 2) << endl;

Minuto 2:27, a eso se le conoce como cast, o casteo por su t茅rmino espa帽olizado.

Comparo mi codigo:

#include <iostream>

using namespace std;

int main()
{
    char letra = 'A';
    char *puntero = &letra;

    cout << "El contenido de la variable letra es               : " << letra << endl;
    cout << "La direccion de la variable letra es               : " << (int *) &letra << endl;
    cout << endl;
    cout << "El contenido de la variable puntero es             : "  << (int *) puntero << endl;
    cout << "La direccion de la variable puntero es             : "  << (int *) &puntero << endl;
    cout << endl;
    cout << "El contenido de lo apuntado por puntero *puntero es: " << *puntero << endl;
    
    return 0;
}
![](https://static.platzi.com/media/user_upload/image-1e91b900-2e80-43ba-a8cb-a4cfdcecbaeb.jpg) Ejercicios extra ![](https://static.platzi.com/media/user_upload/image-572e7af1-aa5e-4a3f-b435-82f8ea8325b8.jpg)![](https://static.platzi.com/media/user_upload/image-8037fc1c-732a-4877-9e2c-dd6f88a5ac3e.jpg)
Yo uso Visual Studio (No Visual Studio Code) porque es lo que usamos en la universidad y al momento de compilar este c贸digo (segunda imagen) que ser铆a el del momento 01:41, lo que me retorna la consola es esto (primera imagen): ![](https://static.platzi.com/media/user_upload/Captura%20de%20pantalla%202023-10-04%20a%20la%28s%29%2016.44.40-ec99dc7b-fe50-4453-9841-9b02c00599f9.jpg)![](https://static.platzi.com/media/user_upload/Captura%20de%20pantalla%202023-10-04%20a%20la%28s%29%2016.44.09-5ceafa66-97e6-40e1-8c55-89302f366964.jpg)

para lo que no entendieron & se usa par buscar una direcci贸n en memoria, mientras tanto * no almacena un lugar en memoria .

GitHub copilot me sugirio estas lineas is son super interesantes

#include <iostream>

using namespace std;

int main() {
  char letter = 'a';
  char *ptr = &letter;
  cout << "The value of letter is " << letter << endl;
  cout << "The value of *ptr is " <<  *ptr << endl;
  cout << "The value of ptr is " << ptr << endl;
  cout << "The value of &letter is " << &letter << endl;
  cout << "The value of &ptr is " << &ptr << endl;
  cout << "The value of &*ptr is " << &*ptr << endl;
}

Un granito mas en el camino a convertirme en programador.