Skip to content

Instantly share code, notes, and snippets.

@jacobabrahamb4
Created April 12, 2013 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobabrahamb4/5370145 to your computer and use it in GitHub Desktop.
Save jacobabrahamb4/5370145 to your computer and use it in GitHub Desktop.
using pointers to pointers in c
//taken from http://stackoverflow.com/questions/894604/passing-dynamically-allocated-integer-arrays-in-c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 5
/*
* A string is an array of characters, say char c[]. Since we will be creating
* an array of those, that becomes char *(c[]). And since we want to store the
* memory we allocate somewhere, we must be given a pointer. Hence char
* **(c[]).
*
* An int doesn't require a complete array, just int i. An array of those is
* int i[]. A pointer to those is then int *(i[]).
*/
void
make(char **(chars[]), int *(ints[]), size_t len)
{
static char hw[] = "Hello, World!";
size_t i = 0;
/*
* Allocate the memory required to store the addresses of len char arrays.
* And allocate the memory required to store len ints.
*/
*chars = malloc(len * sizeof(char *));
*ints = malloc(len * sizeof(int));
/* Fill each element in the array... */
for (i = 0; i < ELEMENTS; i++) {
/* ... with a *new copy* of "Hello world". strdup calls malloc under
* the hood! */
(*chars)[i] = strdup(hw);
/* ...with a multiple of 10. */
(*ints)[i] = i * 10;
}
}
int
main(void)
{
/* A string c is a character array, hence char c[] or equivalently char *c.
* We want an array of those, hence char **c. */
char **chars = NULL;
/* An array of ints. */
int *ints = NULL;
size_t i = 0;
/* Pass *the addresses* of the chars and ints arrays, so that they can be
* initialized. */
make(&chars, &ints, ELEMENTS);
for (i = 0; i < ELEMENTS; ++i) {
printf("%s and %d\n", chars[i], ints[i]);
/* Don't forget to free the memory allocated by strdup. */
free(chars[i]);
}
/* Free the arrays themselves. */
free(ints);
free(chars);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment