简体   繁体   中英

what is the type of a pointer to dynamically allocated memory of pointers of type char?

I am new to C. I need to allocate memory and store pointers in it. These pointers are of type char. So what is the type of the pointer to that memory? char? or long because addresses are just numbers?

The type is char** , pointer to pointer to char, aka double pointer to char.

Note that you wouldn't need to manually allocate space for the pointers if you don't want to.

Take the code:

#define POINTER_N 10
//...
char *ptr[POINTER_N]; //array of 10 pointers to char

This already reserves space for these 10 pointers, their size is the size of a pointer to char, this size deppends on your system, for a 64 bit system the pointers are 8 bytes, for a 32 bit one it's 4 bytes, this is generic, there can be differences in these values depending on the implementation.

Already having the pointer you only will then need to allocate space for the strings themselves, so for 20 char strings initialized to \0 you would do:

#include <stdlib.h>
#define STRING_SIZE 21
//...    
for(size_t i = 0; i < POINTER_N; i++){
    ptr[i] = calloc(STRING_SIZE, sizeof *ptr[0]); //21 char long string

This would suffice, note that I'm reserving one extra character for the null terminator.

If you really want to allocate the space for these pointers yourself you would declare a double pointer, and allocate space for the numbers of pointers to char you need:

char **ptr = calloc(POINTER_N, sizeof *ptr); // 10 pointers to pointers to char

And for the strings:

for(size_t i = 0; i < POINTER_N; i++){
    ptr[i] = calloc(STRING_SIZE, sizeof **ptr); 

Assuming I understand what you're asking for, it sounds like this is what you want:

#define N 10 // or however many elements you want
...
char **arr = malloc( sizeof *arr * N ); // sizeof *arr == sizeof (char *)

Each arr[i] will have type char * .

If you want an array of char , then it would be

char *arr = malloc( sizeof *arr * N );

and each arr[i] will have type char .

So, general rule, if you want to allocate an array of type T , use

T *arr = malloc( sizeof *arr * N );

pointers have a type of the pointer to the referenced object. It does not matter how the memory was allocated.

examples

void *ptr = malloc(10);  // pointer to void

int c;
void *ptr = &c;          //pointer to void

int *ptr = malloc(sizeof(*ptr);  // pointer to integer
int *ptr = &c;                   // pointer to integer

char *cp = malloc(100);          // pointer to char
strcpy(cp, "Hello");

void foo(double *x)              // x is a pointer to double.
{
 /* .... */
} 

double **p;                      //pointer to pointer to double

/* etc etc */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM