pointer of array

Discussion in 'C Programming' started by NA Gary, Jun 28, 2003.

  1. NA Gary

    NA Gary Guest

    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)) ;
     
    NA Gary, Jun 28, 2003
    #1
    1. Advertisements

  2. #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.
     
    Martin Ambuhl, Jun 28, 2003
    #2
    1. Advertisements

  3. a usual:

    #inclide <stdlib.h>
    ....
    char *vertex = malloc (3);
    or
    char *vertex = malloc (sizeof *vertex * 3);
     
    Emmanuel Delahaye, Jun 28, 2003
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.