LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   guidlines on working with strings in C? (https://www.linuxquestions.org/questions/programming-9/guidlines-on-working-with-strings-in-c-293522/)

zero79 02-22-2005 03:08 PM

guidlines on working with strings in C?
 
Hi all,

I'm looking for information about properly handling and manipulating strings in C. For example, when should you declare a sring with "char str[300]" vs. "char *str".

If you use the character pointer, is it possible that other strings, reals, etc could take over some of the memory occupied by that string thus leading to seg faults and sig 11s? I guess that it's smart to use the character array in that sense, but then again more memory is used than need be.

In that sense, what would a sensible character limit be for holding a string that consists of a file name and path? I was thinking something like 300 should be reasonable. Should the code just error if the path is too long, or is there a better way to gracefully handle this?

Thanks for any thoughts.

itsme86 02-22-2005 03:54 PM

The difference between char *str; and char str[300]; is that the first one can only point to a string, and the second one can actually store a string.

When you do something like char *str = "this is a string";, the string will be stored in a read-only memory area and then the str pointer points to it. That means that you should not (and usually cannot, you'll get a segmentation fault) modify that string.

When you do char str[300] = "this is a string"; then the compiler creates an array of 300 chars and then copies the string into that array. That gives you full control over the contents so the string can be modified or what-not.

Of couse, you can also do something like:
Code:

char str[300] = "this is a string";
char *strptr = str;

That way, instead of the pointer pointing to a string in read-only memory, it's pointing to an array that you can modify.

As far as a reasonable limit for a filename and path, the most graceful way to handle it would be to use the PATH_MAX macro defined in limits.h:
Code:

#include <limits.h>

int main(void)
{
  char str[PATH_MAX];

  return 0;
}



All times are GMT -5. The time now is 05:05 PM.