Question: I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?

Answer:
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't).

Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.


Question:
```
enum protocol {
    ascii_prot = 3, /* arbitrary value. */
    binary_prot,
    negotiating_prot = 4 /* Discovering the protocol */
};
```

Bothbinary_protandnegotiating_protequals to4?

Answer: Yes.


Question:
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0?

```
int r = arc4random() % (9);
    NSLog(@"Random Number: %d",r);
```

Answer: int r = (arc4random() % 8) + 1


Question: I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?

Answer:
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't).

Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.


Question:
Is there any simple way to create a GUI using OpenCV library or linking some other library with OpenCV.

Just Like the trackbar in OpenCV, is there any way to create push buttons also?

Answer:
OpenCV is a computer vision framework, not a GUI framework (even though OpenCV contains some very basic GUI functions).

For a real GUI, better use something like GTK or Qt.


Question:
I have already GtkTreeView. And I want hide some cells.

There is method

```
gtk_cell_renderer_set_visible  (GtkCellRenderer *cell, gboolean visible);
```

But How I can apply this method for some cells? Use iterator?

Answer: The only way is to 'mask' your model using aGtkTreeModelFilter. With this, you can supply an extra 'visible' column that tells whether the row should be visible or not; or you can use a function to decide which rows should be visible.


Question:
```
void  (*a)(char*, char*);
```

is this a function called a. returns void pointer?
in c?

Answer:
This is a functionpointernameda.  The function signature ofais a function that returns void and takes twochar *arguments.

SeeFunction Pointer Tutorialsfor more information on function pointers.


Question:
I have a source file that I can run via the terminal using

```
gcc source.c -I/usr/include/libxml2 -lxml2 -o output
```

but when I#includethe source file which includes the libxml source files, the compiler complains that thelibxml/xmlmemory.h:,libxml/parser.h:,libxml/xpath.hcannot be found : no such file or directory.

Answer: You need always to keep the-I/usr/include/libxml2in your gcc statement, so that it can find the header files.


Question:
Does anyone know why the following code

```
void foo(const int X)
{
    #pragma omp parallel for private(X)
    for (int i = 0; i < 100; i++)
    {  }
}
```

gives this error

error: 'X' is predetermined 'shared' for 'private'

and how I can really makeXprivate to each thread?

Answer: You are getting an error becauseXis constant. Just removeconstand everything should work.


Question:
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question

Anyone knows what is a kinspect? Is it related to somewhere memory leaks?

Someone please help me, if you'll know.

Thanks in advance

Answer: According to google it's a typo'd version ofLinspect


Question:
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question

Anyone knows what is a kinspect? Is it related to somewhere memory leaks?

Someone please help me, if you'll know.

Thanks in advance

Answer: According to google it's a typo'd version ofLinspect


Question:
Does anybody know how variable arguments are passed in classic C? I did some debugging today and most regular arguments are passed via stack. However it seems that this does not apply for variable arguments. Are those parameters stored somewhere else like constant strings?

Thanks in advance!

Answer: It depends on the platform./usr/include/stdarg.his the place to start looking for details.


Question: Is there a way to get the names of all files inside a directory using C?

Answer: While C itself does not specify a way (or even specify directories), POSIX does. You can either useopendirandreaddiryourself to read an entry at a time, or you can usescandirorglobto get the results all together in memory (and filter which entries get listed).


Question:
When i creating TThread i can't pass parameters to thread, so i need use global variables or what?
I am using Embarcaderos Rad Studio C++ Builder 2010

Answer: You have a class derived from TThread, right?  Can you just make your class constructor take additional arguments (beyond thebool suspendedone that seems to be common)?


Question: I'm using OpenAL as the sound engine for my iPhone game, but still learning how to use it. I managed to play sounds with it, however I'm in one point when I need to concatenate (not merge) 2 sound sources (same file in fact, so this needs no conversion I guess) and I'm stuck. Any help would totally be appreciated:D

Answer:
I wonder if you landed on this:OpenAL Programmers Guide

Try looking intoExtAudioFile.


Question: If fopen( path, "w" ) succeeds, then the file will be truncated.  If the fopen fails, are there an guarantees that the file is not modified?

Answer: No there are no guarantees about the state of a file iffopen(path, "w")fails.  The failure could be coming from any operation from opening the file, committing the truncation to disk, etc ...  The only guarantee a failure provides is that you don't have access to the file.


Question:
I want to delete a string from a particular position in the file. Is thre a function to do that?
Can I delete last line of a file through a function?

Answer:
You have two option

To read whole file, remove what you need and write it backIf the file is big, read file sequentially, remove given part, and move content after that forward


Question:
When i creating TThread i can't pass parameters to thread, so i need use global variables or what?
I am using Embarcaderos Rad Studio C++ Builder 2010

Answer: You have a class derived from TThread, right?  Can you just make your class constructor take additional arguments (beyond thebool suspendedone that seems to be common)?


Question: I'm using OpenAL as the sound engine for my iPhone game, but still learning how to use it. I managed to play sounds with it, however I'm in one point when I need to concatenate (not merge) 2 sound sources (same file in fact, so this needs no conversion I guess) and I'm stuck. Any help would totally be appreciated:D

Answer:
I wonder if you landed on this:OpenAL Programmers Guide

Try looking intoExtAudioFile.


Question: If fopen( path, "w" ) succeeds, then the file will be truncated.  If the fopen fails, are there an guarantees that the file is not modified?

Answer: No there are no guarantees about the state of a file iffopen(path, "w")fails.  The failure could be coming from any operation from opening the file, committing the truncation to disk, etc ...  The only guarantee a failure provides is that you don't have access to the file.


Question:
how do you color mask a 32 bit unsigned integer for the red, green, and blue values

is it like this?
    (color_to_be_masked>>8)

Answer:
This should get you the result you want:

```
short red = (color >> 16) & 0xFF;
short green = (color >> 8) & 0xFF;
short blue = (color) & 0xFF;
```


Question:
I need to know if I can access internet from my proxy, I'm doing this now:

```
if((system("wget -q www.google.it -O /dev/null")); // I don't have access.
```

Is there a better way to solve this problem? Is there a function in C?

Thank you very much.

Answer:
Everyone loves this guide.

http://beej.us/guide/bgnet/

It'll help you learn how to get to grips with networking programming in C very easily.


Question: Is there any difference between the computation of small floats - that are close to 0 - and big floats - that are far from 0?

Answer: As far as I understand how processors work, there should be absolutely no difference at all


Question:
In case a system call function fails, we normally use perror to output the error message. I want to use fprintf to output the perror string. How can I do something like this:

```
fprintf(stderr, perror output string here);
```

Answer:
```
#include <errno.h>

fprintf(stderr, "%s\n", strerror(errno));
```

Note: strerror doesn't apply\nto the end of the message


Question:
Is it possible to put arguments in a systems call?

something like

```
system("rm %s %s", string1, string2)
```

Answer:
The prototype for thesystemfunction is:

```
int system(const char *command);
```

so, no. But, how about:

```
snprintf(buffer, sizeof(buffer), "rm %s %s", target1, target2);
system(buffer);
```


Question:
I am trying to use a open source library under  C++.

The README file states that

You need to link your program with `svm.cpp'.

I am wondering how to link my program with svm.cpp? Do I need to modify the make file to make this happen?

Answer: Compilesvm.cppwith not linking, will resultsvn.oobject file, use it object file with your program linking.


Question: Quite a basic question but can someone tell me the difference between downloading src files against downloading binary files?

Answer: Source files are uncompiled C/C++ code, while binary files are the compiled programs.


Question:
I would like to check if a number is larger than 0.

The 0 is in string format

How do I either

Compare the value to a string representation of 0Cast the string to an int

Answer: strtol()


Question: How do i change the c coding style format in emacs ? Specifically i need to change the indentation in the c code shown by emacs from i  per block to 2 per block

Answer: Type M-x followed by "customize-mode" followed by "c-mode". Then use the built-in customization page to override the default "C Basic Offset" with your new value of "2". When you're done, be sure to select "Save for future sessions" at the top of the page.


Question:
I have a very small program which converts a string to double. The problem is everytime it is printing 0.0000.
Please help me.

Thanks in advance.

```
enter code here

$ export LT_LEAK_START=1.5
$ echo $LT_LEAK_START
  1.5

#include <stdio.h>

int main()
{
  double d;
  d=strtod(getenv("LT_LEAK_START"), NULL);
  printf("d = %lf\n",d);
}
Output:
d=0.0000000
```

Answer:
Try including

```
#include <stdlib.h>
```


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:How many 1s in an n-bit integer?

Hello

How to calculate how many ones in bits?

```
1100110 -> 4
101 -> 2
```

And second question:

How to invert bits?

```
1100110 -> 0011001
101 -> 010
```

Thanks

Answer: If you can get your bits into astd::bitset, you can use theflipmethod to invert, and thecountmethod to count the bits.


Question:
Is there any way to make pointers read a file as a block of memory in C?
Can access of a file can be faster...?

Answer:
Treating a file as memory (and letting the OS do the file IO for you) is termed 'memory mapping'.

On POSIX (e.g.Linux), themmap()function does this.

OnWindows, theOpenFileMapping()function and friends do this.  Microsoft have excellent description of how this works, why to use it, and particulars on their platformhere.


Question:
```
int system(const char *)
```

How can I send output of this command (lets say the command is "pwd") to a char*? Its returning an int but I want the results of the command to be sent to a char*.

Answer:
You can pipe the output of the command directly to a file by using "pwd > tempfile" as command.Another way is to usepopen

```
FILE *output = popen("pwd", "r");
```

That will give you a file pointer where you can read the output from.


Question:
Why would sizeof in the following cases print different values:

```
printf("%d",sizeof("ab")); //print 3

char* t="ab";
printf("%d",sizeof(t)); //print 4
```

In the first case I have 2 characters... Shouldn'tsizeofprint 2? Because they are 2 bytes?

Answer:
Strings in C are null terminated.

"ab" in memory looks like'a' 'b' '\0'

Whiletis a pointer, so size is 4.


Question:
I can read values of elapsed seconds since some reference time which appears in the format1301330553(Decimal)/4D90BA79(hex). I would like to convert these seconds in somedate/timeformat inC.
The elapsed seconds mentioned above are ofu32 data type.

Answer: there's a function called ctime which takes a unix long as a parameter that renders the time in ascii.


Question: I have a C function which accepts a character. I need to extract as well insert bits into that character. I am clear with the extraction part. Can anyone give me an idea of how to insert values to bits?

Answer:
Pretty vague question, I would suggest you brush up on bitwise operators. This should point you in the right direction.

http://www.cprogramming.com/tutorial/bitwise_operators.html


Question:
For the following code snippet I get the output as1. I want to know how it came?

```
void main()
{
int x=10,y=20,z=5,i;
i=x<y<z;
printf("%d",i);
}
```

Answer: i=x<y<z;, gets interpreted asi=(x<y)<z, which in turn gets interpreted asi=1<z, which evaluates to 1.


Question:
I have a very small program which converts a string to double. The problem is everytime it is printing 0.0000.
Please help me.

Thanks in advance.

```
enter code here

$ export LT_LEAK_START=1.5
$ echo $LT_LEAK_START
  1.5

#include <stdio.h>

int main()
{
  double d;
  d=strtod(getenv("LT_LEAK_START"), NULL);
  printf("d = %lf\n",d);
}
Output:
d=0.0000000
```

Answer:
Try including

```
#include <stdlib.h>
```


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:How many 1s in an n-bit integer?

Hello

How to calculate how many ones in bits?

```
1100110 -> 4
101 -> 2
```

And second question:

How to invert bits?

```
1100110 -> 0011001
101 -> 010
```

Thanks

Answer: If you can get your bits into astd::bitset, you can use theflipmethod to invert, and thecountmethod to count the bits.


Question:
Is there any way to make pointers read a file as a block of memory in C?
Can access of a file can be faster...?

Answer:
Treating a file as memory (and letting the OS do the file IO for you) is termed 'memory mapping'.

On POSIX (e.g.Linux), themmap()function does this.

OnWindows, theOpenFileMapping()function and friends do this.  Microsoft have excellent description of how this works, why to use it, and particulars on their platformhere.


Question:
```
int system(const char *)
```

How can I send output of this command (lets say the command is "pwd") to a char*? Its returning an int but I want the results of the command to be sent to a char*.

Answer:
You can pipe the output of the command directly to a file by using "pwd > tempfile" as command.Another way is to usepopen

```
FILE *output = popen("pwd", "r");
```

That will give you a file pointer where you can read the output from.


Question:
For example:

```
struct myCar{
   int price;
   int *uniqueID;
};
```

In C, an int has 4 bytes. I'm assuming a pointer also occupies 4 bytes as well? Therefore, 8 bytes total?

Answer:
Find out:

```
printf("Size of my struct is: %zu\n", sizeof(struct myCar));
```

The size of a pointer is platform dependent. For that matter, the size of anintis platform dependent. Could be 8 bytes for either if you're on a 64bit machine.


Question:
Can a single char be made read-only in C ? (I would like to make '\0' read-only to avoid buffer overflows.)

```
char var[5 + 1] = "Hello";

var[5] = '\0'; // specify this char as read-only ?
```

Answer: You can't make a mixedconst/non-constarray or string. The\0not being overwritten should be guaranteed by the invariants in your program.


Question: How would I make a version of sleep in C spin so it uses cpu cycles?

Answer:
I suppose something like (pseudocode)

```
while (time < endtime)
    ;
```

The implementation of "time < endtime" is OS-dependent, but you just want to compute the end time based on an argument before your loop starts, and then continuously fetch the system time and compare it to that end time.


Question:
```
struct timeval start, end;
.
.
.
elapsedTime = (((end.tv_sec * 1000000) - (start.tv_sec * 1000000)) + (end.tv_usec - start.tv_usec));
```

I just want to double check this returns time in micro sec..

Answer:
The code is correct, but watch out for overflow. It's slightly safer to do

```
(end.tv_sec - start.tv_sec) * 1000000
```

then add in theusecdifference.


Question: Is there an option, part of read() that when calling read() on a file descriptor it only prints out the characters up to the null terminator?

Answer:
Sorry, no, there isn't.read()doesn't look at the data at all; it just reads as many bytes as there are (but not more than your buffer size).

I would do this with the higher-levelstdio.hfunctions, by callinggetc()(and writing to a buffer) until I saw a NUL byte, and thenungetc()on the NUL.


Question: I'd like to know how many instructions are needed for a function call in a C program compiled with gcc for x86 platforms from start to finish.

Answer:
Write some code.Compile it.Look at the disassembly.Count the instructions.

The answer will vary as you vary the number and type of parameters, calling conventions etc.


Question:
What are the recommended XML parsers for parsing a TMX file(XML based tilemap) in C?

What are the pros and cons of each, as I would like to have an efficient one because it will be running on an embedded system.

Answer: We used libxml on an embedded product a while back. It may be right for you.


Question: I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that?

Answer: %Lgis probably what you want: seehttp://developer.apple.com/library/ios/#DOCUMENTATION/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html.


Question: Createprocess API has a option to create a process with CREATE_SUSPENDED flag. Similarly, is there any possiblity in ShellExecute APIs to create the process in suspended state.

Answer: No. ShellExecute doesn't have to imply a process is launched - it's used to perform "shell operations" such as "open" or "print", whichmaylead to a new process being created.


Question:
Part of the code is as follows but not work

```
printf("Enter a line of text (Enter to stop): ");
  fflush(stdin);
  fgets(input, 256, stdin);

  if (input == '\0') {
    exit(0);
  }

  .....
  .....
```

i want if the user only press enter, the program will be terminated. how to do it?
thanks

Answer: Useif(*input == '\n')- iffgetsreads a newline, it's stored in the buffer.


Question:
is there any example of using work/pool (or. Producer/Consumer) scheme for MPI? As for everything I have done, I am getting just one going through application and my app is deadlocked then.

Thanks

Answer:
Just googling around for "MPI Master Worker" or "MPI Master Slave", I see a bunch of examples; one good one hosted at Argonne National Labs is:

http://www.mcs.anl.gov/research/projects/mpi/tutorial/mpiexmpl/src2/io/C/main.html


Question:
Would it be possible to take a users input as a variable to be used in an expresion?

```
scanf("%s", op); //User enters "==" or "!="

if(x op y)
   //Go.
```

Answer:
No. The best you can do is something like:

```
scanf("%s", &op);
if (strcmp(op, "==") == 0) {
    result = x == y;
}
else if (strcmp(op, "!=") == 0) {
    result = x != y;
}

// now use result
```


Question:
Lately I had a task that included printing base-4 representation of a number. Since I didn't find a function to do it for me, I implemented it (which is not so hard of course), but I wonder, is there a way to do it using format placeholders?

I'm not asking how to implement such function, but if such function / format placeholder already exists?

Answer: There is no standard C or C++ function, but you may be able to useitoa


Question: I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that?

Answer: %Lgis probably what you want: seehttp://developer.apple.com/library/ios/#DOCUMENTATION/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html.


Question:
I have two floating point numbers. If I add that 2 numbers means. It will displaying the answer as 4.50000 (I used just %f). If I used (2.%f) means the answer is just 4.
  I want the answer as 4.5. What do I have to modify in this?

Answer:
Try the format string%2.1f:

```
$ printf "%2.1f\n" 4.5
4.5
```

The.1says "one character after the radix".


Question: For example,inttakes 4 bytes on a 32-bit OS, but 8 bytes on a 64-bit OS, does this kind of thing exist in C?

Answer:
Yes. This is precisely what is meant by "platform-specific definitions" for things like the size ofintand the meaning of system calls.

They depend not just on the OS, but also on the target hardware and compiler configuration.


Question:
I want to simplify the following code in C. Is there any hash table in C to make it simple? For example "dict" in Python.

```
int a, b, c, d ......

a = get_value_from_sth( A_NAME )

b = get_value_from_sth( B_NAME )

c = get_value_from_sth( C_NAME )

d = get_value_from_sth( D_NAME )

......
```

Answer: No, C does not have a built-in hash table type like Python's dicts. You may be able to get by with an array, depending on your needs.


Question: The question is self-explanatory. I'm using the C API.

Answer:
No, but it's easy to implement. It's just:

```
UChar *u_strdup(UChar *in) {
    uint32_t len = u_strlen(in) + 1;
    UChar *result = malloc(sizeof(UChar) * len);
    u_memcpy(result, in, len);
    return result;
}
```


Question:
I have two floating point numbers. If I add that 2 numbers means. It will displaying the answer as 4.50000 (I used just %f). If I used (2.%f) means the answer is just 4.
  I want the answer as 4.5. What do I have to modify in this?

Answer:
Try the format string%2.1f:

```
$ printf "%2.1f\n" 4.5
4.5
```

The.1says "one character after the radix".


Question: For example,inttakes 4 bytes on a 32-bit OS, but 8 bytes on a 64-bit OS, does this kind of thing exist in C?

Answer:
Yes. This is precisely what is meant by "platform-specific definitions" for things like the size ofintand the meaning of system calls.

They depend not just on the OS, but also on the target hardware and compiler configuration.


Question:
I want to simplify the following code in C. Is there any hash table in C to make it simple? For example "dict" in Python.

```
int a, b, c, d ......

a = get_value_from_sth( A_NAME )

b = get_value_from_sth( B_NAME )

c = get_value_from_sth( C_NAME )

d = get_value_from_sth( D_NAME )

......
```

Answer: No, C does not have a built-in hash table type like Python's dicts. You may be able to get by with an array, depending on your needs.


Question:
I want to share my local saved image and formatted text on Twitter or Facebook using my application.

For example, I want to combine both image and bolded text in a single post.

Are there any APIs available for it?

Answer:
I recommend usingShareKitin your iOS application.

It is very easy to integrate a variety of Social Networking sites.


Question:
While trying to open the file in Class in function oninitdialog(),It throws exception.If I open the file globally , it works.
How to overcome this?
why the fopen command is behaving like these?

Regards,

karthik

Answer: Actually I made a mistake by creating file descriptor in OninitDialog function in mfc.To overcome this , I create the file descriptor in constructor of the class.


Question:
I'm wondering if it is possible to implement the following logical under Linux and using POSIX thread library.

```
given a mutex
   if (I can get the mutex) {
     lock the mutex
       call fun A
     unlcok the mutex
   }
   else {
      call fun B
   }
```

I'm new to thread programming under Linux, so just use the pseudo-code to show the logic of the code snippet I'm looking for.

Answer: You're looking forpthread_mutex_trylock


Question: I'm trying to write a program that uses tgkill to send a signal to a specific thread, but whenever I compile it with gcc I get an error about an undefined reference to 'tgkill'. I tried compiling with -lpthread but it didn't help. I've googled and googled and can't come up with any answers.  How do I get it to compile??

Answer:
From thetgkill()manpage:

Glibc does not provide wrappers for
  these system calls; call them using
  syscall(2).


Question:
It seems to have no impact on the functionality of sbrk, but in sbrk()'s documentation it says that it requires an intptr_t parameter.

It works (or at least seems to work) when passing an int type as a parameter.

This is in regular C.

Answer: intptr_tchanges size depending on the architecture.intmay or may not change size depending on the architecture- that is, if you are on 64bit, thenintptr_tMUST be 64bits, whereasintmaybe 32bits.


Question:
Is there anycorjavaexample implementingBayesian Net?

I want to solve some things but Do not where to start?.

Answer: Use Weka.  It not only implements Bayes Nets, but also a lot of other ML algorithms.


Question:
Could someone help me with what the equivalent of this C code is in C#?

```
struct { int left, right; } stack[MAX];
```

Thanks!

Answer:
```
public struct PickAName
{
     public int left;
     public int right;
}

private const int MAX = 666;
PickAName[] stack = new PickAName[MAX];
```

or:

```
Stack<PickAName> stack = new Stack<PickAName>();
```


Question:
Why is empty struct in C a constraint violation? Why does this rule get changed in C++?

Are there any historical reasons?

Answer:
since you don't have inheritance in C you don't need them. If you just want to have a distinguishable pointer type you can use pointers to incomplete types.

```
struct opaque;

struct opaque* stranger = 0;
```

should work fine.


Question:
```
fd1 = open("/dev/test_kft" "1",00);
```

What does"/dev/test_kft" "1"mean?

Answer: It's implicit concatenation as performed by the compiler. It results in"/dev/test_kft1".


Question: I am currently working on a linux daemon that needs to be single instance (i.e restricted to 1 user 1 process). What would be the best way of doing so without having to usegetpid()to manually write the pid out to/var/run/and then lock it usingflock()?

Answer: Wrap the start-up and shut-down withstart-stop-daemon.


Question:
Is it safe to do something like the following?

```
#include <stdio.h>
#include <malloc.h>
#include <string.h>

int main(void)
{
    char* msg;

    strcpy(msg, "Hello World!!!");  //<---------

    printf("%s\n", msg);

    return 0;
}
```

Or should the following be used?

```
char* msg = (char*)malloc(sizeof(char) * 15);
```

Answer:
strdup does the malloc and strcpy for you

```
char *msg = strdup("hello world");
```


Question: I installed the build-essential package for ubuntu x86_64, compiling c programs and c++ programs work fine, but in the compiled binary, "Ubuntu linaro" appears. is there a way to remove this?

Answer: You can remove it using a hex editor. And may i ask why do you want to remove it??


Question: Say I have a wrapper function for each file system related system calls e.g, open(), close(), creat() etc and inside each wrapper function I need to find out the process id of the process making the syscall. Would be gratefull for some pointers. Thanks....

Answer: You're probably looking for thegetpid(2)system call; but Jeremiah asks good questions. :)


Question:
```
main()
{
char s[] = "abcdef", *p;
for (p = &s[5]; p >= s; p--) --p*;
puts(s);
return 0;
}
```

The compiler says there is a problem with --p* (expected an expression)?????

Answer:
--p*doesn't make any sense .

Probably you meant--*por--p?
Your code prints`abcdewhen the underlying representation is ASCII. BTW C99 mandates the return type ofmain()to beintin a hosted environment.


Question:
I am porting a Linux code that uses<unistd.h>, specifically gethostid function, to Windows 7.

I need an unique number of 32 bits that I will use in my application. How can I obtain an unique number using API from Windows 7 in the same manner that I do on Linux?

Thanks.

Answer: You would normally implement this by returning the local IP address, for example by callinggetaddrinfo().


Question: So I was wondering if there is like a centralized library management for C? likerubygemsfor C? I realized it might be a silly idea, but there are times when I wish I could have the benefits of rubygems, but for C.

Answer: Mostpackage management systemshave entries for C libraries.


Question:
```
main()
{
char s[] = "abcdef", *p;
for (p = &s[5]; p >= s; p--) --p*;
puts(s);
return 0;
}
```

The compiler says there is a problem with --p* (expected an expression)?????

Answer:
--p*doesn't make any sense .

Probably you meant--*por--p?
Your code prints`abcdewhen the underlying representation is ASCII. BTW C99 mandates the return type ofmain()to beintin a hosted environment.


Question:
I am porting a Linux code that uses<unistd.h>, specifically gethostid function, to Windows 7.

I need an unique number of 32 bits that I will use in my application. How can I obtain an unique number using API from Windows 7 in the same manner that I do on Linux?

Thanks.

Answer: You would normally implement this by returning the local IP address, for example by callinggetaddrinfo().


Question:
I am porting a Linux code that uses<unistd.h>, specifically gethostid function, to Windows 7.

I need an unique number of 32 bits that I will use in my application. How can I obtain an unique number using API from Windows 7 in the same manner that I do on Linux?

Thanks.

Answer: You would normally implement this by returning the local IP address, for example by callinggetaddrinfo().


Question: So I was wondering if there is like a centralized library management for C? likerubygemsfor C? I realized it might be a silly idea, but there are times when I wish I could have the benefits of rubygems, but for C.

Answer: Mostpackage management systemshave entries for C libraries.


Question:
It is said that stl vector is "layout-compatible with C".
Where can I find the definition of "layout-compatible with C"?

Answer: This means that, as long as the vector is not empty,&vector.front()will give you a pointer to a contiguous array of objects, which could be passed to a C API that expects such an array.


Question:
I know my file pointer is at end of the line after printing this string: "xyz".

How can I get it to the start of the line? (pointing to x)

```
offset = ftell(fp);
fseek(fp, offset - sizeof("xyz") , SEEK_SET);
```

Above doesn't seem to work.

How can I achieve that?

Answer:
I would store the offset by issuing abeginning = ftell(fp)before reading/writing you "xyz".
Thenfseek(fp, beginning, SEEK_SET);

Would this be possible?


Question:
I have a 3rd party library that reads RTMP packets from a network socket, using recv() and taking the socket descriptor as an argument. I want it to read these packets from the application buffer instead (allocated in heap).

Is it possible?

Answer: You may be able to usesocketpair, which creates a pair of connected (unix domain) sockets. If you are on Linux, You can stuff the socket usingvmsplice, otherwisesend()as usual.


Question: I've just started learning C and haven't been doing any memory management up to now. Can anyone recommend a good guide/tutorial for memory management in C?

Answer: I think the biggest thing to wrap your head around is storage and lifetime of variables in memory (stack vs heap). You can check outWikiBook's treatment of this topic. I find it to be a gentler introduction to a lot of topics.


Question:
For example, can the output of 'uname -a' be used to create the COMPILED_ON macro below?

```
#include <stdio.h>

#define COMPILED_ON `call uname -a and use the output as a quoted string'

int main( int argc, char **argv ) {
    printf( COMPILED_ON );
    return 0;
}
```

Answer:
no, but:

```
gcc -DCOMPILED_ON="$(uname -a)"
```


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:How does system() exactly work in linux?

For the sake of my curiosity,
I want to know that how does system() function spawn the process and its internal implemenation ?
Is is using fork , exec internally ?

Answer: On my Debian box it uses clone() that itself calls sys_clone(). You can use strace to look at system calls.


Question: Is there a way to find out in which function/file/line set the current errno?

Answer:
Not that I know of,it's just a global static int (no magic in it)(see comment below).

You're supposed to check after each function that could set it when it returns an error.


Question: How can I insert or remove a word in the middle of a text file using C on Linux?

Answer:
Copy the whole file to a temporary location by adding/omitting the word to remove, replace the original source by the temporary file.

There's also the possiblity to use fseek()http://www.manpagez.com/man/3/fseek/


Question:
Is this ok?

```
char buf[] = { 0, 1, 2 };
memcpy(buf, buf + 1, 2);
```

Does having a bigger datatype make any difference? I know I could use memmove(), but I'm just curious.

Answer: The effects ofmemcpyare not defined when the input and output overlap. You should usememmove.


Question: Is it possible to put the equivalent of#define VAR(in a C program) into a makefile, so that one can control which part of the program should be compiled?

Answer:
Accordingly toccmanpage onlinux

```
-D name=definition
           The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive.  In
           particular, the definition will be truncated by embedded newline characters.
```


Question:
I want to display the binary tree as a Max Heap order.

Requirement
1) Input - Binary Tree
2) Output - Max Heap / Min Heap

Thanks a lot.

REgards,
Girija

Answer:
If you are allowed to use other's work:

Use std::make_heap to make a heap from a vector


Question:
I want to display the binary tree as a Max Heap order.

Requirement
1) Input - Binary Tree
2) Output - Max Heap / Min Heap

Thanks a lot.

REgards,
Girija

Answer:
If you are allowed to use other's work:

Use std::make_heap to make a heap from a vector


Question:
I have a DVB receiver (set-top box) similar likeDreamboxand it has MIPS cpu

It hasembedded Linuxand I can connect to it withtelnet

Question is how to compile simple "Hello World" application inC? Where to gettoolchain,SDK?

Answer: You should useCodescape SDK.


Question: Can i store the unspecified type in GtkListStore? For instance, I want to store in one field - the field of int type and the field of GdkColor type ?

Answer: I think you meanunions in C C++


Question:
Is there a way I could get the inode number of a file which has not yet been opened. I would like to do this from inside a c function

Regards,
Lipika

Answer: Usestat(2)(which takes a file path), and check the st_ino field. Do note that it's possible for someone to move or remove the file between the time you callstatand whenever you manage to do anything with the information.


Question:
I read INI file strings through GetPrivateProfileString API. However, the INIs in local windows directory could be read like that.
How can I read and edit a INI file in a Remote machine.

Answer: You should not expect to be able to modify INI files stored on remote machines. Whatever your problem is, this is not the solution.


Question:
How do I read command-line parameters in C? For example, in

```
./test --help
```

or

```
./test --build
```

how do I access "--build" or "--help"?

Answer:
Your parameters are in argv:

```
int main(int argc, char **argv)
```

if you printf the content of argv (argv[0],argv[1] etc) youll get the idea.

try:

```
int main (int argc, char **argv)
{
    for(int i = 0;i< argc;i++)
        printf("%s\r\n",argv[i]);
}
```


Question:
```
char *xyz()
{
   char str[32];
   strcpy(str,"Hello there!");
   return(str);
}

void main()
{
  printf("%s",xyz());
}
```

When I call xyz(), is it will return  a dangling pointer ?
Thanks

Answer:
Yes, it is a dangling pointer. Your program invokes undefined behaviour.

On some systems it might crash your application, on others it might appear to work correctly. But either way, you should not do it.


Question:
is there a C macro or some kind of way that i can check if my c program was compiled as 64bit or 32bit at compile time in C?

Compiler: GCC
Operating systems that i need to do the checks on: Unix/Linux

Also how could i check when running my program if the OS is capable of 64bit?

Answer:
Since you tagged this "gcc", try

```
#if __x86_64__
/* 64-bit */
#endif
```


Question:
I read INI file strings through GetPrivateProfileString API. However, the INIs in local windows directory could be read like that.
How can I read and edit a INI file in a Remote machine.

Answer: You should not expect to be able to modify INI files stored on remote machines. Whatever your problem is, this is not the solution.


Question:
How do I read command-line parameters in C? For example, in

```
./test --help
```

or

```
./test --build
```

how do I access "--build" or "--help"?

Answer:
Your parameters are in argv:

```
int main(int argc, char **argv)
```

if you printf the content of argv (argv[0],argv[1] etc) youll get the idea.

try:

```
int main (int argc, char **argv)
{
    for(int i = 0;i< argc;i++)
        printf("%s\r\n",argv[i]);
}
```


Question:
```
char *xyz()
{
   char str[32];
   strcpy(str,"Hello there!");
   return(str);
}

void main()
{
  printf("%s",xyz());
}
```

When I call xyz(), is it will return  a dangling pointer ?
Thanks

Answer:
Yes, it is a dangling pointer. Your program invokes undefined behaviour.

On some systems it might crash your application, on others it might appear to work correctly. But either way, you should not do it.


Question:
is there a C macro or some kind of way that i can check if my c program was compiled as 64bit or 32bit at compile time in C?

Compiler: GCC
Operating systems that i need to do the checks on: Unix/Linux

Also how could i check when running my program if the OS is capable of 64bit?

Answer:
Since you tagged this "gcc", try

```
#if __x86_64__
/* 64-bit */
#endif
```


Question:
How would you compare strings when the characters(and)should come after the alphanumeric characters. Do I have to write a function or is there any library function available?

Thank you for your answers!

Answer: You can usestd::lexicographical_comparewith a custom predicate. That predicate should take 2 chars, and return false if the first should come before the second.


Question: Should I write OpenGL program by using C or C++? Really confused.

Answer: You can use either. The OpenGL API is in C and C++ is backward compatible with C. Just choose your favourite language.


Question:
I'm patching an OTP module (yubico_pam) and I'm trying to access thecontrol-flagselected by the administrator (e.g.required, sufficient, etc).

Any idea? Is this feasible at all (without parsing the file)?

Answer: There's no way to query this information within the API. We have to avoid the need of knowing this value or specifically instruct the user on what control-flag he should use.


Question:
Each side is 60 degrees. and the top and bottom sides are horizontal

I thinkwidth = (cos(60) * sideLength * 2) + sideLength = sideLength * 2

This seems a bit off

Answer:
width should be2*sideLength(sideLength = cos(60) * sideLength * 2)

height will besin(60) * sideLength * 2 = sqrt(3)*sideLength


Question:
I'm trying to figure out if this could somehow be overflowed:

```
void print_address(char *p)
{
  arp_ hw;
  int i;

  hw.length = (size) *(p + _OFFSET1); //189 + 4 = 193
  memcpy(hw.addr, packet + _OFFSET2, hw.length);

  return;
}
```

where packet is an input read from a .txt file?

Answer: Yes, it can be overflowed; if the value at offset 4 in the packet is greater than 128, you will overflow theaddrfield inhwaddr.


Question:
I'm patching an OTP module (yubico_pam) and I'm trying to access thecontrol-flagselected by the administrator (e.g.required, sufficient, etc).

Any idea? Is this feasible at all (without parsing the file)?

Answer: There's no way to query this information within the API. We have to avoid the need of knowing this value or specifically instruct the user on what control-flag he should use.


Question:
Each side is 60 degrees. and the top and bottom sides are horizontal

I thinkwidth = (cos(60) * sideLength * 2) + sideLength = sideLength * 2

This seems a bit off

Answer:
width should be2*sideLength(sideLength = cos(60) * sideLength * 2)

height will besin(60) * sideLength * 2 = sqrt(3)*sideLength


Question: I.E., you enter the number 5, and the character A and the output would yield F. I have no idea how to even start to go about this, any give me a push in the right direction?

Answer:
Individual characters are represented by numbers according to theASCII code(usually). In C, if you add a number to a character, you're shifting the character down. Try:

```
char c = 'A';
int n = 5;
printf("%c\n", c + n);
```


Question:
I'm making a program which controls other processes (as far as stopped and started states).
One of the criteria is that the load on the computer is under a certain value.

So i need a function or small program which will cause the load to be very high for testing purposes. Can you think of anything?

Thanks.

Answer:
I can think of this one :

```
for(;;);
```


Question:
I have a program which forks off other processes. The arguments to my program include the process name of the process to be forked, along with any arguments.

This means, when I make the call to exec(), I need to be able to handle however many arguments were supplied.

Any ideas?

Thanks.

Answer:
Theexecvfunction takes a pointer to an array of arguments.

Just like inmain, the last element in the array needs to be a null pointer.


Question:
```
static struct K {  int x; };
```

Is this valid in C and C++?

Answer:
In C, it's valid butuseless.

In C++ it's invalid. You can only specify storage class for objects and functions.


Question:
I am searching for a solution to delete all files from my pendrive using a C program. I don't want the code to detect the pendrive as that's not a concern right now. I would appreciate any links that could help me out on this.

Note: I am working on Windows 7 64-bit and I want to delete the entire contents from my pendrive, which contains .exes and .dlls.

Thanks and Regards,
Radix

Answer: The non-hackcorrectway to do this, is via theVirtual Disk Service.


Question:
```
const int size = 10; // realna ilość danych
int tablica[size+1];
```

i have:variable-size type declared outside of any function

Answer:
Use

```
#define size 10
```

instead of aconst int. The latter is not a compile-time constant in C, but a variable that cannot be assigned to (unless via a pointer and a cast to get rid ofconst).

(This is a difference between C and C++.)


Question: I just readhttp://olstrans.sourceforge.net/release/OLS2000-ext3/OLS2000-ext3.htmlwhich is an excellent review of the design issues used when journaling was implemented in ext3. Could someone point me towards the section of the linux kernel code where ext3 journaling is implemented?

Answer:
You can uselxrto search the linux code.

ext3 and journaling interface code ishereand JDB code ishere


Question: Is the strtok function in standard C89?

Answer:
the man page says:

```
CONFORMING TO
       strtok()
              SVr4, POSIX.1-2001, 4.3BSD, C89, C99.

       strtok_r()
              POSIX.1-2001.
```

So I would say yes.

According to the C89 draft I have (the actual standard costs money), the appropriate section is:

4.11 STRING HANDLING <string.h>4.11.5.8 The strtok function


Question:
Is there any way to execute Linux commands with c without usingexeclp(), like predefined functions or something else.

Thanks.

Answer: Usesystem()orpopen()if you need the commands output.


Question:
There is a code snippet,

```
int matchhere(char *regexp, char  *text)
 {
    /* do sth */
    return    *test== '\0';
 }
```

I do not understand what does

```
return    *test== '\0';
```

mean. Or what it will return?  How does "==" function here?

Answer: compare*testto'\0', return 0 if inequal, return 1 if equal.


Question:
Is there easy way to create FILE* from WinApi HANDLE which points to one end of pipe?
Something like we do in unix:fdopen(fd,<mode>);

Answer: You can do this but you have to do it in two steps. First, call_open_osfhandle()to get a C run-time file descriptor from a Win32 HANDLE value, then call_fdopen()to get aFILE*object from the file descriptor.


Question:
I am doing it wrong, yes?

```
...
if( you_think_youre_genius )
    goto goto_sucks:
...
pthread_mutex_lock(&mutex);

    do_stuff();

    goto_sucks:
        do_other_stuff();

pthread_mutex_unlock(&mutex);
```

Answer: Yes, goto is direct jmp down at the binary code level soanyfunction calls between the goto and the label will be skipped, period.


Question:
I have:

printf("%.2s\n", &s[2]);

How can I represent that as a chosen value?

So I would want something like:

printf(%.%is\n", someInt, &s[2]); #
  but this doesnt work, where %i is someInt

Answer: You wantprintf("%.*s\n", someInt, &s[2]);. Consult theprintf man pagefor more details.


Question: In C, how to remove all characters present in one array from another array?

Answer:
Sounds like homework but here's a solution.

Make an array of 256 entries, likechar set[256].
Read the first string. For each charactercsetset[(unsigned char)c]to 1.
Read and copy the second string. For each charactercifset[c]then skipc.

I forgot and left out that you must firstmemset(set, 0, sizeof(set))before setting any of its values to 1.


Question:
So:

```
char *someCArray; # something
```

I want to print out "ethin" from "something".

Answer:
You can use theprintfprecision specifier

```
#include <stdio.h>

int main(void) {
  char s[] = "something";
  int start = 3;
  int len = 5;

  printf("%.*s\n", len, s + start);

  return 0;
}
```

Code also posted to codepad:http://codepad.org/q5rS81ox


Question: Why do local variables use Stack in C/C++?

Answer:
Technically, C does not use a stack.  If you look at theC99 standard, you'll find no reference to the stack.  It's probably the same for the C++ standard, although I haven't checked it.

Stacks are just implementation details used by most compilers to implement the C automatic storage semantics.


Question:
Is there any way to execute Linux commands with c without usingexeclp(), like predefined functions or something else.

Thanks.

Answer: Usesystem()orpopen()if you need the commands output.


Question:
There is a code snippet,

```
int matchhere(char *regexp, char  *text)
 {
    /* do sth */
    return    *test== '\0';
 }
```

I do not understand what does

```
return    *test== '\0';
```

mean. Or what it will return?  How does "==" function here?

Answer: compare*testto'\0', return 0 if inequal, return 1 if equal.


Question:
Is there easy way to create FILE* from WinApi HANDLE which points to one end of pipe?
Something like we do in unix:fdopen(fd,<mode>);

Answer: You can do this but you have to do it in two steps. First, call_open_osfhandle()to get a C run-time file descriptor from a Win32 HANDLE value, then call_fdopen()to get aFILE*object from the file descriptor.


Question:
I am doing it wrong, yes?

```
...
if( you_think_youre_genius )
    goto goto_sucks:
...
pthread_mutex_lock(&mutex);

    do_stuff();

    goto_sucks:
        do_other_stuff();

pthread_mutex_unlock(&mutex);
```

Answer: Yes, goto is direct jmp down at the binary code level soanyfunction calls between the goto and the label will be skipped, period.


Question:
I have:

printf("%.2s\n", &s[2]);

How can I represent that as a chosen value?

So I would want something like:

printf(%.%is\n", someInt, &s[2]); #
  but this doesnt work, where %i is someInt

Answer: You wantprintf("%.*s\n", someInt, &s[2]);. Consult theprintf man pagefor more details.


Question: In C, how to remove all characters present in one array from another array?

Answer:
Sounds like homework but here's a solution.

Make an array of 256 entries, likechar set[256].
Read the first string. For each charactercsetset[(unsigned char)c]to 1.
Read and copy the second string. For each charactercifset[c]then skipc.

I forgot and left out that you must firstmemset(set, 0, sizeof(set))before setting any of its values to 1.


Question:
So:

```
char *someCArray; # something
```

I want to print out "ethin" from "something".

Answer:
You can use theprintfprecision specifier

```
#include <stdio.h>

int main(void) {
  char s[] = "something";
  int start = 3;
  int len = 5;

  printf("%.*s\n", len, s + start);

  return 0;
}
```

Code also posted to codepad:http://codepad.org/q5rS81ox


Question:
I have the following line of code:

```
contents[pos++] ^= key[shift++];
```

What does operator^=mean?

Answer:
It is theXORassignment operator. Basically:

```
x ^= y;
```

is the same as:

```
x = x ^ y;
```


Question: I'm trying to generate a random number that's between 0 and 1. I keep reading aboutarc4random(), but there isn't any information about getting a float from it. How do I do this?

Answer:
Random value in[0, 1[(including 0, excluding 1):

```
double val = ((double)arc4random() / UINT32_MAX);
```

A bit more detailshere.

Actual range is[0, 0.999999999767169356], as upper bound is (double)0xFFFFFFFF / 0x100000000.


Question:
I'm searching with brute force for a floating point number with certain properties (small roundoff error of sin(a)^2+cos(a)^2-1). I therefore want to loop over the neighborhood of a given floating point number by incrementing the significand.

Is there a simple way to do that in C?

Answer: C99 has nextafter and nexttoward; they weren't present in C90.


Question: What is the best way to generate an HTTP session ID and avoid collisions as much as possible? How long should my session ID be?

Answer: Just use a Guid. This will very hard to get a duplicate one.


Question:
Has a way to get the datatype in C?

For example:

```
int foo;

if (foo is int)
{
    // do something
}
```

or something like:

```
if (typeof(foo) == typeof(int))
{
    // do something
}
```

Thanks in advance.

Answer: This is called type introspection or reflection and is not supported by the C language. You would probably have to write your own reflection library, and it would be a significant effort.


Question:
```
char copy, array[20]

    printf("enter ..."):
    scanf("%s", array);

    if (strlen(array) > 20 )
      {
       strcpy(copy, array....);
```

what would I need to do to make it only grab the first 20 character if the input is more then 20 character long

Answer:
```
char array[20+1];
scanf("%20s", array);
```

Problem solved.


Question: What is the best way to generate an HTTP session ID and avoid collisions as much as possible? How long should my session ID be?

Answer: Just use a Guid. This will very hard to get a duplicate one.


Question:
Has a way to get the datatype in C?

For example:

```
int foo;

if (foo is int)
{
    // do something
}
```

or something like:

```
if (typeof(foo) == typeof(int))
{
    // do something
}
```

Thanks in advance.

Answer: This is called type introspection or reflection and is not supported by the C language. You would probably have to write your own reflection library, and it would be a significant effort.


Question:
```
char copy, array[20]

    printf("enter ..."):
    scanf("%s", array);

    if (strlen(array) > 20 )
      {
       strcpy(copy, array....);
```

what would I need to do to make it only grab the first 20 character if the input is more then 20 character long

Answer:
```
char array[20+1];
scanf("%20s", array);
```

Problem solved.


Question: I'm wondering if there would be any merit in trying to code astrlenfunction to find the\0sequence in parallel. If so, what should such a function take into account? Thanks.

Answer: strlen()is sequential by spirit - one step beyond the null-terminator is undefined behavior and the null-terminator can be anywhere - the first character or the one millionth character, so you have to scan sequentially.


Question:
hi every one i want to ask that i want to compare two time values in c how can i do it
time is in form

```
Sat Feb 19 12:53:39 2011
```

thanks

Answer: You need to parse the human readable form viastrptime()and convert to atime_t-- which is (unsigned) integer seconds since the epoch of Jan 1, 1970.  As that is a number, usual comparison operators apply.


Question:
I came across this question:

"Given an integer, write a program that converts the given number to a number (in base 10). The given number could be in any base, but the base is unknown."

Provide an algorithm

Thanks in advance.

Answer: Usestrtolto convert from whatever base to your computer's native integer format.  Then useitoato convert to a base 10 representation.


Question: This pageprovides lots of libraries to handle item resizing and re-adjustment, but they're all for C++. Is there anything I can use for plain C?

Answer:
You can call MoveWindow() do not only move but also resize Windows and Dialogs:

http://msdn.microsoft.com/en-us/library/ms633534%28VS.85%29.aspx


Question:
Is it possible to replace BuildAll of Eclipse CDT by a Makefile?

I mean I have a Makefile in C and I would buildall from this file. I build a Target in Eclipse to compile but I would use the Ctrl+B to buildall. My environment is Eclipse-Cdt.

Answer:
There is no problem in creating a makefile that would invoke other make files.

But achieving interaction between Eclipse and the makefile would be extremely hard.


Question:
hi every kindly tell me how to display pointer position
for eg

fpos_t pos;

(fgetpos(fp, &pos)
how to disply pos value

thanks

Answer:
To do this portably you're not supposed to try and display that pos value.
Try using ftell() instead.

```
long pos;
pos = ftell(fp);
printf("pos is %ld bytes\n", pos);
```


Question:
I am making a program in c that can produce another c code.

How to, using the first program, compile and run the second program immediately after the second program has been produced?

Answer:
One way is to usedsystem()call ...

```
system("cl generated_file.c -o gen_exe") ;
system("./gen.exe");
```

or

```
system("gcc generated_file.c -o gen.exe");
system("./gen.exe");
```

Or you use a simle batch or script or makefile to do this


Question:
What conditions are necessary for open() to fail, with UDP sockets, on Windows?

Thanks.

Answer: The only time I've seen that happen is when I didn't initialize WinSock with WSAStartup().


Question: When creating aGtkNotebookin Glade, I get 3 tabs by default. How can I add another tab?

Answer: Right-click on one of the tabs, and click "Insert page before" or "Insert page after".


Question:
How to catch click on balloon tray icon?
What message it sends to window?
Scenario:
 The application shows balloon and user clicks on some point in the balloon space or to close button on balloon form.

Answer: The message you get sent is always the one you passed to Shell_NotifyIcon. The lParam of the message will be NIN_BALLOONUSERCLICK. You don't get to find out whether the user clicks the close button or not.


Question: I am trying to find a good way to handle multicast group members.Keep track when someone joins/leaves the group. Language is C.

Answer: Unless you are implementing an IP multicast router you should add a subscription management protocol above multicast in the application layer.


Question:
```
unsigned char x = 93;
unsigned char a = x << 4;
printf("a = %d\n", a);
```

I do understand how bit operators work but I don't understand the binary representation of x.

How is a = 208?

Answer:
```
93 = 01011101
```

Shift that left 4 bits and it leaves the following (only 8 bits in your result):

```
11010000 = 208
```


Question: I want to learn OpenGL ES, but so far I don't know anything about it and I was wondering if there is a tutorial which stars from 0 knowledge. Remember that I don't know anything about graphics, drawing, etc.

Answer:
This is a great start since it's specific to iPhone:

OpenGL ES from the Ground Up: Table of Contents


Question: Is there a c atoi() equivalent for wide chars on Linux? I can find something for MS (wtoi) but I can find anything in a standard Linux lib.

Answer: You can usewcstolto convert from wide strings to integer values.


Question:
This method in Cocos2d:

```
/** Returns opposite of point.
 @return CGPoint
 @since v0.7.2
 */
static inline CGPoint
ccpNeg(const CGPoint v)
{
    return ccp(-v.x, -v.y);
}
```

Why does it say 'CGPoint' after inline?  Why not

```
static inline ccpNeg(...
```

?

Answer: Because the function wants to return a CGPoint.


Question: I want to learn OpenGL ES, but so far I don't know anything about it and I was wondering if there is a tutorial which stars from 0 knowledge. Remember that I don't know anything about graphics, drawing, etc.

Answer:
This is a great start since it's specific to iPhone:

OpenGL ES from the Ground Up: Table of Contents


Question: Is there a c atoi() equivalent for wide chars on Linux? I can find something for MS (wtoi) but I can find anything in a standard Linux lib.

Answer: You can usewcstolto convert from wide strings to integer values.


Question: In reference to the thread:memmove implementation in C, I did not understand why would there be a memory overlap for 2 different variables? i.e. is this a normal scenario that the compiler allocates same 'common space' to 2 different variables and why is this policy used by compilers in such cases?

Answer:
Nothing to do with the compiler.  Consider the following:

```
int x[100];

memmove(&x[1], &x[0], 99*sizeof(int));
```


Question:
```
x=4+2%-8;
```

This gives output=6
Please anyone explain how?

Answer:
x=4+2%-8;is equivalent tox = 4 + (2 % -8);which givesx = 4 + 2which is 6.

More:C Operator Precedence Table


Question:
I have a simple question

How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?

Thanks

Answer:
```
main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
// Now str contains the integer as characters
}
```

Hope it will be helpful to you.


Question: In reference to the thread:memmove implementation in C, I did not understand why would there be a memory overlap for 2 different variables? i.e. is this a normal scenario that the compiler allocates same 'common space' to 2 different variables and why is this policy used by compilers in such cases?

Answer:
Nothing to do with the compiler.  Consider the following:

```
int x[100];

memmove(&x[1], &x[0], 99*sizeof(int));
```


Question:
```
x=4+2%-8;
```

This gives output=6
Please anyone explain how?

Answer:
x=4+2%-8;is equivalent tox = 4 + (2 % -8);which givesx = 4 + 2which is 6.

More:C Operator Precedence Table


Question:
I have a simple question

How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?

Thanks

Answer:
```
main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
// Now str contains the integer as characters
}
```

Hope it will be helpful to you.


Question:
```
x=4+2%-8;
```

This gives output=6
Please anyone explain how?

Answer:
x=4+2%-8;is equivalent tox = 4 + (2 % -8);which givesx = 4 + 2which is 6.

More:C Operator Precedence Table


Question:
I have a simple question

How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?

Thanks

Answer:
```
main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
// Now str contains the integer as characters
}
```

Hope it will be helpful to you.


Question:
I am wondering what the difference is between these two variables in C:

```
float price = 3.00;
```

and

```
float price = 3.00f;
```

What is the use of suffixfin this case?

Answer:
3.00is interpreted as adouble, as opposed to3.00fwhich is seen by the compiler as afloat.

Thefsuffix simply tells the compiler which is afloatand which is adouble.

SeeMSDN (C++)


Question:
Can we generate Control flow graph of the c program by Turbo C compiler?

I want to know that there is something given by the compiler to generate a CFG of a C program.

Answer:
Don't think Turbo C has this feature.

Though, modern IDEs have capabilities to draw Class Diagrams, but I personally haven't seen any IDEs drawing Flow diagrams.

Edit:

Hereis a list of tools that does what you want to achieve.


Question:
friends, I have a piece of code which can perform simple add, subtraction, multiplication, division, and formula with brackets.

Is there some kind of conversion tool for translating code from C to Smalltalk?

Or any other relatively easy way to achieve this?

Thanks in advance.

Answer: This should be trivial to write withPetitParser


Question:
Hay All

Can we get the hard-disk number using php or C
Is there possible or not ?

This is not a problem just configuring.

Answer:
If you're using linux just read the file, /etc/fstab

I'm looking around for a windows equivalent.


Question:
Hay All

Can we get the hard-disk number using php or C
Is there possible or not ?

This is not a problem just configuring.

Answer:
If you're using linux just read the file, /etc/fstab

I'm looking around for a windows equivalent.


Question: How would I convert an NSDate to a NSString, formatted with strftime specifiers?

Answer:
you could use strftime.

```
NSDate *date = [NSDate date];
time_t time = [date timeIntervalSince1970];
struct tm timeStruct;
localtime_r(&time, &timeStruct);
char buffer[80];
strftime(buffer, 80, "%d.%m.%Y %H:%M:%S", &timeStruct);
NSString *dateStr = [NSString stringWithCString:buffer encoding:NSASCIIStringEncoding];
```

I hope it's correct.


Question:
Is it equivalent to a unsigned integer ?I'm able to use unsigned unknown_type_var = 3332934;
and print it successfully. This value is greater than a integer variable right ?

Answer: unsigned is totally equivalent to unsigned int, just like long is equivalent to long int, etc.


Question:
I have a script that generates 2 code files (For example, src1.c, src2.c) according to another code file (say origin.h).I use a makefile to build them.Now, I want the script to be executed when src1.c OR src2.c is older that origin.h.

What is the best way to do that?

Thanks.

Answer:
Make src1.c and src2.c jointly dependent on origin.h:

```
src1.c src2.c : origin.h
        build-sources
```


Question:
Refering tohttp://www.devx.com/tips/Tip/13291, it says that I can usememcpywith the size to copy determined bysizeof(), however, isn't the array pointing to a pointer?

Other than iterating through the array, how can I usememcpyto deep copy an array?

Thanks!

Answer: In the linked exampleint weekly_hours[5][5];allocates space for 25 integers. There is no further indirection, so you can safely use memcpy to duplicate it's values.


Question: How do I find what library files I need to include for the implementation of a particular c header if there is not library with the same name?

Answer:
I'd Google for the name of the header or the functions within it.

If you're on a Debian-based system you could also trydpkg -S <full header path>to tell you what package provided the header, then see what other files (in/usr/lib) that same package provides.


Question:
Is it equivalent to a unsigned integer ?I'm able to use unsigned unknown_type_var = 3332934;
and print it successfully. This value is greater than a integer variable right ?

Answer: unsigned is totally equivalent to unsigned int, just like long is equivalent to long int, etc.


Question:
I have a script that generates 2 code files (For example, src1.c, src2.c) according to another code file (say origin.h).I use a makefile to build them.Now, I want the script to be executed when src1.c OR src2.c is older that origin.h.

What is the best way to do that?

Thanks.

Answer:
Make src1.c and src2.c jointly dependent on origin.h:

```
src1.c src2.c : origin.h
        build-sources
```


Question:
Refering tohttp://www.devx.com/tips/Tip/13291, it says that I can usememcpywith the size to copy determined bysizeof(), however, isn't the array pointing to a pointer?

Other than iterating through the array, how can I usememcpyto deep copy an array?

Thanks!

Answer: In the linked exampleint weekly_hours[5][5];allocates space for 25 integers. There is no further indirection, so you can safely use memcpy to duplicate it's values.


Question: How do I find what library files I need to include for the implementation of a particular c header if there is not library with the same name?

Answer:
I'd Google for the name of the header or the functions within it.

If you're on a Debian-based system you could also trydpkg -S <full header path>to tell you what package provided the header, then see what other files (in/usr/lib) that same package provides.


Question:
without using multiplication or division operators.
You can use only add/substract operators.

Answer:
A pointless problem, but solvable with the properties of logarithms:

```
pow(a,b) = exp( b * log(a) )
         = exp( exp(log(b) + log(log(a)) )
```

Take care to insure that your exponential and logarithm functions are using the same base.

Yes, I know how to use a sliderule. Learning that trick will change your perspective of logarithms.


Question:
How would I connect to char* strings to each other.
For example:

```
char* a="Heli";
char* b="copter";
```

How would I connect them to one char c which should be equal to "Helicopter" ?

Answer:
strncat

Or usestrings.


Question: stack is increasing or decreasing using C program ?

Answer: Right, in C usually variables in function scope are realized by means of a stack. But this model is not imposed by the C standard, a compiler could realize this any way it pleases. The word "stack" isn't even mentioned in the standard, and even less if it is in- or decreasing. You should never try to work with assumptions about that.


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:Enter Password in C

Ask user to enter Password without showing the input characters on console?

Answer: You need to set the console to "no echo" mode. This depends on your particular OS. Here is an example of doing it for linux:http://www.cplusplus.com/forum/beginner/1988/page4.html#msg14522


Question: I've a C code where I fetch headers for all mails in the inbox via imap issuing UID FETCH 1:* (FLAGS BODY[HEADER]) command. Due to special authentication requirements I cannot use a standard imap library like vmime or libetpan. I need to parse the mail header values in accordance with RFC 822. Do we have some library/function in C/C++ which will do the job ?

Answer: Mimetic works great ! it also takes care of non-standard mail headers.


Question:
I have a static method in a cpp file (not in class) .
I want to use it globally without redeclaring it as extern .
In that case is it  possible to use a global function pointer to this static method and
use this function pointer globally ??

Answer: It is possible to do what you want, but why would you avoid using extern when it does exactly what you are trying to emulate through a much more convoluted (and unreadable) mechanism?


Question: Is it possible to still use inet_ntoa() and not worry about Windows User Permissions? Do I need to put a try/catch block around inet_ntoa() to catch any possible problems if User Permissions prevent me from getting the IP address of an interface?

Answer:
inet_ntoadoesn't raise exceptions. It returnsNULLin case of an error.

It's hard to see how user permissions could come into this function since it is just an integer to string conversion.


Question:
I have a 16 bit fixed point processor and I want to do fixed point processing with it.  I'm looking for the correct datatype to use for unsigned 16 bit ints..

My question is: what is the difference between auint16_tanduint_fast16_t?  (These are included in thestdint.h.)  Isuint_fast16_tbetter since it is faster??

Thanks!!

Answer: uint16_tis an unsigned 16-bit integer.uint_fast16_tis the fastest available unsigned integer with at least 16 bits.


Question:
```
int solutions[92][81];

void add_solution(int board[81]) {
  solutions[found_sltns++] = board;
}
```

Code sample attached, I get

error: incompatible types when
  assigning to type ‘int[81]’ from type
  ‘int’

when compiling

Any clue?

Answer:
You can't copy array in this manner. You have to perform a element by element copy.

```
int i;
for(i=0;i<81;i++)
 solutions[found_sltns][i] = board[i];
found_sltns++;
```


Question: I've a C code where I fetch headers for all mails in the inbox via imap issuing UID FETCH 1:* (FLAGS BODY[HEADER]) command. Due to special authentication requirements I cannot use a standard imap library like vmime or libetpan. I need to parse the mail header values in accordance with RFC 822. Do we have some library/function in C/C++ which will do the job ?

Answer: Mimetic works great ! it also takes care of non-standard mail headers.


Question:
I have a static method in a cpp file (not in class) .
I want to use it globally without redeclaring it as extern .
In that case is it  possible to use a global function pointer to this static method and
use this function pointer globally ??

Answer: It is possible to do what you want, but why would you avoid using extern when it does exactly what you are trying to emulate through a much more convoluted (and unreadable) mechanism?


Question: Is it possible to still use inet_ntoa() and not worry about Windows User Permissions? Do I need to put a try/catch block around inet_ntoa() to catch any possible problems if User Permissions prevent me from getting the IP address of an interface?

Answer:
inet_ntoadoesn't raise exceptions. It returnsNULLin case of an error.

It's hard to see how user permissions could come into this function since it is just an integer to string conversion.


Question:
I have a 16 bit fixed point processor and I want to do fixed point processing with it.  I'm looking for the correct datatype to use for unsigned 16 bit ints..

My question is: what is the difference between auint16_tanduint_fast16_t?  (These are included in thestdint.h.)  Isuint_fast16_tbetter since it is faster??

Thanks!!

Answer: uint16_tis an unsigned 16-bit integer.uint_fast16_tis the fastest available unsigned integer with at least 16 bits.


Question: As above, say I have a 3 dimensional array, a[][][], and I want to pass this to a function; how should I declare the function parameter?

Answer:
```
void function1(int array[][3][4])
{
    ...use array here...
}

void function2(void)
{
    int array[20][3][4];
    ...load array...
    function1(array);
}
```


Question:
Is there any way I can synchronize the data(data sharing) between C and Java code with JNI using mutex or any other methods.

Please let me know if you have any documentation about the methods for data sharing.

Answer:
You can use any lock you prefer in C and make it available to Java via JNI.
You can do the reverse as well, calling a method in Java from C to use the lock.

I would do it natively in the framework which created the thread.


Question:
Consider printf:

```
int printf ( const char * format, ... );
```

What are the terms used to describe the...and the functions that use it?  I've been calling it an ellipsis, but that's like calling&the "ampersand operator."

Answer:
Variable length parameter list

Edit:

Or, if describing the function itself:Variadic function


Question:
How could I simple initialize a multidimensional C-array with 0 elements like this:

```
int a[2][2] = { { 0, 0 }, {0, 0} }
```

Answer:
This should work:

```
int a[2][2] = {0};
```

EDITThis trick may work for silencing the warning:

```
int a[2][2] = {{0}};
```


Question: How do I do a deep copy of a python object using the C API? I know I can use copy.deepcopy, but I'd prefer to use the C API if I can.

Answer: The functionality ofcopy.deepcopy()iscompletely written in Python.  I don't think they would have done this if there was a single C call to achieve the same thing, so my guess is you will have to callcopy.deepcopy().


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:How do I call unmanaged C/C++ code from a C# ASP.NET webpage

I have a dll file that is written in "C" language, i want to use it in C#. How can i do that?

Answer:
You can usePInvoke

Platform Invocation Services (PInvoke)
  allows managed code to call unmanaged
  functions that are implemented in a
  DLL.

Hereis a great tutorial by the NAG (Numerical Algorithms Group) group


Question: As above, say I have a 3 dimensional array, a[][][], and I want to pass this to a function; how should I declare the function parameter?

Answer:
```
void function1(int array[][3][4])
{
    ...use array here...
}

void function2(void)
{
    int array[20][3][4];
    ...load array...
    function1(array);
}
```


Question:
Is there any way I can synchronize the data(data sharing) between C and Java code with JNI using mutex or any other methods.

Please let me know if you have any documentation about the methods for data sharing.

Answer:
You can use any lock you prefer in C and make it available to Java via JNI.
You can do the reverse as well, calling a method in Java from C to use the lock.

I would do it natively in the framework which created the thread.


Question:
Do you know a good example of nonlinear programming?, I have search over google, but any text just formulate and do not solve the problem, They mention lingo and even excel for solving it.

Could you please post an example and explain a little of if?

Thanks in advance

P.d
You know the idea is to see some results, and numbers, using C, java.
Thanks

Answer:
try these (java):

Example1

Example2

Example3


Question:
```
int *(*(*P)[2][2])(int,int);
```

P is a pointer to 2x2 array of pointers to a function with 2 type int parameters, that returns a int type pointer. Is this correct?

Answer:
cdeclis a great tool for figuring these kinds of problems out:

```
$ cdecl
Type `help' or `?' for help
cdecl> explain int *(*(*P)[2][2])(int,int);
declare P as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int
```

So yes, you're correct.


Question: Given atime_tas1291121400, how do I get the date of that day formatted as20101130?

Answer:
Usegmtime(3)orlocaltime(3)to convert it into astruct tm(Or, better, the reentrant versionsgmtime_rorlocaltime_r), and
then usestrftime(3)to turn it into a string. For example, if you
want the output in UTC:

```
struct tm tm;
char buf[9];
gmtime_r(&my_time_t, &tm);
strftime(buf, sizeof(buf), "%Y%m%d", tm);
printf("The date is: %s\n", buf);
```


Question: I saw some C while loop with predicate as while(*ptr), and ptr is usually of char * type, how does this work? Does this mean "while()" will also accept values other than 1 or 0 as predicates?

Answer: In C, any non-zero value is considered "true", sowhile (*ptr)will loop as long as*ptris non-zero.


Question:
Using Linux and glibc, when originating a TCP/IP connection (calling connect() on a socket), how can I choose explicitly from which of my IP local adresses I want to originate that connection, providing I have more than one interface (with different IPs) from where I can reach the remote host?

Is it possible to do so, or it is always up to the operating system IP stack to chose the route automatically?

Answer: Bind to a specific address instead of0.0.0.0or::.


Question: i need to get the terminal cursor position then set it, i already know how to set it using "move", that's in ncurses, any ideas?

Answer:
Have you triedgetyx()?

Or, if you prefer legacy curses functions,getcurx() and getcury()?


Question: Given atime_tas1291121400, how do I get the date of that day formatted as20101130?

Answer:
Usegmtime(3)orlocaltime(3)to convert it into astruct tm(Or, better, the reentrant versionsgmtime_rorlocaltime_r), and
then usestrftime(3)to turn it into a string. For example, if you
want the output in UTC:

```
struct tm tm;
char buf[9];
gmtime_r(&my_time_t, &tm);
strftime(buf, sizeof(buf), "%Y%m%d", tm);
printf("The date is: %s\n", buf);
```


Question: I saw some C while loop with predicate as while(*ptr), and ptr is usually of char * type, how does this work? Does this mean "while()" will also accept values other than 1 or 0 as predicates?

Answer: In C, any non-zero value is considered "true", sowhile (*ptr)will loop as long as*ptris non-zero.


Question:
Using Linux and glibc, when originating a TCP/IP connection (calling connect() on a socket), how can I choose explicitly from which of my IP local adresses I want to originate that connection, providing I have more than one interface (with different IPs) from where I can reach the remote host?

Is it possible to do so, or it is always up to the operating system IP stack to chose the route automatically?

Answer: Bind to a specific address instead of0.0.0.0or::.


Question: i need to get the terminal cursor position then set it, i already know how to set it using "move", that's in ncurses, any ideas?

Answer:
Have you triedgetyx()?

Or, if you prefer legacy curses functions,getcurx() and getcury()?


Question:
```
void foo()
{
    char *var = kmalloc(1, GFP_KERNEL);
    return;
}
```

This code will cause kernel level memory leaks, what is the difference between this and user land memory leaks

This is a question from a interview today. I did bad about this question.Can anyone give any thoughts?

Answer: Memory leaked in userspace is reclaimed at process termination, but memory leaked in kernel space cannot be reclaimed until the machine is rebooted.


Question:
When compiling this code with gcc

```
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct _Nodo
{
    unsigned int id_thread;
    int id_mutex;
    _Nodo *solicita;
    _Nodo *asignado;

}Nodo;
```

I get:

```
libdrm.c:13: error: expected specifier-qualifier-list before ‘_Nodo’
```

Why?

Answer: Try:struct _Nodo *solicita.


Question:
can anyone explain these lines to me:

```
int xyz( void )
{
extern void abc( void );
}
```

a function declaration within a function definition?
or am I missunderstanding something?

Answer: Yes, your guess is correct.  It's declaring the existence of the functionabc(), so it may be referenced withinxyz().  Note that theexternis unnecessary, as functions areexternby default.


Question:
In C/C++, what does the following mean?

```
for(;;){
    ...
}
```

Answer: It's an infinite loop, equivalent towhile(true).  When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).


Question:
I'm fairly sure the set code should look like this:

```
function setPYR(float pitch, float yaw, float roll) {
    glLoadIdentity();
    glRotatef(pitch, 1, 0, 0);
    glRotatef(yaw, 0, 1, 0);
    glRotatef(roll, 0, 0, 1);
}
```

How can I get the pitch, yaw and roll from the current modelview matrix?

Answer: Give a look atThe Matrix and Quaternions FAQ.


Question:
So I have my config file .vimrc that has this code which should save the file compile and run it when I press F3. This doesn't work.

```
map <F3> ^M:w^M:!gcc *.c -g; ./a.out^M
```

Answer:
Your keymapping worked for me (assuming you type^Mas e.g. Ctrl-V Ctrl-M).

If you have a makefile setup (and you probably should) you can just use:make.

You can set themakeprgoption if you use something other thanmake, e.g.cmakesconsantor something else.


Question:
Hi I created a server program that forks a new process after its accepts a socket connection.
There are several statically allocated global variables defined in the program.  My question is are these static buffers allocated twice after the fork?  Or does the fork only duplicate address space on the heap and the call stack?

Answer: Theentireaddress space is duplicated, including all global variables and the program text.


Question:
Already read throughthis related question, but was looking for something a little more specific.

Is there a way to tell your compiler specifically how wide you want your enum to be?If so, how do you do it? I know how to specify it in C#; is it similarly done in C?Would it even be worth doing? When the enum value is passed to a function, will it be passed as anint-sized value regardless?

Answer:
I believe there is a flag if you are using GCC.

-fshort-enums


Question:
My string length is constant but actual data length will vary as like below,

```
"           1,54" // will be displayed as "- 1,54"
"123456789012,12" // will be dsiplayed as "- 123456789012,12"
```

Answer:
Wouldn't it be easiest to just put a '-' in the format string when you display the data?

```
printf("-%f", 1.54);
```


Question:
My string length is constant but actual data length will vary as like below,

```
"           1,54" // will be displayed as "- 1,54"
"123456789012,12" // will be dsiplayed as "- 123456789012,12"
```

Answer:
Wouldn't it be easiest to just put a '-' in the format string when you display the data?

```
printf("-%f", 1.54);
```


Question:
I want to generate 2 random numbers between 0 and 20

```
int one = rand() % 20;
```

it gives me 1 steady value i.e 1...

Am I missing something?

Answer:
You have to give a seed to the random number.

```
srand( time(NULL) );
int num1 = rand() % count;

int num2 = rand() % count;
```

Random number between 1 and 20

```
int num = rand() % 20 ;

if( num == 0 )
    num += 2;

else if( num == 1 )
    ++num ;
```


Question: I am a beginner of C. I run the C program, but the window closes too fast before I can see anything. How can I pause the window?

Answer:
you can put

```
getchar();
```

before the return from the main function. That will wait for a character input before exiting the program.

Alternatively you could run your program from a command line and the output would be visible.


Question: Suggestions needed for best instrumentation tools for a C project. I actually like to know when control was transferred from a function to another function and therefore I want to do something like instrumenting printf commands at the end and start of each function.

Answer: Thevalgrindtool has all sorts of hooks you can program that would let you watch this happen.  In particular,thecallgrindtoolmight be appropriate here.


Question: Given a unsigned char bitmapRep[8192], how to efficiently find out all "1" bits' positions? Thanks.

Answer:
What do you mean by "find"?

This may seem like a smart-ass answer, but I'm perfectly serious:  you alreadyhavefound them.  There's a perfect map describing exactly where all the 1 bits are found, and it has a bit set in the corresponding positions.


Question: I need to print a variable which is a COLORREF.

Answer:
You might also want to break it up into the individual RGB components:

```
printf("R: %i, G: %i, B: %i", GetRValue(color), GetGValue(color), GetBValue(color));
```

this would give you something like:

R: 255, G: 150, B: 75


Question:
For my compiler tests, I need to generate this warning "Statement has no effect" in my test code. How can I do this?

Using VS cl.exe compiler

Answer:
```
so ross$ cat > noeff.c
void f(void) {
  1;
}
so ross$ cc -Wall -c noeff.c
noeff.c: In function ‘f’:
noeff.c:2: warning: statement with no effect
so ross$
```


Question:
Expanding myother question..

```
unsigned char* s_char = data + offset;
(*s_char) = size_t(((*s_char) & 0xf0)) | new_doff;
```

How to print s_char's bit representation?

Answer:
You'll need to manually print it using something like:

```
printf("%d%d%d%d%d%d%d%d", *s_char & 0x80, *s_char & 0x40, ..., *s_char & 0x01);
```


Question:
I have a C program that usessprintf_s. It works fine in Windows, but when I compile my code in Linux it gives this error:

```
sprintf_s was not declared in this scope.
```

Why does this happen and how can I fix it?

Answer:
It's not standard, you won't find such function on Linux.

Standard functionsnprintfshould have a similar semantics.


Question:
What's the quickest, easiest way to find the memory address of the first local variable in the activation record? (In C..)

Doesn't matter what we have declared already. Could be simple as char *s = 'Hello world!'

Thanks!

Answer: You can't do that - the C standard doesn't even require that thereisa stack, let alone requiring a standard way to find out the order in which variables were put on it.


Question:
It seems that some autoconf projects use aconfigure.infile to generate aconfigurescript, and some useconfigure.ac.

What is the difference/advantage between using one or the other?

Answer: Its just a matter of style.  Historically autoconf files were namedconfigure.in.  Nowconfigure.acis the preferred naming scheme.  Its also discussed in thedocumentation.


Question: Anyone please tell me where the main() function of the 'C' language returns its value?

Answer:
C'smainfunction returns an int... that int goes to the program which executed it (the parent process, if you will) as an exit status code.

Specifically, on most operating systems, a 0 exit code signifies a normal run (no real errors), and non-zero means there was a problem and the program had to exit abnormally.


Question:
It seems that some autoconf projects use aconfigure.infile to generate aconfigurescript, and some useconfigure.ac.

What is the difference/advantage between using one or the other?

Answer: Its just a matter of style.  Historically autoconf files were namedconfigure.in.  Nowconfigure.acis the preferred naming scheme.  Its also discussed in thedocumentation.


Question: Anyone please tell me where the main() function of the 'C' language returns its value?

Answer:
C'smainfunction returns an int... that int goes to the program which executed it (the parent process, if you will) as an exit status code.

Specifically, on most operating systems, a 0 exit code signifies a normal run (no real errors), and non-zero means there was a problem and the program had to exit abnormally.


Question: Is there an easy way, on *nix platforms(Linux specifically) to get the IP address of a hostname, while supplying a custom DNS server to use in place of the system's configured one? I want to access this information from a C program.

Answer: You will need to use your own resolver, directly sending DNS packets, instead of relying on the system's resolver andgethostbyname. You would probably want to use a library, such asadns.


Question:
```
int x = 0;
x^=x || x++ || ++x;
```

and the answer for x at last is 3.
How to analysis this expression?
little confused about this.
Thanks a lot.

Answer: This is undefined behaviour.  The result could be anything.  This is because there is nosequence pointbetween the++xand thex ^=, so there is no guarantee which will be "done" first.


Question:
```
file * fp = fopen()
file * fd = ????
```

I want to use*fdto write file which*fpopened before.

How can I do it?

Add some, the key of this question is use another pointer to do it. See, *fd is the different pointer. Wish i made this clear.

Answer:
```
file* fd = fp;
```

If I understand you correctly, of course.


Question: I have a program that executes various shell commands viasystem()and occasionally prints tocout. I want to redirect all output coming fromsystem()calls to a log file so they don't clutter up the normal output. Can I do this without having to append> logto all my system commands?

Answer: Looks like you can usepopen


Question:
i want to do some modification and development for VLC. i download its source code, vlc-1.1.5. and it is written by C. so usually which development environment should i use, xcode or some others?

thx...

Answer: I thought VLC was developed inQt. Do you see the class names starting with Q? In case it is developed in Qt,Qt CreatororKDevelopwould be a good choice of development environment.


Question: im trying to read newline terminated strings using windows api and saw that the serialport class has a serialport.newline member. i want to know if it is possible to use the serialport class in c and how

Answer: In (Microsoft) C, you'd need to callCreateFileto get a handle to the serial port, and_open_osfhandle(handle, _O_TEXT)to convert it to a file descriptor. You can get aFILE*from that file descriptor with_fdopen. After that,fscanfwill read lines.


Question:
```
error: expected ‘)’ before ‘[’ token
  error  line is - void display(ptr[i]);
```

this is the error which i get after compilation, what does it mean, i have written a simple program in C

Answer: I can only imagine you are missing a ')' on the line above that line. But more source code would help in identifying the problem.


Question: Is there any way to check the granularity of gettimeofday()  function provided by POSIX?

Answer: Instead ofgettimeofday(), consider usingclock_gettime()(specifying theCLOCK_REALTIMEclock).  This is also POSIX, and supports aclock_getres()function to obtain the resolution.


Question: Is there any way to check the granularity of gettimeofday()  function provided by POSIX?

Answer: Instead ofgettimeofday(), consider usingclock_gettime()(specifying theCLOCK_REALTIMEclock).  This is also POSIX, and supports aclock_getres()function to obtain the resolution.


Question:
How do I set a fixed window size for a GTK+ app? I have:

```
gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
gtk_window_set_policy (GTK_WINDOW(mainWindow), FALSE, FALSE, FALSE);
```

but the window gets very small. There are no widgets yet.

Answer:
Usegtk_window_set_resizablefunction for this purpose

```
gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
gtk_window_set_resizable (GTK_WINDOW(mainWindow), FALSE);
```


Question:
As C does not have boolean types, how can I write a function like this in C:

```
bool checkNumber()
{
   return false;
}
```

Answer:
Thebooltype is defined in the<stdbool.h>header, and is available under the name_Boolotherwise (assuming you're using a C99 compiler).  If you don't have C99, you can always invent your own bool type like this:

```
typedef enum {false, true} bool;
```


Question:
As C does not have boolean types, how can I write a function like this in C:

```
bool checkNumber()
{
   return false;
}
```

Answer:
Thebooltype is defined in the<stdbool.h>header, and is available under the name_Boolotherwise (assuming you're using a C99 compiler).  If you don't have C99, you can always invent your own bool type like this:

```
typedef enum {false, true} bool;
```


Question:
As C does not have boolean types, how can I write a function like this in C:

```
bool checkNumber()
{
   return false;
}
```

Answer:
Thebooltype is defined in the<stdbool.h>header, and is available under the name_Boolotherwise (assuming you're using a C99 compiler).  If you don't have C99, you can always invent your own bool type like this:

```
typedef enum {false, true} bool;
```


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:C Analog To STL

Is there something like STL for C.

Answer: You can have a look at theglib, which provides lots of interesting features


Question:
I need a good implementation of a (thread safe) cyclic buffer written in c.
Does anybody know where i can get it?

thanks!

Answer:
Have you looked atthiswikipedia record? They give an example, and have more external links.

As for thread-safe access just wrap the object with your own if needed, and throw a lock() / unlock() at it.


Question:
I want to copy folder A and paste to desktop.

I am currently using C++ so preferably an OO interface if available.

Answer:
On Windows (Win32), you could useSHFileOperation, eg:

```
SHFILEOPSTRUCT s = { 0 };
s.hwnd = m_hWnd;
s.wFunc = FO_COPY;
s.fFlags = FOF_SILENT;
s.pTo = "C:\\target folder\0";
s.pFrom = "C:\\source folder\\*\0";
SHFileOperation(&s);
```


Question: There is a Ruby process and has a string var named "switch", and the "switch" will be updated by user.  There are also 2 C daemon process, which need to access the "switch" in a loop and decide the logic in runtime, how to deal with this case ? thanks!

Answer: A socket (or a common file) can be used as a pipe between them.


Question:
Given two events with integer start and end times, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap.

I have the solution, but I'm curious to see what others come up with.

EDIT: OK, here's my solution:

```
e1 > s2 || (s1 > s2 && e2 < s1)
```

Answer: bool overlap = (s1 <= e2) && (s2 <= e1)


Question:
I want to copy folder A and paste to desktop.

I am currently using C++ so preferably an OO interface if available.

Answer:
On Windows (Win32), you could useSHFileOperation, eg:

```
SHFILEOPSTRUCT s = { 0 };
s.hwnd = m_hWnd;
s.wFunc = FO_COPY;
s.fFlags = FOF_SILENT;
s.pTo = "C:\\target folder\0";
s.pFrom = "C:\\source folder\\*\0";
SHFileOperation(&s);
```


Question: There is a Ruby process and has a string var named "switch", and the "switch" will be updated by user.  There are also 2 C daemon process, which need to access the "switch" in a loop and decide the logic in runtime, how to deal with this case ? thanks!

Answer: A socket (or a common file) can be used as a pipe between them.


Question:
Given two events with integer start and end times, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap.

I have the solution, but I'm curious to see what others come up with.

EDIT: OK, here's my solution:

```
e1 > s2 || (s1 > s2 && e2 < s1)
```

Answer: bool overlap = (s1 <= e2) && (s2 <= e1)


Question:
Is there a way to convert a hexdump e.g. aec4d2f3c6a4e70ea6cea074f65812d2a34b180cc92b817edcd867167e7a91c5beb942f0
to a string in c so that every two hexadecimal digits make a char? If so, what?

Answer:
Reads from stdin and prints to stdout:

```
int main()
{
    int ch;
    while(scanf("%2x", &ch) == 1)
        putchar(ch);
}
```

I think you can modify it easily yourself for your specific source and destination requirements.


Question:
I am checking to make sure a float is not zero. It is impossible for the float to become negative. So is it faster to do thisfloat != 0.0for thisfloat > 0.0f?

Thanks.

Edit: Yes, I know this is micro-optimisation. But this is going to be called every time through my game loop, and I would like to know anyway.

Answer: There is not likely to be a detectable difference in performance.


Question:
This question already has answers here:Closed11 years ago.

Possible Duplicate:How do you read C declarations?

I Don't understand the following:

```
int * (*(*p)[2][2])(int,int);
```

Can you help?

Answer:
For things like this trycdecl, decoded to;

```
declare p as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int
```


Question:
```
#include<stdio.h>
double i;

int main()
{
    (int)(float)(char) i;
    printf("%d", sizeof((int)(float)(char)i));
    return 0;
}
```

The above outputs 4 on a Micrsoft compiler. Why?

Answer:
sizeofis the size, in bytes, of the variable. In this case,iis being cast to anintwhich is 4 bytes.

These are the sizes of types on MS C++:http://msdn.microsoft.com/en-us/library/cc953fe1(v=vs.71).aspx


Question:
The following C/C++ code results in an Unused Entity Issue with XCode 4 (Clang LLVM).

```
void stringMethod(const char *string){
  while(*string!=0){
    *string++;
    //...
  }
}
```

Its on that line: *string++; so it seems like clang didnt realize that the pointer address is increased?
I don't get, how to adjust this code... Any ideas?

Answer: Try to remove the dereferencing operator*, you don't need to dereference the pointer when you increase it.


Question:
```
int i;        // A.
extern int i; // B.
```

I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variablei. But what is B? What's the difference between the definition and the declaration?

Answer: It's a declaration.  It says there is an integerithat will be defined elsewhere.


Question: I want to include an IP packet in Socket programming. I have a readymade Ip packet which contains igmp packet. I don't want to design igmp protocol but want to use that packet to sent igmp query. By some how the Ip packet  I have must be recognize as IP packet and not as TCP/UDP data.

Answer: You have to usethe raw socketwithsendmsg.  This needrootpermission.


Question:
The following C/C++ code results in an Unused Entity Issue with XCode 4 (Clang LLVM).

```
void stringMethod(const char *string){
  while(*string!=0){
    *string++;
    //...
  }
}
```

Its on that line: *string++; so it seems like clang didnt realize that the pointer address is increased?
I don't get, how to adjust this code... Any ideas?

Answer: Try to remove the dereferencing operator*, you don't need to dereference the pointer when you increase it.


Question:
```
int i;        // A.
extern int i; // B.
```

I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variablei. But what is B? What's the difference between the definition and the declaration?

Answer: It's a declaration.  It says there is an integerithat will be defined elsewhere.


Question: I want to include an IP packet in Socket programming. I have a readymade Ip packet which contains igmp packet. I don't want to design igmp protocol but want to use that packet to sent igmp query. By some how the Ip packet  I have must be recognize as IP packet and not as TCP/UDP data.

Answer: You have to usethe raw socketwithsendmsg.  This needrootpermission.


Question: I see "printf" instruction in sample codes of c language for microcontroller particularly in 8051. Since microcontrollers has no fixed output display what is the use of the "printf" instruction?

Answer: More likely than not, so you can attach a debugging console, either through an RS232 port, or as virtual output from an in-circuit emulator.


Question:
gcc 4.4.4 c89

Does any one know any sdp parses. That I can link to my application. Currently we are developing a SIP project. However, we need to parse the SDP for incoming/answering.

However, we don't have much time to implement. So just wondering if there are some simple ones out there they are easy and quick to work with.

Our application is written in c.

Many thanks for any advice,

Answer: Check outFreeSDP. But it is distributed under GPL