How to best handle global Strings / strings / text data?

My goof! Although interestingly,

  • Same ‘error’ did not show up in a bare cpp test app (VSC but not using Workbench),
  • And sizeof(arrd) did print out “128”,
  • So I tested/searched further…

And few nuances, for strncpy() I could pass in a sizeof() for the 3rd arg but it’s compiled into a constant anyway right? So doing strncpy() on any yet-to-be-generated (variable) strings may not work properly. I guess one best practice is #define a standard buffer length for all C-strings and just stick to that as the absolute max string length for all manipulations. And could make a custom function wrapper for strncpy() to -

  1. Always clear the destination array (use a for loop w/ arrd[i] = ' ')
  2. Do strncpy()
  3. Put ‘\0’ at end of copied string up to size of buf
  4. Do some error checking on lengths

Also I should change declaration of ‘wrapper function’ to this (pointers to arrays, not copies of the arrays), with void return since it’s actually manipulating the global instance of arr1:

void scpy(char *arr1, const char *arr2, int len);

For dynamically created variables sizeof() is not determined at compile time but at runtime. So it will work.

A better way to clear an array would be

  memset(arr, 0, sizeof(arr));

This will also take care of 3.

I'd rather have your function either return the length of the resulting string (like snprintf() or
do the same as strncpy() and return the pointer to the string for direct handling of the result.

2 Likes

Thank you! Patience of community members like yourself is unmatched.

1 Like

interesting remark! I have never stopped to think about it, but now I know why it must be done that way.
Thanks

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.