Question:
I need maximum performances using GMP and I wonder whether there is a better way to compute the absolute value of the difference of two numbers.
Currently I use:

```
mpz_sub(x, a, b);
mpz_abs(x, x);
```

Is there a most efficient way to do that ?

Answer: Your code should already be close to optimal. When the source and destination are the same,mpz_abstakes constant time: it does not read the big number and only performs a trivial operation on the sign.


Question:
I have make two librarieslibsa.aandlibsb.a.
The functionfuncainlibsa.aandfuncbinlibsb.awhich callsfunca.

In the main function, I only callfuncb. The compiler display that "... undefined reference to `funca'". The compiler command like "gcc main.c -o main -lsa -lsb".

The problem is resolved when I add afuncain the main function.

What can I do?

Sorry for my poor English!

Answer: Change the order:gcc main.c -o main -lsb -lsa


Question:
If you want a dynamically allocated array ofint size, there two ways you can get that in C:

```
int* array = new int [size]; //method 1
int* array2 = malloc (sizeof(int) * size); //method 2
```

When should you use each method?

Answer:
If you're in C, the second one.

If you're in C++, usestd::vector<int>if you can; otherwise use the first one (rarely needed).


Question:
the codes is:

```
#define O_ACCMODE       00000003
#define ACC_MODE(x) ("\000\004\002\006"[(x)&O_ACCMODE])
```

How to understand it?Thank you.

Answer:
"\000\004\002\006"defines array of 4 bytes/chars, we can replace it with:

char array[4] = {0, 4, 2, 6};

x&3 means - get only far right 2 bits in integer, basically it is equivalent ofx%4

so, this macro do:array[ x % 4 ]- takes proper value based on index


Question:
I need to get PID of foreground app programatically(in C or Obj C) in OS X.

How to solve the following problem?

Answer:
This should do it:

```
pid_t pid=NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier;
```


Question:
I am looking for a decent one line c statement to keep a character between'0'and'9'on increment

What I have right now is this:

```
char c;
...
c = (((c % 48 ) + 1) % 10) + 48;
```

Is there a better way of dong this?

Answer:
Use'0'instead of hardcoding its ASCII value. Also I likec - '0'better thanc % '0'; it matches up with the+ '0'better.

```
c = (c - '0' + 1) % 10 + '0'
```


Question: I want to know, ifWriteProcessMemoryorReadProcessMemoryfunctions access program code, or data. Thanks.

Answer:
It can access both.

Program text and data live in the same address space, and are somewhat intermingled for things like read-only data.


Question: Is there a C or C++ library available for parsing, editing, and writing/etc/network/interfaceson Linux (in the form described athttp://manpages.ubuntu.com/manpages/hardy/man5/interfaces.5.html)?

Answer:
http://augeas.net/

Augeas is a configuration editing tool. It parses configuration files in their native formats and transforms them into a tree. Configuration changes are made by manipulating this tree and saving it back into native config files.


Question:
i Want to catch keyboard key on a real time game, for example im printing each 0,3s with usleep(300000) something like that

```
// #####
// ##a##
// #####
```

and I want to move my 'a' arround with the directional keyboard key (left, right...) the problem is each time I call read the program is paused till I enter a key

Answer:
You have two choices:

multi-threadingasynchronous I/O


Question: I am trying to extract the minor device number from the tty_nr attribute in /proc/pid/stat. According to the documentation it is said that, minor device number is a combination 0-7 and 20-30 bits in tty_nr. How can I extract these bits from the tty_nr number?

Answer: There are macros already defined for this purpose.  Use theMAJOR()andMINOR()macros that are defined inlinux/kdev_t.h.


Question:
As the title suggests how do i print 17 in the hexadecimal format(0x11).
I have triedprintf("%04x",number);but it prints the number as 0011(correct but not what i want).

Answer:
Try this its clean and simple.

Hexadecimal ->printf("%#x",17);

Octal       ->printf("%#o",17);

More about#. Here's the linkhttp://www.cplusplus.com/reference/cstdio/printf/


Question:
As the title suggests how do i print 17 in the hexadecimal format(0x11).
I have triedprintf("%04x",number);but it prints the number as 0011(correct but not what i want).

Answer:
Try this its clean and simple.

Hexadecimal ->printf("%#x",17);

Octal       ->printf("%#o",17);

More about#. Here's the linkhttp://www.cplusplus.com/reference/cstdio/printf/


Question:
I have a strange line in my stacktrace that I want to investigate further:

```
12  libsystem_c.dylib               0x3aa272dc free + 168
```

If I understand correctly, libsystem_c is C standard library. Is the version used in the iOS open-sourced? Where can I get that source?

Answer: To be more specific, I think it is hosted here:https://opensource.apple.com/source/Libc/


Question: I see everyone recommends just using openGL and some others but I don't wanna. I just want to know if graphic.h will only compile in turbo c and not with gcc, Thanks

Answer: You might getgraphics.hcompiled (as#included part of some sources), but the linking (coming after the compilation) will fail, as gcc's linker (ld) would not link the compilation's result against the library (graphics.lib) implementing whatgraphics.hprototyped.


Question:
I have Linux and I have a physical address: (i.e. 0x60000000).I want to read this address from user-space Linux program.

This address might be in kernel space.

Answer:
You need a kernel driver to export the phyisical address to user-level.

Have a look at this driver:https://github.com/claudioscordino/mmap_alloc/blob/master/mmap_alloc.c


Question:
I have Linux and I have a physical address: (i.e. 0x60000000).I want to read this address from user-space Linux program.

This address might be in kernel space.

Answer:
You need a kernel driver to export the phyisical address to user-level.

Have a look at this driver:https://github.com/claudioscordino/mmap_alloc/blob/master/mmap_alloc.c


Question:
This question already has an answer here:how to use the compiling time as automatic versioning-info?(1 answer)Closed9 years ago.

So what I want is to have some preprocessor which gives the time of compilation. So that I can know which version of the program I'm running, by printing that time. Is it possible?

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

int main(void)
{
  printf("%s %s\n", __DATE__, __TIME__);
  return 0;
}
```

Otherstandard predefined macros


Question:
This question already has an answer here:how to use the compiling time as automatic versioning-info?(1 answer)Closed9 years ago.

So what I want is to have some preprocessor which gives the time of compilation. So that I can know which version of the program I'm running, by printing that time. Is it possible?

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

int main(void)
{
  printf("%s %s\n", __DATE__, __TIME__);
  return 0;
}
```

Otherstandard predefined macros


Question:
In C/C++ when I want to find sum of two chars - I get result in int.For example:

```
#include <stdio.h>
int main(){
   char a = 'a', b = 'b';
   printf("%d + %d = %d\n", sizeof(a), sizeof(b), sizeof(a + b));
   return 0;
}
```

Prints

```
1 + 1 = 4
```

Why?

Answer: Because althoughaandbare each of typechar, the expressiona + bis of typeint. Anytime you do math with char types, they are converted to int before doing the actual calculations.


Question: How do use vector or in-built sort function in C++ with most of the language in C? I am trying to just sort an array for a C program. Can it explained with a simple code with sort implementation? I am very new to C++.

Answer:
If you want to sort inCthen you should useqsort.

If you want to sort inC++then you should usestd::sort


Question:
Which of the following declaration is the standard and preferred?

```
int x = 7;
```

or

```
int x(7);
```

Answer:
```
int x(7);
```

isnotthevalidway of declaring & initializing a variable in C;

I suggest you to get a good book for learning C and use a good compiler.


Question:
Which of the following declaration is the standard and preferred?

```
int x = 7;
```

or

```
int x(7);
```

Answer:
```
int x(7);
```

isnotthevalidway of declaring & initializing a variable in C;

I suggest you to get a good book for learning C and use a good compiler.


Question: I'm modifying a linux filesystem and I would like to know if there a way to get astruct file *from an absolute pathname? Specifically the struct defined inlinux/fs.h.

Answer: I know this is a little late, but for anyone looking for an answer to this I used theopenfunction on the pathname.


Question: I'm modifying a linux filesystem and I would like to know if there a way to get astruct file *from an absolute pathname? Specifically the struct defined inlinux/fs.h.

Answer: I know this is a little late, but for anyone looking for an answer to this I used theopenfunction on the pathname.


Question:
In xcode 5 I get this warning:

"implicit declaration of function free is invalid in c99"

How should I free my c structures if I can't use the function free()?

Answer: You should include<stdlib.h>.


Question:
I have a register which 31 bit wide ,Now I am confused between two number that could be used as last address 31 bit scheme .

Would  0x7fff-fffc or 0x80000000 be the last address can be used in 31 scheme.

Answer: Addresses start at zero. So0x7FFFFFFFif you are addressing bytes.0x7FFFFFFCif you are addressing 32-bit words.


Question: When using theC interface to LLVM, how do I determine whether twoLLVMTypeRefs represent the same type?

Answer: IIUC, if the two types were created in the sameLLVMContextit should be the same pointer, since types are uniqued in LLVM. C API functions usewrapto "convert" C++TypetoLLVMTypeRef, which just usesreinterpret_caston the pointer.


Question:
I have a register which 31 bit wide ,Now I am confused between two number that could be used as last address 31 bit scheme .

Would  0x7fff-fffc or 0x80000000 be the last address can be used in 31 scheme.

Answer: Addresses start at zero. So0x7FFFFFFFif you are addressing bytes.0x7FFFFFFCif you are addressing 32-bit words.


Question: If I call a function in C and pass in a struct (not by pointers nor references for those c++ readers), it copies the object. If I pass in a struct with an array in it, it copies the array (as stated by professor in class). But what happens if I pass in a struct that contains a circular reference back to the object. How does it copy the whole struct?

Answer: It copies the struct, and the pointer inside the copied struct contains the address of the original object.


Question:
```
void empty() { }
```

will be compiled to

```
push ebp
mov ebp, esp
ret
```

How do I declare the function so that it has no "decoration" code? just plainret.
If that is not possible, is this possible to define completely assembler function inside the.Cfile? It is possible to define assembler function in the.asmfile.

Answer: Declare the function with the__declspec(naked)modifier.


Question:
is this valid C code ? Is possible to have switch in switch ?

```
switch (i){
 case 1:
  switch(c){
   case 1:
    c = 0;
    break;
   case 3:
    c = 5;
    break;
   }
case 2:
 // another code
}
```

Answer:
Yes, to have switch in switch is valid.

§ 6.4.2The switch statement

4Switch statements can be nested; a case or default label is associated with the smallest switch enclosing
  it.


Question: If I call a function in C and pass in a struct (not by pointers nor references for those c++ readers), it copies the object. If I pass in a struct with an array in it, it copies the array (as stated by professor in class). But what happens if I pass in a struct that contains a circular reference back to the object. How does it copy the whole struct?

Answer: It copies the struct, and the pointer inside the copied struct contains the address of the original object.


Question:
```
void empty() { }
```

will be compiled to

```
push ebp
mov ebp, esp
ret
```

How do I declare the function so that it has no "decoration" code? just plainret.
If that is not possible, is this possible to define completely assembler function inside the.Cfile? It is possible to define assembler function in the.asmfile.

Answer: Declare the function with the__declspec(naked)modifier.


Question:
I'm debugging my C code

and I want to know the value of a chars array.

the problem is that it is seen like this:

0x63d7c4c8 "\327\220\327\250\327\225\327\236"

how can I convert to Hebrew chars, via eclipse debug window?

Answer:
```
bash ~ $ printf "\327\220\327\250\327\225\327\236\n"
ארומ
bash ~ $
```

Not sure you can change it in the debug window, but take a lookhere.


Question:
This question already has answers here:C++ : why bool is 8 bits long?(7 answers)Closed9 years ago.

Forbool, it's 8 bit while has only true and false, why don't they make it single bit.

And I know there'sbitset, however it's not that convenient, and I just wonder why?

Answer:
The basic data structure at the hardware level of mainstream CPUs is a byte. Operating on bits in these CPUs require additional processing, i.e. some CPU time.
The same holds forbitset.


Question:
I executed the following code.

```
#include <stdio.h>

int main()
{char *a="awake";
 printf("%s\n", *(a+1));
 return 0; // expected out_put to be wake
}
```

Answer: You're dereferencing the pointer, which makes it acharbut trying to output a string. Change your print statement toprintf("%s\n", a+1);


Question:
What mark does a language leaves on a compiled library that we need language bindings if we have call its functions from a different language?

object code looks 'language free' to me.

While learning OpenGL in c in Linux environment I have across language bindings.

Answer:
Binding provides a simple and consistent way for applications to present and interact with data.

Source: The tag under your question


Question:
I executed the following code.

```
#include <stdio.h>

int main()
{char *a="awake";
 printf("%s\n", *(a+1));
 return 0; // expected out_put to be wake
}
```

Answer: You're dereferencing the pointer, which makes it acharbut trying to output a string. Change your print statement toprintf("%s\n", a+1);


Question: When I compile a C project it can take about 90 seconds even though I use a fast Intel I7 CPU. Is it because compilation is a low-level task or why are my build times so long? My environment is the Nios 2 IDE for Altera DE2 FPGA.

Answer: if your project is managed by Makefile, try "make -jn" to trigger mul-threads in compiling, n is thread num for compiling, e.x. "make -j10"


Question:
I know a pointer to a function is 8 byte because of virtualization but why a pointer to a pointer to a function is 8 byte?

```
typedef void(*fun())();
sizeof(fun*); // returns 8 byte
```

Answer: If you have a 64-bit system with 8-bit bytes (and it sounds like you do), probablyallpointers will be 8 bytes in size.  Virtualization doesn't have anything to do with it.


Question:
Is it a standard to have only dynamic libraries mostly without their static version? I am particularly asking about math library. In my fedora 17 (linux machine on Intel 32 processor), I have latest gcc and it has libm-2.15.so and symbolic link file libm.so  but there is no libm.a.

Is libm.a missing on my system?

Answer:
Install the static libraries:

```
# yum install glibc-static
```


Question:
Is it possible to do multiple operations in increment part of for loop in C/C++?
Something like this:

```
int a = 0, b = 0, c = 5;
for(; a < c; increase a by 1 and increase b by 2)
```

Answer:
Use the comma operator:

```
for (; a < c; ++a, b += 2)
```


Question:
I'm trying to use the functionsisDigit()I have the correct include statement,#include <ctype.h>however, I seem to be getting a warning when I compile,

```
warning: implicit declaration of function 'isDigit' is invalid in C99 [-Wimplicit-function-declaration]
```

The line that compiles the warning isif(isDigit(atoi(inputLine)) {can anyone give me feedback as to what I am missing here? Thanks.

Answer: include this header file in your program :#include<ctype.h>


Question:
I want to write a simple C program which would print the number of times that program itself got executed (by user).

for example,

output should beYou are executing this program 3rd time

I first thought of using file handling but later came to know aboutvolatileandregister.

Is there any use ofvolatileorregisterin this context?

Answer: No,volatileandregisterare only meaningful within the same run. Instead, store a counter in a file.


Question:
```
#ifndef _WINDOWS
   if(condition)
   {
     printf("to do in linux");
   }
   else
   #endif
   {
      printf("should work in both linux and windows...");
   }
```

My question: does this code work for both in linux and windows?

Answer:
You have more logic than you need - you can just do this:

```
#ifndef _WINDOWS
     printf("to do in Linux");
     // ...
#endif
     printf("to do in both Linux and Windows");
     // ...
```


Question:
Suppose I have the following code. While debugging, I want Eclipse to stop when it has done 1 million iterations. How to do this? I cannot manually do 1 million times.

```
for(int i = 0; i < 10000000; i++) {
    //some code
}
```

Answer:
You can put conditional break point in eclipse:

Put a breakpointRight-click->PropertiesTurn on "condition" check-boxPut condition codei == 1000000


Question:
Does such a function result in a dangling pointer?

```
int *foo () {
    int a[2] = {2, 3};
    int *p = NULL;
    p = a;
    return p;
}
```

Answer: Yes. You are returning a pointer to an array with automatic storage duration.  When the function returns the pointer is invalid.


Question:
Whether there are situations when the object needs to be created in memory to a certain address? Where it can be necessary (example)?

Thank you.

Answer:
Take a look at placement new: "What uses are there for "placement new"?"

Good examples are writing your own memory allocator, garbage collector, or trying to precisely lay out memory due to cache performance.

It's a niche thing, but sometimes very useful.


Question:
This question already has an answer here:Pointer to a specific fixed address(1 answer)Closed9 years ago.

I need to write 0x00001234 in the address 0x8000000, is it possible in C?

Answer:
If you work with hardware register in embedded system then standard way is:

```
int volatile * const p_reg = (int *) 0x8000000;
*p_reg = 0x1234;
```

You can have a lot of problems with optimizing compiler, if you omitvolatile


Question:
I want to use getaddrinfo() but get only the first result.

more specifically, I want the function to first scan the hosts file and fetch the first result found, and only if not found in hosts I want to query the dns server.

is it possible?

thanks.

Answer: You can't. It behaves as documented. You only have touseone result: that's up to you.


Question:
Hi I have this book with a practice question which I am unable to answer. And no...this is not a homework question. This is my self study from a book recommended to me called: "Computer systems, A programmer's perspective"

Here is the question:

Any help is appreciated!

Answer: lengthis unsigned, so if you pass0for that parameter,length - 1will beUINT_MAX, not-1like you want it to be;  therefore the loop will run and you'll make acceses outside the size ofa.


Question: When to use sqlite3_blob_write and sqlite3_blob_read? When this functions is more useful than sqlite3_prepare_v2 + sqlite3_bind_blob?

Answer:
You use them when the blobs are too large for the memory available for your program, or when you need to access only a small part of a large blob.

This matters mostly in embedded applications.


Question:
In my programming class we are not allowed to use || && and ! for this assignment. How can you do a "not" statement without the use of !? Also, how to do && would be useful but I think I can figure it out.

(we can use % / * pow abs ln + -)

Answer: !ais equivalent to1-a, providedais guaranteed to take only the values 0 or 1.


Question:
I have achar* linefromfgets (line , 255 , pFile)that I want to add the character "#" to the end of.  How do I do this in c++?

Something like

```
while ( fgets (line , 255 , pFile) != NULL )
{
    line = line + '#'
}
```

Answer:
```
strcat(line, "#");
```

Of course the correct answer is to usestd::stringinstead.


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

int main()
{
    printf(5 + "abhishekdas\n") ;
    return 0 ;
}
```

The output of the program ishekdas. How is it working? Shouldn't it show error? How is it possible to write something like5 + "abhishekdas"insideprintffunction ?

Answer:
```
5+"abhishekdas\n"  ==> "abhishekdas\n"+5 ==> &"abhishekdas\n"[5] ==> "hekdas\n"
```


Question:
How to convert a 32-bit integer value to an ip-address?

I am havingint value=570534080and want to convert it to192.168.1.34.

Answer:
```
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(void) {
    int value=570534080;
    struct in_addr addr = {value};
    printf( "%s", inet_ntoa( addr ) );
    return 0;
}
```

Test:http://ideone.com/RCDgj4

For Windows use#include <winsock2.h>


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

int main()
{
    printf(5 + "abhishekdas\n") ;
    return 0 ;
}
```

The output of the program ishekdas. How is it working? Shouldn't it show error? How is it possible to write something like5 + "abhishekdas"insideprintffunction ?

Answer:
```
5+"abhishekdas\n"  ==> "abhishekdas\n"+5 ==> &"abhishekdas\n"[5] ==> "hekdas\n"
```


Question:
How to convert a 32-bit integer value to an ip-address?

I am havingint value=570534080and want to convert it to192.168.1.34.

Answer:
```
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(void) {
    int value=570534080;
    struct in_addr addr = {value};
    printf( "%s", inet_ntoa( addr ) );
    return 0;
}
```

Test:http://ideone.com/RCDgj4

For Windows use#include <winsock2.h>


Question:
Is stdin is a pointer, as I have seen its usage in fgets().

I used '0' as we use for read or write mistakenly for stdin and got a segfault during fgets.

Is STDIN macro and 0 are the same.

Is stdin is a file pointer. Please explain about this

Answer:
stdin is aFILE *fromstdio.h

```
STDIN_FILENO == fileno(stdin)
```

STDIN_FILENOis inunistd.hand is used for functions likewrite, whereas stdin as a File * is used for stdio functions likeprintf


Question:
This question already has answers here:Print part of a string in C(4 answers)Closed9 years ago.

Is it possible inCto set a number of chars to be output from string?

```
char const *str = "abcdefgh";
printf("%???s", str);
```

What should be placed instead of ??? to outputabc?

Answer:
Yes, you could use a precision specifier, which would look something like this

```
printf("%.3s", str); // this prints "abc"
```


Question:
How can I make a pointer point to the last byte of
the physical memory and access its data?
Is this even possible?

Answer:
No, since the language C does not specify the underlying memory architecture.

On select OS/architecture you may in an OS dependent or creative fashion.


Question:
How can I make a pointer point to the last byte of
the physical memory and access its data?
Is this even possible?

Answer:
No, since the language C does not specify the underlying memory architecture.

On select OS/architecture you may in an OS dependent or creative fashion.


Question:
Is there a way to put an array inside another array without using loops? This loop feels a bit weird:

```
uint8_t buf0[50];
populate_buf( buf0 );
uint8_t buf1[100];
buf1[0] = 'S';
for ( uint8_t i = 0; i < 50; i++ )
    buf1[1+i] = buf0[i];
```

Answer:
```
memcpy(&buf1[1], &buf0[0], sizeof buf0);
```


Question:
Is there a way to put an array inside another array without using loops? This loop feels a bit weird:

```
uint8_t buf0[50];
populate_buf( buf0 );
uint8_t buf1[100];
buf1[0] = 'S';
for ( uint8_t i = 0; i < 50; i++ )
    buf1[1+i] = buf0[i];
```

Answer:
```
memcpy(&buf1[1], &buf0[0], sizeof buf0);
```


Question:
I would like to dynamically allocate memory for an input string whose size is unknown at the time of input,with exact precision, i.e.
if the string is "stack" I would like to allocate 6 bytes only.

I guess the only way is to keep on increasing the upper limit of the array depending on the input but I am unable to figure out the piece of code.

Answer:
strdup()is your friend.

```
char *p = strdup("stack");
```


Question: If I encounterfeof()and thenstatshows that the file has grown, is there a way to read the added data without doing afclose()andfopen()?

Answer: Yes. You can callclearerron the file, or perform any seek opereration such asfseek(f, 0, SEEK_CUR).


Question:
given this definition:

```
typedef enum mytype {
    FIRST = 0,
    TWO = 1,
    Three = 2
} mytype_t;
```

and

```
somefunction(mytype_t param_one) { (some code) }
```

How I can get the integer value of param_one inside the function or assign it to a integer variable?

Answer:
You just use it - it is an integer type already:

```
int x = param_one;
```


Question:
In C,stdinis a valid file pointer, thus we could usestdin(and the 2 others) with the "file" version of the input functions if we want or need to.

Why might us need to (Rather than just pipe in from shell)? Could anyone come up with some examples please?

Answer:
Here's an example:

```
FILE * input = argc == 2 ? fopen(argv[1], "r") : stdin;

fgets(buf, sizeof buf, input);
```

Now you can use your tool asmagic data.txtand asmagic < data.txt.


Question:
In C,stdinis a valid file pointer, thus we could usestdin(and the 2 others) with the "file" version of the input functions if we want or need to.

Why might us need to (Rather than just pipe in from shell)? Could anyone come up with some examples please?

Answer:
Here's an example:

```
FILE * input = argc == 2 ? fopen(argv[1], "r") : stdin;

fgets(buf, sizeof buf, input);
```

Now you can use your tool asmagic data.txtand asmagic < data.txt.


Question:
This question already has answers here:How do you check the windows version in Win32 at runtime?(2 answers)Closed10 years ago.

I wanted to ask, is there any possibility to determine the Windows version via the application, I have made some research, but haven't found,
Thank you in advance ^^

Answer: Err... How aboutGetVersionEx()?


Question:
This question already has answers here:How do you check the windows version in Win32 at runtime?(2 answers)Closed10 years ago.

I wanted to ask, is there any possibility to determine the Windows version via the application, I have made some research, but haven't found,
Thank you in advance ^^

Answer: Err... How aboutGetVersionEx()?


Question:
i am trying query windows for a list of all usb hdi devices that are connected to my computer.
Somehow i the microsoft dokumentation is not exactly to helpfull for me. Can anybody please point me to something? I would like to use c/c++
Thanks!

Answer: here you can find anything you want:https://github.com/signal11/hidapi


Question:
Could someone outline how to use c99 when my c-programs compile? I cannot use the for(int i = 0...) loop without it. Note - all the answers I have found are either outdated, or for the cygwin compiler.

thanks in advance

Answer: In the project build settings set-std=c99in the "Other flags" text box.


Question:
I am very beginner in c and I am reading now the classic example of the TicTacToe game.
I am not sure about what thisreturnstatement does:

```
{.....
     return (ch == X) ?O :X;
```

This must be some conditional statement on the variable ch (that in my case stands for the player (X or O) but I am not sure about its meaning. Can anyone please tell me what does it do?

Answer:
It means

```
if (ch == X)
    return O;
else
    return X;
```


Question:
It's quite a simple question but has it's gotchas.So here it goes.

Does each new Lua state created using the lua_newthread C API method get it's own individual LUA_REGISTRYINDEX accessible through it's new created Lua state or does it use a global shared LUA_REGISTRYINDEX?

Answer:
All threads of the same Lua state share a single registry, as can be seen in thesource.

Different Lua states have different registries.


Question: Using theCprogramming language, what is the best way to make a multicore Red Hat Linux processor, use only one core in a test application?

Answer:
There is aLinux system callspecifically for this purpose calledsched_setaffinity

Forexample, to run on CPU 0:

```
#include <sched.h>
int main(void)
{
    cpu_set_t  mask;
    CPU_ZERO(&mask);
    CPU_SET(0, &mask);
    result = sched_setaffinity(0, sizeof(mask), &mask);
    return 0;
}
```


Question:
It's quite a simple question but has it's gotchas.So here it goes.

Does each new Lua state created using the lua_newthread C API method get it's own individual LUA_REGISTRYINDEX accessible through it's new created Lua state or does it use a global shared LUA_REGISTRYINDEX?

Answer:
All threads of the same Lua state share a single registry, as can be seen in thesource.

Different Lua states have different registries.


Question: Using theCprogramming language, what is the best way to make a multicore Red Hat Linux processor, use only one core in a test application?

Answer:
There is aLinux system callspecifically for this purpose calledsched_setaffinity

Forexample, to run on CPU 0:

```
#include <sched.h>
int main(void)
{
    cpu_set_t  mask;
    CPU_ZERO(&mask);
    CPU_SET(0, &mask);
    result = sched_setaffinity(0, sizeof(mask), &mask);
    return 0;
}
```


Question: Using theCprogramming language, what is the best way to make a multicore Red Hat Linux processor, use only one core in a test application?

Answer:
There is aLinux system callspecifically for this purpose calledsched_setaffinity

Forexample, to run on CPU 0:

```
#include <sched.h>
int main(void)
{
    cpu_set_t  mask;
    CPU_ZERO(&mask);
    CPU_SET(0, &mask);
    result = sched_setaffinity(0, sizeof(mask), &mask);
    return 0;
}
```


Question:
I'm having a problem casting, so is there a way to cast a type of:

```
char *result;
```

to a type of

```
char *argv[100];
```

?

If so, how would I do this or is there a safe way to do this?

Answer:
char * resultis a string

and

char * argv[100]is array of strings.

You cannot convert string into array of strings. However, you can create an array of strings where the first array value is result.

```
argv[0] = result;
```


Question: Is there anyway I can load a c pointer into a specific register like eax? I want to take an array, like int array[10], and load array (or &array[0], but either way they're the same thing) into register eax.

Answer:
This is compiler dependent. Gcc has an extension to theregisterkeyword

```
register unsigned* p __asm__("eax") = a;
```


Question: Is there a way to get my Spotify play history using either their js or C APIs? I saw a couple of examples, but that was using their outdated API version.

Answer:
Spotify play history is not available through any API.

Disclaimer: I'm a Spotify employee.


Question:
Will it be precise to say that in

```
void f() {
    int x;
    ...
}
```

"int x;" means allocatingsizeof(int)bytes on the stack?

Are there any specifications for that?

Answer: Nothing in the standard mandates that there is a stack. And nothing in the standard mandates that a local variable needs memory allocated for it. The variable could be placed in a register, or even removed altogether as an optimization.


Question: Is there a way to get my Spotify play history using either their js or C APIs? I saw a couple of examples, but that was using their outdated API version.

Answer:
Spotify play history is not available through any API.

Disclaimer: I'm a Spotify employee.


Question:
I'm compiling a C code in Xcode 4.6.3, however I don't know which compiler I'm using. I need to use gcc 4.2.

Thanks in advance.

Answer: If youreallyneed to change to gcc, you can do so in the build settings:


Question:
When I do something like

```
typedef long a;
extern a int c;
```

It gives me error :two or more data types in declaration specifiers.Why?

EDIT

```
typedef long a;
extern a c;
```

works fine.So why not above?

Answer: It's a typedef, not a macro. The compiler doesn't seeextern long int c, it seesextern a int c, which contains two different types (aandint).


Question:
Code:

```
int main()
{
  char *name=NULL;
  int n;
  printf("\nenter the string\n");
  scanf("%s",name);
  n=strlen(name);
  printf("%d",n);
  return 0;
}
```

I am getting segmentation fault. Whats wrong with the code? I have includedstdio.h,stdlib.h,string.h.

Answer:
You didn't allocate any memory for pointer to charname.

Example:

```
char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ;
```


Question:
Code:

```
int main()
{
  char *name=NULL;
  int n;
  printf("\nenter the string\n");
  scanf("%s",name);
  n=strlen(name);
  printf("%d",n);
  return 0;
}
```

I am getting segmentation fault. Whats wrong with the code? I have includedstdio.h,stdlib.h,string.h.

Answer:
You didn't allocate any memory for pointer to charname.

Example:

```
char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ;
```


Question:
In my program the user inputs the number of decimal places he requires in an output. I save this input as deci. How do I use this variabledecias a precision modifier?

Sample:
Input a number: 23.6788766
Input number of decimals: 2
Output: 23.67

Answer:
If it is C you can do:

```
float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);
```


Question:
Let the first row be:

```
#define TAG_LEN 32
```

Now, I need to concatenate it with a literal string constant; something like that:

```
puts("Blah" [insert your answer] TAG_LEN); // I need "Blah32".
```

Answer:
```
#define STR_NOEXPAND(tokens) # tokens
#define STR(tokens) STR_NOEXPAND(tokens)
puts("Blah" STR(TAG_LEN));
```


Question:
My compiler warns:operation on j may be undefined

Here's the C code:

```
for(int j = 1; pattern[j] != '\0' && string[i] != '\0';){
    if(string[i+j] != pattern[j++]){//this is on the warning
        found = 0;
        break;
    }
}
```

Is that undefined?

Answer: YES.string[i+j] != pattern[j++]is having two different execution based on variablejwithout anysequence pointin between. So it is example ofundefined behaviour.


Question: So I was using CGo for a number crunching web app and it happens that CGo seems faster. Is there any that I can use CGo on Google App Engine Go runtime.

Answer: Nope.  CGo is not supported yet, and perhaps never will.  This isPaaSafter all and they need to isolate the platform.  But you never know.  Perhaps a restricted version.


Question: So I was using CGo for a number crunching web app and it happens that CGo seems faster. Is there any that I can use CGo on Google App Engine Go runtime.

Answer: Nope.  CGo is not supported yet, and perhaps never will.  This isPaaSafter all and they need to isolate the platform.  But you never know.  Perhaps a restricted version.


Question:
Here are some links documenting the functions that I want to use:

xmlNewNodexmlNewChildxmlNewProp

Since these functions use dynamic memory allocation, I want to do error checking, but I couldn't find information about behavior of these functions in case of an error. Do these functions simply return NULL on failure ?

Answer: Yes, like most of thelibxml2functions which return pointers, these returnNULLon failure.


Question:
I'm trying to implement HTTP/1.1 protocol using Socket in C language. I just want to know if the Body inside a request can contain strings like: "\r\n" i.e a CR LF.

Also, please let me know if there is a maximum limit to the number of characters inside the body.

Answer: There are no limits to the size or content of the body in an HTTP request or response.


Question:
Are the following same:

```
extern int a[];
```

and

```
extern int *a;
```

I mean, are they interchangable?

Answer:
No they are not.  You'll see the difference when you try something likea++.

There's plenty of questions about the difference between pointers and arrays, I don't think it's necessary to write more here.  Look it up.


Question:
Is there a OpenCV way to (gaussian) smooth just 1 channel in a 3 channel (RGB) image?

Any of Python or C or C++ OpenCV is fine.

Answer:
You can useSplitto split the image into its channels and then useFilter2Don one of the components.

```
Split(src, src_r, src_g, src_b)
Smooth(src_r, dst_r)
Merge(dst_r, src_g, src_b, dst)
```


Question:
I've created a Plain C project in Qt Creator in Linux, but I'm getting this error:

```
error: 'for' loop initial declarations are only allowed in C99 mode
note: use option -std=c99 or -std=gnu99 to compile your code
```

What should I put in my *.pro file to enable C99?

Answer:
```
QMAKE_CFLAGS += -std=c99
```

This worked for me, even though it is not documented and the intellisense doesn't recognize it.


Question:
I've created a Plain C project in Qt Creator in Linux, but I'm getting this error:

```
error: 'for' loop initial declarations are only allowed in C99 mode
note: use option -std=c99 or -std=gnu99 to compile your code
```

What should I put in my *.pro file to enable C99?

Answer:
```
QMAKE_CFLAGS += -std=c99
```

This worked for me, even though it is not documented and the intellisense doesn't recognize it.


Question: I have the coordinates of 4 points, and I want to to draw a quad based on those coordinates in opencv! is there in function that can based on those point draw a region! I know thatrectcan do that but I know I'll not always have a rectangle!

Answer: I would suggest to use polygon drawing withpolylinesorfillPolyseedrawing functionsfor more information.


Question: How One can access a variable from ONLY two functions that a file consists of total five functions.(No global or static declaration)

Answer: You can't in C; the file is the compilation unit that defines the boundaries forstaticvariables of that sort, since anyone who can edit or view that file could work with all of the functions in it. If you really need to separate visibility, you have to split the functions into multiple files.


Question: When I press Ctrl+c then SIGINT will be passed to signal() . What value will be pass to the system call signal() when i press a key A ?

Answer:
No signal will be raised.

The purpose of signals is to inform about a special condition outside normal program flow. Processing input, like the letter A, is part of normal program flow. These two are completely separate, and have different goals.

If you're on UNIX, typeman signalon your console.


Question: I have developed C/C++ binaries and I have android app. I have ported binaries on linux base server and now I would like to use this binaries in my android app. Can i call this binaries from my app? Is it possible, please excuse me as I don't have any idea about this.

Answer:
Here you will find a nice tutorial to implement C code into your Android Project:

JNI tutorial


Question:
I have the following code to open a buffer in the memory and write some data to it:

```
int main() {
    char buf[1000] = {0};
    FILE * os = fmemopen(buf, 1000, "w");
    fprintf(os, "%d", 100);
    fclose(os);

    printf("%d\n", buf);

    return 0;
}
```

The output is some random numbers such as :895734416or a negative number... why is this happening?

Answer: printf("%d\n", buf);output the address ofbufinstead of the return value.


Question:
this is a part of my little 'C' program...

```
printf("Time to sleep for the end of process: %d sec\n", getpid() % 10);
```

I would like to come down the seconds, without the line on the terminal changes. Like an animation.

How can i do this in 'C'?

Thanks everyone!

Answer: Replace your\nwith a\r, and as long as your numbers are all the same length (number of digits), I believe that should work.


Question:
I tried finding it but could not find the solution to this.

I just want to know what does this mean in terms of return value. Does it mean that return value can be any of the 5 values present. Or the return value is all of these 5 numbers

```
static int is_navmsg(int msg)
{
          return msg==1019||msg==1020||msg==1044||msg==1045||msg==1046;
}
```

Answer: It will return1if the value ofmsgis1019or1020or1044and so on. Otherwise0.


Question: I wrote a script for downloading a hdf5 file using libcurl, but I cannot find way to open it in c, I don't want to store it in disk and H5Fopen it. Is there a way to do the H5Fopen work on the downloaded memory buffer? Thanks:)

Answer:
It is called File Image and you need recent HDF5 to do that:

http://www.hdfgroup.org/HDF5/doc/Advanced/FileImageOperations/HDF5FileImageOperations.pdf


Question: I wrote a script for downloading a hdf5 file using libcurl, but I cannot find way to open it in c, I don't want to store it in disk and H5Fopen it. Is there a way to do the H5Fopen work on the downloaded memory buffer? Thanks:)

Answer:
It is called File Image and you need recent HDF5 to do that:

http://www.hdfgroup.org/HDF5/doc/Advanced/FileImageOperations/HDF5FileImageOperations.pdf


Question:
I am trying to execute the following clearcase command through a c program.

```
system("ct pwv");
```

But I'm getting this error. :permission denied.

would you please suggest some solution to this problem. Thanks.

Answer:
Try withcleartool:

```
system("cleartool pwv");
```


Question:
I am trying to do this inc:

```
scanf("%d",a+i);
```

whereais an array of size10. Andiis counter for loop. So is this possible?

Answer:
Absolutely: ifais anint*or an arrayint a[10], andiis between 0 and 9, this expression is valid.

Thea+iexpression is the pointer arithmetic equivalent of&a[i], which is also a valid expression to pass toscanf.


Question: Does OMP ensure that the contents of an dynamic array is up-to-date and is visible to all threads after an OMP barrier?

Answer: Yes. A barrier causes all threads' view of all accessible memory to be made consistent; that is, it implicitly flushes the entire state of the program.


Question: How can i compile the contents of the clipboard, i tried piping the contentspbpaste | gccbut it did not work it gave the errori686-apple-darwin11-llvm-gcc-4.2: no input filesI  have heard that i can use temporary file with the commandmktempbut I could not get it to work.

Answer:
Using-xc -will allow you to processstdin:

```
gcc -xc -
```

You can see a live examplehere.


Question:
I'm currently writing a little program but I keep getting this error when compiling

error: empty character constant

I realize it's because I'm trying to replace a valid char with empty spacec[i]=''but I have not been able to find another way to represent it.

Answer:
You can usec[i]= '\0'or simplyc[i] = (char) 0.

The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.


Question:
Can I use Goto to jump into other functions? for example

```
void x(){
 printf("hello");
}

void y(){
 printf("hi");
}

int main(){     /*assume that all var are declared */

 scanf("%d",&input);
  if(input == 1) goto y();
  else(input == 2) goto x();
}
```

Answer: You cannot usegototo branch into a different function; agotomay only branch within the current function.  You would simplycallthe functionsx()andy().


Question: I would like to check if I have openssl installed using C/C++ code. Is it even possible? I mean, is there a macro, or something which will be a portable way of doing this? Thanks

Answer:
The following will work on Windows and Linux:

```
#ifdef WIN32
libHandle = LoadLibrary( libraryName );
#else
libHandle = dlopen( libraryName, RTLD_LOCAL | RTLD_NOW );
#endif
```


Question: In Java, it is required by the compiler to name your files<Classname>.java. In C, does it matter what the file name is?

Answer: No, the source files can in principle be called anything. However, the name should reflect the contents of the file for readability. Header files also don'thaveto be called the same as the corresponding source files; they justshould.


Question: I would like to check if I have openssl installed using C/C++ code. Is it even possible? I mean, is there a macro, or something which will be a portable way of doing this? Thanks

Answer:
The following will work on Windows and Linux:

```
#ifdef WIN32
libHandle = LoadLibrary( libraryName );
#else
libHandle = dlopen( libraryName, RTLD_LOCAL | RTLD_NOW );
#endif
```


Question: In Java, it is required by the compiler to name your files<Classname>.java. In C, does it matter what the file name is?

Answer: No, the source files can in principle be called anything. However, the name should reflect the contents of the file for readability. Header files also don'thaveto be called the same as the corresponding source files; they justshould.


Question:
This question already has answers here:C++ difference between 0 and 0.0(4 answers)C++: difference between 0. and 0.0?(5 answers)Closed10 years ago.

I just saw this for the first time. The source code I'm looking at is in C

```
if( rate < 0.){
   ...
 }
 else{
   ...
 }
```

What happens ifrate=0?

Answer: 0.is a literal of typedouble(and value zero). By contrast,0is a literal of typeint.


Question:
This question already has answers here:C++ difference between 0 and 0.0(4 answers)C++: difference between 0. and 0.0?(5 answers)Closed10 years ago.

I just saw this for the first time. The source code I'm looking at is in C

```
if( rate < 0.){
   ...
 }
 else{
   ...
 }
```

What happens ifrate=0?

Answer: 0.is a literal of typedouble(and value zero). By contrast,0is a literal of typeint.


Question:
This question already has answers here:How to achieve function overloading in C?(16 answers)Closed9 years ago.

I need to develop a function in C that will be called with the same definition with or without parameters like this:

```
char *fnc(???)
{
    char *str;
    ....
    return str;
}
char *c1 = fnc();
char *c2 = fnc(param);
```

How to do it?

Answer: This is calledFunction OverloadingYou can't do it in C


Question:
I have a webpage, say atwww.mypage.com, which uses$_GETto fetch data and then saves the fetched data into theMySQLdatabase.

I need to send thisHTTP Requestfrom a Cpp File.

How can I send aHTTP Requestfrom Cpp file?

Answer: Yes, libcurl should be helpful. You can send some data by GET parameters or by POST and read responses. (Maybe necessary to verify a successful transmission) Here are some examples:http://curl.haxx.se/libcurl/c/example.html


Question:
I have a webpage, say atwww.mypage.com, which uses$_GETto fetch data and then saves the fetched data into theMySQLdatabase.

I need to send thisHTTP Requestfrom a Cpp File.

How can I send aHTTP Requestfrom Cpp file?

Answer: Yes, libcurl should be helpful. You can send some data by GET parameters or by POST and read responses. (Maybe necessary to verify a successful transmission) Here are some examples:http://curl.haxx.se/libcurl/c/example.html


Question:
A short example excerpted from wdm.h

```
typedef struct _KMUTANT {
    DISPATCHER_HEADER Header;
    LIST_ENTRY MutantListEntry;
    struct _KTHREAD *OwnerThread;
    BOOLEAN Abandoned;
    UCHAR ApcDisable;
} KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX;
```

I know 'P' means 'Pointer', but I don't know what 'R' means.

Any interpretation?

Answer: TheRidentifies the pointer as arestricted pointer.


Question:
A short example excerpted from wdm.h

```
typedef struct _KMUTANT {
    DISPATCHER_HEADER Header;
    LIST_ENTRY MutantListEntry;
    struct _KTHREAD *OwnerThread;
    BOOLEAN Abandoned;
    UCHAR ApcDisable;
} KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX;
```

I know 'P' means 'Pointer', but I don't know what 'R' means.

Any interpretation?

Answer: TheRidentifies the pointer as arestricted pointer.


Question:
A short example excerpted from wdm.h

```
typedef struct _KMUTANT {
    DISPATCHER_HEADER Header;
    LIST_ENTRY MutantListEntry;
    struct _KTHREAD *OwnerThread;
    BOOLEAN Abandoned;
    UCHAR ApcDisable;
} KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX;
```

I know 'P' means 'Pointer', but I don't know what 'R' means.

Any interpretation?

Answer: TheRidentifies the pointer as arestricted pointer.


Question: I have a daemon process namedmydaemon. Now I want to have an other process to send something for me , and when I fork a child process , it has the same name with the parent process. How can I have a different process name withoutexecfunction?

Answer:
Under Linux you can use theprctl()function to set the process name:

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

prctl(PR_SET_NAME, "foobar");
```


Question:
I am a beginner C coder and I want to know how the make it so the program will do this.

```
printf("which direction would you like to go?\n");
/*they type an arrow key*/
printf ("you went left/right/up/down\n");
```

I have a Mac

Answer:
Try these suggestions. You can get the ASCII codes by
     getch()


Question:
I'm trying to understand what's wrong with:

```
typedef *void (*pfun)(**int, *float);
```

as far as I understand the problem is that I can't pass the function the pointers as

```
typedef *void (*pfun)(int, float);
```

doesn't generate an error but I have no idea why that is the case.

Answer: Did you meanvoid*,int**andfloat*?


Question:
I need to print aULONGLONGvalue (unsigned __int64). What format should i use inprintf?
I found%lluin another question but they say it is for linux only.

Thanks for your help.

Answer: Using Google to search for “Visual Studio printf unsigned __int64” producesthis pageas the first result, which says you can use the prefixI64, so the format specifier would be%I64u.


Question:
After you have opened a file using:

```
const char *fMode = "r";
FILE *filePointer = fopen(location,fMode);
```

What's the fastest cross platform (Windows and Linux) way to get its size so you can allocate the right amount of memory usingmalloc?

I've seen thatftellonly works if you open the file in binary mode.

Answer: You can find the size usingstatorfstatbefore you open the file.


Question:
Is it possible to stop an io buffer from flushing itself in C/C++?

To get maximum performance, I'm trying to save data and then flush after an operation is complete.

I can just write to an array and then print that out later, I was just wondering if this is possible.

Answer: You can increase the size of the buffer by using a call tosetvbuf.


Question:
When I simply pass the int I get the warning:

WARNING: Incompatible integer to pointer conversion passing int to parameter of
  type int *

In another words what isint *

Answer:
This requires theaddressof an integer variable, not the integer variable itself. You can get the address of a variable with the&operator. So the following code would work:

```
int i = 10;
wait( &i );
```


Question:
When I simply pass the int I get the warning:

WARNING: Incompatible integer to pointer conversion passing int to parameter of
  type int *

In another words what isint *

Answer:
This requires theaddressof an integer variable, not the integer variable itself. You can get the address of a variable with the&operator. So the following code would work:

```
int i = 10;
wait( &i );
```


Question:
This question already has answers here:Declaring a C function to return an array(5 answers)Closed10 years ago.

How can one have a function returning a pointer to an array and what are the general things that one needs to keep in mind while doing that?

Answer:
```
int (*foo(void))[4];
```

declaresfooas a function with no parameters that returns a pointer to an array 4 ofint.

For example:

```
int (*p)[4];
p = foo();
```


Question:
Why doesn't the following line of code produce an error?

```
double x = 4.2, y;
```

Also, x seems to be assigned to 4.2, and not the value of y (which seems to be 1e-39, or very close to 0).

Answer:
It does the same as:

```
double x = 4.2;
double y;
```

The "y" variable contains some junk value (since its value is unspecified) until you give it a value.  It acts this way because the comma operator has lower precedence than assignment in C/C++.


Question: I have written an openssl program, and now I want to know, if the openssl library calls its own cleanup functions, or if I have to call myself the cleanup functions like SSL_CTX_free and SSL_free?

Answer: You have to explicitly call the cleanup functions. I recommend using Valgrind in order to track memory leaks in your program.


Question: I have written an openssl program, and now I want to know, if the openssl library calls its own cleanup functions, or if I have to call myself the cleanup functions like SSL_CTX_free and SSL_free?

Answer: You have to explicitly call the cleanup functions. I recommend using Valgrind in order to track memory leaks in your program.


Question: My machine is a Windows 8 machine. I want to read the "UpperFilters" key fromHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{36fc9e60-c465-11cf-8056-444553540000}from my custom driver to get the presence of filter drivers over USB devices.

Answer: I haven't written a driver since the days of XP, but assuming you're talking about a kernel mode driver I belive you wantZwOpenKey,ZwQueryValueKeyandZwClose. General guidancehere.


Question:
I need to create a C compatible (friendly) return type so that my C++ functions can be used to work with C-based functions.

How I can convert a vector ofwstringto awchar_t**array?

Answer: You can iterate through the wstring vector and add eachwstring::c_str()to yourwchart_t**array.


Question:
I need to create a C compatible (friendly) return type so that my C++ functions can be used to work with C-based functions.

How I can convert a vector ofwstringto awchar_t**array?

Answer: You can iterate through the wstring vector and add eachwstring::c_str()to yourwchart_t**array.


Question: What is the height of a complete binary tree with N nodes? I'm looking for an exact answer, and either a floor or ceiling value.

Answer:
It'sCEIL(log2(n+1))-1

1 node gives log2(2) = 13 nodes gives log2(4) = 27 nodes gives log2(8) = 315 nodes gives log2(16) = 4...

EDIT: According to wikipedia, the root node (rather un-intuitively?) does not count in the height, so the formula would beCEIL(log2(n+1))-1.


Question: In a gcc makefile, you can use the -D flag to specify a define in the compiled program. For example, instead of putting #define SOMETHING, you can specify -DSOMETHING in the makefile. What is the equivalent of this in SCons?

Answer: I believe you want theCPPDEFINESconstruction variable. Seethe SCons documentation pagefor some more details, underCPPDEFINES.


Question:
I am running the below code but getting no output on console screen. Please Explain:

```
#include <stdio.h>

void main()
{
    enum days {sun,mon,tue,wed,thru,fri,sat};
}
```

Answer:
```
#include <stdio.h>
int main()
{
    printf("sun, mon, tue, wed, thru, fri, sat\n");
    return 0;
}
```

Is that what you were trying to do?


Question:
I am running the below code but getting no output on console screen. Please Explain:

```
#include <stdio.h>

void main()
{
    enum days {sun,mon,tue,wed,thru,fri,sat};
}
```

Answer:
```
#include <stdio.h>
int main()
{
    printf("sun, mon, tue, wed, thru, fri, sat\n");
    return 0;
}
```

Is that what you were trying to do?


Question:
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed7 years ago.

Why doesn't this program print the%sign?

```
#include <stdio.h>

main()
{
     printf("%");
     getch();
}
```

Answer:
Your problem is that you have to change:

```
printf("%");
```

to

```
printf("%%");
```

Or you could use ASCII  code and write:

```
printf("%c", 37);
```

:)


Question:
```
#include<stdio.h>
void main()
{
   float a = 5, b = 2;
   int c;
   c = a % b;
   printf("%d", c);
}
```

I am getting floating point error n this program-me..someone please explain this..

Answer: You can only use%operator with integer operands. Usefmodfunction (declared inmath.h) for floating point operands.


Question:
Is there a way to typedef a 2 dimensional array in C? Something like:

```
typedef char[10][10] board;
```

This example doesn't compile. Is there any way to do it? Or any other solution?

Answer:
Try this:

```
typedef char board[10][10];
```

Then you can define new array as this:

```
board double_array = {"hello", "world"};
```

It's the same with:

```
char double_array[10][10] = {"hello", "world"};
```


Question: Why do GTK+ and several other frameworks provideTRUEandFALSEmacros? Is there any advantage to usingTRUEandFALSEinstead of the built-in C valuestrueandfalse? You can see their implementation here:http://www.gtk.org/api/2.6/glib/glib-Standard-Macros.html#TRUE:CAPS

Answer: C99 hastrueandfalse, earlier versions do not.  That is why you often seeTRUEandFALSE#defined.  As you can readhere,trueandfalseare1and0respectively, same asTRUEandFALSE.


Question:
I compiled a C program (which has some assembly language instructions) like this.

```
TCC -Emasm.exe protect.c
```

It gives an errorUnable to execute masm.exe.
What should I do or where can I findmasm.exe?

Answer: You need to get microsoft assembly compiler, which is called masm.


Question:
I have variable that must be 16 bit long. How should I define it to be exactly 16 bit independently on the platform?

I can define it asshort, but depending on the platform it can be 16 bits or more.

Answer: Assuming you're using C99, then useuint16_t(orint16_t) from<stdint.h>.  These are guaranteed to exist so long as the compiler has an underlying 16-bit type available.


Question:
I've two functions:

```
void foo0(int bar);
void foo1(int bar);
```

I wan't to be able create a macroQUXthat will expand to these function names based on another macroBAZ. I tried the following:

```
#define BAZ 0
#define QUX(x) foo##BAZ(x)
```

But it did not work since the generated function wasfooBAZ(). How can I get it to generatefoo0()?

Answer:
```
#define CAT_I(a,b) a##b
#define CAT(a,b) CAT_I(a, b)
#define QUX(x) CAT(foo, BAZ) ## (x)
```


Question:
While I examine the source code of ffmpeg, I see this line:

```
enum AVDurationEstimationMethod av_fmt_ctx_get_duration_estimation_method
(const AVFormatContext* ctx);
```

What is the functionality ofenumhere?

Answer: av_fmt_ctx_get_duration_estimation_methodis a function which returns an object of enum typeAVDurationEstimationMethod.


Question: I have read about usingsampler2DRectandtexture2DRectto use rectangular textures. My question is whether its use is recommended for creating sprites 2D using GLSL, or if there is another alternative to using images that are not necessarily a power of two.

Answer: If all you need arenon-power-of-two textures, that's something OpenGL has supported foralltexture types since GL 2.0. So you don't need rectangle textures if NPOTs are all you want.


Question:
This question already has answers here:Is a += b more efficient than a = a + b in C?(7 answers)Closed10 years ago.

what is the difference betweeni = i + j; andi += j; in C?
Are they equivalent? Is there any side effect ofi?

I was trying to check the assignment mechanism in C using the GCC compiler.

Answer: They're almost the same.  The only difference is thatiis only evaluated once in the+=case versus twice in the other case.


Question: I have read about usingsampler2DRectandtexture2DRectto use rectangular textures. My question is whether its use is recommended for creating sprites 2D using GLSL, or if there is another alternative to using images that are not necessarily a power of two.

Answer: If all you need arenon-power-of-two textures, that's something OpenGL has supported foralltexture types since GL 2.0. So you don't need rectangle textures if NPOTs are all you want.


Question:
This question already has answers here:Is a += b more efficient than a = a + b in C?(7 answers)Closed10 years ago.

what is the difference betweeni = i + j; andi += j; in C?
Are they equivalent? Is there any side effect ofi?

I was trying to check the assignment mechanism in C using the GCC compiler.

Answer: They're almost the same.  The only difference is thatiis only evaluated once in the+=case versus twice in the other case.


Question:
Can someone explain how we calculate the value of Hexadecimal Floating point constant.
I was reading a book and found 0x0.3p10 represents the value 192.

Answer:
The exponent is still expressed in decimal, but the base is two, and the mantissa is in hex.

So 0.3P10 is (3 × 16−1) × 210, which is 3/16 × 210, which is 3 × 26= 192.

Each hex digit of the mantissa gobbles up four units of exponent, since 16 = 24.


Question: I have a long list of variable for private and share. How do I write in multiple lines? I am repeating the question here, just because stackoverflow wouldn't let me submit the question otherwise.

Answer:
Pragmas are interpreted by the compiler after preprocessing, so you can just use the normal line-continuation mechanism:

```
#pragma omp parallel
```

can become:

```
#pragma \
omp \
parallel
```


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

void main(){

    exit(0);

}
```

This is my code in c how could I make the console exit??I have tried to use the exit function but it seems like it doesn't work

Answer:
exitcausesyour programto exit, not the shell that you ran it from.  Your program is equivalent to:

```
int main(void)
{
  return 0;
}
```

You might want to look intokill(2).

Editorial note:mainshould returnint, notvoid.


Question:
I have a function that returns me a string asconst char *:

```
const char* get_text();
```

I need to call a functionAfxMessageBox(LPCTSTR text).

How can I convert the string that I got byget_text()?

Answer:
As you're using MFC and assuming a UNICODE build (or you wouldn't have this error!), probably the simplest way is to instantiate awchar_tcompatibleCStringdirectly:

```
CStringW szWide(getText());
AfxMessageBox(szWide);
```


Question: I have a long list of variable for private and share. How do I write in multiple lines? I am repeating the question here, just because stackoverflow wouldn't let me submit the question otherwise.

Answer:
Pragmas are interpreted by the compiler after preprocessing, so you can just use the normal line-continuation mechanism:

```
#pragma omp parallel
```

can become:

```
#pragma \
omp \
parallel
```


Question:
I want to type "man time" and info about thetime.htime function, but instead I am getting the linux time system command.

man time 2orman time 3doesn't do any different. How can I find the right man page?

Answer: How aboutman man? Then you would find out thatman 3 timeworks.


Question:
can anyone tell me how to install opencv2.4.6 using cmake, I found several tutorials but I can't find the common folder inc:\opencv\build_common_ **   to past the **tbb41_20130613ossfolder any idea can I do that.

thanks in advance

Answer:
You need to build the library, and then execute targetinstall.

When usingmakeit will be

```
make
make install
```

On visual studio You need to select the targets manually (I think).


Question: All is in the title. How to check a possible overflow when using the two functions exp() and log()?

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

When an oferflow occurs, thenerrnois set toERANGE.

Next time, do your homework before asking.

Googling: "c++ exp" returned this as the first resulthttp://www.cplusplus.com/reference/cmath/exp/In the middle of the page, there is EXACTLY what you're looking for.


Question: All is in the title. How to check a possible overflow when using the two functions exp() and log()?

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

When an oferflow occurs, thenerrnois set toERANGE.

Next time, do your homework before asking.

Googling: "c++ exp" returned this as the first resulthttp://www.cplusplus.com/reference/cmath/exp/In the middle of the page, there is EXACTLY what you're looking for.


Question:
I've got an array of sixuint16_twhich is actually threeuint32_t, with the bits in the right order and all. How can I cast the former to the latter as effectively as possible?

The number of elements in the array is known at compile-time.

Answer:
Like this perhaps:

```
uint16_t arr16[6];
uint32_t *parr32 = (uint32_t*)(&arr16);
```

And now you can useparr32[i]to refer to elements of the overlayedarr16array.


Question:
This question already has answers here:What is the difference between NULL, '\0' and 0?(11 answers)Closed10 years ago.

As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL?
Further what should be the correct usage. Thanks!

Answer: The correct usage is to useNULL: It's more readable (p == NULL-> you know thatpis a pointer)


Question: In a boot loader code i found that, they are using volatile keyword when accessing physical address. Is it necessary to use volatile keyword even we are accessing physical memory address?

Answer: You need to use "volatile" whenever the data can change, without the compiler being able to know about it.


Question:
I am having some problem with Coderunner. It was running with out any problem but now it is not.As you see in image below.

Please, can you help me to resolve this problem. Thanks!http://yadi.sk/d/tDkp1K8v6aeby

Answer:
Did you uninstall Xcode, or upgrade your OS recently ? Because Coderunner need Command Line Tool to work properly.

How to install Command Line Tool for Lion and above.


Question:
This question already has answers here:What is the difference between NULL, '\0' and 0?(11 answers)Closed10 years ago.

As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL?
Further what should be the correct usage. Thanks!

Answer: The correct usage is to useNULL: It's more readable (p == NULL-> you know thatpis a pointer)


Question: In a boot loader code i found that, they are using volatile keyword when accessing physical address. Is it necessary to use volatile keyword even we are accessing physical memory address?

Answer: You need to use "volatile" whenever the data can change, without the compiler being able to know about it.


Question:
I am having some problem with Coderunner. It was running with out any problem but now it is not.As you see in image below.

Please, can you help me to resolve this problem. Thanks!http://yadi.sk/d/tDkp1K8v6aeby

Answer:
Did you uninstall Xcode, or upgrade your OS recently ? Because Coderunner need Command Line Tool to work properly.

How to install Command Line Tool for Lion and above.


Question: Suppose I have dynamically allocated variables in the program run by the debugger, is it safe to press the stop button of the IDE or stop the debugger? I mean safe...will the variables get deleted/deallocated?

Answer:
Yes. It is safe.

When a program exits, all the allocated resources returned to the operating system.


Question: So I'm writing a Unix shell in C, and have been encountering a race condition.  I've determined that I can resolve it if, after one of my Fork() calls, I can ensure the parent runs before the child.  Is there any way that I can do that using signaling or any other type of inter-process communication?

Answer: You could set up a signal handler and let the child wait for it, e.g. SIGUSR1.


Question:
Using plain C, (not C++ / C# / Objective-C) how do I get the screen resolution in Windows?

My compiler is MingW (not sure if relevant). All solutions I have found online are for C++ or some other C variant.

Answer:
UseGetSystemMetrics()

```
DWORD dwWidth = GetSystemMetrics(SM_CXSCREEN);
DWORD dwHeight = GetSystemMetrics(SM_CYSCREEN);
```


Question: Suppose I have dynamically allocated variables in the program run by the debugger, is it safe to press the stop button of the IDE or stop the debugger? I mean safe...will the variables get deleted/deallocated?

Answer:
Yes. It is safe.

When a program exits, all the allocated resources returned to the operating system.


Question:
I was trying this code:

```
int main()
{
    char *ch="hello";
    printf("%u",&ch);
    return 0;
}
```

From the aboveprintf()statement I have address of ch i.e65524My question is Can i find value if any address is given like*(65524)rather than*(&ch)?

Answer:
Yes, you can:

```
printf("%d\n", *(unsigned char *) 65524);
```

If the address does not point to a valid object, you are invoking undefined behavior.


Question:
I'm having to do the following a lot in a USB (libusb) C based command line utility I am writing:

```
char pid[20];
sprintf(pid, "Product ID : %#06x", anInteger);
puts(pid);
```

Is there a shorter, one-liner way to do this?

Answer:
Instead of usingsprintf&puts, just change toprintf:

```
printf("Product ID : %#06x", descriptor.idVendor);
```


Question: why do i get a kernel crash ofcpuacct_chargewhen i try to allocate 600 blocks of 2 MB memory using -pci_alloc_consistent, is there a better way to do it ?

Answer:
You are probably running out of 32-bit-addressable memory.

If your PCIe chip actually supports larger addresses, your driver should usedma_set_maskanddma_set_consistent_maskto tell the kernel about this.
(SeeDocumentation/DMA-API-HOWTO.txt.)


Question: I have this byte:10111011and i want to split into 2 nibble (msb and lsb).After that i want to take the last 2 bits from the lsb (so i want11from1011).I know that:With10011011 >> 4i get the msb (1001)With10011011 & 0xfi get the lsb (1011)Now what can i do to take the11from lsb1011?

Answer: Just the same:bits = lsb & 0x03


Question:
I'm having to do the following a lot in a USB (libusb) C based command line utility I am writing:

```
char pid[20];
sprintf(pid, "Product ID : %#06x", anInteger);
puts(pid);
```

Is there a shorter, one-liner way to do this?

Answer:
Instead of usingsprintf&puts, just change toprintf:

```
printf("Product ID : %#06x", descriptor.idVendor);
```


Question: why do i get a kernel crash ofcpuacct_chargewhen i try to allocate 600 blocks of 2 MB memory using -pci_alloc_consistent, is there a better way to do it ?

Answer:
You are probably running out of 32-bit-addressable memory.

If your PCIe chip actually supports larger addresses, your driver should usedma_set_maskanddma_set_consistent_maskto tell the kernel about this.
(SeeDocumentation/DMA-API-HOWTO.txt.)


Question: I have this byte:10111011and i want to split into 2 nibble (msb and lsb).After that i want to take the last 2 bits from the lsb (so i want11from1011).I know that:With10011011 >> 4i get the msb (1001)With10011011 & 0xfi get the lsb (1011)Now what can i do to take the11from lsb1011?

Answer: Just the same:bits = lsb & 0x03


Question: Is there any specific function or any way by which the number of lines in aGDBMfile can be counted?Otherwise, I want to retrieve all the lines in aGDBMfile at once(Iam able to retrieve the key value pairs usinggdbm_fetch()but only one at a time.

Answer:
I got the solution to the above problem.

Now I am able to retrieve all the key value pairs.

Solution :here


Question: Is there any specific function or any way by which the number of lines in aGDBMfile can be counted?Otherwise, I want to retrieve all the lines in aGDBMfile at once(Iam able to retrieve the key value pairs usinggdbm_fetch()but only one at a time.

Answer:
I got the solution to the above problem.

Now I am able to retrieve all the key value pairs.

Solution :here


Question:
Is

```
*(ary[3]+8)
```

and

```
ary[3][8]
```

are the same ? If yes, please explain how ? ary[3] returns the address of first element or the value in ary[3][0] ? ary is a two dimensional array.

Thanks in advance.

Answer:
Yes

a[i]is same as*(a+i)

ary[i][j]is same as*( *(ary+i)+j))


Question: I am trying to show user a text file after an operation completed in a c program using winapi but I want the file to be opened using notepad (or the default text processor application). how do I do this (opening a text file using window's default application) using winapi?

Answer:
ShellExecute()is what you are looking for, eg:

```
#include <shellapi.h>

ShellExecute(NULL, NULL, "C:\\path\\to\\myfile.txt", NULL, NULL, SW_SHOWNORMAL);
```


Question: Where are the options forcurl_easy_setoptdefined? I'm trying to look for the integer values of CURLOPT_VERBOSE and some others, but these don't seem to be explicitly defined incurl.h

Answer:
Line 792:

```
#ifdef CURL_ISOCPP
#define CINIT(na,t,nu) CURLOPT_ ## na = CURLOPTTYPE_ ## t + nu
```

line 953:

```
CINIT(VERBOSE, LONG, 41),      /* talk a lot */
```

There it is.


Question:
Is

```
*(ary[3]+8)
```

and

```
ary[3][8]
```

are the same ? If yes, please explain how ? ary[3] returns the address of first element or the value in ary[3][0] ? ary is a two dimensional array.

Thanks in advance.

Answer:
Yes

a[i]is same as*(a+i)

ary[i][j]is same as*( *(ary+i)+j))


Question: I am trying to show user a text file after an operation completed in a c program using winapi but I want the file to be opened using notepad (or the default text processor application). how do I do this (opening a text file using window's default application) using winapi?

Answer:
ShellExecute()is what you are looking for, eg:

```
#include <shellapi.h>

ShellExecute(NULL, NULL, "C:\\path\\to\\myfile.txt", NULL, NULL, SW_SHOWNORMAL);
```


Question: Was there any site that compares the current C11 standard conformance/support between implementation/compilers? (gcc, clang, intel, open64, pelles)

Answer:
To my knowledge there is no general site (this is a good time to start one :).  However, most projects maintain their own list:

http://clang.llvm.org/cxx_status.html(clang)http://clang.llvm.org/compatibility.html#c

http://gcc.gnu.org/wiki/C11Status(gcc)


Question: Was there any site that compares the current C11 standard conformance/support between implementation/compilers? (gcc, clang, intel, open64, pelles)

Answer:
To my knowledge there is no general site (this is a good time to start one :).  However, most projects maintain their own list:

http://clang.llvm.org/cxx_status.html(clang)http://clang.llvm.org/compatibility.html#c

http://gcc.gnu.org/wiki/C11Status(gcc)


Question:
Is it possible to form a two way link between structs? I tried to achieve it like this:

```
typedef struct
{
    int foo;
    b *b;
} a;

typedef struct
{
    int bar;
    a *a;
} b;
```

But the struct a does not know what b is because it's declared afterwards.

Answer:
Try this,

```
typedef struct a a;
typedef struct b b;

struct a
{
    int foo;
    b *b;
} ;

struct b
{
    int bar;
    a *a;
} ;
```


Question:
Would some please tell me why this code leads to such an error?

```
unsigned char buffer;
fread(&buffer,1,1,image_ptr);
printf("%s ",buffer);
```

The image is 8-bit grayscale. Thank you.

Answer: %sis the format specifier to print a string, butbufferis not a string.  That causes undefined behaviour.  You want%cor maybe%uor%xdepending on what you want as output.


Question:
I can use display list + glsl? something like using vbo + glsl.

if this can be, you can write an example.

Answer:
Well in terms of OpenGL-2, yes you can use GLSL shaders on geometry drawn through a display list that was compiled from immediate mode calls. The question is: Why would you want to do this?

OpenGL-3 removed display lists (good riddance). So don't expect it to work for any GLSL version beyond 1.2x.x


Question:
I have two functions:

```
void a(int * p);
int b();
```

Is it possible to pass the address of the return value of functionbto functionasomething like this:a(&b())?

Answer:
A compound literal seems to do the trick (requires a C99 compiler):

```
int a()
{
    return 5;
}

void b(int *a)
{
    // do something with a
    printf("%d\n", *a);
}

int main(void)
{
    b(&(int){ a() });
}
```

Output is5.


Question:
```
( s1[i] = s2[i] ) != '\0'
```

Does the inequality checks2[i]with'\0'ors1[i]?

Answer:
s2[ i ]will be assigned tos1[ i ]and then value ofs1[ i ]will be compared against ZERO.

Pleaserefer herefor more info.


Question:
I have two functions:

```
void a(int * p);
int b();
```

Is it possible to pass the address of the return value of functionbto functionasomething like this:a(&b())?

Answer:
A compound literal seems to do the trick (requires a C99 compiler):

```
int a()
{
    return 5;
}

void b(int *a)
{
    // do something with a
    printf("%d\n", *a);
}

int main(void)
{
    b(&(int){ a() });
}
```

Output is5.


Question:
```
( s1[i] = s2[i] ) != '\0'
```

Does the inequality checks2[i]with'\0'ors1[i]?

Answer:
s2[ i ]will be assigned tos1[ i ]and then value ofs1[ i ]will be compared against ZERO.

Pleaserefer herefor more info.


Question:
I have a Python code calling some C code (.so file).

Is there a way, from within the C code, go get the line number it has been called from at the Python side?

Answer: I eventually found thePyFrame_GetLineNumber(PyFrameObject *f)C function, whose source is located inframeobject.c.


Question:
I'm creating a camera driver for Android. I've got my mydriver.c file.
Apparently I need to compile it into a .ko, is that right ?

And then to load it I should do a#insmod ./mymodule.ko, will it work ?

Do I need to be root ? And how I put the .ko file on my Android tablet ?

Answer: Yes, you need to be root. And, insmod ./yourmodule.ko should work fine.


Question:
I would like to ask if there is any fast way(using memset for example) to clear a char table like

```
char mytable[2][10];
```

For example as I know using memset

```
memset(mytable, 0, sizeof(mytable));
```

is used for 1D tables.

Answer:
They're calledarrays,not "tables".

And thevery same code worksfor any array with arbitrary number of dimensions.


Question: Does the standard Cctimefunction return the Gregorian calendar date? In particular, I want to verify that it will account for leap years and thus displayFeb 29for the respective dates.

Answer: For times in the future and in the recent past, yes. For times before the Gregorian calendar reform... I don’t know, but those times are only relevant on systems with 64 bittime_t.


Question:
can somebody explain these answers? I can understand 2. , 4. but the rest i can not

```
int a[ ] ={2,4,3,1,10,5,9,6,8,7};
int *pa = &a[4],*pb = &a[1];

What is the value of the below?
1.*(a + 3)
2.*pb-*pa
3.pb[3]
4.*pa + 5
5.*(pa-2)
6.pa[4]

Answer:

1.*(a + 3)=1
2.*pb-*pa=-6
3.pb[3]=10
4.*pa + 5=15
5.*(pa-2)=3
6.pa[4]=8
```

Answer: x[y]is equivalent toy[x], which is equivalent to*(x+y)or*(y+x). So*(a+3)is equivalent toa[3]or3[a].


Question:
Trying to compile in win7 x64 cmd prompt. The following command:

```
nvcc -o kernal.cu
```

yields the following error message.

```
nvcc : fatal error : No input files specified; use option --help for more information
```

Answer:
try

nvcc -o xxx kernal.cu

where xxx is the output file name you want.


Question:
When linking a static library as athin archivethe .o-files are not copied into the archive, but rather they are referenced with their relative path from the .a file.

How can I check if a given .a file is a thin archive or not?

Answer:
How can I check if a given .a file is a thin archive or not?

```
head -1 t.a
!<thin>
```

Eventually,file(1)should be able to tell you. Myfile-5.09just saysdata.


Question:
When linking a static library as athin archivethe .o-files are not copied into the archive, but rather they are referenced with their relative path from the .a file.

How can I check if a given .a file is a thin archive or not?

Answer:
How can I check if a given .a file is a thin archive or not?

```
head -1 t.a
!<thin>
```

Eventually,file(1)should be able to tell you. Myfile-5.09just saysdata.


Question:
I've encountered the following line in a .cuh file:

```
#define mp_ptr(n)     P##n
```

What does theP##npart mean?

Answer:
It means concatenation. It's a C preprocessor directive.

So,mp_ptr(1)becomesP1,mp_ptr("foobar")becomesP"foobar", etc.


Question:
I have the following code:

```
typedef struct
{
   int a;
   float b;
   int c;
} Hello;

Hello hello[100];
```

I know I can assign value to the first element of this array:

```
hello[0] = {1,2.0,3};
```

but how to assign the first element when we declare thehello: Hello hello[100];

Answer:
Requires additional set of{}(outer{}for the array, inner set(s) for the elements of the array):

```
Hello hello[100] = { {1, 2.0, 3} };
```


Question:
I've encountered the following line in a .cuh file:

```
#define mp_ptr(n)     P##n
```

What does theP##npart mean?

Answer:
It means concatenation. It's a C preprocessor directive.

So,mp_ptr(1)becomesP1,mp_ptr("foobar")becomesP"foobar", etc.


Question:
I'm using visual studio to write a c code.

This is the malloc code line i was told to use:

```
root = (Coor)malloc(sizeof(Coor));
```

It doesn't let me use it for the following error:

```
identifier not found
```

Can anyone tell me why it happens and how to fix it?

Thanks,

Answer: Please check if you have included<stdlib.h>and<malloc.h>.


Question:
I want to implementing my own system call. (See below link)

http://www.tldp.org/HOWTO/html_single/Implement-Sys-Call-Linux-2.6-i386/

But adding new system call requires kernel compilation.

How to implement my own system call without recompiling the Linux kernel?

Answer:
You can't.

Without recompiling the kernel, all you can do is build and load kernel modules, and kernel modules cannot add new system calls.


Question:
For wcscmp() and wcscoll() are wide-character comparison.
What is differences ?

Answer:
Thewcscollwill interpret the parameters as appropriate to theLC_COLLATEcategory of the current locale.

If local is not an issure,wcscmpfunctions should be used, especially with large wstrings for performance.


Question: I have 8 uint32 elements and i want to break each uint32 into 4 uint8 then add all uint8 beside each others as unsigned chars in the array , how can i do that ?

Answer:
You can make use of the power ofunionfor this

```
union value
{
   uint32 number;

   struct bytes
   {
       uint8 bytevalue[4];
   };
};
```


Question:
For wcscmp() and wcscoll() are wide-character comparison.
What is differences ?

Answer:
Thewcscollwill interpret the parameters as appropriate to theLC_COLLATEcategory of the current locale.

If local is not an issure,wcscmpfunctions should be used, especially with large wstrings for performance.


Question:
I would like to synchronize folders and files between a server and some client. Due to the fact that the client part is limited by firewalls and proxy server, I'm forced to use a HTTP based solution.

Is there any HTTP/REST based library (both server and client side) optimized for file synchronization?

(Python or C based solutions would be nice.)

PS: the server side has to run on linux

Answer:
You could tryWebDAV

Python hassome librariesto handle it


Question:
This question already has answers here:Forcing GCC to compile .cpp file as C(2 answers)Closed10 years ago.

I have a C++ project [IDE = codelite] which tries to compile .c extention using g++ I want to specify a flag for .c file so that g++ treats it as c

What is the g++ command line option to make it behave as gcc ?

Answer:
Either

```
gcc file.c
```

or

```
g++ -x c file.c
```

will do what you want...


Question: Is there a convenient library call that allows me to open the default browser that I can use from C? I poked around in glib and didn't see anything. There is xdg-open, and I can just system that I guess. Any better ideas?

Answer: Since you tagged this question with "glib", the right solution is probably to useg_app_info_launch_default_for_uri(or one of the other GAppInfo methods, depending on your exact use case).


Question: I need to create user timer and thread in windows kernel program. Anyone please give a clue that if the regular threading headers are applicable in this mode?

Answer:
You need to look into KMDF or WDM if you are using some old drivers.

For timers see this:

http://msdn.microsoft.com/en-us/library/windows/hardware/ff550050(v=vs.85).aspx

And here are threads or work items:

http://msdn.microsoft.com/en-us/library/windows/hardware/ff551203(v=vs.85).aspx


Question: I need to create user timer and thread in windows kernel program. Anyone please give a clue that if the regular threading headers are applicable in this mode?

Answer:
You need to look into KMDF or WDM if you are using some old drivers.

For timers see this:

http://msdn.microsoft.com/en-us/library/windows/hardware/ff550050(v=vs.85).aspx

And here are threads or work items:

http://msdn.microsoft.com/en-us/library/windows/hardware/ff551203(v=vs.85).aspx


Question: How I can make a file unexecutable in winapi ?Something like quarantine in anti-viruses .Is it possible or not ?Thanks a lot .

Answer: If you overwrite the first two bytes of the file with something other than MZ it won't be recognised as an executable file any more.


Question: How I can make a file unexecutable in winapi ?Something like quarantine in anti-viruses .Is it possible or not ?Thanks a lot .

Answer: If you overwrite the first two bytes of the file with something other than MZ it won't be recognised as an executable file any more.


Question:
Standard C utility librarystdlib.hhas these function names:

(String as 'a'):

atofatoiitoa

(String as 'str'):

strtoulstrtolstrtod

Why is a string sometimes called an "a" and sometimes called an "str"?

Answer: astands forASCII, so in atoi it isASCIIto integer.See here. Theatofamily of functions have been deprecated bystrfunctions.


Question: I want to create a program like gdb or gnuplot that has it's own command prompt. I'm looking for a library that will handle the parsing/input validation as well as provide a command history. So far googling for this topic is difficult because any search with the terms 'c' and 'shell' will only produce results for 'csh'.

Answer: History is usually managed byreadlineorlibedit. Parsing is usually done withflex/bison.


Question:
came across this and was wondering what it does

```
LPCTSTR szmyLPCTSTR;

// doing _tcsncpy things with that string

//at the end then there is this line which i am not sure what it does
szmyLPCTSTR[122] = 0;
```

Thanks !!

Answer: LPCTSTR is simply a pointer to characters. It's adding a null terminator to the string.


Question: I am trying to figure out how to use this. I'm way out of my element here, so thanks for bearing with me.

Answer:
Libgit2 works primarily on repositories that you have disk access to, meaning you have to clone the repository before you can use libgit2 to work with it.

Once you've got that, you'll get a handle to your repository usinggit_repository_open, and create the branch usinggit_branch_create.


Question:
What's wrong in my function 'front'?
I want to pass the pointer to an specific line in my array to read/edit it.

```
struct queue
{
  char itens[LN][CL];
  int front,rear;
};

char *front(struct queue * pq)
{
  return pq->itens[pq->front+1][0];
}
```

Answer:
You're currently returning a singlechar, not a pointer to a row.  Take off the[0]:

```
char *front(struct queue *pq)
{
    return pq->itens[pq->front+1];
}
```


Question: Where can I find the implementation of if_nametoindex? It seems to be externed in net/if.h but searching through the source code I cannot find any hint on the implementation. A better question is, how would I find what library it is defined in etc...

Answer: You can try to search through all projects, not just apple sources:http://code.metager.de/source/s?&sort=relevancy&defs=if_nametoindex&reset=trueTake a look atfreebsd implementationfor example.


Question:
Eclipse popped a new one on me this morning. See the circled icon in the image.
I have looked at lots of links from similar posts on SO (though didnt find any for thsi exact icon) and none of the links have mentioned this.

FYI this is in Texas Instruments Code Composer Eclipse "package", or however it's termed, but searching over at TI has been just as fruitless.

Answer: It means this folder is in a workspace path.


Question:
Is there a way to to something like:

```
char* a = "Hello";
char* b = NULL;
char* c = a | b;

Result should be c = "Hello";
```

Seems like it does not work with Char*, but is there a way to do something like that?

Answer: This is nonsense not only because bitwise operators on pointers would have very... interesting... results, but mainly becauseNULL is not guaranteed to be represented by 0.


Question:
Is there a way to to something like:

```
char* a = "Hello";
char* b = NULL;
char* c = a | b;

Result should be c = "Hello";
```

Seems like it does not work with Char*, but is there a way to do something like that?

Answer: This is nonsense not only because bitwise operators on pointers would have very... interesting... results, but mainly becauseNULL is not guaranteed to be represented by 0.


Question:
When we do not give the value in a macro substitution.

```
#define YES
printf("%d",YES)
```

The value of YES is not given, is it by default 0 or garbage?

Answer: You just defined YES tonothing. So the result program after preprocessor should beprintf("%d",)


Question:
When we do not give the value in a macro substitution.

```
#define YES
printf("%d",YES)
```

The value of YES is not given, is it by default 0 or garbage?

Answer: You just defined YES tonothing. So the result program after preprocessor should beprintf("%d",)


Question:
Am I using scanf() in some wrong way?

```
char *input;
scanf("%s", input);
printf("%s\n", input);
```

This fails at the run-time.

Answer: Declaring achar *only creates a pointer, it does not allocate any memory for the string. You need to allocate memory for input. You can do that dynamically viamalloc(andfreewhen done) or you can declare an array of static size likechar input[100].


Question:
In a makefile, what is the difference in meaning betweenincludeand-include?

Examples:

```
-include $(APPINCLUDES)

include $(CONTIKI)/platform/$(TARGET)/Makefile.$(TARGET)
```

Answer:
The difference is that-includewon't generate an error if the include file doesn't exist.

The-prefix can be used many places in theMakefileto perform actions that you don't mind if they fail.


Question:
Is it to check for the WS_CHILD bit:

```
LONG style = GetWindowLong(hwnd, GWL_STYLE);
    int isTopLevel = !(style & WS_CHILD);
```

Or is there a better way?

Assume: Straight C calling only existing Windows API code.

Answer: Way #1: TesthWnd==GetAncestor(hWnd,GA_ROOT)Way #2: UseIsTopLevelWindow(user32 Win7, undocumented)


Question:
Is there a macro to return (ideally as aconst char*or indeedcont char *const) the typename of its parameter or some information on it?

This is atcompile time, not runtime, so C++'s typeinfo will not do. I run with-fno-rttianyway.

Answer:
There isn't.

C++11 does have the__func__identifier inside function definitions, which produces a string variable with the function name.  Most C++ compilers have variations on this to have "decorated" function names.


Question:
I am using Eclipse IDE on ubuntu to code in C. I use its normal debugging and default compiler ( GCC )

am writing code with OpenMP features. Eclipse just skips the pragmas and compiles the code in serial. So I end up running the program from terminal with the -fopenmp parameters.

I was wondering if there is a way to make eclipse compile and debug the OpenMP parts as well ?

Answer: You need to go toBuild > Settings > Miscellaneous > All optionsand add-fopenmp.


Question:
Is there a macro to return (ideally as aconst char*or indeedcont char *const) the typename of its parameter or some information on it?

This is atcompile time, not runtime, so C++'s typeinfo will not do. I run with-fno-rttianyway.

Answer:
There isn't.

C++11 does have the__func__identifier inside function definitions, which produces a string variable with the function name.  Most C++ compilers have variations on this to have "decorated" function names.


Question:
I am using Eclipse IDE on ubuntu to code in C. I use its normal debugging and default compiler ( GCC )

am writing code with OpenMP features. Eclipse just skips the pragmas and compiles the code in serial. So I end up running the program from terminal with the -fopenmp parameters.

I was wondering if there is a way to make eclipse compile and debug the OpenMP parts as well ?

Answer: You need to go toBuild > Settings > Miscellaneous > All optionsand add-fopenmp.


Question:
I want to detect the kill signal of my program inorder to execute some C instruction before leaving my program. my program is running on linux

Is it possible to do that? If yes how I can do it?

Answer: You can register asignal handlerusingsigaction().  Note that you cannot handleSIGKILLorSIGSTOPthough.


Question: Where is _TRACE macro defined? What's the purpose of it? Does it trace the stack and lets you know when your app crash?

Answer:
If you want you can define it compile time using below command

```
make CFLAGS=-D_TRACE
```


Question: How do I represent extremely large or small numbers in C with a certain amount of significant figures. For example, if I want to do calculations on 1.54334E-34, how could I do this. Also, is this applicable to OpenCL code?

Answer:
```
float var = 1.54334E-34;
double var2 = 1.54334E-34;

printf("\n normal:%f\n sci:%e \n or \n sci:%E   \n",var,var,var);
printf("\n normal:%f\n sci:%e \n or \n sci:%E   \n",var2,var2* 1.0E3 ,var2 * 1.0e3);
```


Question:
I am looking at taking the 10 bit data from my ADC conversion and storing it into 1 16 bit integer data looks like 0x03 ADRESH 0xFF ADRESL. What I am doing right now is

```
data = 0x03 & ADRESH;
    data = data << 8;
    data = data & 0x03FF & ADRESL;
```

will this work how I think it should or am I missing something? thanks for the help

Answer: Why don't you use the|operator ?short data = ((0x03 & ADRESH) << 8) | ADRESL;should work fine.


Question:
How to memcpy the two dimensional array in C:

I have a two dimensional array:

```
int a[100][100];

int c[10][10];
```

I want to usememcpyto copy the all the values in array c to array a, how to do this using memcpy?

```
int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i][10], c, sizeof(c));
}
```

is this correct?

Answer:
That should work :

```
int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i], &c[i], sizeof(c[0]));
}
```


Question:
I was experimenting withwchar_tand I tried to copy one array into another array.
here is my code:

```
wchar_t name[]=L"Aayman Khalid";
wchar_t Name[50]=L"";
wcscpy_s(Name,sizeof(name),name);
printf_s( "Name = %s\n", Name );
```

however when I run this code,I get the first letter i.eA.
could someone explain to me as to why that is?
Also how could I get the full name copied?

Answer: Useprintf_swith"%ls"specifier.


Question: Where is _TRACE macro defined? What's the purpose of it? Does it trace the stack and lets you know when your app crash?

Answer:
If you want you can define it compile time using below command

```
make CFLAGS=-D_TRACE
```


Question: How do I represent extremely large or small numbers in C with a certain amount of significant figures. For example, if I want to do calculations on 1.54334E-34, how could I do this. Also, is this applicable to OpenCL code?

Answer:
```
float var = 1.54334E-34;
double var2 = 1.54334E-34;

printf("\n normal:%f\n sci:%e \n or \n sci:%E   \n",var,var,var);
printf("\n normal:%f\n sci:%e \n or \n sci:%E   \n",var2,var2* 1.0E3 ,var2 * 1.0e3);
```


Question:
I am looking at taking the 10 bit data from my ADC conversion and storing it into 1 16 bit integer data looks like 0x03 ADRESH 0xFF ADRESL. What I am doing right now is

```
data = 0x03 & ADRESH;
    data = data << 8;
    data = data & 0x03FF & ADRESL;
```

will this work how I think it should or am I missing something? thanks for the help

Answer: Why don't you use the|operator ?short data = ((0x03 & ADRESH) << 8) | ADRESL;should work fine.


Question:
How to memcpy the two dimensional array in C:

I have a two dimensional array:

```
int a[100][100];

int c[10][10];
```

I want to usememcpyto copy the all the values in array c to array a, how to do this using memcpy?

```
int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i][10], c, sizeof(c));
}
```

is this correct?

Answer:
That should work :

```
int i;
for(i = 0; i<10; i++)
{
    memcpy(&a[i], &c[i], sizeof(c[0]));
}
```


Question:
I was experimenting withwchar_tand I tried to copy one array into another array.
here is my code:

```
wchar_t name[]=L"Aayman Khalid";
wchar_t Name[50]=L"";
wcscpy_s(Name,sizeof(name),name);
printf_s( "Name = %s\n", Name );
```

however when I run this code,I get the first letter i.eA.
could someone explain to me as to why that is?
Also how could I get the full name copied?

Answer: Useprintf_swith"%ls"specifier.


Question:
recvfrom on IPv6 sockets (GNU/Linux) gives unusual addresses for the client/from address of the forma00::<two_radom_bytes>:</64_network_prefix>.

What are theses addresses called or by what search terms can more information be found?

Answer:
Finally found the problem staring right at me; I used&addrinstead of&addr.sin6_addrfor function inet_ntop.
Sorry for bugging everyone with this silly problem.


Question:
```
char p[3][6]={{'a','b','c','\0'},{'d','e','f','\0'},{'g','h','i','\0'}};
char s[3][6]={"abc","def","ghi"};
```

Are they both same? If different please explain what way and how it is stored in memory?

Answer: They're the same in memory. Here in the VS 2010 debugger, I cast to char* so I can inspect the first 18 raw bytes of p and s:


Question: i wrote a program in C using Dev-Cpp, my question is : how can i change and customize this program icon ?

Answer: The program will default to the lowest-numbered icon in its resources. (If you don't have a resource script yet then you need to add one to your project.)


Question:
I have this piece of code in C:

```
void f(void *x) {
    printf(">>> %p\n", x);
}

int main() {

  f NULL;
    return 0;
}
```

I think is for the definition of NULL, but I'd like an explanation to clarify my doubt.

Answer: IfNULLis defined as((void *)0)or(0), then this expands tof ((void *)0)orf (0), which are proper function calls. The code errors out for anything non-parenthesized during compilation.


Question: I have foundSetupDiGetDeviceRegistryPropertyto get properties from devices, but I havent figured out how to get the parent property (you can see this property when you open a devices properties in device manager, click on details, and choose parent from the property drop down. How do I access that property from native c++ code?

Answer: The predefined DEVPKEY_Device_Parent guid is the key for the Parent property.  Read it with SetupDiGetDeviceInterfaceProperty().


Question: I have foundSetupDiGetDeviceRegistryPropertyto get properties from devices, but I havent figured out how to get the parent property (you can see this property when you open a devices properties in device manager, click on details, and choose parent from the property drop down. How do I access that property from native c++ code?

Answer: The predefined DEVPKEY_Device_Parent guid is the key for the Parent property.  Read it with SetupDiGetDeviceInterfaceProperty().