[vox-tech] C: functions that return a string

Rod Roark vox-tech@lists.lugod.org
Wed, 30 Jan 2002 15:36:56 -0800


ptr is a pointer, not the character buffer itself.  Sounds like whatever 
it's pointing to was on the stack.  Perhaps what you meant to do was 
define ptr as:

    static char[BUFFERSZ];

-- Rod
   http://www.sunsetsystems.com/

On Wednesday 30 January 2002 14:49, Peter Jay Salzman wrote:
> i have a function, GetCPUType(), that returns a local (but static)
> string.  this works from main():
>
>    char buf[BUFFERSZ];
>    strcpy(buf, GetCPUType(proc_cpu));
>    printf("CPU Type: %s", buf);
>
> this doesn't (it prints garbage):
>
>    printf("CPU Type: %s", GetCPUType(proc_cpu));
>
> the function looks like:
>
>    char *GetCPUType(const char *file)
>    {
>       static char *ptr;
>       /* do stuff with ptr */
>       return ptr;
>    }
>
> what's the difference between putting ptr into a buffer and printing the
> buffer vs. printfing the pointer to a string directly?  ptr ends with
> \0.
>
> pete