How do you return a string from a function correctly in Dynamic C?

Posted by aquanar on Stack Overflow See other posts from Stack Overflow or by aquanar
Published on 2010-04-02T16:08:33Z Indexed on 2010/04/02 16:13 UTC
Read the original article Hit count: 175

Filed under:
|
|
|

I have a program I am trying to debug, but Dynamic C apparently treats strings differently than normal C does (well, character arrays, anyway). I have a function that I made to make an 8 character long (well, 10 to include the \0 ) string of 0s and 1s to show me the contents of an 8-bit char variable. (IE, I give it the number 13, it returns the string "0001101\0" )

When I use the code below, it prints out !{happy face] 6 times (well, the second one is the happy face alone for some reason), each return comes back as 0xDEAE or "!\x02.

I thought it would dereference it and return the appropriate string, but it appears to just be sending the pointer and attempting to parse it. This may seem silly, but my experience was actually in C++ and Java, so going back to C brings up a few issues that were dealt with in later programming languages that I'm not entirely sure how to deal with (like the lack of string variables).

How could I fix this code, or how would be a better way to do what I am trying to do (I thought maybe sending in a pointer to a character array and working on it from the function might work, but I thought I should ask to see if maybe I'm just trying to reinvent the wheel).

Currently I have it set up like this:

this is an excerpt from the main()

display[0] = '\0';
for(i=0;i<6;i++)
{
     sprintf(s, "%s ", *char_to_bits(buffer[i]));
     strcat(display, s);
}
DispStr(8,5, display);

and this is the offending function:

char *char_to_bits(char x)
{
     char bits[16];
     strcpy(bits,"00000000\0");
     if (x & 0x01)
         bits[7]='1';
     if (x & 0x02)
         bits[6]='1';
     if (x & 0x04)
         bits[5]='1';
     if (x & 0x08)
         bits[4]='1';
     if (x & 0x10)
         bits[3]='1';
     if (x & 0x20)
         bits[2]='1';
     if (x & 0x40)
         bits[1]='1';
     if (x & 0x80)
         bits[0]='1';
     return bits;
}

and just for the sake of completion, the other function is used to output to the stdio window at a specific location:

void DispStr(int x, int y, char *s)
{
     x += 0x20;
     y += 0x20;
     printf ("\x1B=%c%c%s", x, y, s);
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about strings