Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

233
Vistas
What is the right way to initialize double pointer in c

As title, I want to know how to initialize double pointer with sizeof a pointer.

For instance

int **p=malloc(sizeof *p * rows);

for(size_t i = 0; i < rows; i++){
    p[i]=malloc(sizeof ? * cols);
}

What should I fill in ?.

Any help would be appreciated.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

What should I fill in ?.

In general when you have

X = malloc(sizeof ? * NUMBER);

the ? is to be replaced with the type that X points to. That can simply written as *X.

So the line:

p[i]=malloc(sizeof ? * cols);

is to be:

p[i]=malloc(sizeof *p[i] * cols);

Notice that a 2D array can be created much simpler. All you need is

int (*p)[cols] = malloc(sizeof *p * rows);

Here p is a pointer to an array of cols int. Consequently sizeof *p will be the size of an array of cols int.

Using this VLA based technic means that you can allocate the 2D array using a single malloc. Besides making the code more simple (i.e. only 1 malloc) it also ensures that the whole 2D array is in consecutive memory which may give you better cache performance.

over 4 years ago · Santiago Trujillo Denunciar

0

It looks like you want p to be an array that can hold pointers, and the number of pointers is rows. So you can allocate memory for p like this:

int ** p = malloc(sizeof(int *) * rows);

Now if you want p[i] to point to an array that holds cols ints, do this:

p[i] = malloc(sizeof(int) * cols);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda