Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How "back slash(\)" behaves in strings? 2

Status
Not open for further replies.

anvartk

Programmer
Dec 19, 2000
7
IN
void main()
{
char s[]="\12345s\n";
printf("%d",sizeof(s));
}
Output:6 How?


void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}
Output:2 How?
What is the difference?

 
The only reason I could think that there would be a difference is if the memory model you're using makes s[] a far pointer, and *s a near pointer. You're asking for the size of the pointer, not the size of the string anyway, so that must be the difference. I'm not willing to bet but it's what I would guess.

I don't think that the \ has anything to do with it. Shouldn't you be using malloc anyway? When you declare *s, you only allocate a pointer, you don't actually allocate memory, same with s[], right? Otherwise, where are you putting the data?

As an answer to your original question, the difference is in pointer size, which I believe is a near/far pointer difference.

MWB. As always, I hope that helped!

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
Hi,

Example 1:

char s[]="\12345s\n";
printf("%d",sizeof(s));

The backslash results in 123 being treated as an octal value. The bytes in s[] can be broken down as:

0123 (ascii 'S')
4
5
s
\n
\0 (terminating null character added by compiler)

Total=6 bytes

Note that s[] is an array and /not/ a pointer.

Example 2:

char *s="\12345s\n";
printf("%d",sizeof(s));

Same sequence of characters, except for s is now a pointer. sizeof calculates the size of the pointer itself, which on your implementation is 2 (on mine it's 4). You would get the same result with the expression:

printf("%d\n",sizeof(char *));

It is perfectly ok to initialize a pointer like this BTW. The compiler creates storage for the string literal and sets s to point to the first element.

Pedantic Note 1:

main should return an int and be of the form:

int main() or int main(int,char **)

The results of returning void from main are undefined and therefore may result in your program crashing (or little green men invading your home and abducting your family).

Pedantic Note 2:

In your sizeof expressions the parentheses aren't necessary as sizeof is an operator, not a function, so:

printf("%d",sizeof s);

The parentheses /are/ necessary for type names:

printf("%d",sizeof(char));

MWB, if you were betting, I'd be willing to take you up on it ;-)

HTH,

Russ
bobbitts@hotmail.com
 
Thank you for all
You made me happy now!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top