pointer of array

N

NA Gary

How to "malloc" a pointer of fixed length char array such as char
*(vertex[3]) ?

I encounter syntax errors for these cases

vertex = (**char)malloc(sizeof(char)*3) ;
vertex = (**char)malloc(sizeof(*char)) ;
 
M

Martin Ambuhl

How to "malloc" a pointer of fixed length char array such as char
*(vertex[3]) ?

I encounter syntax errors for these cases

vertex = (**char)malloc(sizeof(char)*3) ;
vertex = (**char)malloc(sizeof(*char)) ;

#include <stdlib.h>
#include <stdio.h>
#define NPTRS 3
#define SSIZE 256

int main(void)
{
char *(vertex[NPTRS]);
size_t i, j, n = sizeof vertex / sizeof *vertex;
printf("'vertex' is an array of %lu pointers to char\n"
"On this implementation, sizeof(char *) is %lu\n"
" sizeof vertex is %lu\n"
" and sizeof *vertex is %lu\n"
"Since vertex is an array, it makes no sense to\n"
"try to allocate it. You allocate space for the\n"
"%lu pointers to point to.\n\n"
"For example,\n"
" vertex = malloc(%lu * sizeof *vertex);\n"
"makes no sense.\n\n",
(unsigned long) n,
(unsigned long) sizeof(char *),
(unsigned long) sizeof vertex,
(unsigned long) sizeof *vertex,
(unsigned long) n,
(unsigned long) n);
printf
("Attempting to allocate %d bytes for each of the %lu pointers
\n",
SSIZE, (unsigned long) n);
for (i = 0; i < n; i++) {
if ((vertex = malloc(SSIZE)))
printf("malloc for vertex[%lu] succeeded.\n",
(unsigned long) i);
else {
printf("malloc for vertex[%lu] failed.\n"
"quiting ...", (unsigned long) i);
for (j = 0; j < i; j++)
free(vertex);
exit(EXIT_FAILURE);

}
}
for (i = 0; i < n; i++)
free(vertex);
return 0;
}


'vertex' is an array of 3 pointers to char
On this implementation, sizeof(char *) is 4
sizeof vertex is 12
and sizeof *vertex is 4
Since vertex is an array, it makes no sense to
try to allocate it. You allocate space for the
3 pointers to point to.

For example,
vertex = malloc(3 * sizeof *vertex);
makes no sense.

Attempting to allocate 256 bytes for each of the 3 pointers
malloc for vertex[0] succeeded.
malloc for vertex[1] succeeded.
malloc for vertex[2] succeeded.
 
E

Emmanuel Delahaye

NA Gary said:
How to "malloc" a pointer of fixed length char array such as char
*(vertex[3]) ?
I encounter syntax errors for these cases

vertex = (**char)malloc(sizeof(char)*3) ;
vertex = (**char)malloc(sizeof(*char)) ;

a usual:

#inclide <stdlib.h>
....
char *vertex = malloc (3);
or
char *vertex = malloc (sizeof *vertex * 3);
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top