Tuesday, November 13, 2007

Strings, Array length in C.

Every time you use a string in C, you'll have to remember

Declare C-style strings to have length CONSTANT+1

char name[ NAME_LENGTH + 1 ] = { 0 }; /* string of length NAME_LENGTH */
for ( i = 0; i < NAME_LENGTH; i++ )
name[i] = 'A';
strncpy( name, some_other_name, NAME_LENGTH );

another string copy example:

char* StringCopy(const char* string) {
char* newString;
int len;
len = strlen(string) + 1; // +1 to account for the '\0'
newString = malloc(sizeof(char)*len); // elem-size * number-of-elements
assert(newString != NULL); // simplistic error check
strcpy(newString, string); // copy the passed in string to the block
return(newString); // return a ptr to the block
}

Initialize strings to null to avoid endless strings
Use strncpy() instead of strcpy() to avoid endless strings
Be aware of the difference between string pointers and character arrays.
One common convention is to use ps as a prefix to indicate a pointer to a string and ach as a prefix for an array of characters.
-- CC2(ch.12.4)

In C, use the ARRAY_LENGTH() macro to work with arrays. C example of defining an ARRAY_LENGTH() Macro:

#define ARRAY_LENGTH( x ) (sizeof(x)/sizeof(x[0]))
ratios[] ={0.0, 0.58, 0.9, ....};
for (i = 0; i < ARRAY_LENGTH(ratios); i++)

If you add or subtract entries, you don't have to remember to change a named constant that describes the array's size.
"arrays never be accessed randomly, but only sequentially"

--CC2(ch.12.8)

No comments:

Post a Comment