Question:
Is there any specific way to convert jpeg images to black and white using C? I converted a .bmp image to black and white using C by simply extracting the headers (which in .bmp file is 54 bytes in length) and converting the RGB to the respective gray level using the formula.
But how to do that in jpeg file?

Answer: If you can afford to link a library, I highly recommend OpenCV for this task:http://opencv.willowgarage.com/


Question:
What is the equivalent of cin.peek() for C programming? I need to scan files for '/r' and '/r/n' (these are the end of line markers for DOS files) so I need to "peek" ahead to the next character if the current character is a '/r'

Thanks!

Answer:
There isungetc(), which allows you to push characters back (as if they were not already read), when you've peeked at them.

http://www.zyba.com/reference/computing/c/stdio.h/ungetc.php


Question: I am receiving this error while compiling a C program in MinGW. As far as I know, I thought 'intptr_t' was a type in the C99 standard. Am I not including a file?

Answer:
You need to includestdint.h.

Note thatintptr_tanduintptr_tare indeed C99 types but they are optional.


Question:
I am trying to do

```
memset(&idt_entries, 0, sizeof(idt_entry_t)*256);
```

which produces

error: cannot convert 'idt_entry_t (*)[256] {aka idt_entry_struct ()[256]}' to 'u8int{aka unsigned char*}' for argument '1' to 'void memset(u8int*, u8int, u32int)'

If it helps, it is C code wraped inextern "C" {...}.

Thanks!

Answer:
Are you compiling this as C++?

Add a cast.

memset ((u8int*)idt_entries, 0, sizeof(idt_entry_t)*256);


Question: Well, i have thislinkand i want to parse through it and get only the joke. Its in json format. I would like to use c or c++, not python because i already did it with python.

Answer: Hereis a pretty impressive list of JSON parsers. Take your pick, C and C++ are certainly both supported.


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.

Kindly give an detailed explanation too.
How does it work ?

Answer:
```
return a<b ? a : b
```

is equivalent to

```
if (a<b)
    return a;
else
    return b;
```


Question: I am implementing a user-space network device that makes use of the LinuxTUN/TAP driver. Is it possible to install a custom ioctl handler? I would like to be able to send custom status queries and control commands to the program. Or perhaps there is a slicker way of doing this?

Answer: Have the program listen on another normal socket (AF_LOCAL, AF_INET6, ... non-tun in any case) of your choice.


Question: I am implementing a user-space network device that makes use of the LinuxTUN/TAP driver. Is it possible to install a custom ioctl handler? I would like to be able to send custom status queries and control commands to the program. Or perhaps there is a slicker way of doing this?

Answer: Have the program listen on another normal socket (AF_LOCAL, AF_INET6, ... non-tun in any case) of your choice.


Question:
I preload some lua file withluaL_loadfileand then I execute it multiple timest (it's  a server). I have somedofile()calls in the lua file.

WillluaL_loadfilealso preload alldofile()within the lua file?

Answer: No,luaL_loadfiledoes not executeanycode in the file, In particular, it does not call any embeddeddofile()orrequireor any other function call.


Question: I'm familiar with only one compile time operator in C -sizeof. Are there any others that I as a programmer should be aware of?

Answer: Onlysizeofthat I'm aware, although in C99 sizeof cannot be done at compile time for variable length arrays (VLAs).


Question:
There doesn't seem to be a question for this, and it seems strange that I don't know this.  When I program in c/objective-c, must I escape single quotes nested within double quotes.

example

"'"or"''"

is this needed

"\'"or"\'\'"

thanks

Answer: No, escaping is unnecessary for single-quotes.


Question:
I am Just a begineer in C Programming. While solving a programming assignement I came across the need to convert an array ofunsigned chartointeger.

For Example:

```
unsigned char x[]="567";
unsigned char y[]="94";
```

Now I have to add the integer values in bothxandy. That is:

```
int sum=661;
```

What is the simplest way to do this?

Answer: You're looking foratoi().


Question: How can I get the actual "username" without using the environment (getenv, ...) in a program? Environment is C/C++ with Linux.

Answer:
The functiongetlogin_r()defined inunistd.hreturns the username. Seeman getlogin_rfor more information.

Its signature is:

```
int getlogin_r(char *buf, size_t bufsize);
```

Needless to say, this function can just as easily be called in C or C++.


Question:
We have some old C code with pre-ANSI (K&R-style) function declarations.  For example:

```
int foo(x, y)
double x, y;
{
    /* do some stuff */
}
```

Is there a compiler switch to enable support for this in Visual C++ 2008?

Answer: In order to get this to compile put the code in a .c file vs. a .cpp.  This instructs Visual Studio to compile the code as C instead of C++


Question: I'm familiar with only one compile time operator in C -sizeof. Are there any others that I as a programmer should be aware of?

Answer: Onlysizeofthat I'm aware, although in C99 sizeof cannot be done at compile time for variable length arrays (VLAs).


Question:
There doesn't seem to be a question for this, and it seems strange that I don't know this.  When I program in c/objective-c, must I escape single quotes nested within double quotes.

example

"'"or"''"

is this needed

"\'"or"\'\'"

thanks

Answer: No, escaping is unnecessary for single-quotes.


Question:
I am Just a begineer in C Programming. While solving a programming assignement I came across the need to convert an array ofunsigned chartointeger.

For Example:

```
unsigned char x[]="567";
unsigned char y[]="94";
```

Now I have to add the integer values in bothxandy. That is:

```
int sum=661;
```

What is the simplest way to do this?

Answer: You're looking foratoi().


Question: How can I get the actual "username" without using the environment (getenv, ...) in a program? Environment is C/C++ with Linux.

Answer:
The functiongetlogin_r()defined inunistd.hreturns the username. Seeman getlogin_rfor more information.

Its signature is:

```
int getlogin_r(char *buf, size_t bufsize);
```

Needless to say, this function can just as easily be called in C or C++.


Question:
When creating a pointer array in c what does the effect of adding parentheses do?

For example

int (*poi)[2];

vs

int *poi[2];

Answer:
Pointer to an array of 2ints:

```
int (*poi)[2];
```

An array of twointpointers:

```
int *poi[2];
```

Normally Array has higher precedence than the pointer, but if you add the parentheses then the pointer comes "first".


Question:
Does the two code snipets below do exactly the same thing?

```
do
{
    Delay_us(1);
    status = fetchStatus();
}while(!status);
```

Second snipet ->

```
do
{
    Delay_us(1);
}while(status = fetchStatus(), !status);
```

which is preferable?

Answer:
You can do:

```
do
{
    Delay_us(1);
} while( !fetchStatus() );
```

That way you do not need to create a local variable if youdo notuse it.


Question:
Does C have scope hiding?

For example, if I have a global variable:

```
int x = 3;
```

can I 'declare' inside a function or main 'another' int x?

Answer:
Yes, that's how C works. For example:

```
int x;

void my_function(int x){ // this is another x, not the same one
}

void my_function2(){
  int x; //this is also another x
  {
    int x; // this is yet another x
  }
}
int main(){
  char x[5]; // another x, with a different type
}
```


Question:
I need to convert a formated data to struct like this:

```
struct header
{
    int a;
    int b;
    char c;
}
```

I have to do it manually like this:

```
[data getBytes:&h.a range:(NSRange){0,4}];
[data getBytes:&h.b range:(NSRange){4,4}];
[data getBytes:&h.c range:(NSRange){8,2}];
```

Is there a better way to convert the data to struct?

Answer:
```
[data getBytes:&h range:(NSRange){0, sizeof(struct header)}];
```


Question: Is there any way to convert ".so" file into source code or some in readable format.

Answer:
Source code is probably hard, since the .so doesn't "know" which language it was written in.

But you can browse around in the assembly code by doing something like this:

```
$ objdump --disassemble my_secret.so | less
```


Question:
I am working under Linux, with two physical ethernet interfaces.
I have grouped the two interfaces to a bonding interface for backup... and it works.

I would like to know if there is any way to know, from my C user program, what is the active interface.

Thanks

Answer: Look at/sys/class/net/bond0/bonding/active_slaveand read it using a program or code of your choice. (Replace path accordingly if using an interface name different frombond0.)


Question:
I was reading android source code in that I am not getting what doesOPEN GL ESlibrary do and what doesEGL librarydo.?

Is there any relationship between this two libraries?

I have looked athttp://www.khronos.org/opengles/documentation/opengles1_0/html/but still not getting.

Answer: EGL is the interface between OpenGL ES and the underlying native display platform. It is used to create & manage rendering surfaces & graphics contexts.


Question:
Does the two code snipets below do exactly the same thing?

```
do
{
    Delay_us(1);
    status = fetchStatus();
}while(!status);
```

Second snipet ->

```
do
{
    Delay_us(1);
}while(status = fetchStatus(), !status);
```

which is preferable?

Answer:
You can do:

```
do
{
    Delay_us(1);
} while( !fetchStatus() );
```

That way you do not need to create a local variable if youdo notuse it.


Question:
Does C have scope hiding?

For example, if I have a global variable:

```
int x = 3;
```

can I 'declare' inside a function or main 'another' int x?

Answer:
Yes, that's how C works. For example:

```
int x;

void my_function(int x){ // this is another x, not the same one
}

void my_function2(){
  int x; //this is also another x
  {
    int x; // this is yet another x
  }
}
int main(){
  char x[5]; // another x, with a different type
}
```


Question:
I need to convert a formated data to struct like this:

```
struct header
{
    int a;
    int b;
    char c;
}
```

I have to do it manually like this:

```
[data getBytes:&h.a range:(NSRange){0,4}];
[data getBytes:&h.b range:(NSRange){4,4}];
[data getBytes:&h.c range:(NSRange){8,2}];
```

Is there a better way to convert the data to struct?

Answer:
```
[data getBytes:&h range:(NSRange){0, sizeof(struct header)}];
```


Question: Is there any way to convert ".so" file into source code or some in readable format.

Answer:
Source code is probably hard, since the .so doesn't "know" which language it was written in.

But you can browse around in the assembly code by doing something like this:

```
$ objdump --disassemble my_secret.so | less
```


Question:
I am working under Linux, with two physical ethernet interfaces.
I have grouped the two interfaces to a bonding interface for backup... and it works.

I would like to know if there is any way to know, from my C user program, what is the active interface.

Thanks

Answer: Look at/sys/class/net/bond0/bonding/active_slaveand read it using a program or code of your choice. (Replace path accordingly if using an interface name different frombond0.)


Question:
I was reading android source code in that I am not getting what doesOPEN GL ESlibrary do and what doesEGL librarydo.?

Is there any relationship between this two libraries?

I have looked athttp://www.khronos.org/opengles/documentation/opengles1_0/html/but still not getting.

Answer: EGL is the interface between OpenGL ES and the underlying native display platform. It is used to create & manage rendering surfaces & graphics contexts.


Question:
Does C have scope hiding?

For example, if I have a global variable:

```
int x = 3;
```

can I 'declare' inside a function or main 'another' int x?

Answer:
Yes, that's how C works. For example:

```
int x;

void my_function(int x){ // this is another x, not the same one
}

void my_function2(){
  int x; //this is also another x
  {
    int x; // this is yet another x
  }
}
int main(){
  char x[5]; // another x, with a different type
}
```


Question:
I need to convert a formated data to struct like this:

```
struct header
{
    int a;
    int b;
    char c;
}
```

I have to do it manually like this:

```
[data getBytes:&h.a range:(NSRange){0,4}];
[data getBytes:&h.b range:(NSRange){4,4}];
[data getBytes:&h.c range:(NSRange){8,2}];
```

Is there a better way to convert the data to struct?

Answer:
```
[data getBytes:&h range:(NSRange){0, sizeof(struct header)}];
```


Question: Is there any way to convert ".so" file into source code or some in readable format.

Answer:
Source code is probably hard, since the .so doesn't "know" which language it was written in.

But you can browse around in the assembly code by doing something like this:

```
$ objdump --disassemble my_secret.so | less
```


Question:
I am working under Linux, with two physical ethernet interfaces.
I have grouped the two interfaces to a bonding interface for backup... and it works.

I would like to know if there is any way to know, from my C user program, what is the active interface.

Thanks

Answer: Look at/sys/class/net/bond0/bonding/active_slaveand read it using a program or code of your choice. (Replace path accordingly if using an interface name different frombond0.)


Question:
I was reading android source code in that I am not getting what doesOPEN GL ESlibrary do and what doesEGL librarydo.?

Is there any relationship between this two libraries?

I have looked athttp://www.khronos.org/opengles/documentation/opengles1_0/html/but still not getting.

Answer: EGL is the interface between OpenGL ES and the underlying native display platform. It is used to create & manage rendering surfaces & graphics contexts.


Question:
Hello everyone I want to ask a question about includingguardsin C programming. I know their purpose but in some programms I have seen a1" written after #define like this:

```
#ifndef MYFILE_H
#define MYFILE_H 1
```

What is the purpose of this1? Is it necessary?

Answer: It's not necessary,#define MYFILE_Hshould do the trick. The fact thatMYFILE_Hisdefined(the condition tested byifndef) is separated from its value. It could be 0, ' ', 42, etc.


Question:
What is the correct term/name for the following construction:

```
string myString = (boolValue==true ? "true": "false");
```

Answer: It's a ternary conditional expression.


Question:
Is there any standard (or widely used) simple POSIX path manipulation library for C (path join, filename stripping, etc.) ?

Actually, because I'm mostly working under Windows, I currently use'shlwapi'path functions.

Is there any equivalent set of functions available for POSIX paths?

Answer: path join - snprintf()filename stripping - dirname()etc. - basename(), realpath(), readlink(), glob(), fnmatch()...


Question:
Currently I am doing something like

```
"+" return TADD;
```

in my .l file to return token TADD.I want to know if there is a way I can return '+' directly so that I don't have to add a token for every operator.

Answer:
Is this yacc/lex?  If so, then you can just

```
"+" return '+';
```


Question:
I'm trying to connect to an USB device that's on a remote PC (because there is no 64-bit driver for it, remote PC is 32-bit).

I know the commands that I need to send to make settings on the device but I don't know how I can get connected to it. Is there a C++ or C# library that makes it possible to connect to this device on a remote PC?

Answer: You might be able to build something using Microsoft'sRemoteFXtechnology, assuming Windows is your target platform.


Question:
If I don't return anything in a function which returns something, compiler will warn about the function is not returning anything.

But If I callabort()in the function, compiler won't warn. How can I mark my own function like this.

Answer: __attribute__((__noreturn__))should do it for Clang or GCC.  Since you've tagged your question for Objective-C, that should do it for you!


Question: i need to get a list or any other enumerable class with info about any connected SCSI-disks, with info just like/proc/scsi/sg/devicesPlease help me and thanks in advance

Answer: You've basically named a solution in your question -- just open/proc/scsi/sg/devicesand read from it.


Question: For a weekend project I'm looking for a micro web-framework like bottle.py (http://bottlepy.org) but for plain old C. Sadly Google was not very helpful. Any suggestions are welcome!

Answer: After some more search I foundlibSoup, which looks very nice and is really easy to use. But beware: libSoup is part of GNOME - so this might not be so micro after all when it comes to dependencies.


Question:
Is there a way to create a True Type Font file programmatically inobjective-c? I found this reference,http://developer.apple.com/fonts/TTRefMan/index.html, but it doesn't seem there are any built in methods to accomplish this.

Suggestions?  Guidance?

Answer:
No, there isn't any procedural font creation code.

Your best bet would be to start with FontForge:http://fontforge.sourceforge.net/


Question:
I want to use shared memory, but i want only my application instances to be able to access this memory, somehow want to protect it from accessing by other applications...
I am coding in C on Windows.

Thanks in advance.

Answer: UseCreateFileMappingwith specificLPSECURITY_ATTRIBUTES.


Question:
I want to use shared memory, but i want only my application instances to be able to access this memory, somehow want to protect it from accessing by other applications...
I am coding in C on Windows.

Thanks in advance.

Answer: UseCreateFileMappingwith specificLPSECURITY_ATTRIBUTES.


Question: How do I configure eclipse with Turbo C++ compiler.

Answer:
Short answer: don't!

Embarcadero Technologies (which acquired all of Borland's compiler tools with the purchase of its CodeGear division in 2008) discontinued the support of Turbo C++ 2006. Why use a tool that was abandoned 6 years ago?

Turbo C++ was succeeded by C++Builder, which has it's own IDE.

If you want to do C++ development in Eclipse you should useEclipse IDE for C/C++ Developers (~107MB).


Question: I know it is a Macro we are passing to a function. How do you explain what is the use of this macro, and in which  scenario i have to use this ?.

Answer: _GNU_SOURCEenables GNU extensions to the C and OS standards supported by the GNU C library, such asasprintf. Define it when you're using such non-standard functions and macros.


Question: Could anybody tell me please how can I get framerate of WM_PAINT message in frames per second? I'm trying to make a software renderer, and framerate is very important for debugging.

Answer: This question was asked previouslyhere. As an additional hint, you can use a dynamically allocated structure to store your FPS-related variables and useSetWindowLongPtrto store a pointer to this structure.


Question:
I am using cvCanny function in opencv 2.3 it compiles fine,but while executing it gives an error saying 'tbb.dll' not found.

What is the use of this dll and where can I find this??

thanks,

Answer:
It's part of Intel'sThreading Building Blockslibrary.

You can find a copy of it in your OpenCV install in/build/common/tbband under the platform and compiler your are using. For example, inc:\OpenCV-2.3.1\build\common\tbb\intel64\vc9


Question: Could anybody tell me please how can I get framerate of WM_PAINT message in frames per second? I'm trying to make a software renderer, and framerate is very important for debugging.

Answer: This question was asked previouslyhere. As an additional hint, you can use a dynamically allocated structure to store your FPS-related variables and useSetWindowLongPtrto store a pointer to this structure.


Question:
I am using cvCanny function in opencv 2.3 it compiles fine,but while executing it gives an error saying 'tbb.dll' not found.

What is the use of this dll and where can I find this??

thanks,

Answer:
It's part of Intel'sThreading Building Blockslibrary.

You can find a copy of it in your OpenCV install in/build/common/tbband under the platform and compiler your are using. For example, inc:\OpenCV-2.3.1\build\common\tbb\intel64\vc9


Question:
Тhese are my calculations

```
float c = 5.0 * (12.0 - 32.0) / 9.0;
printf("%f.2", c);
```

Result is -11.111111.2 but I expected to be -11.11. What is wrong ?

Answer:
The format specifier should read"%.2f".

In what you have right now, the.2is misplaced. This is why you get more digits than expected, and why the.2appears verbatim at the end of the output.


Question:
I want to perform a canny edge detection in opencv 2.3,coding in c language. But when I am using cvCanny for the same purpose it gives an error as unresolved external symbol _CvCanny,though I have used a proper prototype of CvCanny.
Is there any library that i have forgot to include or what?

Regards,

Answer: You cannot link because you didn't add the correct path/ libraries to your project


Question: What is the preferred way to compile.c/.cppfiles similar togcc(Linux) incmd(Windows)? What are the most common compilers?

Answer:
I've never used this but it looks like it might be what you're looking for.http://www.mingw.org/

I think most people use Cygwin.http://www.cygwin.com/


Question: I know that this may be common knowledge, but is there a way to edit RGB values of pixels of Windows window fromC/C++without using libraries likeOpenGLorDirectX? If there is, what are the built-in functions to manipulate pixel buffer directly?

Answer: In yourWM_PAINThandler you can callSetPixel.


Question: I want to know that how can we allocate a memory block atrun-timein C or C++ without usingmallocandcallocfunctions.

Answer:
In C, usemalloc. Don't forget tofreeafter use.

In C++, usenewand don't forget todelete. Or better, usestd::vectorif you want a dynamic array.


Question: What is the preferred way to compile.c/.cppfiles similar togcc(Linux) incmd(Windows)? What are the most common compilers?

Answer:
I've never used this but it looks like it might be what you're looking for.http://www.mingw.org/

I think most people use Cygwin.http://www.cygwin.com/


Question: I know that this may be common knowledge, but is there a way to edit RGB values of pixels of Windows window fromC/C++without using libraries likeOpenGLorDirectX? If there is, what are the built-in functions to manipulate pixel buffer directly?

Answer: In yourWM_PAINThandler you can callSetPixel.


Question: I want to know that how can we allocate a memory block atrun-timein C or C++ without usingmallocandcallocfunctions.

Answer:
In C, usemalloc. Don't forget tofreeafter use.

In C++, usenewand don't forget todelete. Or better, usestd::vectorif you want a dynamic array.


Question:
TheUbuntu equivalentwould belibc6-dev, but I can't seem to find it for Solaris?

How can I get types.h and related files for building packages on Solaris or Illumos?

Answer:
You need the system/header package.

I found this viahttp://pkg.oracle.com/solaris/release/en/search.shtml?token=types.h&action=Search


Question: I want to use the unixcryptfunction in an OpenCL program. Does something like that already exist or will I have to translate it on my own?

Answer:
You've probably found an answer by now, but in case anyone else comes here from a search, John The Ripper is open source and has OpenCL acceleration for several hashing algorithms, including the 3DES used in BSD crypt().

https://github.com/magnumripper/JohnTheRipper/tree/bleeding-jumbo/src/opencl


Question:
Is there a C function that doesn't wait for input but if there is one, it detects it?
What I'm trying to do here is continue a loop endlessly until any key is pressed.
I'm a newbie, and all the input functions I've learned so far waits for the user to input something..
I hope I'm clear, although if I'm not I'm happy to post the code..

Answer: WIndows kbhit( ) does exactly thisnon-blocking keyboard char-ready check, and there's a kbhit( ) for Linuxover here


Question:
Is there a C function that doesn't wait for input but if there is one, it detects it?
What I'm trying to do here is continue a loop endlessly until any key is pressed.
I'm a newbie, and all the input functions I've learned so far waits for the user to input something..
I hope I'm clear, although if I'm not I'm happy to post the code..

Answer: WIndows kbhit( ) does exactly thisnon-blocking keyboard char-ready check, and there's a kbhit( ) for Linuxover here


Question:
Is there a C function that doesn't wait for input but if there is one, it detects it?
What I'm trying to do here is continue a loop endlessly until any key is pressed.
I'm a newbie, and all the input functions I've learned so far waits for the user to input something..
I hope I'm clear, although if I'm not I'm happy to post the code..

Answer: WIndows kbhit( ) does exactly thisnon-blocking keyboard char-ready check, and there's a kbhit( ) for Linuxover here


Question:
IN LINUX:
Not sure if it is possible. I have 100 source file, and 100 respective executable files.
Now, given the executable file, is it possible to determine, respective source file.

Answer:
I guess you can give this a try.

```
readelf -s a.out | grep FILE
```

I think you can add somegrepandsedmagic to the above command and get the source file name.


Question: What is the difference between these three functions ?

Answer: Those aren't standard functions, but usually it's the return type: signed int, unsigned, and 32-bit respectively.


Question:
I am having trouble on connecting my C program to mysql. I've done most of the research but seems its quite difficult. Can someone please help? the image below shows the error using the command I typed to compile the code.

Your answers are highly appreciated.
BTW, I am a windows user.

Answer: It looks like your LD_LIBRARY_PATH isn't set.  I believe you need that to be able to find the libraries required by the linker.


Question: Is installed CUDA capable graphics card necessary (in Linux) for compiling CUDA programs withnvcc? Or one can compile programs everywhere and run only on such systems?

Answer:
No, a graphics card is not necessary for compilation.

You don't even need one to run the program; you can have it emulated in software.

UPDATEOk, apparently, SW emulation hasn't been supported since CUDA 3.0.


Question:
I am having trouble on connecting my C program to mysql. I've done most of the research but seems its quite difficult. Can someone please help? the image below shows the error using the command I typed to compile the code.

Your answers are highly appreciated.
BTW, I am a windows user.

Answer: It looks like your LD_LIBRARY_PATH isn't set.  I believe you need that to be able to find the libraries required by the linker.


Question: Is installed CUDA capable graphics card necessary (in Linux) for compiling CUDA programs withnvcc? Or one can compile programs everywhere and run only on such systems?

Answer:
No, a graphics card is not necessary for compilation.

You don't even need one to run the program; you can have it emulated in software.

UPDATEOk, apparently, SW emulation hasn't been supported since CUDA 3.0.


Question:
Is there any library for q-encoding? I need to decode some q-encoded text, such as:

```
**Subject: =?iso-8859-1?Q?=A1Hola,_se=F1or!?=**
```

Answer:
GNU Mailutils libmailutilsis one example of such library.

"Q"-encoding is specified byRFC 2047so using it as a search term gives you other relevant results.


Question: When I use C programs, many of them defines their own error mechanisms. For that cases, I can follow their definition. How about C base libraries? Is it enough with onlyerrno?

Answer: You have to look at each function you call and then handle the return value orerrnosetting as appropriate. There is no general error handling (e.g. exceptions) beyond that.


Question:
Is there a #define that indicates whether Visual Studio is compiling in 64bit mode? I'd like to be able to include some code conditionally like so

```
#ifdef _IS_64BIT
  ...
#else //32 bit
  ...
#endif
```

I know I can create a flag myself, but I'm wondering if the compiler provides one.

Answer:
```
#ifdef _WIN64
  ...
#else
  ...
#endif
```

Documented onMicrosoft docs


Question:
I was wondering if there is a way to get the installed memory type in Windows? I mean is there an API or any other way to query that on a PC there is DDR2 or DDR3 or SDRAM installed?

Thanks!

Answer:
CPU-IDis able to do it, so it's definitely possible. They have aSDKavailable, but it'sexpensive.

QueryingWin32_PhysicalMemoryusing WMI may also help and is possible usingC/C++.


Question:
I am trying to find an integer type length in C. Does anyone have a quick algorithm to check the length of it?

Thanks.

Answer:
Do you mean this?

```
sizeof (int)
```

If you want it measured in bits, try

```
#include <limits.h>
(CHAR_BIT * sizeof (int))
```


Question: I want to create a processBfrom processA. However, I don't wantBto be the child ofA, which will be the case if I simply usefork. How can I achieve that? In other words I want processBto keep on executing even if processAis killed.

Answer:
You can use the setsid() function.

Alternatively, as you have tagged your question "linux", maybe you want to use daemon() instead of fork() + setsid().


Question:
how do I allocate memory forstrlen(esc)in a proper way? Thetempandstrare char datatypes.

```
double esc = t1.tv_sec+(t1.tv_usec/1000000.0);
strAll = malloc(strlen(temp) + strlen(str) + strlen(esc) + 1);
```

Answer: You cannot takestrlen(esc). As I am sure the compiler has already told you, the argument tostrlen()must bechar *, you are passing it adouble. Try first converting thedoubleto array ofcharwithsnprintf().


Question:
Is there a #define that indicates whether Visual Studio is compiling in 64bit mode? I'd like to be able to include some code conditionally like so

```
#ifdef _IS_64BIT
  ...
#else //32 bit
  ...
#endif
```

I know I can create a flag myself, but I'm wondering if the compiler provides one.

Answer:
```
#ifdef _WIN64
  ...
#else
  ...
#endif
```

Documented onMicrosoft docs


Question:
I was wondering if there is a way to get the installed memory type in Windows? I mean is there an API or any other way to query that on a PC there is DDR2 or DDR3 or SDRAM installed?

Thanks!

Answer:
CPU-IDis able to do it, so it's definitely possible. They have aSDKavailable, but it'sexpensive.

QueryingWin32_PhysicalMemoryusing WMI may also help and is possible usingC/C++.


Question:
I am trying to find an integer type length in C. Does anyone have a quick algorithm to check the length of it?

Thanks.

Answer:
Do you mean this?

```
sizeof (int)
```

If you want it measured in bits, try

```
#include <limits.h>
(CHAR_BIT * sizeof (int))
```


Question: I want to create a processBfrom processA. However, I don't wantBto be the child ofA, which will be the case if I simply usefork. How can I achieve that? In other words I want processBto keep on executing even if processAis killed.

Answer:
You can use the setsid() function.

Alternatively, as you have tagged your question "linux", maybe you want to use daemon() instead of fork() + setsid().


Question:
Is there any possiblty to swap three numbers in a single statement

Eg :

a = 10b = 20c = 30

I want values to be changed as per the following list

```
a = 20
b = 30
c = 10
```

Can these values be transferred in a single line?

Answer:
```
$ python
>>> a, b, c = 10, 20, 30
>>> print a, b, c
10 20 30
>>> a, b, c = b, c, a
>>> print a, b, c
20 30 10
```


Question:
Is there any possiblty to swap three numbers in a single statement

Eg :

a = 10b = 20c = 30

I want values to be changed as per the following list

```
a = 20
b = 30
c = 10
```

Can these values be transferred in a single line?

Answer:
```
$ python
>>> a, b, c = 10, 20, 30
>>> print a, b, c
10 20 30
>>> a, b, c = b, c, a
>>> print a, b, c
20 30 10
```


Question: What is the best way to represent a C array in Erlang?  I plan on passing a C array to Erlang using NIF.  The array is composed of bytes and I'll need to modify some of the bytes as the program runs.  Any help is appreciated.

Answer: If function in NIF not reallocate array than you can represent you array as a tuple with two elements - raw pointer and elements count.


Question:
When I disassembled my C code, I saw the following. What does this code do exactly? Does it have something to do with floating points?

```
movsd  (%rdx,%rax,8),%xmm0
mulsd  %xmm0,%xmm0
movsd  %xmm0,0x30(%rsp)
```

Answer:
it squares a number:

```
xmm0=*(rdx*8+rax);
xmm0*=xmm0;
rsp[0x30]=xmmm0;
```

xmm0 is a floating point register.


Question: How can you know ifpopen()succeeded/done running the shell or failed?

Answer:
popen return value:

Upon successful completion, popen() shall return a pointer to an open
  stream that can be used to read or write to the pipe. Otherwise, it
  shall return a null pointer and may set errno to indicate the error.

```
fp = popen("ls *", "r");
if (fp == NULL)
    /* Handle error */;
```


Question: How to process (in read-only fashion) a big binary file inC/C++onLinuxas fast as possible? Viareadormmap? What buffer size? (No boost or anything.)

Answer:
mmap is faster and optimal for read only applications.  See answer here:

https://stackoverflow.com/a/258097/1094175


Question: How can you know ifpopen()succeeded/done running the shell or failed?

Answer:
popen return value:

Upon successful completion, popen() shall return a pointer to an open
  stream that can be used to read or write to the pipe. Otherwise, it
  shall return a null pointer and may set errno to indicate the error.

```
fp = popen("ls *", "r");
if (fp == NULL)
    /* Handle error */;
```


Question: How to process (in read-only fashion) a big binary file inC/C++onLinuxas fast as possible? Viareadormmap? What buffer size? (No boost or anything.)

Answer:
mmap is faster and optimal for read only applications.  See answer here:

https://stackoverflow.com/a/258097/1094175


Question:
Can someone explain please how to set a filter usingstruct bpf_programmemberstruct bpf_insn? All documentation and tutorials are welcome, for example what would be the struct bpf_insn if i want to filter for example dhcp, dns or ...?

Thanks for your help.

Answer:
This tutorial uses struct bpf_program to create a filter program, not sure if that helps much but it's worth a look. (scroll down to the tcp bit).

http://www.enderunix.org/docs/en/rawipspoof/


Question:
I'm learning C . I want to list an array's values.

In PHP :

```
$arr = array("laguna", "megane", "clio");
foreach($arr as $no => $name)
{
     echo $no." ) ".$name;
}
/*
Output :
0) Laguna
1) Megane
2) Clio
*/
```

How can i do it in C?

Answer:
In C

```
char* arr[] = {"laguna","megane","clio",NULL};

for( int i = 0; arr[i]; i++)
{
   printf("%d) %s\n",i,arr[i]);
}
```


Question:
What is mnemonic for "W" i.e. what does "W" mean in the following macros:

```
int WIFEXITED (int status)
int WEXITSTATUS (int status)
int WIFSIGNALED (int status)
int WTERMSIG (int status)
int WCOREDUMP (int status)
int WIFSTOPPED (int status)
int WSTOPSIG (int status)
```

Also seeProcess Status Completion.

Answer: It is simply related toW-aiting functions like thewaitpidsyscall.


Question: Is there an efficient way of finding thetask_structfor a specified PID, without iterating through thetask_structlist?

Answer:
What's wrong with using one of the following?

```
extern struct task_struct *find_task_by_vpid(pid_t nr);
extern struct task_struct *find_task_by_pid_ns(pid_t nr,
            struct pid_namespace *ns);
```


Question: Is there an efficient way of finding thetask_structfor a specified PID, without iterating through thetask_structlist?

Answer:
What's wrong with using one of the following?

```
extern struct task_struct *find_task_by_vpid(pid_t nr);
extern struct task_struct *find_task_by_pid_ns(pid_t nr,
            struct pid_namespace *ns);
```


Question:
Is it possible to write a string on aIplImagewith Opencv 2.1 in C/C++?

Thank you.

Answer:
Yes,cvPutText():

```
CvFont font;
double hScale=1.0;
double vScale=1.0;
int    lineWidth=1;
cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth);

cvPutText (img,"My comment",cvPoint(200,400), &font, cvScalar(255,255,0));
```


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

Possible Duplicate:Meaning of U suffix

I'm going through code that has a bunch of defines that look like:
    #define HEX_NUMBER (0x000000FFu)

What is the trailing u?  I've tried compiling with and without it and I don't see any difference.

Answer: Appendinguto any integral constant makes the compiler interpret it as unsigned.


Question: Using x86 platform ,  I want to start my application named myapp  through  this method:execl("./myapp","");It's OK! But  failed when I'm using ARM platform + embedded linux. Why ?   Any help will be appreciated. Thanks in advance.

Answer:
Your invocation is wrong:execl()'s argument list MUST be terminated withNULL.

The fact that it works at all on x86 is a miracle ;)


Question:
I know that I am asking an incredibly low level question, but I am unfamiliar with C and am trying to convert an expression to Objective-C. What does this mean?

```
double (*x)[2]
```

Thanks.

Answer: With a semicolon at the end, it declares and defines a pointer (namedx) to a array of 2 doubles. If it's a function (or method) argument, its type is the same: a pointer to an array of 2 doubles.


Question:
The standard predefined macro__FILE__available in C shows the full path to the file. Is there any way to shorten the path and get just the filename? I mean instead of

```
/full/path/to/file.c
```

I see

```
to/file.c
```

or

```
file.c
```

Answer:
Try

```
#include <string.h>

#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
```

For Windows use '\\' instead of '/'.


Question:
How to swap the nibble bit positions of a number?

For example: 534, convert it into binary, the rightmost 4 bits has to be interchanged with the leftmost 4 bits and then make a new number with that.

Anyone know how to do this?

Answer:
Sean Anderson's bit twiddling guidehas the following:

```
// swap nibbles ...
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
```

under the entry forReverse an N-bit quantity in parallel in 5 * lg(N) operations.


Question:
The standard predefined macro__FILE__available in C shows the full path to the file. Is there any way to shorten the path and get just the filename? I mean instead of

```
/full/path/to/file.c
```

I see

```
to/file.c
```

or

```
file.c
```

Answer:
Try

```
#include <string.h>

#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
```

For Windows use '\\' instead of '/'.


Question:
How to swap the nibble bit positions of a number?

For example: 534, convert it into binary, the rightmost 4 bits has to be interchanged with the leftmost 4 bits and then make a new number with that.

Anyone know how to do this?

Answer:
Sean Anderson's bit twiddling guidehas the following:

```
// swap nibbles ...
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
```

under the entry forReverse an N-bit quantity in parallel in 5 * lg(N) operations.


Question:
Iwant to transfer a file to a particular directory on FTP server . If it does not exists on the server then it has to be created there and file will be placed .

Platform : Linux , gcc compiler
Thanks .

Answer: Start with theftpuploadexample inlibcurl.


Question:
I got a pcap file with voip conversation, how i can separate RTP packets from the other packets?

I can obtain sip packets, but I can't differenciate the RTP packets from the rest.

Answer: Search for RTP headers as defined inRFC3550within your file. Or better use pcap-filter, for instance withthiswiki (look for "Q: What is a good filter for just capturing SIP and RTP packets?").


Question:
Iwant to transfer a file to a particular directory on FTP server . If it does not exists on the server then it has to be created there and file will be placed .

Platform : Linux , gcc compiler
Thanks .

Answer: Start with theftpuploadexample inlibcurl.


Question:
I was just wondering whether it was possible to do something like this:

```
char yn;

scanf("%79/6ec",yn);
```

so yn can only become either y (0x79) or n (0x6e)

Answer:
No , but you could use scanf to read a char

```
scanf("%c" , &yn );
```

after that you have to check whether it is y/n or illegal input.

```
if ( yn == 'y' ) {
  ...
}
```


Question:
How do I format a time_t structure to something like this year-month-day h:m:s,
I have already tried using ctime:

```
time_t t = time((time_t*) NULL);
char *t_format = ctime(&t);
```

but it doesn't give me the desired results

example :
2011-11-10 10:25:03. What I need is a string containing the result so I can write it to a file. Thanks

Answer:
Usestrftimefromtime.hlike so:

```
char tc[256];
strftime(tc, 256, "%Y-%m-%d %H:%M:%S", tm);
```


Question:
I have C program ( program.c )  that calls a shell script ( command.sh ).
command.sh returns an output (a password), i  need to get this output in my program.c.
usingsystem(command);, i can't get hold of the output.
is there any other way in C to solve my problem?

Answer:
Not in pure C. You want POSIX. Specificallypopenfunction.

The specification has a nice example, that you can just copy 1:1http://pubs.opengroup.org/onlinepubs/009604499/functions/popen.html


Question:
Is there a tool toautomaticallygenerate Fortanbindingsfrom C library header, using intrinsiciso_c_bindingsmodule from Fortran 2003 standard?

I am not interested intranslatingC to Fortran, but only generating bindings.

Answer: An automatic tool was used to get thegtk-fortranbindings. It is a Python scriptcfwrapper.py. You might be able to adapt it to for your needs, although for my small problems I finally chose to make the bindings by hand.


Question: I need to create a string on the heap, I was wondering if there is something similar already included in the standard libraries, or do I have to implement it myself (using malloc())?

Answer:
You could usemalloc(),calloc()orstrdup()(the latter is POSIX, not standard C).

It is not totally clear what you mean by "implement it myself (usingmalloc())" -- what exactly is there to implement?


Question:
I have a string,

```
char* str = "HELLO"
```

If I wanted to get just theEfrom that how would I do that?

Answer:
```
char* str = "HELLO";
char c = str[1];
```

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" isstr[0], "E" isstr[1], the first "L" isstr[2]and so on.


Question:
I have two filesPosit.candHeadPose.cpp

Posit.ccompiled toPositnew

My question is

How to call already compiled Positnew like thissystem("Positnew");from HeadPose.cpp

Answer:
Just use c keywordexternto declare the function then the linker will make sure that it can be linked either dynamically or statically.

extern void Positnew()


Question:
I want to set up an environment on my PC (Win7x64) that I will be able to combine these projects and compile them into one executable:

FFmpegAMV codec tools

For this I need an environment that can compile/debug both the above projects (creating a Windows compatible exe).

Any ideas?

Answer: http://ffmpeg.arrozcru.org/wiki/index.php?title=Main_PageNetBeans can handle MinGW.  (Might be other IDEs, but I've used MinGW under NetBeans so I know it can.)


Question:
I want to set up an environment on my PC (Win7x64) that I will be able to combine these projects and compile them into one executable:

FFmpegAMV codec tools

For this I need an environment that can compile/debug both the above projects (creating a Windows compatible exe).

Any ideas?

Answer: http://ffmpeg.arrozcru.org/wiki/index.php?title=Main_PageNetBeans can handle MinGW.  (Might be other IDEs, but I've used MinGW under NetBeans so I know it can.)


Question:
I am new to the C language and pointers and I am confused by this function declaration:

```
void someFunction(int (*)(const void *, const void *));
```

Can anyone explain in layman's terms what this does and how it works?

Answer:
It's the prototype of a function that takes:

a pointer to a function that takes aconst void*and aconst void*as arguments and returns anint

as an argument, and returnsvoid.


Question: Are there some libraries with C API to draw pictures? Just like the librarymatplotlibin python. I will use it to draw lines, dots, circles and I hope it has detailed documentation and opensource. My platform is gentoo.

Answer:
The most comprehensive one is probablyImageMagick. They suggest using theMagickWandAPI.

Other options arecairo, with a image buffer output device, or maybelibgd.


Question: I'm using__get_cpuid()to get info on thex86andx86_64processors my programs run on. With GCC on Linux and Mac OS, it seems to compile and run OK without include any header, but how portable is that? Would it work with other compilers? Should I include a header for that?

Answer: It has two leading underscores. Any leading underscore at all is a big hint that the variable or function is not portable.


Question:
Is there a way to do something like this.

```
printf("Display Time is %S\n",system("date"));
```

I know I can use the time structure to printout the date but I would like to know whether I can do something like this.

Answer:
system("date > out.txt");

after read out.txt

or

popen()


Question:
for example in Python:

```
number = struct.unpack('!L', socket.inet_aton(ip))[0]
ip = socket.inet_ntoa(struct.pack('!L',number))
```

Answer: inet_addr,inet_aton,inet_ntoa, there are quite a few functions, try looking up the documentation.


Question:
for example in Python:

```
number = struct.unpack('!L', socket.inet_aton(ip))[0]
ip = socket.inet_ntoa(struct.pack('!L',number))
```

Answer: inet_addr,inet_aton,inet_ntoa, there are quite a few functions, try looking up the documentation.


Question: OK, when a program tries to access a page which is not there in the physical memory, we say a page fault has occurred. But say, program tries to write to a page which is read-only and is there in the physical memory. What is that fault called?

Answer:
According to Intel terminology, it'smemory access violation, aka#AVexception.

(I know, there is [linux] tag, but also there is [x86] tag.)


Question:
How do I make the functions align at 4-byte boundaries with GCC, target 680x0?

-malign-functions=4does not seem to do the trick, by itself anyway. Some kind of option meant to improve cache performance on 68020 and up perhaps?

Answer: -malign-functions=4should do the trick but it can be overridden with thefunction attributealigned(). Make sure that your code doesn't use this (for example with a macro).


Question:
Let us say that I declare and initialize

```
int a[3] = {1, 2, 3};
```

How can I later asisgn the entire array in one fell swoop? i.e.

```
a = {3, 2, 1};
```

Answer:
If your c compiler supports compound literals, you can usememcpy:

```
memcpy(a, (int[]){3, 2, 1}, sizeof a);
```

If you don't plan to stick any variables in there (you can; isn't C99 amazing?),(int[])can be replaced by(const int[])to put the literal into static memory.


Question: If I want to transport a signed long (32 bit integer) across the network what do I do?  If I send as a signed long then at other end I won't know (potentially) how remote machine represents signed numbers?  So what do I do?

Answer: Just usentohlandhtonland cast or implicitly convert back and forth betweenuint32_tandint32_t.


Question:
Is there any way to convert C/C++ to Assembly not to HEX.

Not like something that gcc or other compiler done(C/C++ --> ASM --> HEX).

Only Convert It to ASM.

Is there any way to do it by gcc,I mean stop compiler when translate C/C++ to ASM?

with special thanks for your attention,and so sorry for my basic question

Answer:
Use the-Soption of gcc, for example:

```
gcc -S hello.c
```

This will give you a filehello.swith assembly instructions.


Question: I need to write files to the /etc folder on an embedded system with the root partition mounted as Read Only and have them persist. Can I do this in C or C++ assuming that the application is running as root?

Answer:
You can always do the obvious:

```
system("mount -o remount,rw /etc");
```

Most embedded systems should be complete enough that mount is available.


Question:
I am using Ubuntu 10.10 (64 bit) withgccand I wanted to use a 64 bit integer in my C++ program.

On my system the outputs ofsizeof(long),sizeof(long long int)andsizeof(int64_t)are all 8 bytes (64 bits).

Which qualifier (long,long long, orint64_t) would you recommend for using 64 bit integers?

Answer: int64_t-- This is because it is the most portable representation. The other two could be represented differently on other machines.


Question: If I want to transport a signed long (32 bit integer) across the network what do I do?  If I send as a signed long then at other end I won't know (potentially) how remote machine represents signed numbers?  So what do I do?

Answer: Just usentohlandhtonland cast or implicitly convert back and forth betweenuint32_tandint32_t.


Question:
Is there any way to convert C/C++ to Assembly not to HEX.

Not like something that gcc or other compiler done(C/C++ --> ASM --> HEX).

Only Convert It to ASM.

Is there any way to do it by gcc,I mean stop compiler when translate C/C++ to ASM?

with special thanks for your attention,and so sorry for my basic question

Answer:
Use the-Soption of gcc, for example:

```
gcc -S hello.c
```

This will give you a filehello.swith assembly instructions.


Question: I need to write files to the /etc folder on an embedded system with the root partition mounted as Read Only and have them persist. Can I do this in C or C++ assuming that the application is running as root?

Answer:
You can always do the obvious:

```
system("mount -o remount,rw /etc");
```

Most embedded systems should be complete enough that mount is available.


Question: I have a C console app where I need to output the absolute path to a file given a (possibly) relative path. What is the best way to do this in C in a Windows environment?

Answer: I think you are looking for_fullpath().


Question: Could someone say me where I can found the source file where are the definitions of the standard libraries?For example, where is the filestring.cthat contains the definitions of the function prototyped instring.h? And above all, it exists?

Answer: its all in compilled state, some of maybe optimized by asm. You need find sources of your compiler to see definitions


Question:
While debugging a multithreaded c program using GDB, how do I find out the execution position of individual threads in situations like " the execution of a program hanging midway".

Thanks

Answer: Hit Contol-C to get the(gdb)prompt, and thenthread apply all where.


Question: How to put the contents of a 32 bit CPU register in a byte array?

Answer:
Basically you need to write inline assembly to read contents of some register. For example - to read ESP register into some int variable (Windows & Visual Studio) - you would do something like this:

```
int stackpointer = 0;
    __asm {
        mov stackpointer, esp
    }
    printf("stack pointer: %i\n", stackpointer);
```


Question: Assume we have a pointer(e.g., defined as int* p) to the beginning of an array and the size of the array(e.g., 1000). We want to reset all 1000 array values to 0. What is the simplest way?

Answer:
The simplest way would be to use memset.

```
memset(p, 0, 1000 * sizeof(int));
```


Question:
Does there exist a test framework for C that forces race conditions?

Or for C++ and Java, for that matter.

Answer: The Valgrind toolHelgrinddetects (among other things) data races in C or C++ programs that use pthreads.


Question:
I need to extract hours, minutes and seconds from a string formatted as e.g: "00:53:12" to variables a, b and c.

How would I go about this in C?

Thanks in advance!

Answer:
You can usestrptime

```
struct tm tm;

if (strptime("00:53:12", "%H:%M:%S", &tm) != NULL)
   printf("hour: %d; minutes: %d; seconds: %d;\n",
      tm.tm_hour, tm.tm_min, tm.tm_sec);
```


Question: What is the best or recommended method for bit shifting a large amount of binary data in C? I have a 200K binary file and I want to left, then right shift the entire lot.

Answer:
If your OS can support it use a memory mapped file. Then do a bit shift It'll be very very efficient.

See this answer for more info:What are the advantages of memory-mapped files?


Question:
Does there exist a test framework for C that forces race conditions?

Or for C++ and Java, for that matter.

Answer: The Valgrind toolHelgrinddetects (among other things) data races in C or C++ programs that use pthreads.


Question:
Is there a way to change the defaulta.outto something nicer, likefile.cautomatically becomesfile?

I know one can do this withgcc file.c -o file, but... is there something easier?

Answer:
No.

Although if you havemakeavailable, you can just do:

```
make file
```


Question:
How to formatstruct timespecto string? This structure is returned e.g. byclock_gettime()on Linux gcc:

```
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};
```

Answer:
One way to format it is:

```
printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec);
```


Question:
Why is:

```
if(x!=y!=z)
```

handled as:

```
x=1
y=1
z=2
```

??

I just noticed it today.

Answer:
x != yandx == yreturn booleans.You're comparingzto those booleans.

Neither of them will work they way you want them to.


Question: What is the best way to duplicate an integer array? I knowmemcpy()is one way to do it. Is there any function likestrdup()?

Answer:
There isn't, andstrdupisn't in the standard, either. You can of course just write your own:

```
int * intdup(int const * src, size_t len)
{
   int * p = malloc(len * sizeof(int));
   memcpy(p, src, len * sizeof(int));
   return p;
}
```


Question: I'm used to//to mark a single line comment from Java and Visual Studio and was surprised that this does not exist for Ansi-C. Using/* my comment */is quite annoying. Is there any other way to mark a single line comment when using Ansi-C?

Answer: ANSI-C, no, but the current standard revision allows them, and has done so ever since C99.


Question:
Recently I foundthis articlethat claims that the idea to preferfor(;;)overwhile(1)for infinite loop came because the C compiler originally available on PDP-11 generated an extra machine instruction forwhile(1).

Btw now even Visual C++ warningstend to favor the former.

How realistic is such attribution offor(;;)idiom?

Answer: The "for(;;)" idiom is explicitly mentioned in the original K&R.  That's attribution enough for me :)


Question: What is a "verbose build" in C? I can's seem to find a good answer. There's a check box in Pelles C for Verbose Build and I can't figure out what this does. Does it include libraries in with the exe or something?

Answer: No, it simply spits out more messages for you during the building process.


Question:
Is there a way to loop through all the included/defined header files and then#undefthem all?

If looping is the issue, is there another way to#undefall of them with ease?

Answer:
GNU cpp provides a -dM directive to do exactly that, you can list all the defines:

gcc -E -dM -c foo.c

You can then use a sed script to undef them on command line :)

gcc -E -c foo.c | sed 's/#define/#undef/'

or do whatever...

have fun :)


Question:
I need some clever logging library for a daemon-likeC(notC++) program on Linux. It needs to be open-source. It should support logging to files, maybe sockets etc.

Or at least some good tips or tricks or best practices.

Answer: Usesyslog() . This decouples your in program logging from how the logs are handled.rsyslogis used on most Linux distributions nowadays, and allows great flexibility on how the logs are processed.


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.Closed10 years ago.

Please, advise me SDK for emulating a file system? (Windows)

Thanks.

Answer: There are multiple possibilities of applications for windows . I'm usingboxedapp.


Question:
How do you convert anint(integer) to a string?

I'm trying to make a function that converts the data of astructinto a string to save it in a file.

Answer:
You can usesprintfto do it, or maybesnprintfif you have it:

```
char str[ENOUGH];
sprintf(str, "%d", 42);
```

Where the number of characters (plus terminating char) in thestrcan be calculated using:

```
(int)((ceil(log10(num))+1)*sizeof(char))
```


Question:
Current way:

```
while(read(pipe, input, sizeof(input))>0);
```

Is there a better one with seeking?

Answer: Pipes on computers are like pipes in the "real" world... Data flows from one end to the other, and once it's gone from the pipe there is no getting it back. And like a real pipe there is no knowing when the flow will stop, so there is no meaning to try and find the end of the flow before it actually ends.


Question: Is it possible to create (or open existing) C program files in Netbeans without creating an entire project? Can these be later run and compiled?

Answer: You can use Netbeans as fancy oversized editor for C files, but if you want to build program from Netbeans, you will need a project.


Question:
Any sample on makingEntryElementalign to the right?

I can't figure out how to inherit/override theEntryElement.

Thanks,
Mojo

Answer:
This looks near identicalMonoTouch.Dialog: Setting Entry Alignment for EntryElement

See my ownanswerabout overridingCreateTextField.


Question: Does it make sense to both write and read on a socket (SOCK_STREAM) in parallel with multiple threads? On Linux. Do those syscalls block each other?

Answer: Yes, it makes sense. Since they are in separate threads they do not block each other.


Question: Is it possible to create (or open existing) C program files in Netbeans without creating an entire project? Can these be later run and compiled?

Answer: You can use Netbeans as fancy oversized editor for C files, but if you want to build program from Netbeans, you will need a project.


Question: How can I, in C, output a value from a syscall to the Linux console so that it will be visible after admesg? What method do I use for printing?

Answer: You're looking for theprintk()function; some documentation on the types that it supports is found inDocumentation/printk-formats.txt. It is defined inkernel/printk.c.


Question:
```
class app {
        public int x = 3;

        static void Main(string[] args)
        {
        }
}
```

it's possible get the memory address allocated byxvariable?

the example can be inC,C++,C#orD.
I hope it is clear
Thanks in advance

Answer:
The ampersand (&) is the "address-of" operator in most C-like languages:

```
int x;
printf("Address of x is %p\n", &x);
```

The return value of&is effectively apointerto its operand.


Question: I'm using Netbeans to write a C program. Where do I need to paste my input.txt file for the program to read it if I don't want to specify a directory in the program?

Answer: In the currentworking directorywhere the program executes.  You'll have to see where exactly Netbeans causes the binary to be output, but most likely, you will want your input.txt file to be in that same directory. Possibly abinsubdirectory of wherever your source is.


Question:
The Names array of char* is located in file1.cpp

```
char* Names[] = {

    "name1",
    "name2",
    ...
    "nameN"
};
```

How do I declare it as "extern" in file2.cpp in order to get the values?

Answer:
```
extern char *Names[];
```

This should probably go in file1.h.


Question: How can I, in C, output a value from a syscall to the Linux console so that it will be visible after admesg? What method do I use for printing?

Answer: You're looking for theprintk()function; some documentation on the types that it supports is found inDocumentation/printk-formats.txt. It is defined inkernel/printk.c.


Question:
```
class app {
        public int x = 3;

        static void Main(string[] args)
        {
        }
}
```

it's possible get the memory address allocated byxvariable?

the example can be inC,C++,C#orD.
I hope it is clear
Thanks in advance

Answer:
The ampersand (&) is the "address-of" operator in most C-like languages:

```
int x;
printf("Address of x is %p\n", &x);
```

The return value of&is effectively apointerto its operand.


Question: I'm using Netbeans to write a C program. Where do I need to paste my input.txt file for the program to read it if I don't want to specify a directory in the program?

Answer: In the currentworking directorywhere the program executes.  You'll have to see where exactly Netbeans causes the binary to be output, but most likely, you will want your input.txt file to be in that same directory. Possibly abinsubdirectory of wherever your source is.


Question:
The Names array of char* is located in file1.cpp

```
char* Names[] = {

    "name1",
    "name2",
    ...
    "nameN"
};
```

How do I declare it as "extern" in file2.cpp in order to get the values?

Answer:
```
extern char *Names[];
```

This should probably go in file1.h.


Question:
The Names array of char* is located in file1.cpp

```
char* Names[] = {

    "name1",
    "name2",
    ...
    "nameN"
};
```

How do I declare it as "extern" in file2.cpp in order to get the values?

Answer:
```
extern char *Names[];
```

This should probably go in file1.h.


Question:
Looking at man 2 write:

```
"On error, -1 is returned, and errno is set appropriately."
```

But if write(2) just fail, it makes nonsense to write an error message right after...
maybe i should write an error message on stderr or maybe just exit() on the first write error?

What do you think?

Answer: In a typical command line program, error messages shouldalwaysbe written tostderr, that's what it's for.


Question:
my question is on execution what will happen to parent stack?

```
main()
{
    f();
    g();
}
f()
{
   vfork();
}
g()
{
    int blast[100],i;
    for(i=0;i<100;i++)
        blast[i]=i;
}
```

Answer:
The behavior is undefined as perhttp://pubs.opengroup.org/onlinepubs/009695399/functions/vfork.html

the behavior is undefined if the process created by vfork() [...] returns from the function in which vfork() was called [...]


Question:
When I use C Api for Mysql, I heard that I need to compile with gcc like
gcc $(mysql_config --cflags --libs) source.c
but it is tired using this awkward whenever compile c file using mysql.

isn't there any good ways to compile like
gcc source.c
when using Mysql C api.

please help me!

Answer: Learn how to write a smallMakefile, and you'll simply typemaketo compile your program.


Question:
I need a way using the Win32 API to force shutdown my machine.

I am currently using Windows 7 but O'd really like if the code would work for Vista and XP.

Answer: Isn'tExitWindowsEx()enough for your needs?


Question:
I have  a C program that invokes a java program but I have a problem:
my java program returns an int [], how can I use JNI to get the result of it in C, since JNI only has CallIntMethod?

Answer: Arrays are objects, so you can useCallObjectMethod(). UseGetIntArrayElements()to access the array elements.


Question:
my question is on execution what will happen to parent stack?

```
main()
{
    f();
    g();
}
f()
{
   vfork();
}
g()
{
    int blast[100],i;
    for(i=0;i<100;i++)
        blast[i]=i;
}
```

Answer:
The behavior is undefined as perhttp://pubs.opengroup.org/onlinepubs/009695399/functions/vfork.html

the behavior is undefined if the process created by vfork() [...] returns from the function in which vfork() was called [...]


Question:
When I use C Api for Mysql, I heard that I need to compile with gcc like
gcc $(mysql_config --cflags --libs) source.c
but it is tired using this awkward whenever compile c file using mysql.

isn't there any good ways to compile like
gcc source.c
when using Mysql C api.

please help me!

Answer: Learn how to write a smallMakefile, and you'll simply typemaketo compile your program.


Question:
I work on a library to parse connection information from a satellite modem. It sends this information as an UDP package over the network, which I receive withrecvfrom().

What information do I get via thebufferparameter ofrecvfrom()? Is it only the UDP message field, or do I get more information about the UDP package?

Answer: The buffer will only receive the payload data of the packet. Headers are not included.


Question:
Do signal handlers have a separate stack, (like each thread have separate stacks)?

This is in Linux/C context.

Answer:
From the Linux manual pagesignal(7):

```
By default, the signal handler is invoked on the normal process stack.
It is possible to arrange that the signal handler uses an alternate stack;
see sigaltstack(2) for a discussion of how to do this and when it might
be useful.
```


Question: I have a number for example:2.4444444. I need to get first digit after the dot -- in my case it's4. How to implement it?

Answer:
How about

```
( (int)(floor( fabs( num ) * 10 ) ) ) % 10
```


Question:
Is it possible to place a linked list index before the output of result in opencv?
For example, I have code

```
for( ; i!= 0; i= i->h_next )
    {
    printf("Index number = %d   Area = %.2f \n",n, area);
    }
```

Now, my question is, how to print this index number? As the values ofiare not in 1,2,3 and so on..

Answer:
Maybe try:

```
int cnt = 0;
for ( .. ) {
    printf("%d\n", cnt++);
}
```


Question:
I simply write this:

```
char* test="test";
printf("%s",test[0]);
```

it says seg fault;
then I change toprintf("%s",&test[0]);the error gone
But this is not what I want;
the console print: "test "
how to get just value "t" from that pointer?

Answer:
If you want just thet, you should do:

```
printf("%c",test[0]);
```

The format%c, will print a singlechar.

%swill print the entire null-terminated string.


Question: I have a number for example:2.4444444. I need to get first digit after the dot -- in my case it's4. How to implement it?

Answer:
How about

```
( (int)(floor( fabs( num ) * 10 ) ) ) % 10
```


Question:
Is it possible to place a linked list index before the output of result in opencv?
For example, I have code

```
for( ; i!= 0; i= i->h_next )
    {
    printf("Index number = %d   Area = %.2f \n",n, area);
    }
```

Now, my question is, how to print this index number? As the values ofiare not in 1,2,3 and so on..

Answer:
Maybe try:

```
int cnt = 0;
for ( .. ) {
    printf("%d\n", cnt++);
}
```


Question:
I simply write this:

```
char* test="test";
printf("%s",test[0]);
```

it says seg fault;
then I change toprintf("%s",&test[0]);the error gone
But this is not what I want;
the console print: "test "
how to get just value "t" from that pointer?

Answer:
If you want just thet, you should do:

```
printf("%c",test[0]);
```

The format%c, will print a singlechar.

%swill print the entire null-terminated string.


Question: I am using Visual studio in windows for developing C library. Can someone please provide me simple example of creating thread in windows console application and starting it. Thanks

Answer:
C++ and C doesn't have support for Threads.
You have to use Win32 APIs for threading support for which you can google,BING.


Question:
GCC has a statment expression feature that allows macro to be defined as:

```
#define maxint(a,b) \
   ({int _a = (a), _b = (b); _a > _b ? _a : _b; })
```

This is illegal in Visual Studio.

Is there an equivalent feature in microsoft visual studio?
(I know, I would better use GCC. But I am just curious).

Or, do we just have to resort to inline functions?

Answer: There is no equivalent in the MS compiler to this non-standard GCC language extension.


Question: I am using Visual studio in windows for developing C library. Can someone please provide me simple example of creating thread in windows console application and starting it. Thanks

Answer:
C++ and C doesn't have support for Threads.
You have to use Win32 APIs for threading support for which you can google,BING.


Question:
GCC has a statment expression feature that allows macro to be defined as:

```
#define maxint(a,b) \
   ({int _a = (a), _b = (b); _a > _b ? _a : _b; })
```

This is illegal in Visual Studio.

Is there an equivalent feature in microsoft visual studio?
(I know, I would better use GCC. But I am just curious).

Or, do we just have to resort to inline functions?

Answer: There is no equivalent in the MS compiler to this non-standard GCC language extension.


Question:
How to set (in most elegant way) exactlynleast significant bits ofuint32_t? That is to write a functionvoid setbits(uint32_t *x, int n);. Function should handle eachnfrom0to32.

Especially valuen==32should be handled.

Answer:
Here's a method that doesn't require any arithmetic:

```
~(~0u << n)
```


Question:
How to set (in most elegant way) exactlynleast significant bits ofuint32_t? That is to write a functionvoid setbits(uint32_t *x, int n);. Function should handle eachnfrom0to32.

Especially valuen==32should be handled.

Answer:
Here's a method that doesn't require any arithmetic:

```
~(~0u << n)
```


Question:
When writing a basic c program.

```
#include <stdio.h>

main(){
  printf("program");
}
```

Is the definition ofprintfin "stdio.h" or is theprintffunction automatically linked?

Answer:
Usually, instdio.hthere's only the prototype; the definition should be inside a library that your object module is automatically linked against (the various msvcrt for VC++ on Windows, libcsomething for gcc on Linux).

By the way, it's<stdio.h>, not"stdio.h".


Question:
What does this do and how?

```
typedef int map_t [1<<MAX];
```

What does that line do?

Answer:
AssumingMAXis a constant known at compile-time, then this code:

```
typedef int map_t [1<<MAX];
map_t x;
```

is the same as this code:

```
int x[1 << MAX];
```


Question:
Is it possible to execute a process whose argc = 0? I need to execute a program but it is extremely important for its argc to be equal to 0. Is there a way to do that?
I tried to put 2^32 arguments in the command line so that it appears as if argc = 0 but there is a maximum limit to the number of arguments.

Answer: You can write a program that callsexecdirectly; that allows you to specify the command-line arguments (including the program name) and lack thereof.


Question:
What API is available to use Facebook from C or C++, and is there a library to do the grunt work for me?  (So that you for instance can use Facebook from a desktop program written in C++.)

Thankssehe.

Answer:
Yes you are able to develop Facebook application using C/C++.

Here's a good APIhttp://projects.seligstein.com/facebook/


Question: If we want to write a module in C and have to compile it as C++ withg++, is it OK to develop a piece of code in C++ without any own classes, only using "global / static functions" as in C? So, simply said, to code C in C++ (with only few system header changes etc.)

Answer: Yes. In fact, it's generally a good idea because C++ enforces stronger type-checking than C.


Question:
I'm looking for a tool that can statically discover invariants in C programs. I checked outDaikonbut it discovers invariants only dynamically.

Is there a tool available for what I'm looking for? Thanks!

Answer: SeeThe SLAM project: debugging system software via static analysis.  It claims to infer invariants statically, for just what you asked for, the C language.  The author, Tom Ball, is widely known for stellar work in program analysis.


Question:
If I have an array and want to assign pointer to id'th element of the array are these equivalent?

```
int* hello = &Array[id];

int* hello = &(Array[id]);
```

Answer: No, parentheses are not necessary, and yes these two are equivalent. Array subscripthas higher precedencethan Address operator.


Question:
What API is available to use Facebook from C or C++, and is there a library to do the grunt work for me?  (So that you for instance can use Facebook from a desktop program written in C++.)

Thankssehe.

Answer:
Yes you are able to develop Facebook application using C/C++.

Here's a good APIhttp://projects.seligstein.com/facebook/


Question: If we want to write a module in C and have to compile it as C++ withg++, is it OK to develop a piece of code in C++ without any own classes, only using "global / static functions" as in C? So, simply said, to code C in C++ (with only few system header changes etc.)

Answer: Yes. In fact, it's generally a good idea because C++ enforces stronger type-checking than C.


Question:
I'm looking for a tool that can statically discover invariants in C programs. I checked outDaikonbut it discovers invariants only dynamically.

Is there a tool available for what I'm looking for? Thanks!

Answer: SeeThe SLAM project: debugging system software via static analysis.  It claims to infer invariants statically, for just what you asked for, the C language.  The author, Tom Ball, is widely known for stellar work in program analysis.


Question:
If I have an array and want to assign pointer to id'th element of the array are these equivalent?

```
int* hello = &Array[id];

int* hello = &(Array[id]);
```

Answer: No, parentheses are not necessary, and yes these two are equivalent. Array subscripthas higher precedencethan Address operator.


Question:
I need to send a variable of type mode_t through a socket. How do i do it? I mean I could convert it to a string using snprintf()..but is it ok?

Thanks

Answer:
mode_tis an integer.

Indeed, having textual protocols on sockets is practically useful (easier to debug and to evolve).


Question:
I have been googling a bit, but did not find what i was looking for.

I want to start a process with arguments(in C) using the win32 API.

Does anybody have some examples or pointers which i can use/see?

Answer: The win32CreateProcessfunction does what you need.


Question:
I'm new to valgrind and I was wondering if I can invoke valgrind in such a way that it causes my mallocs to fail for lack of available memory.

Something like:
$valgrind helloworld --heapsize=10

Answer: No, valgrind tries to not interfere with the operation of your program. You should be able to useulimit -dto restrict the amount of memory available to your program, though, independent of valgrind.


Question:
Can this cast fail and when?

```
long x=-1;
long y = (long)(void*)x;
assert(x==y);
```

More specifically, how to detect if the above cast is OK at compile time.

Answer: A more portable way (on the C99 standard variant) is to#include <stdint.h>and then cast pointers tointptr_t(and back). This integer type is guaranteed to be the size of a pointer.


Question:
Please highlight the difference between the following function declarations:

void (*p) (void *a[], int n)void *(*p[]) (void *a, int n)

Answer: void (*p) (void *a[], int n)definesa pointer to a function that takes avoid*array and anintas parametervoid *(*p[]) (void *a, int n)definesan array of pointers to functions that return avoid*, and take avoid*and anintas parameter.


Question:
When programming in C, is it possible to set aconstwith a value of a user-input?
If so, how?

Answer:
Why not?

```
void some_function(int user_input)
{
    const int const_user_input = user_input;
    ...
    return;
}

int main (void)
{
    int user_input;
    scanf("%d", &user_input);
    some_function(user_input);
    return 0;
}
```


Question: Canepoll(on Linux) be somehow useful for regular files? I know it's primarily used with sockets but just wonder.

Answer: Not really.epollonly makes sense for file descriptors which would normally exhibit blocking behavior on read/write, like pipes and sockets. Normal file descriptors will always either return a result or end-of-file more or less immediately, soepollwouldn't do anything useful for them.


Question:
When programming in C, is it possible to set aconstwith a value of a user-input?
If so, how?

Answer:
Why not?

```
void some_function(int user_input)
{
    const int const_user_input = user_input;
    ...
    return;
}

int main (void)
{
    int user_input;
    scanf("%d", &user_input);
    some_function(user_input);
    return 0;
}
```


Question:
If we want mainly anepollbased loop over file-descriptors, what else features does thelibeventoffer (not interested inhttpordnsstuff)??

I know it's quite a big project, but it looks quite simple to me to write anepollwrapper API.

Answer: epollis only available on Linux;libeventcontains some abstractions such that it'll use other similar APIs on other operating systems (for instance:kqueueon OpenBSD).


Question:
I want the user to enter two numbers with a space between them, then take the two numbers and place them in a 2-element array. For example it would look like:

```
Please enter two values:
  >> 1 6
```

Wherearray[0] = 1andarray[1] = 6

How would I do this in C?

Answer:
Probably usingscanf():

```
if (scanf("%d %d\n", &i1, &i2) != 2)
    ...oops...
```


Question: I read it's possible to use C/C++ code in PHP by writing an extension. Is there a simpler way, like wrapping magic or things like that (I must say, I heard the word, but don't know much about what a wrapper is).

Answer: Compiling a php extension isn't very hard. There is a little API to learn just like C programs has the main function and how to pass variables to the main function.


Question:
Imagine a function myFunctionA with the parameter double and int:

```
myFunctionA (double, int);
```

This function should return a function pointer:

```
char (*myPointer)();
```

How do I declare this function in C?

Answer:
typedefis your friend:

```
typedef char (*func_ptr_type)();
func_ptr_type myFunction( double, int );
```


Question:
Is there a way to convert cvMat to cvMAt* in opencv?
I basically have to convert a Mat object to cvMat*. So initially I convert the Mat object to a cvMat object. Now, I need to convert it into a cvMat* pointer.

Answer:
This isn't an OpenCV question, it's basic C. If you're this unfamiliar with C, perhaps you should try some other solution.

That said, converting fromObject somethingtoObject *somethingis as easy as passing&somethingto the function you're calling.


Question:
I have a pretty simple question. Is there a way to dynamically shift bitwise to the left OR to the right, e.g. depending on the sign of an int.

```
signed int n = 3;
signed int m = -2;

int number1 = 8;
int number2 = 8;

//number1 shift n;
//number2 shift m;
```

In this case I want to shift number1 3 bits to the left and number2 2 bits to the right. Is there a way withoutif else?

Answer:
For 32 bit:

x = (((long long)x) << 32) >> (32 - n)


Question:
I have a pretty simple question. Is there a way to dynamically shift bitwise to the left OR to the right, e.g. depending on the sign of an int.

```
signed int n = 3;
signed int m = -2;

int number1 = 8;
int number2 = 8;

//number1 shift n;
//number2 shift m;
```

In this case I want to shift number1 3 bits to the left and number2 2 bits to the right. Is there a way withoutif else?

Answer:
For 32 bit:

x = (((long long)x) << 32) >> (32 - n)


Question:
What is the difference between constant and restrict pointers, for example:

```
int * const ptr,  int * restrict ptr
```

Answer: They do completely different things. Aconstpointer will not change. Arestrictpointer will be the only way in which the object pointed to is accessed.


Question: Having done some C++ I have noticed that C also has structs - surely C should be considered OOP if it has them?

Answer: Because it does not have some of the basic OOPs features of:InheritancePolymorphism  and so on


Question: Having done some C++ I have noticed that C also has structs - surely C should be considered OOP if it has them?

Answer: Because it does not have some of the basic OOPs features of:InheritancePolymorphism  and so on


Question: I wanted to know more about tools that assist in writing code-generators for C. Essentially how do we achieve functionality similar to c++ templates.

Answer: Even though it's not a perfect solution and it takes some time to master it, I've used them4 macro processorin the past for generic C code generation (kinda like C++ templates). You may want to check that out.


Question:
I was going through a possible implementation method for library functionstrcpy. It is :

```
void strcpy(char *src, char *dest)
{
while (*dest++ = *src++)
            ;
}
```

How can this possibly work without check of'\0'??

Answer: The result of*dest++ = *src++is the value of*srcbefore the increment ofsrc. If this value is\0, the loop terminates.


Question: I have a bunch of file references when i run doxygen on my c code and I'd rather it not say where on my machine the file is located. how do i get rid of this in the config file? Thanks

Answer:
In Doxyfile, set

```
FULL_PATH_NAMES = NO
```


Question:
I was going through a possible implementation method for library functionstrcpy. It is :

```
void strcpy(char *src, char *dest)
{
while (*dest++ = *src++)
            ;
}
```

How can this possibly work without check of'\0'??

Answer: The result of*dest++ = *src++is the value of*srcbefore the increment ofsrc. If this value is\0, the loop terminates.


Question: I have a bunch of file references when i run doxygen on my c code and I'd rather it not say where on my machine the file is located. how do i get rid of this in the config file? Thanks

Answer:
In Doxyfile, set

```
FULL_PATH_NAMES = NO
```


Question:
Which character should be used forptrdiff_tinprintf?

Does C standard clearly explains how to printptrdiff_tinprintf? I haven't found any one.

```
int a = 1;
int b = 2;

int* pa = &a;
int* pb = &b;

ptrdiff_t diff = b - a;

printf("diff = %?", diff); // % what?
```

Answer: It's%td.  Seehere.


Question:
I have a int that has values like 1235 and 12890. I want only the 1st 2 digits from this int. How can I extract it?

I thought for some time and couldn't come up with any solution.

Answer:
Reduce the number until you only have two digits left:

```
while (n >= 100) n /= 10;
```


Question:
Has anyone had any success with libcurl and POP3 with APOP authentication?
I had success with the clear authentication but not with APOP since the library
sends the USER command almost immediately after making a connection.

How do I make libcurl send APOP command and stop it sending USER command?

Answer: libcurl currently doesn't support APOP. You need to dive in and make it so!


Question:
I have a int that has values like 1235 and 12890. I want only the 1st 2 digits from this int. How can I extract it?

I thought for some time and couldn't come up with any solution.

Answer:
Reduce the number until you only have two digits left:

```
while (n >= 100) n /= 10;
```


Question:
Has anyone had any success with libcurl and POP3 with APOP authentication?
I had success with the clear authentication but not with APOP since the library
sends the USER command almost immediately after making a connection.

How do I make libcurl send APOP command and stop it sending USER command?

Answer: libcurl currently doesn't support APOP. You need to dive in and make it so!


Question: How can I make sure that a pipe is closed when my C program is stopped by a SIGINT?

Answer:
You could usesignal handlingfor that:

```
#include <signal.h>

void sigHandler(int sig) {
  // Respond to the signal here.
}

int main(..) {
  signal(SIGINT, &sigHandler);
  ..
}
```


Question: I am doing an assignment, which require to develop a simple text editor using C/C++. But it is a GUI application, which may port to different platform, for example, windows, linux and mac. Please recommend a ui framework to serve the purpose. Thanks.

Answer:
Qtis a cross-platform application and UI framework for
  developers using C++ or QML, a CSS & JavaScript like language.

Quoted fromqt-project.org


Question:
I'm using clang's libraries to write a program that will take the parsed
code and put it into a structure.
is there any up to date information about clang's libraries?
reference and tutorial would be nice.

Answer:
Have a look at thedocand atutand atut more.

Edit: Anewer tutorial. Should only be 5 days old.

You might want to have a look at theclang Internals Manualand thecfe-devmailing list.


Question: If there someone who worked with Amazon S3 API in C? I can't manage to sign my REST request proper. Can someone share his successful experience in that?

Answer: I've never tried it, but a quick Google turned upthe libs3 C library API for Amazon S3. That might make things easier, so you don't have to deal with raw HTTP requests viacurl.


Question:
I need to define an iterator structure and method in C (for a BST), so far I realise that the iterator struct must have a pointer to a current node, and possibly a parent node. Is there anything else I should have in there, or that would be good to have?
Thanks

Answer: Do the BST elements have a pointer to their own parent node? If not, you'll need a stack of parent node pointers.


Question:
How do I determine if a character is a forward slash ('/ ')?

I'm looking for something along the lines of:

```
if (isupper(varToTest)) {//do something}
```

but for the life of me I can't find it.

Answer:
```
if (varToTest == '/') { //do something}
```


Question:
How do I determine if a character is a forward slash ('/ ')?

I'm looking for something along the lines of:

```
if (isupper(varToTest)) {//do something}
```

but for the life of me I can't find it.

Answer:
```
if (varToTest == '/') { //do something}
```


Question: In a declaration such asint i, v[5], j;, how will the variables be allocated? Is the compiler allowed to change their order?

Answer:
Yes, the compiler can do whatever it wants, as long as the meaning of the program stays the same. These variables might be optimized out of existence, stored only in a register, reused for other purposes, reordered for alignment requirments.

(note that a compiler cannot reorder variables within a struct)


Question:
Can i go to the line of error , while compiling aC or C++project ? Usually by executingmake, and parse the error string , and go to the specific file , and the line with errors.

Is there already an usable plugin ?

Answer: Yeah this is already buit into vim. After typing:maketype:cwindowto bring up the error list. You can then navigate to the errors using this window.


Question:
I got a code snippet in which there is a

```
printf("%.*s\n")
```

what does the%.*smean?

Answer:
You can use an asterisk (*) to pass the width specifier/precision toprintf(), rather than hard coding it into the format string, i.e.

```
void f(const char *str, int str_len)
{
  printf("%.*s\n", str_len, str);
}
```


Question:
I have a problem assigning an array like:

```
int a[];
int b[] = {1,2,3};
&a = &b;
```

I know I could use pointers but I want to try it that way...

Answer:
You can't assign arrays in C.  You can copy them with thememcpy()function, declared in<string.h>:

```
int a[3];
int b[] = {1,2,3};

memcpy(&a, &b, sizeof a);
```


Question:
I want to turn off the buffering for the stdout for getting the exact result for the following code

```
while(1) {
    printf(".");
    sleep(1);
}
```

The code printf bunch of '.' only when buffer gets filled.

Answer:
You can use thesetvbuf function:

```
setvbuf(stdout, NULL, _IONBF, 0);
```

Here're some other links to the function.

POSIXC/C++


Question: I want to change the background texture of a Gobject clutter actor whenever it is highlighted. Is there any way i can replace the texture during runtime ?

Answer:
you can use theclutter_texture_set_*family of functions, like:

clutter_texture_set_from_fileclutter_texture_set_from_rgb_dataclutter_texture_set_area_from_rgb_data

all documented here:http://developer.gnome.org/clutter/stable/ClutterTexture.html


Question:
I have a problem assigning an array like:

```
int a[];
int b[] = {1,2,3};
&a = &b;
```

I know I could use pointers but I want to try it that way...

Answer:
You can't assign arrays in C.  You can copy them with thememcpy()function, declared in<string.h>:

```
int a[3];
int b[] = {1,2,3};

memcpy(&a, &b, sizeof a);
```


Question:
I want to turn off the buffering for the stdout for getting the exact result for the following code

```
while(1) {
    printf(".");
    sleep(1);
}
```

The code printf bunch of '.' only when buffer gets filled.

Answer:
You can use thesetvbuf function:

```
setvbuf(stdout, NULL, _IONBF, 0);
```

Here're some other links to the function.

POSIXC/C++


Question: I want to change the background texture of a Gobject clutter actor whenever it is highlighted. Is there any way i can replace the texture during runtime ?

Answer:
you can use theclutter_texture_set_*family of functions, like:

clutter_texture_set_from_fileclutter_texture_set_from_rgb_dataclutter_texture_set_area_from_rgb_data

all documented here:http://developer.gnome.org/clutter/stable/ClutterTexture.html


Question:
I want to turn off the buffering for the stdout for getting the exact result for the following code

```
while(1) {
    printf(".");
    sleep(1);
}
```

The code printf bunch of '.' only when buffer gets filled.

Answer:
You can use thesetvbuf function:

```
setvbuf(stdout, NULL, _IONBF, 0);
```

Here're some other links to the function.

POSIXC/C++


Question: I want to change the background texture of a Gobject clutter actor whenever it is highlighted. Is there any way i can replace the texture during runtime ?

Answer:
you can use theclutter_texture_set_*family of functions, like:

clutter_texture_set_from_fileclutter_texture_set_from_rgb_dataclutter_texture_set_area_from_rgb_data

all documented here:http://developer.gnome.org/clutter/stable/ClutterTexture.html


Question:
In Visual Studio 2005, I'm trying to compile a .c file:

```
int i = 6;
int a[i];
```

It doesn't work, so which standard does my compiler follow?

Answer: Visual Studio only supports C89/90. They have no support for C99. Therefore you cannot use variable-length arrays in Visual Studio. Furthermore, Microsoft has no plans to add support for C99 in their C compiler.


Question: When using functions such asscanfyou read bytes from a buffer where (usually) data coming from the keyboard is stored. How is this data stored? Is it stored inside a fixed size vector? Is there any way to access it directly from code?

Answer: The buffer used by the standard libraries input routines is private to the implementation of the standard library. You cannot access it other than through the published interface to the standard library.


Question:
While looking through some example C code, I came across this:

```
y -= m < 3;
```

What does this do? It it some kind of condensed for loop or something? It's impossible to google for as far as I know.

Answer:
m < 3is either1or0, depending on the truth value.

Soy=y-1whenm<3istrue, ory=y-0whenm>=3


Question:
Is there any way to get the number of keys from an .ini file?

ie.
[mysection]

```
server=192.168.1.100
port=1606
blah1=9090
temp1=abcd
```

etc

I want to get number of key (from the above example it should return 4)

Please, any help will be great.

Answer: Kernel32.dll exports GetPrivateProfileSection() which returns a null-separated list of name/value pairs.  You can count the pairs.


Question: Inwindows process management, if we want to pass the values of more than oneinheritable handleto a child process, how should it be done.. ? I understand that we can use STARTUPINFO to pass one handle value, but how can I pass multiple handle values to achild process..?

Answer: The command line is a convenient place to pass all sorts of information.


Question:
Is it possible in X to create a window that is not visible? I looked at the XCreateSimpleWindow API but did not find any attributes to make it hidden. Is there a way?

Thanks

Answer: You may be looking for an InputOnly window.  You can specify the class as InputOnly when using XCreateWindow.


Question:
Is it possible in X to create a window that is not visible? I looked at the XCreateSimpleWindow API but did not find any attributes to make it hidden. Is there a way?

Thanks

Answer: You may be looking for an InputOnly window.  You can specify the class as InputOnly when using XCreateWindow.


Question: I need to make a binary plugin in C that works with both Firefox and Chromium, on Linux. Where can I find a simple example of an NPAPI plugin for Linux, written in C?

Answer: Use FireBreath the cross platform/cross browser plugin projecthttp://firebreath.org


Question: I need to make a binary plugin in C that works with both Firefox and Chromium, on Linux. Where can I find a simple example of an NPAPI plugin for Linux, written in C?

Answer: Use FireBreath the cross platform/cross browser plugin projecthttp://firebreath.org


Question:
On a sftp server i create a "lockfile.lock" if another application is manipulating data.
No in my c application i would like to check if the lockfile.lock exists and than "WAIT 5 SECONDS".

How do i wait 5 seconds in c without blasting the CPU to 100%?

Thanks

Answer: On windows and linux there is a system call "sleep()".Windows,Linux


Question: When you exit the program, how do theseFILE*objects get closed and released?

Answer: They are closed by the C runtime code which is automatically linked to your program - the code that calls your main() function also calls exit() after main() returns.


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

int main()
{
    printf("%x",-2<<2);  //left shift of a negative integer
    return 0;
}
```

If negative integers are represented with a sign bit, then I fear the sign bit will be lost.
Please explain a bit.

Answer: The behaviour is at best 'implementation defined', and possibly 'undefined behaviour'.


Question:
I know how to create ajobjectand would like to convert an existingchar **into a correspondingbyte[][]and pass it to thejobjectusing JNI.

How would I go about doing it?

Answer: Thishttp://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.htmldescribes the about Multi-Dimensional Arrays in JNI


Question: I have been trying to run some sample c programs that uses the cv.h library, but what happened was that the compile complains the file could not be found. So I am guessing I need to some how set the compiler's path. How do I do that?

Answer:
On linux, I usepkg-configto assist me on that task:

```
g++ program.cpp -o program `pkg-config --cflags --libs opencv`
```


Question: How do I set the size of a file in c ? Would I do this after I fopen?

Answer:
Yes you would do it after fopen - you can create what is know as a sparse file

```
#include <stdio.h>
int main(void) {
        int X = 1024 * 1024 - 1;
        FILE *fp = fopen("myfile", "w");
        fseek(fp, X , SEEK_SET);
        fputc('\0', fp);
        fclose(fp);
}
```

That should create you a file for X Byte for whatever you need, in this case it's 1MiB


Question:
I am pretty new to programming and I want to know how to detect a memory leak? If you are going to recommend a utility, please try to find one that works on Mac OS X Lion.

P.S. I tried valgrind, it doesn't work on 10.7/Lion.

Answer:
Valgrind is an excellent cross platform toolhttp://valgrind.org/

And best of all its Open Source


Question: I have been trying to run some sample c programs that uses the cv.h library, but what happened was that the compile complains the file could not be found. So I am guessing I need to some how set the compiler's path. How do I do that?

Answer:
On linux, I usepkg-configto assist me on that task:

```
g++ program.cpp -o program `pkg-config --cflags --libs opencv`
```


Question: How do I set the size of a file in c ? Would I do this after I fopen?

Answer:
Yes you would do it after fopen - you can create what is know as a sparse file

```
#include <stdio.h>
int main(void) {
        int X = 1024 * 1024 - 1;
        FILE *fp = fopen("myfile", "w");
        fseek(fp, X , SEEK_SET);
        fputc('\0', fp);
        fclose(fp);
}
```

That should create you a file for X Byte for whatever you need, in this case it's 1MiB


Question:
I am pretty new to programming and I want to know how to detect a memory leak? If you are going to recommend a utility, please try to find one that works on Mac OS X Lion.

P.S. I tried valgrind, it doesn't work on 10.7/Lion.

Answer:
Valgrind is an excellent cross platform toolhttp://valgrind.org/

And best of all its Open Source


Question:
I'm writing a simple library for checking the internet access status of network interfaces by C on Linux.

Checking the status for all network interfaces (configured or not configured)

Would you please give me where i can refer ( such as documents, example code ...) or any hints?

Answer: The simplest method is probably to check for the existence of a default route through that interface.  You could call out to/bin/ip routeto do this.


Question:
Can someone please shed some light about this particular for loop in matlab C ? Initial is equal to each other !

```
for(ir = ir; ir<=temp; ir++){
}
```

Thanks in advance.

Answer: Ifiris an integer, then the loop essentially doesir = max(ir, ceil(temp))


Question:
why doesn't the following line of code work?

typedef float[MAT_ROW_SIZE][MAT_COL_SIZE] mat;

what should I do?

(I wanna avoid defining a struct)

Answer:
The identifier (the name) must come first. Try

```
typedef float mat[MAT_ROW_SIZE][MAT_COL_SIZE];
```


Question: I was recently asked in an interview how to set the 513th bit of achar[1024]in C, but I'm unsure how to approach the problem. I sawHow do you set, clear, and toggle a single bit?, but how do I choose the bit from such a large array?

Answer:
```
int bitToSet = 513;
inArray[bitToSet / 8] |= (1 << (bitToSet % 8));
```

...making certain assumptions about character size and desired endianness.

EDIT: Okay, fine. You can replace8withCHAR_BITif you want.


Question:
I'm writing a simple library for checking the internet access status of network interfaces by C on Linux.

Checking the status for all network interfaces (configured or not configured)

Would you please give me where i can refer ( such as documents, example code ...) or any hints?

Answer: The simplest method is probably to check for the existence of a default route through that interface.  You could call out to/bin/ip routeto do this.


Question:
Can someone please shed some light about this particular for loop in matlab C ? Initial is equal to each other !

```
for(ir = ir; ir<=temp; ir++){
}
```

Thanks in advance.

Answer: Ifiris an integer, then the loop essentially doesir = max(ir, ceil(temp))