#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