简体   繁体   中英

Pointer Array Malloc (C Programming)

I found this one line that I don't understand. It says

char (*storage)[15] = malloc(sizeof *storage * 8)

Does anybody know what this is mean? why I see a lot of * ?

I don't get it because why he/she multiplied by 8 (it seems like that) but then declared it was [15] too?

Correct me if I'm wrong.

char (*storage)[15] = malloc(sizeof *storage * 8)

It allocates memory for 8 character arrays of size 15 .

For all * you ask-

char (*storage)[15]              // pointer to array of 15 chars 

and this -

sizeof *storage * 8   // this is 8 times sizeof type to which storage points 

char (*storage)[15] is a pointer to 15-element array of char .

sizeof *storage * 8 is 8 times the size of the type at which storage points.

char (*storage)[15] = malloc(sizeof *storage * 8);

dynamically allocates an 8x15 array of char . This is roughly similar to writing

char storage[8][15];

except that

  • The lifetime of a dynamically-allocated object lasts until it is explicitly deallocated with free , whereas the lifetime of an automatically-allocated object lasts until the program exits the object's enclosing scope;
  • The storage for a dynamically-allocated object is (usually) taken from a different memory segment than automatically-allocated objects;
  • You can extend the size of a dynamically-allocated array as necessary. IOW, if you realized you needed two more rows, you could write
     size_t curRows = 8; char (*tmp)[15] = realloc( storage, sizeof *storage * (curRows + 2)); if ( tmp ) { storage = tmp; curRows += 2; } 
    You can't do that with an automatically-allocated array.

An alternate way of dynamically allocating an 8x15 array is something like this:

char **storage = malloc( sizeof *storage * 8 );
if ( storage )
{
  for ( size_t i = 0; i < 8; i++ )
  {
    storage[i] = malloc( sizeof *storage[i] * 15 );
  }
}

Note that all three versions can be indexed as storage[i][j] .

The main advantage of the last method is that each row can be different lengths if you want them to be. The main disadvantages are that the rows won't necessarily be adjacent in memory, and you have to free each storage[i] before you can free storage .

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