How "back slash(\)" behaves in strings?
How "back slash(\)" behaves in strings?
(OP)
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?
{
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?
RE: How "back slash(\)" behaves in strings?
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.
RE: How "back slash(\)" behaves in strings?
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
http://home.earthlink.net/~bobbitts
RE: How "back slash(\)" behaves in strings?
You made me happy now!!!