Question:
What will be solution in the following code

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

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

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

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

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

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


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

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

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

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


Question:
Can anyone explain what I'm doing wrong here to not get 11 as my output?

```
void foo {
    int *n = malloc(sizeof(int));
    *n = 10;
    n++;
    printf("%d", *n)
}
```

Answer:
n++increments the pointern, not the integer pointed to byn.  To increment the integer, you need to dereference the pointer and then increment the result of that:

```
(*n)++;
```


Question: What are some data structures that help me storing and calculating the factorial for numbers with more than 50 digits?

Answer: Try anArbitrary Precisioninteger library likeGMPorBigDigits.


Question:
Some laptops have a trackpad that can do horizontal scrolling as well as vertical (WM_MOUSEWHEEL), and some desktop mice have ability to tilt their wheels.

How can I handle horizontal scrolling from a trackpad or mouse wheel?

Answer: WM_MOUSEHWHEELis sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated, and is also useful for horizontal scrolling from a trackpad's horizontal scrolling control


Question:
In the following piece of code,

```
#include<stdio.h>
typedef struct {
    int bit1:1;
    int bit3:4;
    int bit4:4;
} node;

int main(){
    node n,n1,n2,ff[10];

    printf("%d\n",sizeof(node));
    return 0;
}
```

How do I predict the size of the structure?

Answer: You cannot predict it without knowing the compiler and the target platform it compiles to.


Question:
How can I retrieve uptime under linux using C? (without using popen and/or /proc)

Thanks

Answer:
Viatopor viauptime, but I don't know about any syscall, someone will for sure :)

uptimeshould be rather easy to parse.

Just stumbled into this:

```
#include <sys/sysinfo.h>

struct sysinfo info;
sysinfo(&info);
printf("Uptime = %ld\n", info.uptime);
```


Question: Is there a Cocoa class has similar functionality to enumerated values from C?  I know that I can just use enums in Cocoa, but what if I want to put an enum in an NSArray (which only accepts objects)?

Answer: An enum is just an integer type - you can wrap it inNSNumberto put it in anNSArray.


Question:
Is there any way to write log(base 2) function?

The  C language has 2 built in function -->>

1.logwhich is base e.

2.log10base 10;

But I need log function of base 2.How to calculate this.

Answer:
Simple math:

log2(x) = logy(x) / logy(2)

whereycan be anything, which for standard log functions is either 10 ore.


Question:
I would like to create a pseudo filesystem like /proc to access an applications configuration.

How could i achieve this or where could i find some introductory documentation about it?

Answer: The easiest way is to useFUSE. This is particularly easy with high-level language bindings, such asfuse-python.


Question:
I read something like pointer must be byte-aligned.
My understanding in  a typical 32bit architecture... all pointers are byte aligned...No ?

Please confirm.

can there be a pointer which is not byte-aligned ?

Basically this is mentioned in a hardware reference manual for tx descriptor memory.

Answer: Yes, you cannot address any amount of memory smaller than a byte.


Question:
I want to print"%SomeString%"in C.

Is this correct?

```
printf("%%s%",SomeString);
```

Answer:
No, %% outputs %, so the right syntax is:

```
printf("%%%s%%",string);
```


Question:
What is the correct syntax for this code:
is it:

```
printf("printf(\"\%d\",%s);", some_var);
```

or

```
printf("printf(\"%%d\",%s);", some_var);
```

Or something else?

Answer:
The second one.%dis defined by printf, not the C language, so you need to escape it with the printf%%, not a character escape.

A more complex example with a character escape sequence:

```
printf("printf(\"%%d\\n\",%s);\n", some_var);
```


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

Possible Duplicate:Cross Platform C library for GUI Apps?

Is there any crossplatform GUI library for C language? (I mean at least win mac lin) If there is any XML-like GUI editing model, any GUI editing crossplatform visual programms it'l be grate!)

Answer: Take a look at theIUP Toolkit. It is written largely in C, and is also easily bound toLua.


Question: In C in Windows, how do I open a website using the default browser? In Mac OS X, I dosystem("open http://url");

Answer:
You have to useShellExecute().

The C code to do that is as simple as:

```
ShellExecute(NULL, "open", "http://url", NULL, NULL, SW_SHOWNORMAL);
```

This was documented by Microsoft Knowledge Base article KB 224816, but unfortunately the article has been retired and there's no archived version of it.


Question:
What type T makes the following code compilable?

```
T f(){ return &f; }
```

I'd prefer a C answer, but I marked the question as C and C++ in case there is only an answer using templates.

Answer:
I hope this isn't cheating (C++ only):

```
class T {
private:
    T (*_func)();

public:
    T(T (*func)()) : _func(func) {}

    T operator()() {
        return *this;
    }
};

T f() { return &f; }

int main() {
    f()()()()()()()();
}
```


Question: Is there any crossplatform C library for using Pixel Shading filters? to run pixel shader inside your programm, beter as native part of your programm (not like precompiled file), and better for using with abstract data - not only images

Answer: Does this do what you want?http://www.khronos.org/opencl/The question is not very detailed, or clear, but I think OpenCL qualifies as an answer...


Question: Is there any crossplatform small\portable C image editing library?

Answer: TheIMlibrary is cross platform and supports a very wide array of operations on images out of the box. It can also be extended. Its close relativeCDis also occasionally useful for creating text and line art to annotate an image. Both are readily scripted fromLua.


Question:
I would like to create a pseudo filesystem like /proc to access an applications configuration.

How could i achieve this or where could i find some introductory documentation about it?

Answer: The easiest way is to useFUSE. This is particularly easy with high-level language bindings, such asfuse-python.


Question:
I read something like pointer must be byte-aligned.
My understanding in  a typical 32bit architecture... all pointers are byte aligned...No ?

Please confirm.

can there be a pointer which is not byte-aligned ?

Basically this is mentioned in a hardware reference manual for tx descriptor memory.

Answer: Yes, you cannot address any amount of memory smaller than a byte.


Question:
I want to print"%SomeString%"in C.

Is this correct?

```
printf("%%s%",SomeString);
```

Answer:
No, %% outputs %, so the right syntax is:

```
printf("%%%s%%",string);
```


Question: I have enabled blur on my window. I have some edit fields and some custom controls and I would not want these to be affected by the blur, they are semi transparent as a result. How could I only blur the main window itself, not its child controls (sort of like Chrome). Thanks

Answer: Black is treated as transparent since good old GDI does not support alpha channel (the alpha byte in ARGB is always 0) I'm thinking you have to do some sort ofowner draw.


Question:
How can i get the paths of a folder and its content. Say i have folder named MyFolder as

/tmp/MyFolder/ where it has subfolders SubFolder1, SubFolder2... and some files

Answer: You may take a look at theopendir()family functions.


Question:
How can i copy multiple char* variables into one char* at single instance operation.

say i have

char* text1 = "Hello";

char* text2 = "World";

i want to copy text1, text2 and '2' and "12345" into char* text3 in single function call.

Answer:
```
char text3[100];
sprintf( text3, "%s%s%s%s", text1, text2, "2", "12345" );
```


Question: How can i create a temporary folder in /tmp directory.

Answer:
Try themkdtempfunction.

```
char *tmpdir;
strcpy (template, "/tmp/myprog.XXXXXX");
tmpdir = mkdtemp (template);

if (!tmpdir) {
    // Error out here
}

printf ("Temporary directory created : %s", tmpdir);
```


Question: I have enabled blur on my window. I have some edit fields and some custom controls and I would not want these to be affected by the blur, they are semi transparent as a result. How could I only blur the main window itself, not its child controls (sort of like Chrome). Thanks

Answer: Black is treated as transparent since good old GDI does not support alpha channel (the alpha byte in ARGB is always 0) I'm thinking you have to do some sort ofowner draw.


Question:
How can i get the paths of a folder and its content. Say i have folder named MyFolder as

/tmp/MyFolder/ where it has subfolders SubFolder1, SubFolder2... and some files

Answer: You may take a look at theopendir()family functions.


Question:
How can i copy multiple char* variables into one char* at single instance operation.

say i have

char* text1 = "Hello";

char* text2 = "World";

i want to copy text1, text2 and '2' and "12345" into char* text3 in single function call.

Answer:
```
char text3[100];
sprintf( text3, "%s%s%s%s", text1, text2, "2", "12345" );
```


Question: How can i create a temporary folder in /tmp directory.

Answer:
Try themkdtempfunction.

```
char *tmpdir;
strcpy (template, "/tmp/myprog.XXXXXX");
tmpdir = mkdtemp (template);

if (!tmpdir) {
    // Error out here
}

printf ("Temporary directory created : %s", tmpdir);
```


Question: Is this from the C standard?

Answer:
If you're confused by a C declaration, you can use thecdeclprogram to explain it:

```
~$ cdecl
Type `help' or `?' for help
cdecl> explain char (*a)[12];
declare a as pointer to array 12 of char
```


Question:
I have code which works on windows, that callsLocalAllocas follows:

```
LocalAlloc(LMEM_ZEROINIT, size)
```

I need the equivalent malloc or calloc call to get this to work on Unix systems, through Mono.  Simple answer?

Answer: From what I understand it just allocs zeroed memory, so acalloc(1, size)should suffice to allocatesizezeroed bytes.


Question:
I hear 3 years ago problem and apparently have infinity solutions.
I want to find one of this infinity set.

Problem:Write program (have only one file example "selfsource.c") who printing on stdout self source code and exits.

All techniques all alowed. Anyone can help me?

Answer:
This is called aQuine.

Wikipedia has anexample in C.


Question: Is this from the C standard?

Answer:
If you're confused by a C declaration, you can use thecdeclprogram to explain it:

```
~$ cdecl
Type `help' or `?' for help
cdecl> explain char (*a)[12];
declare a as pointer to array 12 of char
```


Question:
I have code which works on windows, that callsLocalAllocas follows:

```
LocalAlloc(LMEM_ZEROINIT, size)
```

I need the equivalent malloc or calloc call to get this to work on Unix systems, through Mono.  Simple answer?

Answer: From what I understand it just allocs zeroed memory, so acalloc(1, size)should suffice to allocatesizezeroed bytes.


Question:
I hear 3 years ago problem and apparently have infinity solutions.
I want to find one of this infinity set.

Problem:Write program (have only one file example "selfsource.c") who printing on stdout self source code and exits.

All techniques all alowed. Anyone can help me?

Answer:
This is called aQuine.

Wikipedia has anexample in C.


Question: anyone has an idea how to?

Answer:
I suggest FindFirstFile() and FindNextFile().

Docs with nice example -http://msdn.microsoft.com/en-us/library/aa364418%28VS.85%29.aspx


Question:
How to search fast in a non-sorted array? I am unable to think of any other search mechanism apart from linear search.

Any pointers will be helpful.

Answer: Yes, without sorting the data a linear search is about as good as you can do.


Question:
I am using Ubuntu and I want to read the version of its kernel. I found a file named version in /proc/ that records the version of the current kernel.

If I dont want to read file, is there any other way, like built-in function in C, that I can read the version in C?

Thanks

Answer: You can use theuname()system call.


Question: Does C support inheritance? If so, is it by usingstructs since classes are not defined in C?

Answer:
Yes, it does. Seehttp://gcc.gnu.org/ml/gcc/2010-05/msg00725.html. See Axel-Tobias Schreiner's bookObject-Oriented Programming with ANSI C. There's an English translation of it available.

Also, seeObject-orientation in CandHow can Inheritance be modelled using C?.


Question:
I have simple from written on C/gtk+ and i have function in this appliction. I need to run this function in a separate thread from gui form. Where can i see example?

Thank you.


Question:
I need to write such a define in C/C++

```
#define scanf( fscanf(inf,
```

in order to replace eachscanf(withfscanf(inf,literary

But I do not know how...

Thanks

Answer:
You want to use aVariadic macro.

In your case, I believe you want:

```
#define scanf(...) fscanf(inf,__VA_ARGS__)
```


Question:
I need to write such a define in C/C++

```
#define scanf( fscanf(inf,
```

in order to replace eachscanf(withfscanf(inf,literary

But I do not know how...

Thanks

Answer:
You want to use aVariadic macro.

In your case, I believe you want:

```
#define scanf(...) fscanf(inf,__VA_ARGS__)
```


Question:
What are these data types for? __m64, __m128,
__m256 ?

Answer:
A quick google-search gives me:

The __m64 data type is for use with the MMX and 3DNow! intrinsicsThe __m128 data type, for use with the Streaming SIMD Extensions and Streaming SIMD Extensions 2 instructions intrinsics

Unfortunately I can't readily find what __m256 is but I suspect it is along the same lines.

Basically, data structures for MMX and similar technologies.


Question:
I have this code:

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

int main()
{
  wchar_t *foo = L"ðħ";
  wprintf(L"[%ls]\n", foo);      return 0;
}
```

And when I compile it, it gives me theimplicit declaration of function ‘wprintf’warning. I know that I should link the wchar library during compilation, but how do I do that?

Answer: Have you tried invoking the compiler with -std=c99 ?


Question: How can I make GNU Make use a different compiler without manually editing the makefile?

Answer:
You should be able to do something like this:

```
make CC=my_compiler
```

This is assuming whoever wrote the Makefile used the variable CC.


Question:
```
char in[100], *temp[10],var[10][10];
int i, n = 0,
double val[10];
var[0][]="ANS";
```

I want to assign a string to var[0][0,1,2] which is 'ANS', but does not work and i cannot figure where i am wrong about this

Answer:
Perhaps instead using,

```
strncpy(var[0], "ANS", 3);
```


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

Possible Duplicate:How to generate a random number from within a range - C

I'm looking for something I can use in C that will give me a random number between a and b. So something like rand(50) would give me a number between 1 and 50.

Answer: From the comp.lang.c FAQ:How can I get random integers in a certain range?


Question: i know it sounds crazy but, i just want to ask if is a compiler support multi programming language? like Delphi could also support C/C++/C# etc? if there is, please let me know. or how?

Answer:
The GNU Compiler Collection includes
  front ends for C, C++, Objective-C,
  Fortran, Java, and Ada

http://gcc.gnu.org/


Question: I have a function that is doing memcpy, but it's taking up an enormous amount of cycles. Is there a faster alternative/approach than using memcpy to move a piece of memory?

Answer: memcpyis likely to be the fastest way you can copy bytes around in memory. If you need something faster - try figuring out a way ofnotcopying things around, e.g. swap pointers only, not the data itself.


Question: i am working on C source to translate to delphi but i was stuck on reading files on ftell() function, can you help me find the equivalent function in delphi?

Answer: If you have an object of typeFile, then you may use theFilePos()function,described here.


Question: Is there any C\C++ Cross-platform library for sharing data between app's?

Answer: Obviously the answer to your question is.. Yes there are many cross platform libs for sharing data between applications. For example Boost hasBoost Serialization, for data storage and reading, andBoost Interprocess, for in-memory data sharing.


Question: I'm trying to make a script that can generate a kind of chat client in cygwin on windows but I don't have a clue how to start, I saw something like gtk+ but how do I get that inside of cygwin, and what have I to do after that?

Answer: Cygwin has anassortmentof gtk packages.  After that you need to read some documentation and learn how to use the toolkit to make your program.Hereis a tutorial to get you started.


Question:
Suppose I have One set of numbers i.e
{1, 6, 3, 5, 7, 9}
I want to Generate Random number from this set of number only i.e. a Generated number should be random and should be from these number({1, 6, 3, 5, 7, 9}) only.

standard C/C++ function will also do...

Answer: arc4random%(set count) = a random index.


Question: Is there a portable C library to access .zip archives? "gzip" or "zlib" (the closest I could find) only handle compressed data, I need to be able to list the files inside the archive, and access each one individually, and if they're compressed using the 'deflate' method, I can use zlib on it.

Answer:
Minizip, maybe?

http://www.winimage.com/zLibDll/minizip.html


Question:
I was wondering if you knew of a robust implementation of a hashtable in C. I'm looking for something other than ghashtable in glib.
Thanks.

Answer: I've heard good things about theGLib Hash Table.


Question: Is there a portable C library to access .zip archives? "gzip" or "zlib" (the closest I could find) only handle compressed data, I need to be able to list the files inside the archive, and access each one individually, and if they're compressed using the 'deflate' method, I can use zlib on it.

Answer:
Minizip, maybe?

http://www.winimage.com/zLibDll/minizip.html


Question:
I was wondering if you knew of a robust implementation of a hashtable in C. I'm looking for something other than ghashtable in glib.
Thanks.

Answer: I've heard good things about theGLib Hash Table.


Question:
does ansi c allows serial communication on rs232 null modem?

if yes then any one give me example?

thanx in advance

Answer: Ansi C has nothing to do with serial communications. ANSI C is a formal description of the C language, it doesn't define libraries. Communicating with an RS-232 modem is possible with C language, but it will be completely different in different platforms (Windows, Linux, embedded processors).


Question: I need to know if there is an iPhone C compiler that can be installed on the iPhone. Then I would like to know what parameter I would put in thesystem("compile Foo")function. Thanks for the help in advanced.

Answer: Unfortunately for your purposes, an app store app is not permitted to launch another process, which would mean that you couldn't use another compiler even if you could install one on the phone.


Question:
The way being suppose the data is
123 134 2312 32131 2131231 211212

It should take them as different numbers and store them in an integer array .

Answer: You can usefscanfwith%dformat specifier to read successive integer values from a text file.


Question: Does Windows provide some sort of evented API so I can run some code whenever a drive (say a usb stick) is attached?Similar to howReadDirectoryChangesWis for events on the filesystem?I am not interested only in hardware changes, a user can also mount a volume, a ftp drive or similar.

Answer: I am not sure of the API, but you can handle theWM_DEVICECHANGEmessage.


Question:
MY scenario is... I have 6,000 datas in Excel Sheet.. I try to import to Access Database.It enters the Database like this..

UNit Price 34512.00   Vat 4.00

BUt when i Retrieve to DataGridColumn it Shows vat Rate as 4(whole number).I accept zeros has no values..But I need that to be displayed in Grid as 4.0  . How to achieve this

Answer: Use a format string, here is some referenceStandard Numeric Format Stings


Question:
I was wondering how I can show description text. By this I mean, for example if you hover over the Start button a small description will appear saying "Start". How are these invoked?

Thanks

Answer: You are looking forTooltip Controls


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

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

is there a way to link the two?

Answer: P/Invokeis the approach you want


Question:
Is there a way of converting a char into a string in C?

I'm trying to do so like this:

```
char *array;

   array[0] = '1';

   int x = atoi(array);

   printf("%d",x);
```

Answer:
```
char c = '1';
int x = c - '0';
printf("%d",x);
```


Question:
I was wondering how I can show description text. By this I mean, for example if you hover over the Start button a small description will appear saying "Start". How are these invoked?

Thanks

Answer: You are looking forTooltip Controls


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

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

is there a way to link the two?

Answer: P/Invokeis the approach you want


Question:
Is there a way of converting a char into a string in C?

I'm trying to do so like this:

```
char *array;

   array[0] = '1';

   int x = atoi(array);

   printf("%d",x);
```

Answer:
```
char c = '1';
int x = c - '0';
printf("%d",x);
```


Question:
Content ofX.c:

```
int i;
main ()
{
fun ();
}
```

Content ofY.c:

```
int i;
fun ()
{
}
```

Why does these two files compile with no error ? (using GCC)

But if i useint i = 10;it prints a multiple definition error.

Answer:
You may be interested in this question and the answers. Keywords: "tentative definition".

Tentative definitions in C99 and linking


Question:
I need to get last four bytes out of a double variable .The platform is Arm and compiler is RVCT.Programming language used is C.What is the safest way.

Thanks

Answer:
```
int lastFour = *(((char*) &origDouble) + sizeof(double) - 4)
```


Question: I have a set of characters, minimum hundreds of characters. How could i get the position of a  particular character in that list efficiently.

Answer:
If you set of characters is sorted, you can usebsearch().

If not, you're pretty much out of luck - you'll have to use a simple scan, likestrchr().


Question:
I am programming in C, using the Windows API, and would like to know how I could drawseparators. I would appreciate a code example.

Edit: Here's an illustration.

(source:microsoft.com)

Answer: Use a static control/window with theSS_ETCHEDHORZstyle (This is what explorer does and should give you the most accurate rendering when it comes to Visual Styles)


Question:
I need to execute a file when I only know the descriptor. It is also possible that there are no links to the file so finding out the name somehow is not an option. All the execve(), execvp(), etc functions take a file name. dlopen() also takes a name.

Ugly solutions (like reading the file and calling some function pointer) are OK.

Answer:
Usefexecve.

PS: reading the file and calling some function pointer is definitelynotOK. :)


Question: can somebody please explain, I have a program on C, can I convert it to assembly? if yes, how?

Answer: If you use gcc you can dogcc -O2 -S -c foo.caccording tothispage to get the output assembly in a human readable form.


Question:
I am programming in C, using the Windows API, and would like to know how I could drawseparators. I would appreciate a code example.

Edit: Here's an illustration.

(source:microsoft.com)

Answer: Use a static control/window with theSS_ETCHEDHORZstyle (This is what explorer does and should give you the most accurate rendering when it comes to Visual Styles)


Question:
I need to execute a file when I only know the descriptor. It is also possible that there are no links to the file so finding out the name somehow is not an option. All the execve(), execvp(), etc functions take a file name. dlopen() also takes a name.

Ugly solutions (like reading the file and calling some function pointer) are OK.

Answer:
Usefexecve.

PS: reading the file and calling some function pointer is definitelynotOK. :)


Question: On Linux, how can I make sure that my program is the only one accessing a file?

Answer: I am not sure, but I believe you are referring tofile locking. Seethisandthisand don't forgetthis. Your display name is gcc but if you are doing this on windows, seeLockFileEx.


Question:
Please excuse my C newbiness.

Consider the following C procedure:

```
int doSomething() {
    char *numbers="123456";
    ...
}
```

Before this procedure exits should I be releasing the 'numbers' pointer?

Answer:
No, you didn'tmallocit. Why should you release it?

Often, the string is placed in a read only section of the executable.


Question:
How do I get the UTC time in milliseconds under the Windows platform?

I am using the standard library which give me UTC time in seconds. I want to get the time in milliseconds. Is there a reference of another library which give me the accurate UTC time in milliseconds?

Answer: UseGetSystemTimeAPI function, or perhapsGetSystemTimeAsFileTimeif you want a single number.


Question:
I have seen some performance figures are represented by MCPS unit, especially in some dsp codec performance.

Can anybody clarify me this?

/kanu__

Answer: It essentially means that some trivial operation can be done N million times each second. For example, the processor could perform up to N million arithmetic operations of certain kind each second and not more.


Question:
I have calledgetpeernameon my connected socket and now have an IPv6 address of the connected peer.  How do I tell whether my peer's IP address is localhost?

Edit:  To clarify, I mean specificallylocalhost, as in the loopback IP address.

Answer:
In IPv6, the loopback address is::1.

At the binary level, that is 127 0's followed by a single 1.


Question:
Quick and easy C question:char* foo

How can I test iffoohasn't still been assigned a value?

Thanks.

Answer:
You can't.

Instead, initialize it withNULLand check whether it isNULL:

```
char *foo = NULL;
...
if(!foo) { /* shorter way of saying if(foo == NULL) */
```


Question:
in Java I think it is possible to cruise through jar files like they were not compressed. Is there some similar (and portable) thing in C/C++ ?

I would like to import binary data into memory from a large (zipped or similar) file without decompressing to disk first and afterwards writing to disk in a compressed way.

Maybe some trick with shell pipes and the zip utility?

Answer: I think you want zlib:http://www.zlib.net/


Question:
Does the Windows native API support timers?

I am aware that POSIX implementations on Windows support timers, but I am interested in Windows SDK APIs.

Answer:
Yes there are timers in Win32 API.
More details you can check here :Timers

In particular you need to check

SetTimerKillTimerTimerProcWM_TIMER


Question:
I have created a control and the mosemove for that control makes it change color, but I want to change it back to default when my mouse moves out of that control. I would have thought WM_MOUSELEAVE would do it but it didn't.

Thanks

Answer:
That would be the correct message.

Are you callingTrackMouseEvent?


Question:
To read anintusing scanf we use:

```
scanf("%d", &i);
```

What ifiis alongnotint??

Note: when using%dwithlongit gives me an irritating warning..

Answer:
Just use

```
long l;

scanf("%ld", &l);
```

it gives me an irritating warning..

That warning is quite right. This is begging for stack corruption.


Question:
How do i add SOCKS support to my application? and where can i get the libs?

any help appreciated thanks

Answer: You could tryBoost.Asiolibrary. It containsan examplewith SOCKS4 protocol implementation.


Question: I am making an iPhone app. I have a code that is in C. The C code contains a lot of pointers and global variables. I want to use this C code in my objective-c project. Can anybody please help me with this?

Answer: Objective-C is a perfect superset of C. Just add the file to your Xcode project like you normally would.


Question: Is there a way to get pre-processedC/Objective-C code? I have some files I acquired and would like to see the code produced by some #defines.

Answer:
From within Xcode:

Xcode 3: Select the file, thenBuild → Preprocess.Xcode 4: Select the file, thenProduct → Generate Output → Generate Preprocessed File.


Question:
i have time of the day in seconds and i have to find the utc time since 1970, is there any api which can directly convert this time to utc time,

i m using ansi c , and working on windows platform
 platform independent api will be preferred

thanx in advance.

Answer: You can fill in atm structwith the time of day you have (you'd have to convert it into seconds/minutes/hours) and the date. Then convert it withmktime()intime.h.


Question: I am making an iPhone app. I have a code that is in C. The C code contains a lot of pointers and global variables. I want to use this C code in my objective-c project. Can anybody please help me with this?

Answer: Objective-C is a perfect superset of C. Just add the file to your Xcode project like you normally would.


Question: Is there a way to get pre-processedC/Objective-C code? I have some files I acquired and would like to see the code produced by some #defines.

Answer:
From within Xcode:

Xcode 3: Select the file, thenBuild → Preprocess.Xcode 4: Select the file, thenProduct → Generate Output → Generate Preprocessed File.


Question:
i have time of the day in seconds and i have to find the utc time since 1970, is there any api which can directly convert this time to utc time,

i m using ansi c , and working on windows platform
 platform independent api will be preferred

thanx in advance.

Answer: You can fill in atm structwith the time of day you have (you'd have to convert it into seconds/minutes/hours) and the date. Then convert it withmktime()intime.h.


Question:
i have time of the day in seconds and i have to find the utc time since 1970, is there any api which can directly convert this time to utc time,

i m using ansi c , and working on windows platform
 platform independent api will be preferred

thanx in advance.

Answer: You can fill in atm structwith the time of day you have (you'd have to convert it into seconds/minutes/hours) and the date. Then convert it withmktime()intime.h.


Question: I want to know aboutconstinternals in C and C++ . How does the compiler impose"constantness"?

Answer:
In generalconstis 100% compiler. When you declare something const,the compilerplaces restrictions on what it will let you write. It won't let you assign to const scalar, assign through a const reference or or pointer, or invoke a non-const function of const object.

There is no guarantee that the compiler will arrange any sort of runtime protection.


Question: Are there examples of recursion using only heap area?

Answer:
In C, function call-based recursion always uses the stack, almost by definition.

If you are willing to convert your recursion to iteration, then it is possible to use only heap space, but that isn't really recursion.  You would do so by implementing a stack in the heap.

Certain problems can usetail recursion, which repeatedly overwrites the same area of the stack.


Question:
i want to prepare a byte buffer as a upd packet i want to fill each value in reverse order how can i do so in ansi c

i have to do this on windows system,

Answer:
Assuming you are doing this so it will work on any receiving system:
Usehtonl()on each byte in your buffer when sending andntohl()on each received byte.


Question:
Pay attentions that there is a space in it.

Which function can I use?

Answer:
You can use

```
if (!strncmp("GET ", str, 4)
{
   ...
}
else if (!strncmp("POST ", str, 5))
{
   ...
}
else
{
   ...
}
```


Question: I have heard of WINE but I don't like it because it's slow on the computers I have tested and almost always crashes. It also has some unpleasant looking gui.I am wondering if there is a "win32" library in c/c++ for linux that producesnative linux codeso that if I have my source code for windows, I can just recompile and produce a working linux application. Is this possible?

Answer: You're looking forWinelib.


Question: Is there anyway to do "insmod" and "rmmod" from C/C++ code?  Other than running system(...), is there a Kernel API that will allow me to do this?

Answer: Have you looked at themodule-init-toolssource?


Question:
Pay attentions that there is a space in it.

Which function can I use?

Answer:
You can use

```
if (!strncmp("GET ", str, 4)
{
   ...
}
else if (!strncmp("POST ", str, 5))
{
   ...
}
else
{
   ...
}
```


Question: I have heard of WINE but I don't like it because it's slow on the computers I have tested and almost always crashes. It also has some unpleasant looking gui.I am wondering if there is a "win32" library in c/c++ for linux that producesnative linux codeso that if I have my source code for windows, I can just recompile and produce a working linux application. Is this possible?

Answer: You're looking forWinelib.


Question: Can somebody please explain what does this warning mean:undefined reference to 'WinMain@16'?

Answer: Googlehaslotsofreferencestothat particular error. You need to provide aWinMainfunction, depending on what type of project you are building (console or Windows app).


Question: I'd like to know if a fd has data available for reading. I have triedioctlwithFIONREADbut that results in a "Operation not supported error". Any ideas?

Answer: You can useselect(), with a zero (notNULL) timeout.


Question: Can somebody please explain what does this warning mean:undefined reference to 'WinMain@16'?

Answer: Googlehaslotsofreferencestothat particular error. You need to provide aWinMainfunction, depending on what type of project you are building (console or Windows app).


Question: I'd like to know if a fd has data available for reading. I have triedioctlwithFIONREADbut that results in a "Operation not supported error". Any ideas?

Answer: You can useselect(), with a zero (notNULL) timeout.


Question: I'm in the process of documenting some firmware but I'm unsure what the standard is (if there is one) for representing static variable declaration in flowcharts

Answer: In the 'classic' flowchart it would just be the rectangle.


Question:
What does theexternkeyword mean? I've seen that in front of an function declaration like

```
extern void DoFoo ...
```

Answer: externgives a nameexternal linkage. This means that the object or function is accessible through this name from other translation units in the program. For functions, this is the default linkage in any case so its usage (in this context) is usually redundant.


Question: What's the "DNS_BLOCK_ASSERTIONS" (C compiler flag)?

Answer: The NS_BLOCK_ASSERTIONS macro (no "D") suppresses the checks performed by NSAssert. You supply it to the compiler using-DNS_BLOCK_ASSERTIONS(see the comments for an explanation of the "D").


Question:
And, if it does, how do you use one? (syntax)

Also, why does or why doesn't C support lambda expressions?

Answer:
No, C has no support for lambda expressions.

If you're willing to use C++, Boost has a library that emulates lambdas. Also, C++0x will have built-in support for lambda expressions.

There wasn't a huge demand for lambda expression support in C at the time, so the language didn't support it.


Question: I'm in the process of documenting some firmware but I'm unsure what the standard is (if there is one) for representing static variable declaration in flowcharts

Answer: In the 'classic' flowchart it would just be the rectangle.


Question:
What does theexternkeyword mean? I've seen that in front of an function declaration like

```
extern void DoFoo ...
```

Answer: externgives a nameexternal linkage. This means that the object or function is accessible through this name from other translation units in the program. For functions, this is the default linkage in any case so its usage (in this context) is usually redundant.


Question: What's the "DNS_BLOCK_ASSERTIONS" (C compiler flag)?

Answer: The NS_BLOCK_ASSERTIONS macro (no "D") suppresses the checks performed by NSAssert. You supply it to the compiler using-DNS_BLOCK_ASSERTIONS(see the comments for an explanation of the "D").


Question:
And, if it does, how do you use one? (syntax)

Also, why does or why doesn't C support lambda expressions?

Answer:
No, C has no support for lambda expressions.

If you're willing to use C++, Boost has a library that emulates lambdas. Also, C++0x will have built-in support for lambda expressions.

There wasn't a huge demand for lambda expression support in C at the time, so the language didn't support it.


Question:
Often I see a function declared like this:

```
void Feeder(char *buff, ...)
```

what does "..." mean?

Answer:
It allows a variable number of arguments of unspecified type (likeprintfdoes).

You have to access the arguments with theva_start,va_argandva_endfunctions.

Seehttp://publications.gbdirect.co.uk/c_book/chapter9/stdarg.htmlorWhere in the C standard variadic functions are described?for more information


Question:
I am using C as the programming language.
How to ignore the sign when using float/signed int  variables?
For example if float/signed int  f = -40 or +40
The result should be same after a mathematical operation like a+b*f

Answer:
Useabsfor ints orfabsfor floats.

```
a+b*abs(f)
```

EDIT:It's not clear wether you want -40 to be treated as 40 or vice versa, if you for some reason wan't the latter:

```
a+b*-abs(f)
```


Question:
In some library I'm using (written in C) its

```
StorePGM(image, width, height, filename)
char *image;
int width, height;
char *filename;
{
  // something something
}
```

All functions are defined this way. I never seen such function definitions in my life. They seem to be valid to MSVC but when I compile it as C++ it gives errors.

What is it? some kind of old version C?

Answer: Yes. K&R, pre-standard C. Avoid using it.


Question:
Often I see a function declared like this:

```
void Feeder(char *buff, ...)
```

what does "..." mean?

Answer:
It allows a variable number of arguments of unspecified type (likeprintfdoes).

You have to access the arguments with theva_start,va_argandva_endfunctions.

Seehttp://publications.gbdirect.co.uk/c_book/chapter9/stdarg.htmlorWhere in the C standard variadic functions are described?for more information


Question: Many places I saw that we can use startupinfoex structure in CreateProcess function. But when I checked the signature is only allowing startupinfo structure. Can anybody please give a snippet how startupinfoex can be used with createprocess function. Thanks in advance....

Answer:
You need to cast theSTARTUPINFOEX*to aSTARTUPINFO*.

Be sure to pass theEXTENDED_STARTUPINFO_PRESENTflag todwCreationFlagsand set theStartupInfo.cbmember tosizeof(STARTUPINFOEX).


Question:
Is there a way to concatenate keywords in a macro and getC to behave in a more dynamic fashion as in:

```
#define macro(fun,ction,var,iable) function(variable)
```

I know this kind of thing exists in other languages.

Answer:
You can use ## to concatinate names in macros

fun##ction ...


Question: I checked out the microsoft documents. it shows how to create a static library upon creation of the project. but not necessarily on how to convert a previously made project, into a static library. So my question is, where do I go to turn my previously made project, into a static lib. so I can include it in my other projects

Answer: Project | Properties -> Configuration Properties -> General -> Configuration Type (Static Library).


Question: I'm looking for the C grammar in GCC source code, more specifically for the grammar in the yacc/bison form.

Answer: Found the C grammar in Yacc specification in the GCC version 3.3 in the file "c-parse.y"


Question: I'm looking for the C grammar in GCC source code, more specifically for the grammar in the yacc/bison form.

Answer: Found the C grammar in Yacc specification in the GCC version 3.3 in the file "c-parse.y"


Question:
I need a powerful HTML parser and manipulator for Objective-C/C, like HTML Agility Pack.

Can anyone tell me some optimal solution? One solution is libxml2, but it seams is not the best.

Thanks in advance!

Answer:
On MacOS X,NSXMLDocumentis a good solution (but you want iPhone).

Two packages that you should look at are:TouchXMLandKissXML.

See alsoiPhone Development - XMLParser vs. libxml2 vs. TouchXML.


Question: In the many search functions of C (bsearch comes to mind) if a result is found, a pointer to the spot in the array is returned. How can I convert this pointer to the index in the array that was searched (using pointer arithmetic, i assume).

Answer:
```
ptrdiff_t index = pointer_found - array_name;
```


Question: How do I execute another program from within a C program in Windows 32 - in a similar way as Perl'ssystem()function or Python's sub-process module - such asDEL,REG, or other cmd.exe programs?

Answer: C does have asystemfunction in its standard library, see e.g. thewikipediaentry about it.


Question:
This is a simple problem, but I can't see it:

```
char *s = "f 8.649292" ;
  double d ;
  sscanf( s, "f %f", &d ) ;

  printf( "d is %f\n", d ) ;
```

Why isdnot containing the double value8.649292?

Answer:
Oh wait, nevermind.  d needs to be afloat.

And to make it work you could use%lffor a double

```
char *s = "f 8.649292 " ;
  double d ;
  sscanf( s, "f %lf", &d ) ;

  printf( "d is %lf\n", d ) ;
```


Question: i have a small program that uses 32bit object file, and i wish to run it under dos operating system. now, after searching i foundDJGPP.is there a way to use DJGPP to compile my program to 16Bit dos executable format?thanks in advance

Answer: Take a look atthisrelated Stack Overflow question. It might help.


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

Possible Duplicate:Uses for multiple levels of pointer dereferences?

I have used functions with doubly dereferenced pointers (**var) to return values. However, I was recently asked a question to figure out a use-case where a triple dereferencing (***var) may be needed. I couldn't think of any practical scenario. Does anyone have any experience here?

Answer: Three dimensional arrays.


Question:
In gcc I can do compile-time warnings like this:

```
#if !defined(_SOME_FEATURE_)
   #warning _SOME_FEATURE_ not defined-- be careful!
#endif
```

But in Visual Studio this doesn't work.  Is there an alternative syntax for #warning?

Answer: About the closest equivalent would be#pragma message, or possibly#error(the latter stops compilation, the former just prints out the specified error message).


Question: How to hide the mouse pointer on the window screen of GDI, kindly give me some hints.

Answer:
TryShowCursor(false);

Sources:

http://msdn.microsoft.com/en-us/library/ms648396.aspx

http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0045.html


Question: Can anybody suggest how to convert actionscript to c code?

Answer:
There is no automatic way of doing that. The languages offer very different sets of features.

You'll have to do it manually, preferably in a top-down manner. This means that when making the C implementation, write the most abstract functionality first, gradually going into the details.


Question: The elements of the array are arranged in non-decreasing order. I need to search the array for a given element in the least possible time.

Answer:
Since the array is sorted you can make use ofBinary Search.

Alinearsearch will takeO(n)time because it does not make use of the sorted property. But abinarysearch will takeO(log n)time.


Question: i have a string of the format "ABCDEFG,12:34:56:78:90:11". i want to separate these two values that are separated by commas into two different strings. how do i do that in gcc using c language.

Answer:
One possibility is something like this:

```
char first[20], second[20];

scanf("%19[^,], %19[^\n]", first, second);
```


Question: i have a small program that uses 32bit object file, and i wish to run it under dos operating system. now, after searching i foundDJGPP.is there a way to use DJGPP to compile my program to 16Bit dos executable format?thanks in advance

Answer: Take a look atthisrelated Stack Overflow question. It might help.


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

Possible Duplicate:Uses for multiple levels of pointer dereferences?

I have used functions with doubly dereferenced pointers (**var) to return values. However, I was recently asked a question to figure out a use-case where a triple dereferencing (***var) may be needed. I couldn't think of any practical scenario. Does anyone have any experience here?

Answer: Three dimensional arrays.


Question:
In gcc I can do compile-time warnings like this:

```
#if !defined(_SOME_FEATURE_)
   #warning _SOME_FEATURE_ not defined-- be careful!
#endif
```

But in Visual Studio this doesn't work.  Is there an alternative syntax for #warning?

Answer: About the closest equivalent would be#pragma message, or possibly#error(the latter stops compilation, the former just prints out the specified error message).


Question: suppose there is a string of characters in an array of d[20] . How to convert to a string d so that i can use it in string functions like strcmp..

Answer: It must be null-terminated. That's the only requirement. I presume you know how to do that.


Question: I have some C code that parses a file and generates another file of processed data. I now need to post these files to a website on a web server. I guess there is a way to do a HTTP POST but I have never done this in c (using GCC on Ubuntu). Does anyone know how to do this? I need a starting point as I have no clue of doing this in C. I also need to be able to authenticate with the website.

Answer: libcurlis probably a good place to start.


Question:
I'm developing C extensions from python and I obtain some segfaults (inevitable during the development...).

I'm searching for a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how can I do that?

Answer:
If you are on linux, run python under gdb

```
gdb python
(gdb) run /path/to/script.py
## wait for segfault ##
(gdb) backtrace
## stack trace of the c code
```


Question: I am looking for a SOAP Library for C. I know there is gSOAP. What other options do I have?

Answer: Take a look at thisblogentry. I know it's C++, but I have had good results with Apache's AXIS. If you can use a C++ compiler, you can wrap around a C library to your generated classes.


Question: How can we implement the modulo operator as a function in C without using the operator?

Answer:
Do an integer division followed by a multiplication, and subtract.

```
#include <stdio.h>
int main()
{
  int c=8, m=3, result=c-(c/m*m);
  printf("%d\n", result);
}
```


Question: I want to know how to announce int to make sure it's 4 bytes or short in 2 bytes no matter on what platform.  Does C99 have rules about this?

Answer: C99 doesn't say much about this, but you can check whethersizeof(int) == 4, or you can use fixed size types like uint32_t (32 bits unsigned integer). They are defined instdint.h


Question:
Is there a way to know whether a variable is defined, by looking at the executable.

Lets say I declare

```
int i;
```

in the main function. By compiling and linking I get an executable my_program.exe.

Now, by looking inside my_program.exe, can I say if it has aninteger variablei?

Answer: Not unless you compile with debugging enabled.


Question: Usually it will ignore C files that are not documented, but I'd like to test the Callgraph feature for example, do you know a way around this without changing the C files?

Answer: Set the variableEXTRACT_ALL = YESin your Doxyfile.


Question:
Is it possible to use C/C++ code in Android?
And how easy is it?

Answer:
Its possible. Use the Native Development Kit (NDK). Seeherefor more discussion and links.

How easy is it? I don't know, I've never tried!


Question:
Whenever any question is asked, and a reference text is needed, I never seeMSDN C++ Language Referencebeing referred.

I was browsing through it and I personally feel that it is extremely well written.

Is there some specific reason it is not used as often as a standard?

Is it because it contains some VC++ specific features?

Answer: I believe it's because those of us referencing a reference reference the actual standard itself.


Question: Given a list of URLs, such as a/b/e/f, b/c/d/k/g, s/e/c/d, how to match an input URL to the one in the list, for example, an input c/d should be matched to s/e/c/d, not b/c/d/k/g

Answer: Why not b/c/d/k/g? Are the "Url"s simply strings? If so simply search it using strstr or one of its derivative (wcsstr, _mbsstr, _mbsstr_l).


Question:
Whenever any question is asked, and a reference text is needed, I never seeMSDN C++ Language Referencebeing referred.

I was browsing through it and I personally feel that it is extremely well written.

Is there some specific reason it is not used as often as a standard?

Is it because it contains some VC++ specific features?

Answer: I believe it's because those of us referencing a reference reference the actual standard itself.


Question: Given a list of URLs, such as a/b/e/f, b/c/d/k/g, s/e/c/d, how to match an input URL to the one in the list, for example, an input c/d should be matched to s/e/c/d, not b/c/d/k/g

Answer: Why not b/c/d/k/g? Are the "Url"s simply strings? If so simply search it using strstr or one of its derivative (wcsstr, _mbsstr, _mbsstr_l).


Question: Given a list of URLs, such as a/b/e/f, b/c/d/k/g, s/e/c/d, how to match an input URL to the one in the list, for example, an input c/d should be matched to s/e/c/d, not b/c/d/k/g

Answer: Why not b/c/d/k/g? Are the "Url"s simply strings? If so simply search it using strstr or one of its derivative (wcsstr, _mbsstr, _mbsstr_l).


Question: if an array of size n has only 3 values 0 ,1 and 2 (repeated any number of times) what is the best way to sort them. best indicates complexity. consider space and time complexity both

Answer: Count the occurences of each number and afterward fill the array with the correct counts, this isO(n)


Question:
I get an "undefined reference to 'typeof'"-error compiling and linking this:

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

int main() {
    typeof(5);
    return 0;
}
```

Version of gcc is 4.3.3, command line is "gcc.exe -std=c99 1.c -o 1.exe".

Answer:
By passing the option-std=c99to GCC you've asked it to compile according to the C99 standard, which doesn't support thetypeofkeyword.

You may want to use-std=gnu99instead.


Question:
I need to work with a binary number.

I tried writing:

```
const char x = 00010000;
```

But it didn't work.

I know that I can use a hexadecimal number that has the same value as00010000, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?

Answer:
If you are using GCC then you can usea GCC extension(which is included inthe C++14 standard) for this:

```
int x = 0b00010000;
```


Question:
Is there a C or C++ compatible library for reading and writing Java class files?

I.e. something like Apache BCEL.

Answer: None that I'm aware of. However, you can call Java from C++. That will let you use BCEL from C++. If you're on one of gcj's supported platforms, you could try using it to compile BCEL to native code.


Question: Can we have a nested function in C? What is the use of nested functions? If they exist in C does their implementation differ from compiler to compiler?

Answer:
You cannot define a function within another function in standard C.

You candeclarea function inside of a function, but it's not a nested function.

gcc hasa language extension that allows nested functions.  They are nonstandard, and as such are entirely compiler-dependent.


Question:
it is possible to display a picture on a window created by winmain i mean using GDI,

i want do create a window that captures my whole screen i have done that by using GDI but unable to show an image on it how can i do so?

Answer: There arelotsofgoodtutorialson theweb.


Question:
String.h

I found this while searching aboutstring.h. Where can I find the source code of functions defined instring.h?

i.e [say] source code of

```
void    *memcpy(void *, const void *, size_t);
```

Also I want to ask how to make your functions as an interface with its implmentation hidden from developer asstring.hfunctions has.

Answer: Here's memmovefrom Ohloh's code search.


Question:
Is there any way to find out the list of undefined symbols in windows static library compiled using VC6?

I know the nm command will list all the symbols in linux and symbols with a tag of "U" can be identified as undefined. But, how to do it Windows?

Answer: You can use dumpbin.exe /symbols on the .lib file.  That lists all the symbols used, the external ones have the "External" prefix.


Question:
I have two pointers,

```
char *str1;
int *str2;
```

If I look at the size of both the pointers let’s assume

```
str1=4 bytes
str2=4 bytes
```

str1++ will increment by 1 byte, but if str2++ it will increment 4 bytes.

What is the concept behind this?

Answer:
Simple, in the provided scenario:

char is 1 byte longint (in your platform) is 4 bytes long

The++operator increments the pointer by the size of the pointed type.


Question:
Quick c question: How to know the length of a char* foo[]?

Thanks.

Answer: You can't.  Not without knowing something about what is inside of the pointers, or storing that data ahead of time.


Question:
I'm implementing some code generators, i would like to know if there's any way in C, if a variable has already been declared ?

I was trying to find something using the preprocessor but without any success...

thanks.

Answer: C is strictly static, you can't "lookup" if a variable has already been declared. If you are creating a code generator, why not read lines of code and see what's been declared?


Question: How do I inputDEADBEEFand outputDEADBEEFas four byte arrays?

Answer:
```
void hexconvert( char *text, unsigned char bytes[] )
{
    int i;
    int temp;

    for( i = 0; i < 4; ++i ) {
        sscanf( text + 2 * i, "%2x", &temp );
        bytes[i] = temp;
    }
}
```


Question:
What does the last function argument mean in C language?
Please, point to documentation where I can read about it.

```
void parse_options( int argc, char **argv, const OptionDef *options,
                   void (* parse_arg_function)(const char*) )
```

Thanks.

Answer:
This is apointer to a functionthat takes aconst char*and returnsvoid.

For more information, seehere.


Question: Is Test Driven Development limited to OO? Or is it possible/useful to use it in conjunction with a procedural language? I have to start a greater project in C the next few weeks and I'm thinking of ways how to the developing.

Answer:
TDD is adesignparadigm and as such is not tied to any specific programming paradigm.

Simply put, you write a test for your code before writing your of code.

Seethisslide deck about TDD with C (the Bowling Game Kata).


Question: can every if...then...else statement be converted into an equivalent statement using only ?:

Answer:
The code:

```
if ( flag ) {
   exit(1);
}
else {
   return 0;
}
```

cannot be converted into:

```
flag ? exit(1) : return 0;
```

A better example- this would be inside a loop:

```
if ( flag ) {
   continue;
}
else {
   break;
}
```

cannot be converted to:

```
flag ? continue : break;
```


Question: As the title described, how to use c library function fgets in assembly language? Indeed, I want to know how to get the file pointer to stdin. Thanks for your reply.

Answer: you can write a simple program using fgets and compile it with gcc -S to see how to do it


Question:
How to reverse bitwise AND (&) in C?

For example I have an operation in C like this:

```
((unsigned int)ptr & 0xff000000))
```

The result is0xbf000000. What I need at this moment is how to reverse the above, i.e. determineptrby using the result from the operation and of course0xff000000.

Is there any simple way to implement this in C?

Answer:
Bitwise&can't be reversed:

```
0 & 1 = 0
0 & 0 = 0
```


Question: As the title described, how to use c library function fgets in assembly language? Indeed, I want to know how to get the file pointer to stdin. Thanks for your reply.

Answer: you can write a simple program using fgets and compile it with gcc -S to see how to do it


Question:
How to reverse bitwise AND (&) in C?

For example I have an operation in C like this:

```
((unsigned int)ptr & 0xff000000))
```

The result is0xbf000000. What I need at this moment is how to reverse the above, i.e. determineptrby using the result from the operation and of course0xff000000.

Is there any simple way to implement this in C?

Answer:
Bitwise&can't be reversed:

```
0 & 1 = 0
0 & 0 = 0
```


Question: I have a static C library (saymylib.a) and I was wondering if it's possible to find out what functions are implemented inside that file. I don't have a corresponding header file. what I need is like the equivalent ofjavapfor Java.

Answer: On Windows you can usedumpbin.  On Linux and friends you can usenm.


Question: after calling JetSetColumns() and then JetUpdate() how do I retrieve the values for any freshly assigned autoincrement values?

Answer:
when you call JetUpdate() the third arg is a 'bookmark'.  Once JetUpdate() completes you can seek to the bookmark using

JetGotoBookmark() -http://msdn.microsoft.com/en-us/library/ms683554(EXCHG.10).aspx


Question:
Is size_t only in C++ standard or C standard as well?

I cannot find a C header in the "/usr/include" tree that defines size_t.

If it is not in the C std, is GCC just doing some magic to make things work?

Thanks,
Chenz

Answer: size_tis defined in both<stddef.h>and<stdlib.h>


Question: I have a static C library (saymylib.a) and I was wondering if it's possible to find out what functions are implemented inside that file. I don't have a corresponding header file. what I need is like the equivalent ofjavapfor Java.

Answer: On Windows you can usedumpbin.  On Linux and friends you can usenm.


Question:
```
char a[]="HELLO";
char *p="HELLO";
```

willa[2]andp[2]fetch the same character?

Answer:
What they will fetch is a char-sized chunk of memory located 2 char-sized steps (2 bytes here) after the beginning of each, or after the address in memory to which each var points. This happens to be 'L' i the example, but this is not the same address in memory.

So yes, in the example given, they will fetch the same character.


Question: How can I use zlib library to decompress a PNG file? I need to read a PNG file using a C under gcc compiler.

Answer: Why not uselibpng? The PNG file format is fairly simple, but there are many different possible variations and encoding methods and it can be fairly tedious to ensure you cover all of the cases. Something like libpng handles all the conversion and stuff for you automatically.


Question: I want to modify the registry of window OS using c. kindly guide me or give me some hints so that I can make it possible.

Answer: You need to use Win32 APIs such asRegOpenKeyExfor doing this.


Question: I want to modify the registry of window OS using c. kindly guide me or give me some hints so that I can make it possible.

Answer: You need to use Win32 APIs such asRegOpenKeyExfor doing this.


Question: I am using CreateProcess function for creating the process, is there any option to get the current state of the process (running or not). Kindly guide me how can I make it possible.

Answer: UseOpenProcessfunction with that dwProcessId if it returns NULL Process is not running otherwise it will return handle to that process


Question: i want to use the dos commands in my ansi-c program how can i do so what type of lib or .h i will need for it if it is possible ?

Answer:
Use thesystemfunction, fromstdlib.h.

Here is Wikipedia documentation of this function


Question: Is there any option to call msi file from CreateProcess in c language in window OS.

Answer: The WindowsShellExecute functionwill open a file of a registered type with the correct application, which I think is what you are asking about.


Question:
Does anyone have code snippet for Triple DES algorithm in C ?

Thanks

Answer: OpenSSLis written in C and provides a 3DES algorithm.  It may not be as simple as some of the other suggestions, but it may be worth checking out.


Question:
How can I encode a file using sha256 and c/c++ ???
Thanks!

Answer:
SHA 256stands for Secure Hash Algorithm ! It will only produce the hash of a given file . You can't retrieve the original file from a given hash otherwise hash functions are useless.

If you want to do encryption/decryptionAESwould be a better solution. Everything you need is inOpenSSL.


Question:
```
#include<conio.h>
#include<stdio.h>
#define abc 7

int main()
{

int abc=1;

printf("%d",abc);

getch();

return 0;
}
```

why this program is giving compile time error

Answer:
You're assigning7=1which is invalid. Since you've definedabcto be 7, the preprocessor translates the line:

```
int abc=1;
```

to:

```
int 7=1;
```

Which is a syntax error in C (mygccsayssyntax error before numeric constant).


Question:
What's the difference of pData1 and pData2, which are build as follows:

pData1 = (int*) calloc (i,sizeof(int));int * pData2 = (int*) calloc (i,sizeof(int));

Answer: Without any more information, it would appear the only difference is thatpData2is local to the allocation since it is declared as anint *.pData1is not declared so it would have to have a larger (global?) scope and be defined elsewhere.


Question:
I need to create a simple application that doesn't work after 30 days.

How can I do that ?

Is there a way to use Trial program after 30 days ?

Answer: There is always a way to use a trial program after 30 days.


Question:
```
#include<conio.h>
#include<stdio.h>
#define abc 7

int main()
{

int abc=1;

printf("%d",abc);

getch();

return 0;
}
```

why this program is giving compile time error

Answer:
You're assigning7=1which is invalid. Since you've definedabcto be 7, the preprocessor translates the line:

```
int abc=1;
```

to:

```
int 7=1;
```

Which is a syntax error in C (mygccsayssyntax error before numeric constant).


Question:
What's the difference of pData1 and pData2, which are build as follows:

pData1 = (int*) calloc (i,sizeof(int));int * pData2 = (int*) calloc (i,sizeof(int));

Answer: Without any more information, it would appear the only difference is thatpData2is local to the allocation since it is declared as anint *.pData1is not declared so it would have to have a larger (global?) scope and be defined elsewhere.


Question:
I need to create a simple application that doesn't work after 30 days.

How can I do that ?

Is there a way to use Trial program after 30 days ?

Answer: There is always a way to use a trial program after 30 days.


Question:
I'm reading a bit of C code in an OS kernel that says

```
x & ~(uint32_t)CST_IEc;
```

What does the~()mean? It's a tilde followed by parentheses!

Answer:
~()is actually two things:

(uint32_t)is a cast.~is a bitwise complement operator.


Question: I have a time in the future when I want a notification to occur and need to know if::CeSetUserNotificationExexpects UTC or local time in thestStartTimefield of theCE_NOTIFICATION_TRIGGERstructure if thedwTypefield is set toCNT_TIME?

Answer:
After actually testing::CeSetUserNotificationExwith both UTC and local time input, I'm in the position of answering my own question:

::CeSetUserNotificationExwants local time.


Question:
i have a task to transfer text files from one pc to another using FTP , i need some directions how can it be done in ansi c as its user requirement to do it in ansi c

windows palte form so windows libs may also be used ..............

looking for help!

Answer:
what platform do you use?

On windows, have a look at the winsock library.on Unix, examine sockets library

Can you use an external library? thenthis heremight come in handy.


Question: I'm writing a Linux kernel module, and I'd like to allocate an executable page. Plainkmalloc()returns a pointer within a non-executable page, and I get a kernel panic when executing code there. It has to work on Ubuntu Karmic x86, 2.6.31-20-generic-pae.

Answer:
```
#include <linux/vmalloc.h>
#include <asm/pgtype_types.h>
...
char *p = __vmalloc(byte_size, GFP_KERNEL, PAGE_KERNEL_EXEC);
...
if (p != NULL) vfree(p);
```


Question:
I'm just wondering exactly what factors affect how quickly createthread executes, and how long it has to live to make it "worth it".

CONTEXT: Where in my game's loops should I spawn threads?

Answer: The main game loop is not the place to spawn worker threads. The main game loop should be as free of clutter as possible. Worker threads should be spawned during program startup and then used as need by the main game loop. Look into thread pooling techniques.


Question:
I'm reading a bit of C code in an OS kernel that says

```
x & ~(uint32_t)CST_IEc;
```

What does the~()mean? It's a tilde followed by parentheses!

Answer:
~()is actually two things:

(uint32_t)is a cast.~is a bitwise complement operator.


Question: I have a time in the future when I want a notification to occur and need to know if::CeSetUserNotificationExexpects UTC or local time in thestStartTimefield of theCE_NOTIFICATION_TRIGGERstructure if thedwTypefield is set toCNT_TIME?

Answer:
After actually testing::CeSetUserNotificationExwith both UTC and local time input, I'm in the position of answering my own question:

::CeSetUserNotificationExwants local time.


Question:
i have a task to transfer text files from one pc to another using FTP , i need some directions how can it be done in ansi c as its user requirement to do it in ansi c

windows palte form so windows libs may also be used ..............

looking for help!

Answer:
what platform do you use?

On windows, have a look at the winsock library.on Unix, examine sockets library

Can you use an external library? thenthis heremight come in handy.


Question: I'm writing a Linux kernel module, and I'd like to allocate an executable page. Plainkmalloc()returns a pointer within a non-executable page, and I get a kernel panic when executing code there. It has to work on Ubuntu Karmic x86, 2.6.31-20-generic-pae.

Answer:
```
#include <linux/vmalloc.h>
#include <asm/pgtype_types.h>
...
char *p = __vmalloc(byte_size, GFP_KERNEL, PAGE_KERNEL_EXEC);
...
if (p != NULL) vfree(p);
```


Question:
I know you can print withprintf()andputs(). I can also see thatprintf()allows you to interpolate variables and do formatting.

Isputs()merely a primitive version ofprintf(). Should it be used for every possibleprintf()without string interpolation?

Answer: putsis simpler thanprintfbut be aware that the former automatically appends a newline.  If that's not what you want, you canfputsyour string to stdout or useprintf.


Question: I want to transfer files across the network using C or C++.  What topics should I look up?  How can I do this?

Answer: You should start by choosing a protocol.HTTPSandSFTPare both good choices, but there are obviously others.  Once you have that straight, you can look up choices for client and server libraries.


Question:
I cannot understand why this throwsundefined reference to `floor'":

```
double curr_time = (double)time(NULL);
return floor(curr_time);
```

Hasn't it been casted to double, which is whatfloorreceives?

Answer:
You possibly have run in to the infamous-lmproblem: Compile as:

```
gcc yourfile.c -o out -lm
```

This is CFAQ 14.3item as well.


Question: I have written the majority of my project in C++. However there are several "filters" or folders which need to be compiled as C and linked to the project. How can I configure this within VStudio? Thanks.

Answer: You can change the Language property by right-clicking on the individual files and settingConfiguration Properties > C/C++ > Advanced > CompileAs ToCompile As C (/TC). No such facility for the filter are present though.


Question:
What was the munch library (or program?) fromcfrontpackage?
What is was used for?

Answer:
Munch was used to scan the nm output and look for static constructors/destructors.

See thecode(with comments) atSoftwarePreservation.com.


Question:
This one is quite obviously a function pointer :

```
typedef int (* foobar) (int a, unsigned char *b, unsigned int c);
```

But what does this one do?

```
typedef int (foobar *) (int a, unsigned char *b, unsigned int c);
```

Answer:
It produces a compiler error, at least in GCC 4.3:

```
foo.cpp:1: error: expected `)' before '*' token
```


Question: Are there any stdin input length limitations (in amount of input or input speed)?

Answer:
No.stdinhas no limits on length or speed.

If you want to get gigabytes of data viastdinyou can, and your computer will supply it as fast as it can.


Question: How do I perform an unsigned right shift (>>> in Java) in C/C++?

Answer:
In C, to get an unsigned shift, you just do a shift on an unsigned type.

```
unsigned int result = (unsigned int)valueToBeShifted >> shiftAmount;
```

Note that there is no guarantee that>>on a signed type gives you a signed shift in C -- this is implementation defined behavior.  Most common implementations produce a signed shift if the type is signed, however.


Question: Is there a canonical colorspace conversion library? I can't find any pre-existing solutions. Is CIELab conversion is too obscure?

Answer:
It is not obscure, I have done it myself recently from RGB to CIELAB.
Look at the source of OpenCV there is a lot of color convesrion functions.
File is: ../src/cv/cvcolor.cpp
Have a look at the function icvBGRx2Lab_32f_CnC3R for example. This is probably what are you looking for.


Question:
I have a c program which I can launch at command prompt.
Is it possible for me the lunch this application in my another c program?
If yes, how? All the google result shows me how to do that using pthread? Will that work?
I suspect that I need a new process for my c program.

Thank you.

Answer: It is system specific, but there is commonlyexecveor something like that and there is alwayssystem("/path/to/program");that you can use that is also system specific


Question:
I have a string"14 22 33 48". I need to insert each of the values in the string into the respective location in the array:

```
int matrix[5];
```

so that

```
matrix[0] = 14;
matrix[1] = 22;
matrix[2] = 33;
matrix[3] = 48;
```

How do I do this?

Answer:
You can usesscanf:

```
sscanf(val,
       "%d %d %d %d",
       &matrix[0],
       &matrix[1],
       &matrix[2],
       &matrix[3]
);
```


Question: Can we use thewmain()function with Unix compilers or it'll work only on/for Windows?

Answer:
The only standard signatures formainare:

```
int main(void);
int main(int argc, char *argv[]);
```

However, a freestanding implementation can provide extensions/allow other signatures. But those are not guranteed to be portable.wmainlooks like a Windows/VS thing. There's not much chance this will work on a *nix/GNU GCC.


Question: Is there an option to enable the drop down menu that appears when coding in other languages such as html/vb/ect for C in Visual Studio?

Answer: You can press Ctrl+Space to produce this menu. For example, after typing "pri", press Ctrl+Space, if you're looking for printf().


Question:
Using my c++ program how can I find out what group the current user running my program belongs to? So my program need to figure out a couple of things :

The current username of the userThe group the user belongs to

How can do the above 2 using c++ on a RedHat / Linux machine?

Answer:
Withgetuid(2)andgetgid(2). Seecredentials(7)for more information.

Usegetpwuid(3)andgetgrgid(3)for the names.


Question: I have written the majority of my project in C++. However there are several "filters" or folders which need to be compiled as C and linked to the project. How can I configure this within VStudio? Thanks.

Answer: You can change the Language property by right-clicking on the individual files and settingConfiguration Properties > C/C++ > Advanced > CompileAs ToCompile As C (/TC). No such facility for the filter are present though.


Question:
What was the munch library (or program?) fromcfrontpackage?
What is was used for?

Answer:
Munch was used to scan the nm output and look for static constructors/destructors.

See thecode(with comments) atSoftwarePreservation.com.


Question: If I want to make an OS X program as self-contained as possible to ease installation, what dynamic libraries can I expect everyone or most people to have? If I know that, I won't have to compile static libraries for everything.

Answer:
All functions listed inSingle UNIX Specification V3are available.

Obviously, all Cocoa frameworks are available as well. The exact contents depend on OS version.


Question:
I stumbled across this C code today. Can anyone tell me what the 'where' keyword means:

```
*y = sy + exit->y + (where * (entry->y + esy - exit->y));
```

Edit:

Ah.. my bad. It is just a variable name. VC++ highlighted it as though it was a keyword though.

Answer:
It's just a variable name...

(Thewhereis highlighted as blue here only because C# supportswhereas a keyword in LINQ.)


Question:
I was curious to know how I can round a number to the nearest whole number. For instance, if I had:

```
int a = 59 / 4;
```

which would be 14.75 if calculated in floating point; how can I store the result as 15 in "a"?

Answer:
The standard idiom for integer rounding up is:

```
int a = (59 + (4 - 1)) / 4;
```

You add the divisor minus one to the dividend.


Question:
This is my warning.

```
implicit declaration of function 'exit'
```

How i can remove it.

i am using linux & gcc compiler.

Answer:
Add:

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

to the top of your program.


Question:
I have a readline-based application with a prompt, however I'd like it to not show when the input is not interactive.

```
$ ./readline-app < command-list > result
$ cat result
prompt> Output line 1
prompt> Output line 2
prompt>
$
```

How can I make the prompt to not print in this case?

Answer: Useisatty(3)to determine whether stdin and/or stdout are connected to a tty.


Question: If 2 or more threads are waiting on an event, doesSetEventunblock one or all of them(Or some of them) ?

Answer: It depends on if it is a manual or auto-reset event.  If it is a manual reset, then multiple threads can be released until it is reset.  If it is auto-reset, then only one will be signaled.


Question:
This is my warning.

```
implicit declaration of function 'exit'
```

How i can remove it.

i am using linux & gcc compiler.

Answer:
Add:

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

to the top of your program.


Question:
I have a readline-based application with a prompt, however I'd like it to not show when the input is not interactive.

```
$ ./readline-app < command-list > result
$ cat result
prompt> Output line 1
prompt> Output line 2
prompt>
$
```

How can I make the prompt to not print in this case?

Answer: Useisatty(3)to determine whether stdin and/or stdout are connected to a tty.


Question: If 2 or more threads are waiting on an event, doesSetEventunblock one or all of them(Or some of them) ?

Answer: It depends on if it is a manual or auto-reset event.  If it is a manual reset, then multiple threads can be released until it is reset.  If it is auto-reset, then only one will be signaled.


Question:
This is my warning.

```
implicit declaration of function 'exit'
```

How i can remove it.

i am using linux & gcc compiler.

Answer:
Add:

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

to the top of your program.


Question:
I have a readline-based application with a prompt, however I'd like it to not show when the input is not interactive.

```
$ ./readline-app < command-list > result
$ cat result
prompt> Output line 1
prompt> Output line 2
prompt>
$
```

How can I make the prompt to not print in this case?

Answer: Useisatty(3)to determine whether stdin and/or stdout are connected to a tty.


Question: If 2 or more threads are waiting on an event, doesSetEventunblock one or all of them(Or some of them) ?

Answer: It depends on if it is a manual or auto-reset event.  If it is a manual reset, then multiple threads can be released until it is reset.  If it is auto-reset, then only one will be signaled.


Question:
Does your editor/ide highlight thata++;in this C/C++ code as part of a comment?

```
int a=1;
//some comment \
a++;
printf("%d\n",a);
```

And what about this?

```
int a=1;
//some comment ??/
a++;
printf("%d\n",a);
```

Answer: VC6, Visual Studio 2003, 2005, 2008, 2010 all do.


Question:
There's a #pragma command to link in a library from the source file rather than from the project settings. I just can't seem to remember it.

Can anyone here remind me?

Thanks

Answer:
```
#pragma comment(lib, "library")
```

http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx


Question:
I am serializing some C structure to string and than deserializing it withstrtok(). But, unfortunately,strtok()don't detect empty fields (eg 1:2::4).

Is there any alternative function?

Answer:
On linux there'sstrsep.

The strsep() function was introduced
  as a replacement for strtok(), since
  the latter cannot handle  empty
  fields.   However,  strtok()
         conforms to C89/C99 and hence is more portable.


Question:
Suppose I do a

```
double d = 234.5;
```

I want to see the memory contents ofd[the whole 8 bytes]

How do I do that?

Answer:
```
unsigned char *p = (unsigned char *)&d;
int i;

for (i = 0; i < sizeof d; i++)
    printf("%02x ", p[i]);
```


Question:
If we have

```
char *val = someString;
```

and then say

```
if(val){
    ....
}
```

what is theifstatement actually checking here?

Answer:
Yourifstatement is equivalent to:

```
if (val != NULL) { ...
```

The comp.lang.c FAQ containsthis question and answerwhich goes into a bit more detail why this is true.


Question: How to design an algorithm to convert a UTF-8 string to a unicode string?

Answer:
The commenters are right. Readhttp://en.wikipedia.org/wiki/Unicodeand rephrase question.

UTF-8 is a ''represenation'' of unicode. You probably want to recode to some other interpretation, maybe Java Strings or Microsoft Visual C++ multibyte chracter strings...


Question:
Does your editor/ide highlight thata++;in this C/C++ code as part of a comment?

```
int a=1;
//some comment \
a++;
printf("%d\n",a);
```

And what about this?

```
int a=1;
//some comment ??/
a++;
printf("%d\n",a);
```

Answer: VC6, Visual Studio 2003, 2005, 2008, 2010 all do.


Question:
When I copy code from another file, the formatting is messed up, like this:

```
fun()
{
for(...)
{
for(...)
{
if(...)
{
}
}
}
}
```

How can I autoformat this code in vim?

Answer:
Try the following keystrokes:

```
gg=G
```

Explanation:gggoes to the top of the file,=is a command to fix the indentation andGtells it to perform the operation to the end of the file.


Question:
I am not able to understand the following statement from the file limits.h. What is the use of this statement and what does it accomplishes?

```
/* If we are not using GNU CC we have to define all the symbols ourself.
   Otherwise use gcc's definitions (see below).  */
#if !defined __GNUC__ || __GNUC__ < 2
```

Answer: It checks if your program is compiled by some other compiler than GCC, or some very old GCC version.


Question:
What happens inside  memory if we try to free a pointer which is pointing to NULL?
Is that ever valid?

Why does it not show any warning/error messages?

Answer:
From C99 section 7.20.3.2 : Thefreefunction

Synopsis

```
1 #include <stdlib.h>
   void free(void *ptr);
```

Description

2 The free function causes the space pointed to by ptr to be deallocated, that is, made
  available for further allocation.If ptr is a null pointer, no action occurs.


Question:
I'm working on a client-server application written in C. I want to broadcast a message to all the machines available on the local network.

How can I do that using the usual socket system calls in C?

Answer: Just send the message to the broadcast address of your subnet, which for 192.168.0.0/24 is 192.168.0.255, or just broadcast to 255.255.255.255.


Question:
Is there any way to get the source code by using object file in C?

For example I have a source code simple.c

cc simple.c

Now I have a.out (object file). By this a.out whether can I get the source?

code of simple.c

Answer: No. Turning a cow into hamburger is fairly easy. Turning hamburger into a living cow, somewhat more difficult.


Question: If 2 file descriptors were dupped to the same file (i.e.506andSTDOUT), will invokingclose(506)cleanup the object associated by both and renderSTDOUTunusable? Or does kernel implement reference counting for its files?

Answer: The kernel implements reference counting, so the kernel object is not closed until all the file handles pointing to it are closed.


Question: How do I convert a binary string like "010011101" to an int, and how do I convert an int, like 5, to a string "101" in C?

Answer:
Thestrtolfunction in the standard library takes a "base" parameter, which in this case would be 2.

```
int fromBinary(const char *s) {
  return (int) strtol(s, NULL, 2);
}
```

(first C code I've written in about 8 years :-)


Question:
How to get the absolute path for a given relative path programmatically in Linux?

Incase of Windows we have the_fullpath()API. In other words, I mean what is analogous API to_fullpathof Windows in Linux?

Answer: As Paul mentioned, userealpath(). Please note though, that since many file systems in Linux supporthard links, any given directory can have a number of different absolute paths.


Question:
this is very basic...but please help me if anybody know about this...
Can an array be called as a const pointer?

Answer:
Do you mean "can array be used where a const pointer is expected"? In that case, yes:

```
void f(const int* p)
{
    ...
}

int ar[10];
f(ar); // this works, array is essentially a pointer
```


Question: How to install new units (i mean includes ex: stdio.h) for my C, and how to download more?

Answer:
put the header file on the same folder as your main source file,
ex:

/folder /-->main.c-->function.h
    -->function.c

then on main.c include it by writing :

```
#include "function.h"
```

the quotes are used to include a header file that's on the same folder as your c source file
u can also write your own and include them like above.


Question: I have been using ! (logical negation) in C and in other languages, I am curious does anyone know how to make your own ! function? or have a creative way of making one?

Answer:
```
int my_negate(int x)
{
    return x == 0 ? 1 : 0;
}
```


Question: I have to write some code to retrieve network packets from an Ethernet card in Windows using ANSI C.  Can anybody tell me where to get started?

Answer: The easiest way to do this is to use the PCAP library, there's a version for Windowshereand a basic examplehere


Question: In the execve() man page it is said that argv is a list of string arguments which is ended by a null pointer. But what is the NP for? I mean, the number of arguments is stored in argc, so what's the point of the null pointer?

Answer:
execvedoes not takeargcas a parameter, it manually counts the arguments you give asargvto determineargcitself.

This is for compatibility withexeclwhich takes a variable number of arguments instead of anargvarray.


Question:
I get a segmentation fault afterfreeing a certain pointer:

```
free(studentDB->name);
```

I can get its value without any errors or warnings:

```
printf("[DBG] studentDB->name: %s\n", studentDB->name);
```

However, as I said, the program crashes when I try to free it. What are the most common causes for afreecommand leading to a segmentation fault?

Answer: If you didn'tmalloc()it, you can'tfree()it.  Where doesstudentDB->namecome from?


Question: Is there any way to decompile Linux .so?

Answer:
There aredecompilers, but a decompiler might not emit code in the same language that the original program was written in.

There are alsodisassemblers, which will reassemble the machine code into assembly.

The Decompilation Wikimay be a good source of additional information.


Question:
I already know that I can trace memory leaks in my code withmtraceandvalgrindon Linux, both of which are unavailable for Windows. Which Windows program would you recommend to trace memory leaks?

I'm an Eclipse user and I've been working with C for a month or two now, so I prefer a user-friendly solution over something more advanced.

Answer: Application Verifier will do this quite well,http://msdn.microsoft.com/en-us/library/ms220948.aspx


Question:
My friend said he thinks i may have made a mistake in my programme and wanted to see if i really did. He asked me to send him the binary opposed to the source. As i am new to this i am paranoid that he is doing someting to it? What can you do with the binary that would mean you wouldnt want the source?

thank

Answer: Black-box testing. Having the source may skew your view on how the program may be behaving.


Question:
If Python was so fast as C, the latter would be present in python apps/libraries?

Example: if Python was fast as C would PIL be written completely in Python?

Answer: To access "legacy" C libraries and OS facilities.


Question:
Consider a float value like1.82set by the user. How do I find the next highest .05 value? For the given example the next highest value is 1.85.

Is there a simple way or does it take a complex algorithm?  I tried to usefloorandceilingfunctions to come up with the distance from the float to the next highest and lowest Integers. But I'm not sure how to proceed once I have that info.

Thanks.

Answer: Multiply by 20, use ceiling, divide by 20.


Question: In the execve() man page it is said that argv is a list of string arguments which is ended by a null pointer. But what is the NP for? I mean, the number of arguments is stored in argc, so what's the point of the null pointer?

Answer:
execvedoes not takeargcas a parameter, it manually counts the arguments you give asargvto determineargcitself.

This is for compatibility withexeclwhich takes a variable number of arguments instead of anargvarray.


Question:
I get a segmentation fault afterfreeing a certain pointer:

```
free(studentDB->name);
```

I can get its value without any errors or warnings:

```
printf("[DBG] studentDB->name: %s\n", studentDB->name);
```

However, as I said, the program crashes when I try to free it. What are the most common causes for afreecommand leading to a segmentation fault?

Answer: If you didn'tmalloc()it, you can'tfree()it.  Where doesstudentDB->namecome from?


Question: Is there any way to decompile Linux .so?

Answer:
There aredecompilers, but a decompiler might not emit code in the same language that the original program was written in.

There are alsodisassemblers, which will reassemble the machine code into assembly.

The Decompilation Wikimay be a good source of additional information.


Question:
I already know that I can trace memory leaks in my code withmtraceandvalgrindon Linux, both of which are unavailable for Windows. Which Windows program would you recommend to trace memory leaks?

I'm an Eclipse user and I've been working with C for a month or two now, so I prefer a user-friendly solution over something more advanced.

Answer: Application Verifier will do this quite well,http://msdn.microsoft.com/en-us/library/ms220948.aspx


Question:
My friend said he thinks i may have made a mistake in my programme and wanted to see if i really did. He asked me to send him the binary opposed to the source. As i am new to this i am paranoid that he is doing someting to it? What can you do with the binary that would mean you wouldnt want the source?

thank

Answer: Black-box testing. Having the source may skew your view on how the program may be behaving.


Question:
If Python was so fast as C, the latter would be present in python apps/libraries?

Example: if Python was fast as C would PIL be written completely in Python?

Answer: To access "legacy" C libraries and OS facilities.


Question:
just a sanity check please:

in VB.NET:

dim myarray(5) as integer

gives six elements 0 to 5

but in c?

int myarray[5];

gives five elements 0 to 4 ?

is this correct?

Answer:
Yes that's correct!

Hope I saved your sanity.


Question:
In a C program I get "passing argument ... from incompatible pointer type" warnings, however I want to get error and terminate compilation instead of warning.

What flag shall I set in makefile?

Answer: If using gcc, I think the option combination you need is-fstrict-aliasing -Wstrict-aliasing=3 -Werror=strict-aliasing. Seethis textfor documentation of thestrict-aliasingoption.


Question:
just a sanity check please:

in VB.NET:

dim myarray(5) as integer

gives six elements 0 to 5

but in c?

int myarray[5];

gives five elements 0 to 4 ?

is this correct?

Answer:
Yes that's correct!

Hope I saved your sanity.


Question:
In a C program I get "passing argument ... from incompatible pointer type" warnings, however I want to get error and terminate compilation instead of warning.

What flag shall I set in makefile?

Answer: If using gcc, I think the option combination you need is-fstrict-aliasing -Wstrict-aliasing=3 -Werror=strict-aliasing. Seethis textfor documentation of thestrict-aliasingoption.


Question: How would you set a variable to equal infinity (or any guaranteed largest number value) in C?

Answer:
```
#include <limits.h>
int x = INT_MAX;
```

EDIT: answered before the questioner clarified, I was just guessing what type they wanted.


Question:
If I have a C file like below, what is the difference betweeniandj?

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

static int i;
int j;

int main ()
{
    //Some implementation
}
```

Answer:
ihas internal linkage so you can't use the nameiin other source files (strictly translation units) to refer to the same object.

jhas external linkage so you can usejto refer to this object if you declare itexternin another translation unit.


Question: In my C++ program, I want to make sure i can write info to a file. How can I perform this check?

Answer: The only sure way to find if you can write to a file is to try to write to a file. It is possible, and even likely in some circumstances, that a file will have its permissions changed between calls to function such as stat and the actual write. Your code must deal with write failures anyway, so it makes sense to centralise the testing code there.


Question: Is it possible to specify per-thread in Linux?

Answer:
Yes, you kinda can do that. However not per-thead, but only per-call, using locale_t structures.

Read more about that at POSIX:

http://www.opengroup.org/onlinepubs/9699919799/functions/newlocale.html

And Ulrich Dreppper's dedsgin documents of what whent into glibc 2.1:

http://people.redhat.com/drepper/tllocale.ps.gz


Question: What is the difference between a re-entrant function and a thread safe function?

Answer:
Re-entrant means no global state (local only).

Thread safe means it is not possible for 2 (or more) threads to conflict with each other (by writing conflicting values).


Question: I am using fprintf command for writing on the text file, but every time when the function called its remove the previous data, I actually want to update the file so that the previous data remain. Kindly guide me how I can make it possible?

Answer:
when you open the file use "a" for append.

```
FILE * file = fopen("filename", "a");
```

http://www.cplusplus.com/reference/clibrary/cstdio/fopen/


Question: How would you set a variable to equal infinity (or any guaranteed largest number value) in C?

Answer:
```
#include <limits.h>
int x = INT_MAX;
```

EDIT: answered before the questioner clarified, I was just guessing what type they wanted.


Question:
If I have a C file like below, what is the difference betweeniandj?

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

static int i;
int j;

int main ()
{
    //Some implementation
}
```

Answer:
ihas internal linkage so you can't use the nameiin other source files (strictly translation units) to refer to the same object.

jhas external linkage so you can usejto refer to this object if you declare itexternin another translation unit.


Question:
When I do#include <stat.h>in Linux, I get a compiler error. I need this library for theS_IWRITEflag, which in its turn is used in the context of system-level IO.

Is stat.h unavailable in Linux?

Answer: stat.h is available under the "sys" folder, try to #include it from there or add it to the list of include directories.


Question:
I noticed that the boost library uses header files of (.hpp).I am curious since most source files I see use normal.hheader files.Could there be any special instances which warrant use of.hppinstead of.h?

Thanks

Answer: Just convention, nothing special. You can use any extension on include files, actually.


Question: I am working with audio data. I'd like to play the sample file in reverse. The data is stored as unsigned ints and packed nice and tight. Is there a way to callmemcpythat will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I callmemcpyandmagicallyreverse them so I get 4,3,2,1.

Answer: No, memcpy won't do that backwards.  If you're working in C, write a function to do it.  If you're really working in C++ use std::reverse or std::reverse_copy.


Question:
I noticed that the boost library uses header files of (.hpp).I am curious since most source files I see use normal.hheader files.Could there be any special instances which warrant use of.hppinstead of.h?

Thanks

Answer: Just convention, nothing special. You can use any extension on include files, actually.


Question: I am working with audio data. I'd like to play the sample file in reverse. The data is stored as unsigned ints and packed nice and tight. Is there a way to callmemcpythat will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I callmemcpyandmagicallyreverse them so I get 4,3,2,1.

Answer: No, memcpy won't do that backwards.  If you're working in C, write a function to do it.  If you're really working in C++ use std::reverse or std::reverse_copy.


Question:
I have a situation here

i am taking input from user

using scanf  can I terminate the scanf as soon as user presses the # key

please enlighten me on this

Answer:
No,scanf()(or rather stdin, by default) is line-oriented so it needs to read a full line.

Look intoncursesor similar libraries for "raw" key-by-key input.


Question:
How can I take a string (in this case it'll be loaded from a file) then remove certain characters and store them in an array.

Ex:

f.e.d.r.t.g.f

remove "." to get f e d r t g f in an array where I can manipulate each individually

Answer: Just iterate through the string and only copy the characters you're interested in, maintaining an index of the current position in the new array.


Question:
If C does not support passing a variable by reference, why does this work?

```
#include <stdio.h>

void f(int *j) {
  (*j)++;
}

int main() {
  int i = 20;
  int *p = &i;
  f(p);
  printf("i = %d\n", i);

  return 0;
}
```

Output:

```
$ gcc -std=c99 test.c
$ a.exe
i = 21
```

Answer: Because you're passingthe valueof the pointer to the method and then dereferencing it to get the integer that is pointed to.


Question:
It's not possible to do something likefputs(4, fptOut);because fputs doesn't like integers. How can I work around this?

Doingfputs("4", fptOut);is not an option because I'm  working with a counter value.

Answer:
What about

```
fprintf(fptOut, "%d", yourCounter); // yourCounter of type int in this case
```

Documentation offprintfcan be foundhere.


Question:
How can I read from the stdout of my program?

One of my threads needs to access the stdout to read what the other threads are logging.

I'm using the dear old plain C.

Answer: Make stdout use a pipe by replacing the stdout fd with the write side fd of apipeusingdup.


Question: I want to archive my database of mysql. Kindly give me some guide lines how I can make it possible, I am using mysql c library for insertion and selection etc. I dont know how to use dump command.

Answer: UseSHOW TABLESandDESCRIBE tbl_namequeries to obtain structure of database and tables. Then, use SELECT to fetch data and proceed it to your output according to the structure.


Question: I hear of a need to call assembly functions/calls when programming embedded systems in C. Is this necessary in C++ or not?

Answer: C++ does not provide any more low-level constructs than C does. Hence, if you need to fiddle around with control registers and ISRs in C, you will need to do it in C++.


Question:
Is there a way to replace any keyword in a text file using POSIX calls, without re creating the file..
If yes Please tell me how to do it..

Thanks in advance..

Answer: If the text and the replacement are the same size then you can open it with moder+, seek, and then write. If their sizes are different then there is no way to replace without recreating.


Question:
Hi I'm working in a Linux environment and I have to link to a object file already compiled which offers me some services (services.o) and I know some of them, but I'd like to know which are all of the exported symbols of it.

Is there any way to accomplish this not having the sources? If so, how?

Thanks you very much.

Answer: Trynm-- this tool is there for just this purpose.


Question: Text is disappearing from the bottom of aRichEditcontrol window and I'd like to ensure the bottom character is always visible. Obviously, I could manually scroll to the bottom, but I'd like to do it under software control.

Answer: Send the EM_SCROLLCARET message.  Position the caret first, GetWindowTextLength() and EM_SETSEL.