Question:
I have an array of double (size more than 60k entries), I have the frequency value. Now I want to create a sound from it using C/C++ which I can play on speaker. My OS is linux.

Thanks. I hope I am clear enough.

Answer:
http://www.linuxjournal.com/article/6735

This is a link to an article in Linux Journal about programming with the ALSA (Advance Linux Sound Architecture).  It contains some example code.


Question:
Do these two structs have the same memory layout? (C++)

```
struct A
{
   int x;
   char y;
   double z;
};

struct B
{
   A a;
};
```

Further can I access x, y, z members if I manually cast an object of this to anA?

```
struct C
{
   A a;
   int b;
};
```

Thanks in advance.

EDIT:

What if they wereclassesinstead ofstructs?

Answer: Yes and yes. The latter is commonly used for emulating OO inheritance in C.


Question:
Is it possible to get the list of #defines(both compile time and defined in the source code) used in a C program while execution.
Because  i am having a project having lot of C source files.

Is there any compile time option to get that?

Answer: GNUcpptakes various-doptions to output macro and define data. See their man pages for more details.


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

Possible Duplicate:C# driver development?

Why do we use C for device driver development rather than C#?

Answer: Because C# programs cannot run in kernel mode (Ring 0).


Question:
How many different ways are there to define constants in C or C++?

I am already aware of using theconstkeyword and the#definedirective. I heard somewhere that there are two more ways to define constants, but I've never seen any others.
Are there any others?

Answer:
enum, as inenum { some_constant= 2 };

EDIT: I also forgot the additions ofconstexprand user defined literals in the C++0x standard. So there are actually three additional ways.


Question:
Let's say I have this line of code in a program:

```
int * number=0;
int mystery=&6[number];
```

Mistery is a number and I can use &5 or &4 obtaining other numbers.

But what does the "&6[]" mean?

Thanks!

Answer: 6[number]is exactly equivalent tonumber[6], so you're getting the address that's six integers away fromnumber.  Since number is0and anintis 4 bytes long, the result is24.


Question:
What must this code segment return ? 16 16 16 right ?

```
int main(int argc,char *argv[])
{
   int a=2,*f1,*f2;
   f1=f2=&a;
   *f2+=*f1+=a+=2.5;
   printf("%d %d %d\n",a,*f1,*f2);
   return 0;
}
```

strangely, it returns 8 8 8 to me ???? :-(

Answer: For an actual understanding of the issue here trycomp.lang.c FAQarticle onsequence points.


Question:
I always find that some people (a majority from India) are using turbo C.
I cannot find any reason to use such outdated compiler...
But I don't know what reasons to give when trying to tell them to use modern compiler(gcc,msvc,...).

Answer: Turbo C is a DOS only product. This means that it no longer runs "natively" on 64-bit versions of Windows, and must be run inside the XP compatibility penalty box.


Question:
I have a string in the following format:
"R:  625.5m E:-32768m"

What's the most efficient way to pull out the 625.5?

Answer:
Your best bet is to usesscanfto read formatted information from the string.

```
sscanf(mystr, "R: %f", &myFloat);
```


Question:
I always find that some people (a majority from India) are using turbo C.
I cannot find any reason to use such outdated compiler...
But I don't know what reasons to give when trying to tell them to use modern compiler(gcc,msvc,...).

Answer: Turbo C is a DOS only product. This means that it no longer runs "natively" on 64-bit versions of Windows, and must be run inside the XP compatibility penalty box.


Question:
I have a string in the following format:
"R:  625.5m E:-32768m"

What's the most efficient way to pull out the 625.5?

Answer:
Your best bet is to usesscanfto read formatted information from the string.

```
sscanf(mystr, "R: %f", &myFloat);
```


Question: Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of aTreeView, but is it available for general widgets?

Answer:
For C/C++:gtk_widget_set_size_request()

Sets the minimum size of a widget; that is, the widget's size request will be width by height.

PyGTK:def set_size_request(width, height)


Question:
I'm not even sure what sliding average is, but someone told me it would help with something I'm working on.

I have a table of random values --table[n] = random(100) / 100

I need to populatetable2with their sliding averages.

I think this is the terminology. Let me know if it doesn't make sense.

Answer: TheMoving averageentry on Wikipedia might be a good start.


Question:
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and  cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.

Can I work with Begali charachters(non ASCII) in C?

Answer: Absolutely. Look into libiconv or ICU.


Question:
How to read command line inputs using a C program.by command line inputs, I don't mean command line arguments!!

example:
* I have a text file 'inputfile.txt' with few lines of names.* Assume my program name is names.exe.* I have to run the program using windows command line using following command:c:>names.exe < inputfile.txt

Thanks.

Answer: Read from thestdinFILE*.


Question:
This function definition is found here.:

```
static void (*resolve_memcpy (void)) (void)
{
    return my_memcpy; // we'll just always select this routine
}
```

I don't understand what it means.

Answer:
resolve_memcpy is a function taking no arguments and returning a pointer to a function taking no arguments and returning void.

EDIT: Here's a link where you can read more about this kind of syntax:http://unixwiz.net/techtips/reading-cdecl.html


Question: As the title says, I always wonder whyscanfmust take theaddress ofoperator (&).

Answer: Because C only has "pass-by-value" parameters, so to pass a 'variable' to put a value into, you have to pass its address (or a pointer to the variable).


Question: There are 2 servers, they need to know the status(live oe dead) each other. my method is a long tcp connecting, Is there any better method? thanks.

Answer: I`m no sysadmin, but why not simply use nmap or the likes to check if the ports your servers are listening on are still open? I mean, you simply want to know if they are alive or dead, right? When one of your server crashes, the port shouldn´t be open anymore.


Question:
Can you please point me to library(ies) for face detection (NO RECOGNITION NEEDED!)?
Any good-working libraries except OpenCV(!!!).
Preferably free of charge - open source is not required.

Answer:
What bothers you about OpenCV? Their API or something else?

There islibfacewhich is an opencv wrapper for face detection and recognition.


Question: Why the range of signed character is-128to127but not-127to128?

Answer:
That is because of the waytwo's complementencoding works: 0 is treated as a "positive" number (signed bit off), so, therefore, the number of available positive values is reduced by one.

Inones' complementencoding (which is not very common nowadays, but in the olden days, it was), there were separate values for +0 and -0, and so the range for an 8-bit quantity is -127 to +127.


Question:
The C99 standard describes them as so:

The integer and real floating types
  are collectively called real types.Integer and floating types are
  collectively called arithmetic types.

Does this mean they're the same thing in C? Or are there any differences between them?

Answer: Complex types are arithmetic types, but not real types.


Question:
I was wandering how could capture video from the built-in camera of my netbook, under Linux, ubuntu. The programming language could is not an issue (but I prefer Java or the old school c)

Thanks in advance for your answers,
Gian

Answer: You can look into OpenCV, for C/C++. It is very powerful.


Question:
I want to add a C file into my .NET application.

How can I built this?
How can i write unmanaged code in C#.
Can someone explain with few lines code.

Thanks

Answer:
You either have to build the C file into it's own DLL and thenuse P/Invokein your C# code to call them or...

You could also try to port the C code to C# which would give you a completely managed codebase.


Question:
I want to add a C file into my .NET application.

How can I built this?
How can i write unmanaged code in C#.
Can someone explain with few lines code.

Thanks

Answer:
You either have to build the C file into it's own DLL and thenuse P/Invokein your C# code to call them or...

You could also try to port the C code to C# which would give you a completely managed codebase.


Question:
WHen specifying library_dirs in a Python distutils.core.Extension I get this error when trying to build:

```
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py:263: UserWarning: Unknown distribution option: 'library_dirs'
  warnings.warn(msg)
```

Why is this? I am using Python 2.5 on Mac OS X.

Answer: The error means you're not passinglibrary_dirstodistutils.core.Extension, but to thedistutils.core.setupfunction.


Question:
I have a program that generates a variable amount of data that it has to store to use later.
When should I choose to use mallod+realloc and when should I choose to use temporary files?

Answer: mmap(2,3p)(orfile mappings) means never having to choose between the two.


Question:
I had found a strange output when I write the following lines in very simple way:

Code:

```
printf("LOL??!\n");
 printf("LOL!!?\n");
```

Output:

It happens even the code is compiled under both MBCS and UNICODE.

The output varies on the sequence of "?" and "!"...

Any idea?

Answer:
??!is atrigraphthat gets replaced by|.

As a rule, you should never place two question mark characters together anywhere in a source file.


Question:
I have come across a few lines of coding I do not understand, and would be grateful for clarification:

if(!(counter&7))ds->direction = ts->direction;

Answer: ifcounteris a multiple of 8set thedirectionelement of*dsequal to thedirectionelement of*ts


Question:
Is there a C library available for operations such as file operations, getting system information and the like which is generic, which can be used when compiled in different platforms and which behaves in a similar way?

Edit: Something like Java or .NET platform abstracting the hardware.

Answer: Have you tried the standard library? It should be implemented on any system that has an ISO compliant C runtime.


Question:
I have a XML document which is received as a character stream. I wish to parse this using libxml2. Well one way would be to save it as an .xml and then open it using one of the libxml2 API's. Is there a way i can directly build a tree on this stream and parse it ?

Env is purely c++/c.

Cheers!

Answer: You can usexlmCtxtReadFdfrom parser.h. There's alsoxmlCtxtReadMemory, if you would rather use a block of memory than a stream.


Question:
I had found a strange output when I write the following lines in very simple way:

Code:

```
printf("LOL??!\n");
 printf("LOL!!?\n");
```

Output:

It happens even the code is compiled under both MBCS and UNICODE.

The output varies on the sequence of "?" and "!"...

Any idea?

Answer:
??!is atrigraphthat gets replaced by|.

As a rule, you should never place two question mark characters together anywhere in a source file.


Question:
I can attach a file with libesmtp?

Does anyone have a sample code?

Thanks

FrankIT

Answer: No.  The library only covers the SMTP protocol, the communication with the server.  It does nothing to help you construct a valid MIME document.


Question:
What is the proper way to name my revisions?

```
v1.0.3.20 Alpha
```

or

```
Alpha v1.0.3.20
```

Answer:
There isn't really any "proper" way. While most people use the dot pattern "x.x.x", it isn't necessarily the proper way to do it. Likewise with your question, it is up to you.

I would suppose that the former is more natural to say, and I would prefer it, but it doesn't really matter either way.


Question:
I was wondering how to, using C, find out what port a client is currently listening to. ie, I want to know what the source port is, not the destination port.

Thanks in advance!

Answer: The socket address structure should be filled-in by the connect() system-call. Check it after a successful return from that call.


Question:
I can attach a file with libesmtp?

Does anyone have a sample code?

Thanks

FrankIT

Answer: No.  The library only covers the SMTP protocol, the communication with the server.  It does nothing to help you construct a valid MIME document.


Question:
What is the proper way to name my revisions?

```
v1.0.3.20 Alpha
```

or

```
Alpha v1.0.3.20
```

Answer:
There isn't really any "proper" way. While most people use the dot pattern "x.x.x", it isn't necessarily the proper way to do it. Likewise with your question, it is up to you.

I would suppose that the former is more natural to say, and I would prefer it, but it doesn't really matter either way.


Question:
I was wondering how to, using C, find out what port a client is currently listening to. ie, I want to know what the source port is, not the destination port.

Thanks in advance!

Answer: The socket address structure should be filled-in by the connect() system-call. Check it after a successful return from that call.


Question: Is there a way to find out if the machine is 32-bit or 64-bit by writing some code in C?

Answer:
```
#include <limits.h>
/* ... */
printf("This machine's pointers to void, in a program "
       "compiled with the same options as this one and "
       "with the same compiler, use %d bits\n",
    (int)sizeof (void*) * CHAR_BIT);
```


Question: Is it possible to change a process parent?ex: parent A has Child B can I make the parent of B is the Init process without killing A?

Answer:
Not from outside of process B.

From inside process B, you can call fork which makes a copy of your process, then let the original exit.  When that happens the new copy B2 will not be a child of A, its parent will be set to 1 (the init process).


Question: I don't want to use system() in my C program, because system(3) blocks and this is not what I want. What is the optimal way to do it?

Answer: I think that a quick and dirty action is to call sytem(command &). the & will spawn the new process.


Question:
What is the fastest way to count lines and words in a text file in pure ANSI C?

A word is terminated by a space or period. Line is terminated by'\n'.

This seems to be in C++.

Answer: Read the file inIterate over charactersincrement character counterCheck if space/end of lineincrement word counterRepeat second and third steps untilEOF


Question: Can I call another function in a thread runner function, called by apthread_create()? Are there any restrictions on such functions?

Answer: Yes, you can (and doing so is fairly frequent). The main restriction is that you need to synchronize threads when two or more access the same data (at least if there's any chance that any of them might modify that data).


Question:
I'm wondering what sort of algorithm could be used to take something like "4.72" into a float data type, equal to

```
float x = 4.72;
```

Answer:
scanf,operator>>for istreams, andstrtofwould be the obvious choices.

Thereisalsoatof, but, likeatoi, it lacks a way to tell you there was an error in the input, so it's generally best to avoid both.


Question:
I've wrote CGI script for www.

This script expects two parameters through GET method, multiply these numbers and write result into the file.

```
mult.cgi?m=1&n=2
```

But now I want to use this script from console too.
I'tried something like

```
./mult.cgi?m=1&n=2
```

But it didnt work, how can I send parameters to script?

thanks.

Answer:
```
QUERY_STRING="m=2&n=4" ./mult.cgi
```


Question: Can anyone give me an example of a Java program which has two native methods declared and defined in C and C++. Actually, I need a procedure as well as the code, so that I can run it and learn from it, thanks.

Answer:
You can do it with JNI  [Java Native Interface]

Check this tutorial WIN env

LinuxEnvironment :-) better one


Question:
I've wrote CGI script for www.

This script expects two parameters through GET method, multiply these numbers and write result into the file.

```
mult.cgi?m=1&n=2
```

But now I want to use this script from console too.
I'tried something like

```
./mult.cgi?m=1&n=2
```

But it didnt work, how can I send parameters to script?

thanks.

Answer:
```
QUERY_STRING="m=2&n=4" ./mult.cgi
```


Question: Can anyone give me an example of a Java program which has two native methods declared and defined in C and C++. Actually, I need a procedure as well as the code, so that I can run it and learn from it, thanks.

Answer:
You can do it with JNI  [Java Native Interface]

Check this tutorial WIN env

LinuxEnvironment :-) better one


Question: I want to forward packets by netfilter, so I want to get some c demos to get start, thanks

Answer:
Did you look at thenetfiltersite? The documentation seems a bit dated, but there's a "Linux netfilter Hacking HOWTO" there.

Then play with thesource:)


Question:
What packages do i need to install in order to use a Makefile. I've already installed cmake, would i need ocamlmakefile?
My problem is that whenever i type 'make' into the terminal, i'm told "make command not found".

Answer:
You need GNU make.

CMake and other make programs use other filenames generally.


Question:
Addresses of 1d arrays are actually taken as

```
a[i]=*(a+i);
```

Are the addresses of 2d arrays calculated as

```
a[i][j]=**(a+i+j);
```

Answer:
The other answers are not quite correct.  It's more like:

```
*(*(a+i)+j)
```


Question:
I've never worked with a language that didn't provide for some form of memory management, and thus managed to get by without ever really groking pointers.

I can dabble inCI guess, as a result of coding inObjective-Cfor a little while.

Answer:
Hmmm, maybe it's the single linked list.

Try it:create, populate, reverse, releasea single linked list

```
struct node {
    int data;
    struct node *next;
};
```


Question:
I've never worked with a language that didn't provide for some form of memory management, and thus managed to get by without ever really groking pointers.

I can dabble inCI guess, as a result of coding inObjective-Cfor a little while.

Answer:
Hmmm, maybe it's the single linked list.

Try it:create, populate, reverse, releasea single linked list

```
struct node {
    int data;
    struct node *next;
};
```


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

Possible Duplicate:“C subset of C++” -> Where not ? examples ?

I'm aware that C++ is not a strict superset of C. What language features prevent C++ from being a superset of C?

Answer:
The elephant in the room: the following is valid C but not valid C++.

```
int typename = 1;
```

Substitute your favorite C++ reserved word.


Question:
```
size_t pixelsWidth = (size_t)bitmapSize.width;
```

Or is it totally fine to do without the casting to size_t? bitmapSize is of type CGSize...

Answer: You should use the proper type, which is probably CGFloat. size_t is something int'ish and inappropriate.


Question:
What libraries for C do I need to play a wav file on a Win32 system?

And what is the code to use those libraries?

Answer:
Use the Win32 API:PlaySound

Include library:Winmm.libHeader include:Mmsystem.h(includeWindows.h)Example:

```
PlaySound(TEXT("recycle.wav"), NULL, SND_FILENAME);
```


Question: e.g. one has a couple of arrays of ints or floats and a few integers to store. Is there a simplistic way to save them for later reloading without having to write a data format from scratch etc.?

Answer:
netcdf (simpler interface)hdf5 (more powerful)

they are not simple, however few hours investment is worth it


Question: My professor and a couple of students are arguing about whetherargvis null terminated or not. My friend wrote a small program and it printed outnullbut another kid said that he is probably simply reading into blank memory. Can someone solve this discussion?

Answer:
From the Standard:

5.1.2.2.1  Program startup...-- argv[argc] shall be a null pointer.

So, yes; argv is null terminated


Question: That is, why doesunsigned short var= L'ÿ'work, butunsigned short var[]= L"ÿ";does not?

Answer: L'ÿ'is of typewchar_t, which can be implicitly converted into anunsigned short.L"ÿ"is of typewchar_t[2], which cannot be implicitly converted intounsigned short[2].


Question:
For debugging reasons, how can one in a C program print some memory address?

For instance, how should I do to print the content of address 0x611268 in form of a 4 byte float?

I know I could use a debugger, but I mean, to print out in screen.

Answer:
More correctly,printf("Value = %f\n", *((float*)0x611268));

Of course this assumes the address you've given is in the address space of the process running theprintf.


Question:
How can I generate a random boolean with a probability ofp(where 0 <= p <= 1.0) using the C standard libraryrand()function?

i.e.

```
bool nextBool(double probability)
{
    return ...
}
```

Answer:
```
bool nextBool(double probability)
{
    return (rand() / (double)RAND_MAX) < probability;
}
```

or (after seeing other responses)

```
bool nextBool(double probability)
{
    return rand() <  probability * ((double)RAND_MAX + 1.0);
}
```


Question:
Is it posible to use the type of a prefiously declared function as a function pointer without using a typedef?

function declaration:

```
int myfunc(float);
```

use the function declaration by some syntax as function pointer

```
myfunc* ptrWithSameTypeAsMyFunc = 0;
```

Answer:
Not as per the 2003 standard. Yes, with the upcoming C++0x standard and MSVC 2010 and g++ 4.5:

```
decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0;
```


Question: I wish to profile CPU (sample if possible), with as small a performance impact as possible (hence similar to GCC's-pg), binaries compiled with Clang. Is there an alternative that uses instrumentation of the code, or produces output similar to gprof?

Answer: I received agood answeron theClang mailing list. To summarize, the use ofGoogle Performance Toolswas the best fit.


Question:
I have a loop as follows

```
while(1)
{
    int i;
}
```

Doesiget destroyed and recreated on the stack each time the loop occurs?

Answer:
Theoretically, it gets recreated. In practice, it might be kept alive and reinitalized for optimization reasons.

But from your point of view,it gets recreated, and the compiler handles the optimization (i.e, keep it at it's innermost scope, as long as it's apodtype).


Question:
I have an IP address stored inin_addr_tand I want to create the corresponding string representation of this data type (e.g.in_addr_tto10.0.0.1).

How can I do that?

Answer: Useinet_ntop()- convert IPv4 and IPv6 addresses from binary to text form.


Question: Suppose you have a string which is NOTnullterminated and you know its exact size, so how can you print that string withprintfin C? I recall such a method but I can not find out now...

Answer:
There is a possibility with printf, it goes like this:

```
printf("%.*s", stringLength, pointerToString);
```

No need to copy anything, no need to modify the original string or buffer.


Question: is there any nice GNU way how to measure average (worst case, best case) execution time of some command line program? I have image filter, unspecified amount of pictures, filtering them using for-loop in bash. So far I am usingtime, but I can't find a way how to get some statistics.

Answer:
You can send the output of time to some file, and then "work" that file

```
echo "some info" >> timefile.txt
time ( ./yourprog parm1 parm2 ) 2>> timefile.txt
```


Question:
While debugging a C program in Visual Studio 2008, is it possible somehow to get the size of variables (in bytes)?

P.D. Of course I can print sizeof(var) for each of them

Answer: You can use theImmediate Windowto evaluatesizeof(...)or any other expression while debugging.


Question: I am starting to learn to debug C programs with Visual Studio 2008. When running in debug mode, how is it possible to know the address of a initialized variable? I choose to watch it but can only know about the value. Thanks

Answer: You can type in a&in front of the variable, which will display it's address.


Question:
i m looking for a bayesian network library that work on the iphone.
any tip ?

Answer: I've never used it, but there's one on Github called BayesianKit:https://github.com/lok/BayesianKit


Question:
Could not find a direct answer to this anywhere. Can someone shed some lights.
Thanks.

Answer: There's no such command built into the language. Sockets need to be used but they are platform dependent.


Question:
I'm writing a program to read a file and display the number of lines and words in said file, simple stuff. What I want is to be able to run the program from terminal (running Ubuntu) by simply typing:

count

But I'm not sure how to get the filename into a variable in the C program. Little help please?

Thanks in advance.

Answer: I think you are looking forargv.


Question:
iOS /  Objective-C: I have a large array of boolean values.

This is an inefficient way to store these values – at least eight bits are used for each element when only one is needed.

How can I optimise?

Answer: see CFMutableBitVector/CFBitVector for a CFType option


Question:
i m looking for a bayesian network library that work on the iphone.
any tip ?

Answer: I've never used it, but there's one on Github called BayesianKit:https://github.com/lok/BayesianKit


Question:
Could not find a direct answer to this anywhere. Can someone shed some lights.
Thanks.

Answer: There's no such command built into the language. Sockets need to be used but they are platform dependent.


Question:
I'm writing a program to read a file and display the number of lines and words in said file, simple stuff. What I want is to be able to run the program from terminal (running Ubuntu) by simply typing:

count

But I'm not sure how to get the filename into a variable in the C program. Little help please?

Thanks in advance.

Answer: I think you are looking forargv.


Question:
iOS /  Objective-C: I have a large array of boolean values.

This is an inefficient way to store these values – at least eight bits are used for each element when only one is needed.

How can I optimise?

Answer: see CFMutableBitVector/CFBitVector for a CFType option


Question:
I am just doing a little work this morning making some static libraries. Why do static libraries end with '.a'?

No one in my office knew, so I thought I would ask around on Stack Overflow. We are writing code in C++, C, and Objective-C.

Answer: I think the .a convention comes from using an "archiver" to place the object files into a static library.


Question:
How can i make that the console, with the output, will not disapear after the program ends in VS 2010 express C++?

i write in c and not in c++, soo i need a function and include path to library.

Thanks

Answer: You can simply poll for input. This performs a block so that the function only returns when the user gives more input - usually enter. If you're on Windows you can also use system("PAUSE").


Question: How to Generate the random number from 0.5 to 1.0 .

Answer:
You can try:

```
float RandomBetween(float smallNumber, float bigNumber)
{
    float diff = bigNumber - smallNumber;
    return (((float) rand() / RAND_MAX) * diff) + smallNumber;
}
```


Question:
I  could see from MSDN documentations that a new windows service will be stored in the registryHKLM\System\CurrentControlSet\Services

However the services registry key does not hold a value for the "service running status"
Can anyone let me know where the service running status will be stored?

Answer: The service running status is not stored in the registry - it's a runtime property which you can query withControlService()service management function.


Question: How can I make a copy of a tree data structure in memory to disk in C programming language?

Answer:
You need to serialize it, i.e. figure out a way to go through it serially that includes all nodes. These are often calledtraversal methods.

Then figure out a way to store the representation of each node, together with references to other nodes, so that it can all be loaded in again.

One way of representing the references is implicitly, by nesting like XML does.


Question:
which visual studio project type should i choose that will best for  c basic library(uni studies).

the problem in visual studio 2010 express that its gives _tmain instead int main().

Thanks

Answer:
I usually select "Win32 Console Application" and then "Empty project". Add a new source file and type in the main() by hand.

I have no idea what R is talking about with his absurd comment.


Question: Under Linux what would be the best way for a program to restart itself on a crash by catching the exception in a crashhandler (for example on a segfault)?

Answer:
simplest is

```
while [ 1 ]; do ./program && break; done
```

basically, you run program until it is return 0, then you break.


Question: I am working on a C project and can not figure out how to pass command line arguments to my main function in Visual Studio 2010 Express Edition. I want to debug - how do these command line arguments work?

Answer: Right click your project in Solution Explorer and select Properties from the menuGo to Configuration Properties -> DebuggingSet the Command Arguments in the property list.


Question: In C, can I say a white space in a string has a NULL type, or something else?In C, which character represents the termination of a string?

Answer:
Thenull character(ASCII value 0,'\0'as a character literal) terminates a string in C. This character isnotusually regarded as a whitespace character.

The space in the middle of this string for example:"Hello world"is the character with ASCII value 32. This is not the same as NULL or\0.


Question:
which visual studio project type should i choose that will best for  c basic library(uni studies).

the problem in visual studio 2010 express that its gives _tmain instead int main().

Thanks

Answer:
I usually select "Win32 Console Application" and then "Empty project". Add a new source file and type in the main() by hand.

I have no idea what R is talking about with his absurd comment.


Question: Under Linux what would be the best way for a program to restart itself on a crash by catching the exception in a crashhandler (for example on a segfault)?

Answer:
simplest is

```
while [ 1 ]; do ./program && break; done
```

basically, you run program until it is return 0, then you break.


Question: I am working on a C project and can not figure out how to pass command line arguments to my main function in Visual Studio 2010 Express Edition. I want to debug - how do these command line arguments work?

Answer: Right click your project in Solution Explorer and select Properties from the menuGo to Configuration Properties -> DebuggingSet the Command Arguments in the property list.


Question: In C, can I say a white space in a string has a NULL type, or something else?In C, which character represents the termination of a string?

Answer:
Thenull character(ASCII value 0,'\0'as a character literal) terminates a string in C. This character isnotusually regarded as a whitespace character.

The space in the middle of this string for example:"Hello world"is the character with ASCII value 32. This is not the same as NULL or\0.


Question: Dolfind/lsearchperform better than a typical looping solution that checks each item until it matches? Is there any special sauce/reason that these functions exist?

Answer:
Probably they are not more efficient that a homebrew version, maybe even a bit less since the comparison function can't be inlined.

But this is certainly not the point with them. They complete the API of the other search functions, in particularbsearchandtsearch.


Question: Dolfind/lsearchperform better than a typical looping solution that checks each item until it matches? Is there any special sauce/reason that these functions exist?

Answer:
Probably they are not more efficient that a homebrew version, maybe even a bit less since the comparison function can't be inlined.

But this is certainly not the point with them. They complete the API of the other search functions, in particularbsearchandtsearch.


Question: I would like to have a function written in C, but callable from C++ which takes a restricted pointer. This is only available in c99, so g++ doesn't like it, even inextern "C"blocks. How can I get around this limitation?

Answer:
```
#ifdef __cplusplus
#   ifdef __GNUC__
#       define restrict __restrict__ // G++ has restrict
#   else
#       define restrict // C++ in general doesn't
#   endif
#endif
```


Question:
I read that pointers passed by malloc() & calloc() get allocated memory dynamically from the heap.

```
char *Name="Ann";
```

In this case, is the static string {'A','n','n','\0'} also stored in the heap?Can I modify the string using the pointer?

Answer: No, the string is allocated statically. (C99, §6.4.5/5)Attempting to modify a string literal gives undefined behavior. (§6.4.5/6)


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

Possible Duplicate:How do you set, clear and toggle a single bit in C?

Can some one help me how to toggle a bit at ith position.
One way is to do((n>>i) ^ 1) << i. Are there any other ways ?

Answer: n ^= 1U << iis easy enough, isn't it?


Question:
in a C program I need to define

```
float (*d_i)[3];
```

but later I realized that I need to define NMAX variables of this type. I tried with

```
float (*d_i)[3][NMAX];
```

but it does not work.

what would be the right syntax?

Thanks

Answer:
Don't guess. Just use atypedef.

```
typedef float (*someType)[3];

someType d_i[NMAX];
```

(In case you really don't want thetypedef,

```
float (*d_i[NMAX])[3];
```

)


Question:
I have a C code written. When I compile it on Linux then in the header file it says the
following error:storage class specified for parameter i32 , i8and so on

```
typedef int i32;

typedef char    i8;
```

Answer: Chances are you've forgotten a semicolon in a header file someplace.  Make sure each line ends in;


Question:
in a C program I need to define

```
float (*d_i)[3];
```

but later I realized that I need to define NMAX variables of this type. I tried with

```
float (*d_i)[3][NMAX];
```

but it does not work.

what would be the right syntax?

Thanks

Answer:
Don't guess. Just use atypedef.

```
typedef float (*someType)[3];

someType d_i[NMAX];
```

(In case you really don't want thetypedef,

```
float (*d_i[NMAX])[3];
```

)


Question:
I have a C code written. When I compile it on Linux then in the header file it says the
following error:storage class specified for parameter i32 , i8and so on

```
typedef int i32;

typedef char    i8;
```

Answer: Chances are you've forgotten a semicolon in a header file someplace.  Make sure each line ends in;


Question: Is there such a thing as Javadoc-type documentation available for C/C++ libraries?

Answer:
Yes,doxygenfor documenting your code.

If you mean documentation of existing libraries :

For the STL, check out thesgisite.

For a general c/ c++ reference seehere.

For a specific library, check its site.


Question: I am writing a program in C for file compression. The method i am trying to use involves doing math on the file as if it were one long number. Can anyone recommend a bignum library that would not try to do all of that in ram, but rather let me do math with file pointers. any help would be appreciated, thanks in advance.

Answer: I doubt such a library exists. You could try mmap()ing the files in memory and see if you can do it that way.


Question: Does a quine print the ACTUAL code of the program i.e not obfuscated or does it print the obfuscated program?

Answer: I don't think obfuscation has anything to do with it. Usually a quine prints the actual source code of the program itself.


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

Possible Duplicate:How would you set a variable to the largest number possible in C?

Can we find the maximum size of a data type in C langauge?

Answer:
If you want to know the maximum and minimum values you can store in a variable of a given data type, you can check with  these different constants:

LONG_MIN, LONG_MAX, seehere, for the rest.


Question:
I need to kill such user processes that are taking longer time than a said expected interval on UNIX (Solaris) operating system. This needs to be done inside the process that is currently being executed.

Please suggest how this can be achieved in C or in UNIX?

Answer: See thealarm()system call.  It provides you with aSIGALRMsignal which your process can handle, and use to quit.


Question: I'm looking for an R-Tree implementation, in C, Objective-c and even C++, which shall be efficient for searching the 2d rectangle in which a point falls ( memory efficiency would also be great, but I can sacrifice a bit more memory for time even while I am on an iPhone ). A good documentation will be appreciated too

Answer: Check outthis page, it provides implementations (in C, C++, Java, etc.) for several variants (R*, R+, etc.).


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

Possible Duplicate:How would you set a variable to the largest number possible in C?

Can we find the maximum size of a data type in C langauge?

Answer:
If you want to know the maximum and minimum values you can store in a variable of a given data type, you can check with  these different constants:

LONG_MIN, LONG_MAX, seehere, for the rest.


Question:
I need to kill such user processes that are taking longer time than a said expected interval on UNIX (Solaris) operating system. This needs to be done inside the process that is currently being executed.

Please suggest how this can be achieved in C or in UNIX?

Answer: See thealarm()system call.  It provides you with aSIGALRMsignal which your process can handle, and use to quit.


Question: I'm looking for an R-Tree implementation, in C, Objective-c and even C++, which shall be efficient for searching the 2d rectangle in which a point falls ( memory efficiency would also be great, but I can sacrifice a bit more memory for time even while I am on an iPhone ). A good documentation will be appreciated too

Answer: Check outthis page, it provides implementations (in C, C++, Java, etc.) for several variants (R*, R+, etc.).


Question:
I have written a source code with a time delay.In unix I have used the

#include <unistd.h>header file andusleepfunction.

What is the equivalent to this on windows?

What library and function should I use if I write the same code on windows.

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

and

```
::Sleep( 1000 /* milliseconds */ );
```


Question:
I see a lot of templates and complicated data structures for implementing a circular buffer.

How do I code a simple integer circular buffer for 5 numbers?

I'm thinking in C is the most straightforward?

Thanks.

Answer:
Have an array,buffer, of 5 integers.  Have an indexindto the next element.  When you add, do

```
buffer[ind] = value;
ind = (ind + 1) % 5;
```


Question: How to complete disable Drag'n Drop from a GtkEntry ?

Answer: I'd discovered that if you set the propertygtk-dnd-drag-thresholdto a value larger than the screen size, it will block the DnD for the whole application.


Question: C parent program does some processing and allocates memory, then calls execvp(). What will happen with all the allocated but not freed memory? Is it automatically freed or stays as a garbage?

Answer: exec*()replaced the memory of the old process completely with the new program. This includes all allocated memory, so there is no garbage staying behind. But note that other resources like file descriptors are not automatically freed or closed.


Question: i'm looking for a ready-made grammar and parser for php (at least 5.2), ideally an utility/library that can parse php code into a readable AST, e.g. xml. The parser itself doesn't have to be written in php, the source language doesn't matter much.

Answer:
To answer my own question I've managed to compilephcon my OSX box, the parser part seems to work well

```
phc --dump-xml=ast foo.php > bar.xml
```

creates an xml representation of the AST.


Question:
Question is simple, i have a object file and i want to read the symbols of the object file via code.  I am aware that the linux command "nm" would be able to do this, but i want to be able to do it inside code.

Also note id like to do this either via C or Python.

Regards

Paul

Answer:
It would be nice to provide more details.

For some pointers:

http://sourceforge.net/projects/python-elf/http://www.grant-olson.net/python/pyasm


Question:
```
#define int_p int*
int_p p1,p2,p3; // only p1 is a pointer !
```

can somebody exlplain why it is so.

Answer:
#defineis just a textual substitution. The code above is equivalent to

```
int *p1, p2, p3;
```

so onlyp1is a pointer. You need

```
typedef int* int_p;
```

instead.


Question:
I need to do the following equation floor(e%100000) where e is a double. I know mod only accepts int values, how do I go about achieving this same result?

Thanks

Answer: Use thefmod()function instead of%. It acceptsdoubleparameters, and returns adoubleresult.


Question: I am looking for a way to make a program in C or C++ that detects if there was any files altered, renamed, moved or deleted in a specified directory for Linux systems. Is there a way to do that?

Answer: You wantinotify(and itsman page.)


Question:
Given

```
struct S {
  SomeType single_element_in_the_struct;
};
```

Is it always true that

```
sizeof(struct S) == sizeof(SomeType)
```

Or it may be implementation dependent?

Answer:
This will usually be the case, but it's not guaranteed.

Any struct may have unnamed padding bytes at the end of the struct, but these are usually used for alignment purposes, which isn't a concern if you only have a single element.


Question: I thought I read about a C standard library function recently that was able to return a pointer to any extern variable whose name was passed to it as a const char *.  I think that it works via linker symbols, if that helps.

Answer: You could be thinking ofdlsym, which is not part of the C standard library but part of the POSIX API.


Question: Can someone please point me to some documentation on the virtual memory maps used for Linux and Windows. By that I mean what virtual addresses, code, writable static data, the stack and the heap (along with other kernel bits) will normally be placed in, in a typical process?

Answer: Since the advent of ASLR, it's mostly on random virtual addresses.


Question:
```
#include<stdio.h>

void f(void)
{
    int s = 0;
    s++;
    if(s == 10)
        return;
    f();
    printf("%d ", s);
}
int main(void)
{
    f();
}
```

what is the output of the programme!??
i m segmentation fault ...what is it?

Answer: Sincesis a local variable, each recursive call tof()gets its own copy of it. So every timeswill be 1 and the you get a stack overflow exception.


Question:
I have a test program which prompts for input from user(stdin), and depending on inputs, it asks for other inputs, which also need to be entered.

is there a way I can have a script do all this work ?

Answer: There's a program calledexpectthat does pretty much exactly what you want -- you can script inputs and expected outputs and responses based on those outputs, as simple or complex as you need.  See also thewikipedia entryfor expect


Question:
What's the equivalent to Windows'sVirtualAllocin OS X? That is, how can i reserve a contiguous address space without actually commiting it and then commit chunks of it later?

Thanks,

Alex

Answer: Themmap()function, called withMAP_ANON | MAP_PRIVATE, is very roughly equivalent toVirtualAlloc()with theMEM_RESERVEflag.  Memory is then committed by touching each page in the mapping.


Question:
How do I use pow() and sqrt() function in Ubuntu?
I have included the math.h header file but it still gives me an error.

Answer: Try adding-lmto your linker command. Most of the math functions live inlibmwhich needs to be explicitly linked in.


Question:
I want to find out for how long (approximately) some block of code executes. Something like this:

```
startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);
```

How?

Answer:
You can use theclockmethod intime.h

Example:

```
clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
```


Question: I am new to writing programs in c++ and i want to know if there is a way to export it to a windows format. Also what is a good way to learn objective-c, is it very different from c++? Thank you in advance.

Answer: Using mingw32 you can cross compile for windows. Seehttp://www.mingw.org/wiki/LinuxCrossMinGW


Question: If I do*ptr[x], is that equivalent to*(ptr[x]), or(*ptr)[x]?

Answer:
*(ptr[x])

See theWikipedia operator precedence table, or, for a more detailed table,this C/C++ specific table.


Question: What is the difference between C & C# on the basis of OOP concepts?

Answer: The difference is in the support of those OOP concepts. C does not support OOP concepts while C# does.


Question: I have binary array in c, I want to compress the array, kindly suggest me algorithm which compress binary array. I have used Lempel–Ziv–Welch (LZW) algorithm but its not suitable for me because there is no repetition in my data.

Answer:
Why not just to use thelibz'sdeflate? As added bonus, libz is available on pretty much every existing platform.

Or newerLZMA? It beats thebzip2on binary data compression.


Question: I have binary array in c, I want to compress the array, kindly suggest me algorithm which compress binary array. I have used Lempel–Ziv–Welch (LZW) algorithm but its not suitable for me because there is no repetition in my data.

Answer:
Why not just to use thelibz'sdeflate? As added bonus, libz is available on pretty much every existing platform.

Or newerLZMA? It beats thebzip2on binary data compression.


Question: I have binary array in c, I want to compress the array, kindly suggest me algorithm which compress binary array. I have used Lempel–Ziv–Welch (LZW) algorithm but its not suitable for me because there is no repetition in my data.

Answer:
Why not just to use thelibz'sdeflate? As added bonus, libz is available on pretty much every existing platform.

Or newerLZMA? It beats thebzip2on binary data compression.


Question: What does the code(10%2)mean?

Answer:
%is themodulusoperator.

So this essentially says - what is the remainder of 10 divided by 2?

```
10 % 2 == 0
10 % 5 == 0
10 % 7 == 3
10 % 3 == 1
```


Question:
I need to print this value as a time string to Mon 16-Aug-2010 06:24 format or something similar.

```
unsigned int t = 1281920090;
```

Answer:
You can use the functionsgmtimeandasctimeas:

```
#include <stdio.h>
#include <time.h>

int main() {
        time_t timestamp = 1281920090;
        printf("%s", asctime(gmtime(&timestamp)));
        return 0;
}
```

Output:

```
$ gcc a.c && ./a.out
Mon Aug 16 00:54:50 2010
```


Question:
Hallo,

I'm looking for a really simple and easily hackable tar library for C or C++. Ideally it should have a permissive license (BSD/LGPL) and not have a ton of Unix/Windows OS dependencies, as I plan to use it from an embedded RTOS...

Any ideas?

Answer: I haven't used it myself, but have you triedlibtar? It is written in C and BSD licensed.


Question:
Is there a built in function to convert ints to Big-endian or little-endian for sending over the network? like htonl and ntohl in c

Also, is there something similar to strings, datetime, etc..

Thanks

Answer: Java streams use network byte order. That means you only have to worry about things likehtonlandntohlin C and it ilk.


Question: how does a call from c++ to c work internally??

Answer: The C++ compiler 'does the right thing' and uses the correct calling convention for the C function - a lame sounding answer but I don't know that there's much more that can be said!


Question:
In applications like Adobe Illustrator, they have a way to simplify a path. I'm not sure how this works exactly. Given a path with points which have 2 bezier handles each (for cubic bezier), how could I go about simplifying the path?

Thanks

Answer: Look atDouglas–Peuckerit is an algorithm for reducing the number of points in a curve that is approximated by a series of points. It is frequently used in GIS solutions.


Question:
hello i got a problem with returning an array of linklists in c
lets say i got

arrlinklist = {linklist1 , linklist 2...,linklist5}

and i want my function to return arrlinklist.
how do i do that... thx in advance.

i wanted to know how to define the signature of my function
i tried
linkedlist* CreateArrayOfList();

Answer: In C you cannot return an array, you can only return a pointer to the first element of the array.


Question: im porting c code to windows 32 bit using visual studio expressnow i have 3 functions that i can't find any alternatives in windowsthey are:alarmbzerobcopywhat are the equivalent methods in C win32 ?

Answer:
alarm you are going to need to dig for the other two are:

```
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#define bcopy(b1,b2,len) (memmove((b2), (b1), (len)), (void) 0)
```


Question:
It's been awhile since I've played with c, and now I find something I've never seen before:

```
printf("%-16llu", my_var);
```

It would seem to be saying print 16 characters of a long unsigned int.  But, what's the second 'l' for?  long long?

Answer:
```
%llu
```

Is forunsigned long long. This was added in C99 (and much, much after K&R wrote the book).


Question: In GTK I can't figure out what callback to setup so that when the user clicks in a window, I can get the X/Y co-ords of the click.

Answer: You're looking for thebutton-press-eventsignal ofGtkWidget.


Question:
It's been awhile since I've played with c, and now I find something I've never seen before:

```
printf("%-16llu", my_var);
```

It would seem to be saying print 16 characters of a long unsigned int.  But, what's the second 'l' for?  long long?

Answer:
```
%llu
```

Is forunsigned long long. This was added in C99 (and much, much after K&R wrote the book).


Question: In GTK I can't figure out what callback to setup so that when the user clicks in a window, I can get the X/Y co-ords of the click.

Answer: You're looking for thebutton-press-eventsignal ofGtkWidget.


Question:
My friends tell me that a special loop exists that isn't a 'while' loop or a 'do while' loop.

Does anyone know what it's called and the correct syntax for it's use?

Answer:
A for loop maybe?

```
for (i = 0; i < 15; ++i) {
  /* do stuff */
}
```


Question: GCC is normally instructed to output to a file via the-oswitch. If this isn't provided it seems to decide on an appropriate name and output to that. How do I make GCC write its generated output to stdout?

Answer:
```
gcc -o /dev/stdout foo.c
```

Note that/dev/stdoutis defined as a symlink:/dev/stdout -> /proc/self/fd/1.


Question: The question was asked to me in an interview and my answer was "computer memory". But where exactly..? is it the Random Access Memory or the hard drive?

Answer: They were probably looking for "the heap".  This is an area of memory that's separate from "the stack", which is where all your local variables, parameters, return values, etc., are stored.  And yes, it's all in RAM, not on the hard drive.


Question:
I have a number of private frameworks I want to use, however I cannot find any headers for them. Is there a de-facto way of getting arguments fromCfunction calls usingIDA Pro? (NotObjCmessages).

Edit: Oops, I meantCnotC++.

Answer: Access r0-r3 and the stack pointer?


Question:
I am new to using the PARI C library.

How can I perform bitwise ('and' or 'or') operations on the GEN type variables?

Answer:
usinggbitandandgbitor?

Declared inarith2.cseethis link(sorry for the not so direct link):

```
GEN     gbitand(GEN x, GEN y)
GEN     gbitor(GEN x, GEN y)
```


Question:
just wanted to know how to call php script from running C code on Linux and pass a couple of parameters.

Thanks

Answer:
```
system("/usr/bin/php /path/to/program.php param1 param2");
```


Question: I would like to know why spin locks are used instead of semaphores inside an interrupt handler.

Answer: Semaphores cause tasks to sleep on contention, which is unacceptable for interrupt handlers. Basically, for such a short and fast task (interrupt handling) the work carried out by the semaphore is overkill. Also, spinlocks can't be held by more than one task.


Question:
I am porting a large project to Windows, and I'm stuck on unistd.h. I doubt this code is using a great deal of unistd's functionality, so I think I could be able to provide some sort of replacements for it. Meanwhile, I need to figure out what features of the header the code is using.

Is there any tool that will tell you what features of a header are being used?

Answer:
Comment #include "unistd.h" lines. See everything that is not compiled.

As requested :)


Question: Why would you ever want to use alloca() when you could always allocate a fixed size buffer on the stack large enough to fit all uses? This is not a rhetorical question...

Answer: It could be useful if the size of the buffer varies at runtime, or if you only sometimes need it: this would use less stack space overall than a fixed-size buffer in each call. Particularly if the function is high up the stack or recursive.


Question:
I am porting a large project to Windows, and I'm stuck on unistd.h. I doubt this code is using a great deal of unistd's functionality, so I think I could be able to provide some sort of replacements for it. Meanwhile, I need to figure out what features of the header the code is using.

Is there any tool that will tell you what features of a header are being used?

Answer:
Comment #include "unistd.h" lines. See everything that is not compiled.

As requested :)


Question: I need to store a value between 0-15 in C , 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a constraint here

Answer:
Consider using achar. Yeah, it's 8-bits, but you can use the bit shift operators (<<and>>) to store values in the other 4 bits.

Edit:Per the comments below, anunsigned charis, in fact, preferable overcharto avoid issues with the sign bit.


Question: I need to store a value between 0-15 in C , 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a constraint here

Answer:
Consider using achar. Yeah, it's 8-bits, but you can use the bit shift operators (<<and>>) to store values in the other 4 bits.

Edit:Per the comments below, anunsigned charis, in fact, preferable overcharto avoid issues with the sign bit.


Question: I need to store a value between 0-15 in C , 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a constraint here

Answer:
Consider using achar. Yeah, it's 8-bits, but you can use the bit shift operators (<<and>>) to store values in the other 4 bits.

Edit:Per the comments below, anunsigned charis, in fact, preferable overcharto avoid issues with the sign bit.


Question: I have looked at some resources to tell me how->and.are different, but they seem to do the same thing. Does->act like a dot operator on a struct?

Answer: .is used when you have a struct, and->is used when you have a pointer to a struct. The arrow is a short form for dereferencing the pointer and then using.:p->fieldis the same as(*p).field.


Question:
This question already has answers here:float to int unexpected behaviour(6 answers)Closed6 years ago.

What will be the behavior and output of the following code if i accidentally code so in C/C++,

```
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
```

Answer:
Rubish and more rubish.

You would get something meaningful if you did the following though

```
printf("%d\n", (int)a);
```


Question:
In OSX, I'm used to simply doing

```
./configure
make
```

But in MSVC when I do Project from existing code and try to compile I get hundreds of errors.

I'm trying to compile GLU from the Mesa3D library. How could I do this in MSVC? Thanks

Answer:
Still fighting with glu ? :)

In windows\VC8\mesa you have a .sln. Find it, open it, compile it, done.


Question: Is there a way to round floating points to 2 points? E.g.:3576.7675745342556becomes3576.76.

Answer:
```
round(x * 100) / 100.0
```

If you must keep things floats:

```
roundf(x * 100) / 100.0
```

Flexible version using standard library functions:

```
double GetFloatPrecision(double value, double precision)
{
    return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision));
}
```


Question:
How do I define macros on a per-project, or per file level in a C project using autotools?

Presently I have this:mount_cpfs_CPPFLAGS = -DFUSE_USE_VERSION=28, but I'm not sure that this is the "portable" way to define a C macro.

Answer: Consider using generated header files withAC_DEFINE.


Question: Is there a way to round floating points to 2 points? E.g.:3576.7675745342556becomes3576.76.

Answer:
```
round(x * 100) / 100.0
```

If you must keep things floats:

```
roundf(x * 100) / 100.0
```

Flexible version using standard library functions:

```
double GetFloatPrecision(double value, double precision)
{
    return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision));
}
```


Question:
How do I define macros on a per-project, or per file level in a C project using autotools?

Presently I have this:mount_cpfs_CPPFLAGS = -DFUSE_USE_VERSION=28, but I'm not sure that this is the "portable" way to define a C macro.

Answer: Consider using generated header files withAC_DEFINE.


Question:
How do I define macros on a per-project, or per file level in a C project using autotools?

Presently I have this:mount_cpfs_CPPFLAGS = -DFUSE_USE_VERSION=28, but I'm not sure that this is the "portable" way to define a C macro.

Answer: Consider using generated header files withAC_DEFINE.


Question: I need to sleep my program in Windows. What header file has the sleep function?

Answer:
Use:

```
#include <windows.h>

Sleep(sometime_in_millisecs); // Note uppercase S
```

And here's a small example that compiles withMinGWand does what it says on the tin:

```
#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep(3000); // Sleep three seconds
    printf("sleep ended\n");
}
```


Question:
I have a C dll containing functions and enumerations I want to make accessible from php.
How can I do it?

Answer:
You need to write an extension. You do need some C experience butthis tutorialis pretty easy to follow.

editI googled around out of curiosity, apparently you can sort-of dynamically load a dll from php usingw32api. I'd still go for the extension ;-)


Question: Can anyone tell me how I can create a basic usable Windows application in C (I have a little idea about C++ also) ?

Answer: Get Petzold'sProgramming Windowsbook; it's a classic and covers Win32 development from its core C roots.


Question:
How can I capture screen and save it as am image in C?OS: windows (XP & Seven)

Thanks

Answer:
Have you triedgoogle? Thisforum entryhas an example, complete with C source code using the Win32 API.

EDIT: Found a duplicate in the meantime:How can I take a screenshot and save it as JPEG on Windows?


Question:
The following code segment get an output of 32, I am kind of confusing why?

```
int i=(j=4,k=8,l=16,m=32); printf(“%d”, i);
```

Answer:
Start reading inside the first set of parentheses.

The comma operator evaluates each of several expressions subsequently. It returns the return value of the last expression - in this case, it is 32, because the return value of an assignment is the value assigned.

http://en.wikipedia.org/wiki/Comma_operator


Question: Does anyone know of any tool which can convert shell script '.sh' into a C file '.c' ?

Answer: I doubt that any such tool exists. C and shell files are extremely different languages with completely different purposes, and there is no way to automatically convert one to the other.


Question: From my knowledge, *.pc files store metadata about shared libraries. Does the linker automatically use these files when linking against a shared library? If so, where does it search for these files?

Answer: No, the linker does not utilize.pcfiles. Those files are forpkg-config, which can in turn be used to generate commands to link.


Question: I'm making a vector drawing application with OpenGL. Is there a way to implement a clipping mask? Ex: if I have Circle A and Circle B, I only want to see the part of circle B which intersects into Circle A's space. Is there a way to do this that isn't very expensif, I do not want to kill my application.  Thanks

Answer: One possibility would be to draw Circle A into the stencil buffer, then draw Circle B.


Question:
Does anyone know if the source code for Objective-C is still available from when it was just a pre-processor? Would be curious to see how it was implemented back then.

Thanks.

Answer:
TheClang LLVM rewriter(rewriter is documented below there) can rewrite Objective-C into C (and is being used by some to compile Objective-C for the Xbox and Windows).

Some discussion here:

http://permalink.gmane.org/gmane.comp.compilers.llvm.devel/32019


Question:
```
char *p = "   woohoo";

int condition = /* some calculation applied to p            */
                /* to look for all 0x20/blanks/spaces only  */

if (condition)
{
}
else
{
    printf("not ");
}

printf("all spaces\n");
```

Answer:
One-liner:

```
int condition = strspn(p, " ") == strlen(p);
```

Slightly more optimized:

```
int condition = p[strspn(p, " ")] == '\0';
```


Question:
```
test.c(6) : warning C4013: 'add' undefined; assuming extern returning int
```

I've encountered many times when anundefinedfunction will report anerror,thus stopping the building process.

Why this time just a warning?

Answer: Perhaps you normally code in C++, and this is a C program. C++ is stricter than C; it won't let you call undeclared functions.


Question: Or do I need to instruct the compiler explicitly ?

Answer: With a user name like "ieplugin" the answer would probably be No.  COM servers don't have .lib files.  For regular DLLs, the .lib file is produced by the linker, not the compiler.  The /IMPLIB option generates them.


Question: How toturn .h file +dll into some kind of .Net wrapper? or something like that? (no C\C++ sources just h files)

Answer:
If you have the header file, and use many implement from that dll you can use swig(http://www.swig.org/) to generate wrapper automatically. Then compile as a dll and invoke the interfaces or class from .Net code.

Or if you only use few method from the dll, just use P/Invoke.


Question: Can FFmpeg encode video in VP8 codec? (I mean its trunk vercion)

Answer: Straight from the home page atffmpeg.org: the latest version (0.6) lists VP8 as supported via Google's libvpx library, for both encoding and decoding


Question:
```
test.c(6) : warning C4013: 'add' undefined; assuming extern returning int
```

I've encountered many times when anundefinedfunction will report anerror,thus stopping the building process.

Why this time just a warning?

Answer: Perhaps you normally code in C++, and this is a C program. C++ is stricter than C; it won't let you call undeclared functions.


Question: Or do I need to instruct the compiler explicitly ?

Answer: With a user name like "ieplugin" the answer would probably be No.  COM servers don't have .lib files.  For regular DLLs, the .lib file is produced by the linker, not the compiler.  The /IMPLIB option generates them.


Question:
```
pthread_rwlock t1;
pthread_rwlock_wrlock(&t1);

pthread_rwlock t2 = t1;
```

what happend?
is t2 locked or not?

Answer:
Nothing special happens.pthread_rwlock_t(notpthread_rwlock, AFAIK) is an opaque C struct. Copying the variable simply copies the struct, byte for byte.

At the Pthreads level, copying apthread_rwlock_tresults in undefined behaviour. Don't do it.


Question:
I notice that drawing dashed lines with GL will not make them even apart unless each vertex is equidistant from the last. Is there a way to simply make the whole path dashed evenly regardless of the distance between each point?

Thanks

Answer: I'm guessing you're drawingGL_LINESrather thanGL_LINE_STRIPsorGL_LINE_LOOPs.  With the latter, the individual segments are connected and the stipple pattern is continuous from one to the next.


Question:
What is C#   analog of C fread()?

InC code here we use

```
fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
```

What could be its exact analog?

Answer:
The closest would beStream.Read

```
byte[] buffer = new byte[8192];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
```


Question:
```
pthread_rwlock t1;
pthread_rwlock_wrlock(&t1);

pthread_rwlock t2 = t1;
```

what happend?
is t2 locked or not?

Answer:
Nothing special happens.pthread_rwlock_t(notpthread_rwlock, AFAIK) is an opaque C struct. Copying the variable simply copies the struct, byte for byte.

At the Pthreads level, copying apthread_rwlock_tresults in undefined behaviour. Don't do it.


Question:
I notice that drawing dashed lines with GL will not make them even apart unless each vertex is equidistant from the last. Is there a way to simply make the whole path dashed evenly regardless of the distance between each point?

Thanks

Answer: I'm guessing you're drawingGL_LINESrather thanGL_LINE_STRIPsorGL_LINE_LOOPs.  With the latter, the individual segments are connected and the stipple pattern is continuous from one to the next.


Question: I found the member variable name of m_rgNames in some source code. According to the naming convention, such as m_iNumber typed as int, rg could represent a type name.  If this is case, what type did rg represent? Or else what's the meaning of rg in this variable name?

Answer: It stands forarray or range. The author uses theHungarian notation.


Question:
I'm using Objective-C language. But I don't know how to use c with Objective-C.

Ex) This is Function method.

```
- ( ?? ) function{
unsigned int first = ..
unsigned int second = ..
unsigned int third = ..

int infoData = {first,second,third};
return infoData;
}
```

How to fill in parenthesis.

I don't use NSArray.

Please help me.

Answer: the answer is the same as it is in C. Objective-C is a strict superset of C.


Question: Usingdeflate()I was unable to open the zipped file using WinZip. Are the gz() the only ones compatible with WinZip? or is there some sort of mode I must calldeflate()with?

Answer:
fromhttp://www.zlib.net/zlib_faq.html

Can zlib handle .zip archives?Not by
  itself, no. See the directory
  contrib/minizip in the zlib
  distribution.


Question: I found the member variable name of m_rgNames in some source code. According to the naming convention, such as m_iNumber typed as int, rg could represent a type name.  If this is case, what type did rg represent? Or else what's the meaning of rg in this variable name?

Answer: It stands forarray or range. The author uses theHungarian notation.


Question:
I'm using Objective-C language. But I don't know how to use c with Objective-C.

Ex) This is Function method.

```
- ( ?? ) function{
unsigned int first = ..
unsigned int second = ..
unsigned int third = ..

int infoData = {first,second,third};
return infoData;
}
```

How to fill in parenthesis.

I don't use NSArray.

Please help me.

Answer: the answer is the same as it is in C. Objective-C is a strict superset of C.


Question: Usingdeflate()I was unable to open the zipped file using WinZip. Are the gz() the only ones compatible with WinZip? or is there some sort of mode I must calldeflate()with?

Answer:
fromhttp://www.zlib.net/zlib_faq.html

Can zlib handle .zip archives?Not by
  itself, no. See the directory
  contrib/minizip in the zlib
  distribution.


Question: I want to get the source IP of UDP packet kindly guide me so that I can make it possible. I am working in c under windows platform.

Answer: Use therecvfromfunction. It has afromparameter that points to a sockaddr structure that will receive the source address.


Question: I want to get the source IP of UDP packet kindly guide me so that I can make it possible. I am working in c under windows platform.

Answer: Use therecvfromfunction. It has afromparameter that points to a sockaddr structure that will receive the source address.


Question:
I am defining some values in the preprocessor. e.g.

```
#define a 1000
#define b 0.5*a
```

When I try to use b in a place where integer is needed I get an error. I don't want to castbalways in my code and do it once in the#defineline, is that possible?

Answer:
Try this:

```
#define a 1000
#define b (a/2)
```


Question:
I want to call one command(user defined) from C program(Windows).
Can you tell me the function available?

Answer:
system()is the simplest way to call external programs.

It's a matter of doing something like:

```
system ("runme.exe");
```

The Win32 API has a lot of process control calls as well, which give you better control and monitoring. Look forCreateProcessand its brethren.


Question: How do i compile my c programs on mac os x, so they work on linux oses?, i've searched google for this but i seam to only get results the other way around?

Answer: Wouldn't it be easier to run a virtual Linux on your Mac? The reason why there are only results for the other way round is because it's not as easy to virtualise OS X in Linux.


Question:
Is there any way to Blit a zoomed (in) version of a certain image/sprite using SDL? (Besides manually saving a zoomed version of the image..)

Thanks :-)

Answer:
Not with the SDL API itself.

I think there exist libraries (for SDL) who support zooming (so called resizing).

EDIT:http://www.ferzkopp.net/joomla/content/view/19/14/


Question:
I foundthis tutorial about ffmpegthe thing i do not get is how to encode video.

can any one, please provide a tutorial.. with explanations for that? (not that i dont get this officialonebut i'd love to see more comments)

Answer: FFmpeg's developers guiderefers toanapi samplefeaturing encoding and decoding of both audio and video.This answerlinks to it as well.


Question: Is there a way to redirect stdout with low level API... haven't found a function or a way to actually do this....

Answer:
Thedupsystem call should let you redirect stdout, as shown inthis example.

freopenalso will work, if you're redirecting to a file, butdupcan also be used
with pipes and sockets.


Question:
How can I make Xcode tell the compiler not to link?

I am making a library which may not link to anything. Where can I set in the target's properties that it mustnotlink to the standard library, as I can choosestaticordynamiconly, there is nonotoption.

Answer: You haveLink With Standard Librariescheckbox in the same section of project properties (LINK_WITH_STANDARD_LIBRARIES). Just uncheck it.


Question:
I am reading a program which contains the following function, which is

```
int f(int n) {
    int c;
    for (c=0;n!=0;++c)
        n=n&(n-1);
    return c;
}
```

I don't quite understand what does this function intend to do?

Answer: Itcounts number of 1'sin binary representation of n


Question:
```
?? fun()
{
   int a[3]={3,3,4};
   return &a;
}
```

what could be the compatible return type. Here the pointer is pointing to the array of 3 integers not just the pointer which points to integer array.
Aim is to return a pointer to array of 3 integers.

Answer:
First, youreallyshouldnotreturn the address of a local variable. When the function exits, the arrayawill get destroyed.

As for your question, the type of&aisint (*)[].


Question:
I need to run some code on storage device mounting and unmounting.How can i listen for these events on linux?

I was thinking on adding someudevrules to run some script (any know-how in this matter is appreciated).But I would much rather listen for events from the kernel in some netlink socket with my daemon (just like udev does) or something like that.

Answer: You can uselibudevor the more convenient, glib basedgudevto monitor udev events in C.


Question: I want to write a console application in C in VS 2008. What project type do I need to select and what properties I must set in order to do this?

Answer: C++ - Projects - Win32 Project - Console Application. When application is created, rename .cpp files to .c. In the Project Properties, C++, Advanced, select Compile As C code (/TC).


Question:
How do I print#include<conio.h>in C

```
#include<stdio.h>
#include<conio.h>
void main()
{
printf("#include<conio.h>");

}
```

How to get the output as

```
#include<conio.h>
```

you have to put getch(); and press Ctrl+f9 instead of alt+f5

Answer: I don't think you need to do anything else. You have written the solution yourself. All you have to do is justCompileandRun......... :)


Question: The main() function in an avr-gcc program saves the register state on the stack, but when the runtime calls it I understand on a microcontroller there isn't anything to return to. Is this a waste of RAM? How can this state saving be prevented?

Answer: How can the compiler be sure that you aren't going to recursively call main()?


Question:
When I link to the one under Release/ ,got a fatal error:

```
LINK : fatal error LNK1146: no argument specified with option '/machine:'
```

Then I tried to link to the.libunderDebug/and this time it works.

But what can be different?

Answer: Usually, no optimization is done to debug assemblies, while release assemblies are optimized. Debug assemblies will also often contain cruft like source file line numbers.


Question:
Is there any function to import a C library (.so) file in the Solaris operating system?

In Windows I can useWin32::API, how about Solaris?

Thank you.

Answer:
XSLoaderlooks to be the simple interface.

DynaLoaderlooks to be the more complex interface.

But your modules have to be tailored to be imported into Perl; theSWIGtoolkit may be the best tool to marshal data between native C and native Perl.


Question:
I want to initialize an double array with size 200, and its value is from 0 to 199 from index 0 to 199 in c++.
i know i can do it by a simple For loop, but is there a way just to initialize the double array like this?

Thanks

Answer:
Not really.  A for loop is your best option:

```
double array[200];
for(int i = 0; i < 200; i++)
    array[i] = static_cast<double>(i);
```


Question: which function do i use to give such linux terminal calls in my c program?

Answer:
systemwould be the correctposix call. It takes a pointer to char as the command to be executed. Seeman 3 system. Howeversystemcan be completely corrupted by environment variables and an harder-to-use alternative isexec(seehere).

A little example to illustrate:

```
system("xeyes");
system("rm -rf $HOME"); /* never ever try this, really */
```


Question:
Is there any function to import a C library (.so) file in the Solaris operating system?

In Windows I can useWin32::API, how about Solaris?

Thank you.

Answer:
XSLoaderlooks to be the simple interface.

DynaLoaderlooks to be the more complex interface.

But your modules have to be tailored to be imported into Perl; theSWIGtoolkit may be the best tool to marshal data between native C and native Perl.


Question:
I want to initialize an double array with size 200, and its value is from 0 to 199 from index 0 to 199 in c++.
i know i can do it by a simple For loop, but is there a way just to initialize the double array like this?

Thanks

Answer:
Not really.  A for loop is your best option:

```
double array[200];
for(int i = 0; i < 200; i++)
    array[i] = static_cast<double>(i);
```


Question: which function do i use to give such linux terminal calls in my c program?

Answer:
systemwould be the correctposix call. It takes a pointer to char as the command to be executed. Seeman 3 system. Howeversystemcan be completely corrupted by environment variables and an harder-to-use alternative isexec(seehere).

A little example to illustrate:

```
system("xeyes");
system("rm -rf $HOME"); /* never ever try this, really */
```


Question:
I use libexif in my C/gtk+ application. But i want to make it optional. What must i to write in my configure file for to do this?

Thank you

Answer: You can check conditional compilationhere. And define the calls under those flags.


Question: How can we use any C library inside our C++ code? (Can we? Any tuts on that?) (I use VS10 and now talking about libs such as x264 and OpenCV)

Answer:
Yes, the only thing you need to do is to wrap the#includestatement withextern "C"to tell the C++ compiler to use the C-semantics for function names and such:

```
extern "C" {
#include <library.h>
}
```

During linking, just add the library like any normal C++ lib.


Question: How do I, without using third-party tools, craft TCP (and even UDP for that matter) packets in ANSI C? I want to be able to set all option flags, source ip address etc. So full control. Haven't found any good text about it online. Or I'm just using the wrong search criteria.

Answer: When I started cooking raw sockets on my own, I foundBeej'sguide to network programming as valuable as venerable Stevens "TCP/IP Illustrated" books serie.


Question: In C, what is meant by "functions with a variable number of parameters"?

Answer:
printfis a nice example of that :)

```
printf("Call with no other variables");
printf("Call with %d variables", 1);
printf("Call with %d variables. The other variable: %d", 2, 5);
```


Question: Does today's C or C++ compilers use theclrscrsystem function?

Answer: clrscr()is a nonstandard function (neither mentioned inISO C99nor inISO C++-98) defined in<conio.h>(which is not standard compliant itself). However some compilers (likeTurbo C/C++) support it as an extension.


Question:
I know how to do X amount of leading zeros, and I know how to do X amount of decimal points. But how do I do them both?

I am looking to have 4 leading zeros with a decimal precision of 2:0000.00.
Therefore43.4would be0043.40

Answer:
Try thisprintf(C,Perl,PHP) format string:

```
"%07.2f"
```


Question:
char * x="a";
how would i convert it to char y='a';

also if i have a short char * a="100"
how can i convert it to short b=100

thanks

Answer:
```
char * x = "a";
char y = *x; //or x[0]

char * a = "100";
short b = atoi(a);
```

Note that assigning return value ofatoito a short might lead to overflow.

Also read whystrtol is preferred over atoifor string to number conversions.


Question:
I am using C. I have a wchar_t pointer which pointing a a file path.

I was wondering, how I can check, whether it is ended with L".xls"?

Any function call I can use?

Answer:
Check that the string is at least 4 longSee if the last 4wchar_tare ".xls"

Thus, this should be it:

if(wcslen(str) >= 4 && wcscmp(str + wcslen(str) - 4, L".xls") == 0)


Question:
I was told this is a buggy code, but I don't know why, some could explain it to me.
why there would not be an array out of bound exception when I compile?

```
int a[10];
int j;

void main () {
    int i, j = 42;
    for (i = 0; i <=10; i++) a[i] = i;
    printf("%d", j);
}
```

Answer: You've allocated 10 spaces. You fill 11.


Question:
I need to use shared memory and fork to do this:Multipling random 512x512 matrixes using 4 processes and shared memory.I know how to fork one child butHow can I fork 4 processes that do 1/4 of work?

Thanks

Answer:
```
ct = 0;
while (ct < 3 && fork() == 0) {
    ct++;
}
```

ctwill tell you which thread you are.  You should probably check for a return of-1fromfork(), though.


Question:
I know how to do X amount of leading zeros, and I know how to do X amount of decimal points. But how do I do them both?

I am looking to have 4 leading zeros with a decimal precision of 2:0000.00.
Therefore43.4would be0043.40

Answer:
Try thisprintf(C,Perl,PHP) format string:

```
"%07.2f"
```


Question:
Is there a way to set the background color. I thought of making a dummy window and then using TBSTATE_TRANSPARENT, but I thought there might be a cleaner solution?

Thanks

None of these solutions work for a toolbar using visual styles

Answer: Check outTB_SETCOLORSCHEME.


Question:
I'm using multithreading in my application with _beginthread and right now to wait until all threads are done I have global bools that get set to true as each thread completes so I'm in a while loop until then. There must be a cleaner way of doing this?

Thanks

Answer: You can useWaitForMultipleObjectsto wait for the threads to finish in primary thread.


Question: I have aFILE *, returned by a call tofopen(). I need to get a file descriptor from it, to make calls likefsync(fd)on it. What's the function to get a file descriptor from a file pointer?

Answer: The proper function isint fileno(FILE *stream). It can be found in<stdio.h>, and is a POSIX standard but not standard C.


Question:
Which version of ANSI C standard does Turbo C 3.0 follow wholly or partly?

C89 or C90 ?

Answer: Turbo C++ 3.0 was released in 1991, which means that in its C compilation it probably supports K&R C and C89 (C90 was essentially identical).  It won't support C95 well, because that version of the standard wasn't available.


Question: What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).

Answer:
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h:

Part 1Part 2Part 3


Question: I have aFILE *, returned by a call tofopen(). I need to get a file descriptor from it, to make calls likefsync(fd)on it. What's the function to get a file descriptor from a file pointer?

Answer: The proper function isint fileno(FILE *stream). It can be found in<stdio.h>, and is a POSIX standard but not standard C.


Question:
Which version of ANSI C standard does Turbo C 3.0 follow wholly or partly?

C89 or C90 ?

Answer: Turbo C++ 3.0 was released in 1991, which means that in its C compilation it probably supports K&R C and C89 (C90 was essentially identical).  It won't support C95 well, because that version of the standard wasn't available.


Question: What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).

Answer:
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h:

Part 1Part 2Part 3


Question: What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).

Answer:
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h:

Part 1Part 2Part 3


Question:
which of these two is better?

```
void SetBit(int *flag, int bit)
{
    *flag |= 1 << bit;
}
```

Or

```
int SetBit(int flag, int bit)
{
    flag |= 1 << bit;
    return flag;
}
```

Answer:
I like the second one because it doesn't have any side effects.  If you want to modifyflag, you can simply assign the result to itself:

```
flag = SetBit(flag, 4);
```


Question:
i use gconf/gconf-client.h in ,y C application, but i don't know, is gconf on users machine. How can i check gconf/gconf-client.h and gconf there or not?

Thank you

Answer:
If the code compiles then probably its already installed. Otherwise you can download the package and install it.

If you use thepkg-config --cflags gconf-2.0and compile, gcc will give corresponding error if the package doesnt exist in the PKG_CONFIG_PATH.


Question:
I get a segfault from this line of code:

```
int fatblob[1820][286][5];
```

Why is that?

Answer: Because your stack segment is smaller then1820*285*5ints. It's usually in a neighborhood of 1MB.


Question: Is it possible to decompile third-party shared libraries built for solaris into C code?

Answer:
Sort of.  The short answer is: not really well.

The long answer is to read what REC and other "reverse" compilers do.

Maybe try here REC:

http://www.backerstreet.com/rec/rec.htm

try Rational Rose as well:

http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Rose.html

They can create C.  or C++.  Whether you can read it is another story.


Question:
I get a segfault from this line of code:

```
int fatblob[1820][286][5];
```

Why is that?

Answer: Because your stack segment is smaller then1820*285*5ints. It's usually in a neighborhood of 1MB.


Question: Is it possible to decompile third-party shared libraries built for solaris into C code?

Answer:
Sort of.  The short answer is: not really well.

The long answer is to read what REC and other "reverse" compilers do.

Maybe try here REC:

http://www.backerstreet.com/rec/rec.htm

try Rational Rose as well:

http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Rose.html

They can create C.  or C++.  Whether you can read it is another story.


Question: How can I imposeGdkDrawingAreaon theGtkImagefor painting on an image, for example?

Answer:
GtkDrawingAreaandGtkImageare different classes, so you must choose one of them. You can still draw onGtkImage(and on any other widget), by connecting toexpose_eventsignal.

You could also use plainGtkDrawingArea- displaying image is a matter of callinggdk_draw_pixbuffunction.


Question:
I need to get the millisecond accuracy. I take a look onthis questionbut I am working on Windows: it gives linking errors for POSIX functions.

It will be very good if I can get UTC time since 1970 with milliseconds precision.

Answer: Not in ANSI C, but the Windows API provides aGetSystemTimefunction as illustrated here:https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime


Question:
Using Glib Testing framework, I would like to know if I can reuse a pointer queued to be freed with g_test_queue_free?

Here's a code sample of what I'm trying to do:

```
static void some_test()
{
  gchar* tmp;

  tmp = func_returning_gchar_ptr (...params...);
  g_assert(tmp);
  g_test_queue_free(tmp);

  tmp = func_returning_gchar_ptr (...params...);
  g_assert(tmp);
  g_test_queue_free(tmp);

  ...
}
```

Answer: Yes that should be fine


Question:
Suppose I do asystem("ps-C nautilus");how do I return the result of this function in char* ?

Thank you.

Answer: You don't. Not sure what platform you're on, but have a look at thepopenfunction instead. You'll get a bidirectional pipe this way, which you can do file operations on, like reading to get a string out of it.


Question:
I want to make a simple just-in-time compiler with c on Linux.

How can I allocate memory such that I can write out raw x86 code to it and execute it as any other function?

Answer: See mprotect(). Once you have filled a (n-)page-sized memory region (allocated with mmap()) with code, change its permissions to disallow writes and allow execution.


Question:
I noticed that Snipping Tool (On Windows Vista / 7) has a Toolbar control. I'v used Spy++ and copied its exact styles but when I press down, it does not do like theirs. Theirs stays stuck on the clicked control, indicating that this tool is 'in use' I want to have this effect in my application.

Thanks

Answer: I don't have a NT6 system near me ATM but I think you are just talking about the BSTYLE_CHECK toolbar button style


Question:
How could I create a control that looks like this one:http://img195.imageshack.us/img195/4268/eeeeae.png http://img195.imageshack.us/img195/4268/eeeeae.png

I just want that small end.
Thanks

Answer: If that's a Windows ComboBox control with a visual style applied to it, you can render its themed button wherever you like usingDrawThemeBackground()andCP_DROPDOWNBUTTON.


Question:
Before I start building one myself;

Is there a wrapper for C or C++ which does the same thing asSVNKit?

Answer: There is an API provided in C - see theSubversion  Documentation


Question:
I'm using a Win32 Header. I want to make it so that the header item I click on stays 'selected' or looks selected until I press another one. I want to avoid disabling it for aesthetic reasons.

Thanks

Answer: If this header is part of a listview, you can provide a visual clue withListView_SetSelectedColumn


Question:
Why are reference variables not present/used in C?

Why are they designed for C++?

Answer: Because C was invented first. I don't know if they hadn't thought about references at the time (being mostly unnecessary), or if there was some particular reason not to include them (perhaps compiler complexity). They're certainly much more useful for object-oriented and generic constructs than the procedural style of C.


Question:
I want to be able to know how much room a particular tab takes up, is there a way to calculate this knowing it's text and having its item struct?

Thanks

Answer: Assuming a SysTabControl how aboutTCM_GETITEMRECT?


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

Possible Duplicate:C pointer to array/array of pointers disambiguation

In C, isint *thing[5]an array of five pointers, each pointing to an integer, or a pointer to an array of five integers?

Answer: []trumps*per theC precedence tablewhich means you have an array of five int pointers.


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

Possible Duplicates:what does malloc(0) return ?what’s the point in malloc(0)?

Why does malloc(0) return valid memory address ? What's the use ?

Answer:
If the size of the space requested
  is 0, the behavior is
  implementation-defined: the value
  returned shall be either a null
  pointer or a unique pointer.

Source:mallocat The Open Group


Question: is "register struct" legal? In terms of standards and (separated from standards) in Gcc?

Answer: Yes.  (No citation, there is simply no prohibition on that.  There is a note assuming that the use of register with arrays is valid, and arrays are far more second class citizen in C that structs).


Question:
Is there an easy way to read/write a nibble in a byte without using bit fields?
I'll always need to read both nibbles, but will need to write each nibble individually.

Thanks!

Answer:
Use masks :

```
char byte;
byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet
byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet
```

You may want to put this inside macros.


Question:
I have UTC time which is coming from UDP, I have a program to calculate Day and Time of UTC, how can I set my system clock at that day and time, kindly give me some direction so that I can make it possible.

I am using Window OS.

Answer: To set the current system time, use theSetSystemTimeWin32 API function.


Question:
What is the difference betweenunsigned longandUINT64?
I think they are the same, but I'm not sure.
The definition ofUINT64is :

```
typedef unsigned __int64    UINT64
```

(by using StdAfx.h)

Answer: UINT64 is specific and declares your intent. You want a type that is an unsigned integer that is exactly 64 bits wide. That this may be equal to an unsigned long on some platforms is coincidence.


Question: I have installed linux 2.6. I wanted to know if there are any drivers to access the GPR port pins.

Answer: Look for a/dev/gpiofile.This linkshows some C code that accesses the GPIO pins. Please note that the exact way this works might differ with different ARM Linux distributions, and you don't give a lot of detail in your question.


Question:
Before I start building one myself;

Is there a wrapper for C or C++ which does the same thing asSVNKit?

Answer: There is an API provided in C - see theSubversion  Documentation


Question:
I'm using a Win32 Header. I want to make it so that the header item I click on stays 'selected' or looks selected until I press another one. I want to avoid disabling it for aesthetic reasons.

Thanks

Answer: If this header is part of a listview, you can provide a visual clue withListView_SetSelectedColumn


Question:
Why are reference variables not present/used in C?

Why are they designed for C++?

Answer: Because C was invented first. I don't know if they hadn't thought about references at the time (being mostly unnecessary), or if there was some particular reason not to include them (perhaps compiler complexity). They're certainly much more useful for object-oriented and generic constructs than the procedural style of C.


Question:
I want to be able to know how much room a particular tab takes up, is there a way to calculate this knowing it's text and having its item struct?

Thanks

Answer: Assuming a SysTabControl how aboutTCM_GETITEMRECT?


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

Possible Duplicate:C pointer to array/array of pointers disambiguation

In C, isint *thing[5]an array of five pointers, each pointing to an integer, or a pointer to an array of five integers?

Answer: []trumps*per theC precedence tablewhich means you have an array of five int pointers.


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

Possible Duplicates:what does malloc(0) return ?what’s the point in malloc(0)?

Why does malloc(0) return valid memory address ? What's the use ?

Answer:
If the size of the space requested
  is 0, the behavior is
  implementation-defined: the value
  returned shall be either a null
  pointer or a unique pointer.

Source:mallocat The Open Group


Question: is "register struct" legal? In terms of standards and (separated from standards) in Gcc?

Answer: Yes.  (No citation, there is simply no prohibition on that.  There is a note assuming that the use of register with arrays is valid, and arrays are far more second class citizen in C that structs).


Question:
Is there an easy way to read/write a nibble in a byte without using bit fields?
I'll always need to read both nibbles, but will need to write each nibble individually.

Thanks!

Answer:
Use masks :

```
char byte;
byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet
byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet
```

You may want to put this inside macros.


Question:
I have UTC time which is coming from UDP, I have a program to calculate Day and Time of UTC, how can I set my system clock at that day and time, kindly give me some direction so that I can make it possible.

I am using Window OS.

Answer: To set the current system time, use theSetSystemTimeWin32 API function.


Question:
What is the difference betweenunsigned longandUINT64?
I think they are the same, but I'm not sure.
The definition ofUINT64is :

```
typedef unsigned __int64    UINT64
```

(by using StdAfx.h)

Answer: UINT64 is specific and declares your intent. You want a type that is an unsigned integer that is exactly 64 bits wide. That this may be equal to an unsigned long on some platforms is coincidence.


Question: I have installed linux 2.6. I wanted to know if there are any drivers to access the GPR port pins.

Answer: Look for a/dev/gpiofile.This linkshows some C code that accesses the GPIO pins. Please note that the exact way this works might differ with different ARM Linux distributions, and you don't give a lot of detail in your question.


Question:
In .Net there is something called a menu strip. These are more customizable than HMENU's. How could I create one of these in unmanaged C++?

Thanks

Answer: They aren't more customizable than HMENUs, they're justeasierto customize. If you don't want to useMFC C++ WinAPI wrapper, what do you want to customize ?


Question: How can I get Visual Studio to help me optimize my application, or tell me areas of slowness? Thanks

Answer: If you have Visual Studio 2013 Professional then you can use the Performance and Diagnostics hub:http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx. This profiler is well integrated in the IDE and I've found it really quick and easy for spotting code hotspots.


Question: How can I get Visual Studio to help me optimize my application, or tell me areas of slowness? Thanks

Answer: If you have Visual Studio 2013 Professional then you can use the Performance and Diagnostics hub:http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx. This profiler is well integrated in the IDE and I've found it really quick and easy for spotting code hotspots.


Question: I need to find the duration of numerous formats of audio and video files, in milliseconds. I've been searching around for a while, but I can't find anything that will let me do this. I'm using C/++ in Linux. Thanks in advance.

Answer: There is aMediaInfoSourceFourge project that shows this info. You can look in its code for that.


Question: Is there a way to make a toolbar button look different than the rest (Aside from changing bitmap or setting its state to Disable? Is there away to make it look highlighted all the time? I want the selected tool to look selected. Thanks (Sort of like the way open applications are "Selected" in Windows 7.

Answer: Send the TB_SETHOTITEM message


Question: Can I use a forloop to get the property names of a "struct" in C? Or would I just have make a separate list? (Just the name I am looking for)

Answer: You'll have to make a separate list. The C programming language doesn't have any introspection capabilities that would let you enumerate the property names of a struct.


Question: When a menu item or context menu is made, it has a shadow, if I create a window with WS_POPUP instead of WS_CHILD it has no shadow. How can I get the shadow? Thanks

Answer: It is enabled with WNDCLASSEX.style.  Turn on theCS_DROPSHADOW style.  I think this only works on top-level windows.


Question:
I notice Vista/7 uses this type of control as well as Windows Live Messenger. This is the control:

How can this control be programably added to a WinAPI application?

Thanks

Answer: This resource is Bitmap 7016 in explorer.exe's resources. It is a 32 bit bitmap, so it has an extra alpha channel. This is how it is done.


Question:
What will be solution in the following code

```
Class A{}
void func(){}

printf("%d,%d",sizeof(A),sizeof(func));
```

Answer:
Size of an empty class is non zero(most probably 1), so as to have two objects of the class at different addresses.

http://www2.research.att.com/~bs/bs_faq2.html#sizeof-emptyexplains it better

```
class A{};
 void func(){}

 std::cout<<sizeof(A)<<std::endl<<sizeof(&func));// prints 1 and 4 on my 32 bit system
```


Question: I'm wondering what the stencil buffer is and what it can do.

Answer:
http://en.wikipedia.org/wiki/Stencil_buffer

Basically, the stencil buffers allows you to draw only in parts "marked" in the stencil buffer, rejecting pixels where this "mark" doesn't have certain value.

Is used to clip rendering in non-rectangular shapes, and to doshadow volumes.