?
Solved

printing integer varaible through %s format

Posted on 2005-04-07
14
Medium Priority
?
341 Views
Last Modified: 2011-10-03
What is wrong with following code

int a = 102;
printf("%s",(char *)(&a));

above is printing nothing.
0
Comment
Question by:pattha
  • 4
  • 4
  • 2
  • +3
14 Comments
 
LVL 45

Expert Comment

by:sunnycoder
ID: 13724686
Hi pattha,

ints are generally 32 bits ... so a would be 0x00 00 00 XX
You cast it to char * an d try to print it ... %s would stop interpretation on first 00 ... remaining 3 bytes would be left in the stack ...

You should not be mixing data types around unless you are absolutely sure of what you are doing..

Cheers!
sunnycoder
0
 

Author Comment

by:pattha
ID: 13724756
Hi sunnycode,

I agree with you.
But if i put a = 2pow(31) -1 which is maximum value i can put in a integer, then i think memory structure of a will be
                            0Xff ff ff ff.
But even in this case above code is printing nothing.
one more thing, can you tell me that why below code is wrong.

char *p = (char *)malloc(100);
*p = strlen("hello");
strcpy(p+1,"hello");
printf("%s",p);
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 13725627
But if i put a = 2pow(31) -1 which is maximum value i can put in a integer, then i think memory structure of a will be
                            0Xff ff ff ff.
If my memory serves me right, result of RHS is a float and not an int!!!

If your data types and format specifiers do not match, results are unpredictable

I cant see why you are mixing ints and chars and pointers around
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 22

Expert Comment

by:grg99
ID: 13726011
What are you trying to do?    Perhaps that info would help us guide you.  

In general printing a binary integer as a string is not going to work very well.

Your example with char * p = slrlen("Hello");  suggests you think strings have a leading length byte.
they do in some old Pascal systems, but in C generally strings are zero-terminated, no length byte.

0
 

Author Comment

by:pattha
ID: 13732213
Hi grg99,

I want to simulate pascal string in C.
i know that in C, string are '\0' terminated.
So i thought that in first byte of aray , i will put length of string and from next byte onwards, i will put actualu string.
so i coded like:

char *p = (char *)malloc(100);
*p = strlen("hello");
strcpy(p+1,"hello");
printf("%s",p);

but above code's output is
      hello.

I am not able to understande why p is not storing length of string in 1st byte.
0
 

Author Comment

by:pattha
ID: 13732271
Hi sunny,

as i told above that i am trying to simulate pascal string in C.
while tryinig to do this, i came to just thinking of storing integer in char string and so i tried following code.
int a = 2pow(31) -1;
printf("%s",(char *)(&a));


one more thing in above assignment RHS is not a float , it is integer only.
i am woring on

SunOS au1646s 5.8 Generic_117000-01 sun4u sparc SUNW,Sun-Fire-15000
and in this platform, int is 4 byte long and  above assignment assign
a= 2147483647

and if i print a with %d format, it is working fine.

I know that through above code, i am not achieving anything, but my question is why it is not working.
Can you provide a link of document, where i can get information about how computer access variable's memory area in printf command.
0
 
LVL 22

Expert Comment

by:grg99
ID: 13732724
>I want to simulate pascal string in C.

But WHY do you want to form a Pascal string in C?  All the C string routines expect a zero-terminated string.  You can't use strcpy, strcat, or "%s" format to handle these strings.   So why make one at all?  



>i know that in C, string are '\0' terminated.
>So i thought that in first byte of aray , i will put length of string and from next byte onwards, i will put actualu string.
>so i coded like:

char *p = (char *)malloc(100);
*p = strlen("hello");
strcpy(p+1,"hello");
printf("%s",p);

>but above code's output is
>      hello.

>I am not able to understande why p is not storing length of string in 1st byte.

It is putting the string length in the first byte, but the %s format thinks that first byte is jsut the first character of the string, so it tries to print it.  But chr(5) in ASCII is a non-printing character, so you don't see it.  printf merrily goes along and keeps printing characters until it hits a zero byte.    Which it did.
0
 
LVL 5

Accepted Solution

by:
cryptosid earned 375 total points
ID: 13732828
Hi,

The issue is because printf() expects ascii character in the first byte... when you directly store strlen("hello") .. it stores 5 in p[0]. which is correct.. however it doesn't display in printf because the ascii character pertaining to 5 is NOT a printable character.. so it printf will print a space ! ... check the ascii table at http://www.lookuptables.com/

anyways try this...

try this...
char *p = (char *)malloc(100);

p[0] = strlen("hello") + 48;
p[1] = NULL;
strcat(p,"hello");

printf("%s",p);

This should work....

p[0] = strlen("hello") + 48;
initializes the first character to lenght of string... 48 is the ascii value of the Number 0 so 49 is 1, 50 is 2 and so on...
hence in our case it will store 53 in p[0]... since strlen("hello") will yield 5 and 5+48 = 53... which is the ascii value of "5".

Now after that we do a strcat... which concatenates "5" and  "hello" .. before strcat note that you have to initialize p[1] to NULL otherwise things won't work...

after strcat however p[1] will contain 'h' ,p[2]='e'... and so on...

I hope this helps.

regards,
cryptosid
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 13733356
Hi pattha,

>int a = 2pow(31) -1;
>printf("%s",(char *)(&a));

>one more thing in above assignment RHS is not a float , it is integer only.

pow returns a double ... double - int is double and storing it in an int will give you not so reliable results .. be careful!!!

If you wish to implement Pascal strings on your own, do them cleanly ... declare a struct

struct string_struct
{
        int  length;
        char * str;
};

typedef it to your string data type and use this to perform all manipulations .... mixing around chars, ints and pointers is never a good idea ...

Hi Sid,

Long time no see ... where are you now-a-days

Cheers!
sunnycoder
0
 

Author Comment

by:pattha
ID: 13733677
Hi sunny,

i think i have sent some wrong information due to my wrong way of writing.

actually assignment in my code is

int a = 2147483647;
printf("%s",(char *)(&a));

Earlier i written 2pow(31) -1 , just to show you clearly.

so problem came to back where it was.

and thanks for idea of declaring structure for pascal string.its really good, but it will be much helpful, if you can clear my idea
about why

printf("%s",(char *)(&a));
is not printing when memory structure of a should be 0x ff ff ff ff.


0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 13734064
is ff a printable character? ... I dont think so ..

try this

char a = 0xff;

printf ("%c",a);
0
 
LVL 7

Expert Comment

by:aib_42
ID: 13742068
0xFF is not a printable character. It is a blank character in every ASCII set I've ever seen.
0
 
LVL 12

Expert Comment

by:stefan73
ID: 13744055
Hi pattha,
> printf("%s",(char *)(&a));
> is not printing when memory structure of a should be 0x ff ff ff ff.
I don't see where this journey should lead to. You shouldn't cast around pointer types. Even if by mere coincidence there are zeros after a's address (that's likely), it's completely arbitrary.


Cheers!

Stefan
0
 
LVL 5

Expert Comment

by:cryptosid
ID: 13746445
sunnycoder...

long time no see... mail me at yahoo:<E-mail id removed by sunnycoder, Page Editor>

Regards,
Sid
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question