Site Archive (Complete)
C++
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
March 01, 2002
The New C:

VLAs, Part 4: VLA typedefs and Flexible Array Members

(Page 1 of 2)
Randy Meyers
The Rest of the Story on variable-length arrays in C99. Yes, they're well-behaved and very flexible, but use them with caution.
March 2002/The New C/Listing 1

Listing 1: A flexible array member

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// The representation of a PL/I string
struct PLIstring {
  unsigned short count;
  // s is a flexible array member
  char s[];
};

// Convert the C language string cstr to a PL/I string
// allocated on the heap
struct PLIstring *toPLI(char *cstr)
{
  struct PLIstring *pli;
  size_t len = strlen(cstr);
  // We allocate len extra bytes as storage for the s array
  pli = malloc(sizeof (struct PLIstring) + len);
  assert(pli != NULL);
  pli->count = len;
  // Copy len bytes into the flexible array s.  Note the zero byte
  // ending the C string is not copied.
  memcpy(pli->s, cstr, len);
  return pli;
}

int main(int argc, char **argv)
{
  int i;

  // Convert our program arguments to PL/I strings and print them

  for (i = 0; i < argc; ++i) {
    struct PLIstring *pli = toPLI(argv[i]);
    // print the PL/I string.  By specifying a precision for %s, we
    // can force it to stop printing before finding a zero byte.
    // By making the precision be *, we can pass it as an argument
    // to printf.
    printf("count=%hu, s=\"%.*s\"\n", pli->count, pli->count, 
        pli->s);
  }

  return EXIT_SUCCESS;
}
— End of Listing —
1 | 2 Next Page
TOP 5 ARTICLES
No Top Articles.
DR. DOBB'S CAREER CENTER
Ready to take that job and shove it? open | close
Search jobs on Dr. Dobb's TechCareers
Function:

Keyword(s):

State:  
  • Post Your Resume
  • Employers Area
  • News & Features
  • Blogs & Forums
  • Career Resources

    Browse By:
    Location | Employer | City
  • Most Recent Posts:



    MICROSITES
    FEATURED TOPIC

    ADDITIONAL TOPICS

    INFO-LINK



     



    Related Sites: DotNetJunkies, SD Expo, SqlJunkies