Mixing types in arrays

Ray Spalding cc100aa at prism.gatech.EDU
Fri Feb 15 06:54:59 AEST 1991


I keep finding myself wanting to store shorts and longs (as well as
chars) in arrays of char, such as in the following simple example.

This works on all the systems I've tried, but is it "guaranteed"?  I
guess I'm worried that a pointer to char cast into a pointer to long
might somehow point to the wrong place.

I know (a) converting the value to char (e.g., ASCII) would be
guaranteed, but, I want to minimize storage space (and conversion
overhead); (b) the mixed array, if written to a file and read by
another system, would not necessarily be intelligible; and (c) the
example is not optimized (for purposes of clarity and focusing on the
issue at hand rather than other details).

But, are there other pitfalls?  Systems on which this won't work?  A
better way?

char *strcpy();

int
savevalue(key,value,bufptr)
	char *key;
	long value;
	char *bufptr;
{
	*(long *)bufptr = value;
	bufptr += sizeof value;
	(void) strcpy(bufptr,key);
	return sizeof value + strlen(key) + 1;
}

long
getvalue(key,bufptr,bufend)
	char *key;
	char *bufptr;
	char *bufend;
{
	while (bufptr < bufend) {
		if (strcmp(key,bufptr+sizeof(long)) == 0) {
			return *(long*)bufptr;
		}
		bufptr += sizeof(long);
		bufptr += strlen(bufptr) + 1;
	}
	printf("%s not found.\n",key);
	return -1;
}

main()
{
	char buffer[1000];
	char *bufptr = buffer;
	long value;

	bufptr += savevalue("First item",1234567L,bufptr);
	bufptr += savevalue("Second item",987654321L,bufptr);
	bufptr += savevalue("Third item",33333333L,bufptr);
	value = getvalue("Second item",buffer,bufptr);
	if (value == 987654321L) {
		printf("It worked.\n");
	} else {
		printf("It didn't work.\n");
	}
	return 0;
}
-- 
Ray Spalding, Technical Services, Office of Information Technology
Georgia Institute of Technology, Atlanta Georgia, 30332-0715
uucp:     ...!{allegra,amd,hplabs,ut-ngp}!gatech!prism!cc100aa
Internet: cc100aa at prism.gatech.edu



More information about the Comp.lang.c mailing list