Looks good to me. Like Peter says, the function returns the pointer correctly, and the compiler should put that string in a static memory location instead of on the stack.

Now if you were to do something like this:

  char * x;

  printf("%s\n", get_static_string());
  x = get_static_string();
  x[20] = 'X';
  printf("%s\n", get_static_string());

The result should be this:

  This is a statically allocated C string
  This is a staticallyXallocated C string

So we know we're pointing to the same static area with each call. But if you were to change the function to a local variable like this:

  char str[81] = "This is a statically allocated C string";

... now we're allocating locally and that memory is gone (or maybe reused?) when the function returns the address. Not what you want probably.

Frank Swarbrick wrote:
I know there are at least a few C developers here, so I was wondering if you 
could answer a question.  Is the following valid C?  (I'm not asking if one 
should actually do it; only if its valid at all.)
char *get_static_string(void) {
    static char str[81] = "This is a statically allocated C string";
    return str;
}


printf("%s", get_static_string());


I don't have a C compiler available at work else I'd try it myself.

Frank

----------------------------------------------------------------------
For IBM-MAIN subscribe / signoff / archive access instructions,
send email to lists...@listserv.ua.edu with the message: INFO IBM-MAIN



----------------------------------------------------------------------
For IBM-MAIN subscribe / signoff / archive access instructions,
send email to lists...@listserv.ua.edu with the message: INFO IBM-MAIN

Reply via email to