On 12/06/2008, at 7:35 AM, Lim Hock-Chai wrote:

can somebody help me understand how char * work?

It's just a pointer to one or more characters.

char * s1;

pointer (named s1) to char (probably) initialised to NULL.

s1 = "assign a value";

s1 contains address of null-terminated string "assign a value".

s1 = "assign another value";

s1 now contains address of null terminated string "assign another value".

//does c auto deallocate storage and
reallocate a longer one for this assignment?

No because both strings are literal constants. The compiler makes space for both constants and they remain in existence for the life of the program. However, unless you stored the first address of s1 before assigning the second address you have lost addressability to the first string.

. .

char * s1

Again, a pointer (named s1) to char (probably) initialised to NULL.

int myInt = 10;

An integer (4-bytes) initialised to the value 10

sprintf(s1, "test %i", myInt);

Convert the value in myInt to character representation and concatenate to the string "test " and copy the new string to the buffer addressed by s1.

//why is s1 contains *null after this assignment?

Because s1 is NULL on the call to sprintf(). There is no buffer addressed by s1 so it remains NULL. That is, sprintf() does nothing.

You have to either define s1 to point to a sufficiently large buffer

char s1[100];

or dynamically allocate sufficient storage and set s1 to point to it.

char * s1;
s1 = malloc(100);

Note that sprintf() presumes sufficient space is available and will quite happily walk off the end of any supplied space. snprintf() is a safer choice.

If only C understood fixed-length or varying character data life would be so much easier. Why use a compiler that does so little for you?

Simon Coulter.
FlyByNight Software OS/400, i5/OS Technical Specialists

Phone: +61 2 6657 8251 Mobile: +61 0411 091 400 /"\
Fax: +61 2 6657 8251 \ /
ASCII Ribbon campaign against HTML E-Mail / \

As an Amazon Associate we earn from qualifying purchases.

This thread ...


Follow On AppleNews
Return to Archive home page | Return to MIDRANGE.COM home page

This mailing list archive is Copyright 1997-2021 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].

Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.