How to declare a dynamic array

L

Linda

How can I declare a two dimention array of character with dynamical
first dimention and static second dimention using mix of pointer* and
[]. I think "char *A[4]" means first dimention is static and second
dimension is dynamical. Thank you.
 
E

Emmanuel Delahaye

In said:
How can I declare a two dimention array of character with dynamical
first dimention and static second dimention using mix of pointer* and
[]. I think "char *A[4]" means first dimention is static and second
dimension is dynamical. Thank you.

char (*A)[4] = malloc (sizeof *A * nb_of_elements);
 
M

Malcolm

Linda said:
How can I declare a two dimention array of character with dynamical
first dimention and static second dimention using mix of pointer* and
[]. I think "char *A[4]" means first dimention is static and second
dimension is dynamical. Thank you.
char *A[4];

is the same as

char* A[4];

which you will see is an array of 4 character pointers.

char (*A)[4] is what you want, but this syntax is horrible. 2d arrays in C,
beyond the very simplest declaration, are horrible.
What most programmers would do is declare

char *A;

and just manage the second dimension by hand. You see this quite commonly in
24 bit rgb images, for example.
 
C

Christopher Benson-Manica

Malcolm said:
char (*A)[4] is what you want, but this syntax is horrible. 2d arrays in C,
beyond the very simplest declaration, are horrible.
What most programmers would do is declare

Is the syntax really that bad? I would think your original
declaration would do a better job of conveying to an informed reader
that you have a dynamic array of 4 byte arrays...
 
M

Malcolm

Christopher Benson-Manica said:
Malcolm said:
char (*A)[4] is what you want, but this syntax is horrible. 2d arrays in
C, beyond the very simplest declaration, are horrible.
What most programmers would do is declare

Is the syntax really that bad? I would think your original
declaration would do a better job of conveying to an informed reader
that you have a dynamic array of 4 byte arrays...
Yes it is. If you follow the ng you will see that there is a steady trickle
of newbies hopelessly confused by C's multi-dimensional arrays, largely
because most introductory textbooks introduce the 2d array at the same time
as the 1d array.
char (*A)[4] is gibberish. No-one should be expected to follow such a
construct, or use it in real code. Even the informed reader, who can work
out what it means, will find it hard to read and make mistakes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top