Question:
I'm looking for a very simple implementation of RSA in C. I need to place it in a DSP, so I'd like to use something very thin and straightforward.
Nonetheless, I just found only examples with little numbers (int or long) while I need to implement RSA at least at 1024 bits, so I also have to cope with large numbers.

Can you point me to some libraries or examples for this?

Answer: TheLibTomCryptand related projects are very clean and understandable.


Question:
I'm looking for a very simple implementation of RSA in C. I need to place it in a DSP, so I'd like to use something very thin and straightforward.
Nonetheless, I just found only examples with little numbers (int or long) while I need to implement RSA at least at 1024 bits, so I also have to cope with large numbers.

Can you point me to some libraries or examples for this?

Answer: TheLibTomCryptand related projects are very clean and understandable.


Question: Is it possible to usescanfin order to give a value to a macro substitution calledSIZE(#define SIZE) but without saving the value that came withscanfin another variable?

Answer: Macros are evaluated at pre-compilation by pre-compilerscanfis evaluated by the compiler. Compiler doesn't understand macros. So no.


Question:
Do standard C library implementations, especiallyglibc(the GNU C Library) provide linked lists, stack et al. data structures, or do we have to roll our own?

Thanks.

Answer:
The C  Standard does not provide data structures like linked list and stack.Some compiler implementations might provide their own versions but their usage will be non portable across different compilers.

So Yes, You have to write your own.


Question:
First apologize for asking this dumb question:

How to call this function in c (GNU C)

```
char *ftoa(float f, char *buf, int places)
```

Answer:
This is how you call it:

```
int decimal_places = 10;
char* result = malloc(decimal_places + 1);
ftoa(SOME_FLOAT_VALUE, result, decimal_places);
```

The function returns itsbufargument. As always, don't forget to free() theresultstring when you're done with it.


Question:
With:

```
char *x = malloc(1024);
strcpy(x, "asdf");
x = strdup(x);
free(x); // OK
free(x); // Segfault
```

If I just free it once, will I still be leaking? And if so, how to avoid it?

Answer:
You leak memory because you forget the first pointer. Do it like this:

```
char * x = malloc(1024);
strcpy(x, "asdf");
char * y = strdup(x);

free(x);
free(y);
```


Question: Is it possible to usescanfin order to give a value to a macro substitution calledSIZE(#define SIZE) but without saving the value that came withscanfin another variable?

Answer: Macros are evaluated at pre-compilation by pre-compilerscanfis evaluated by the compiler. Compiler doesn't understand macros. So no.


Question:
Do standard C library implementations, especiallyglibc(the GNU C Library) provide linked lists, stack et al. data structures, or do we have to roll our own?

Thanks.

Answer:
The C  Standard does not provide data structures like linked list and stack.Some compiler implementations might provide their own versions but their usage will be non portable across different compilers.

So Yes, You have to write your own.


Question:
First apologize for asking this dumb question:

How to call this function in c (GNU C)

```
char *ftoa(float f, char *buf, int places)
```

Answer:
This is how you call it:

```
int decimal_places = 10;
char* result = malloc(decimal_places + 1);
ftoa(SOME_FLOAT_VALUE, result, decimal_places);
```

The function returns itsbufargument. As always, don't forget to free() theresultstring when you're done with it.


Question:
With:

```
char *x = malloc(1024);
strcpy(x, "asdf");
x = strdup(x);
free(x); // OK
free(x); // Segfault
```

If I just free it once, will I still be leaking? And if so, how to avoid it?

Answer:
You leak memory because you forget the first pointer. Do it like this:

```
char * x = malloc(1024);
strcpy(x, "asdf");
char * y = strdup(x);

free(x);
free(y);
```


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

Possible Duplicate:C/C++ line number

I want to display the line number where the printf is triggered?

It may look like this:

```
printf("the line number is: %d",SOME_LIBC_MACRO);
```

How to do it?

Answer:
Use the__LINE__macro

```
printf("the line number is: %d", __LINE__);
```

Lists of other pre-defined macros are available forGCCandVisual Studio


Question: I printed sizeof(struct tm) in C using sizeof() operator it gives me 44 bytes.But in man page of ctime it has 9 int variables for time.then its size should be 36. How it is giving 44?

Answer:
http://linux.die.net/man/3/ctime

The glibc version of struct tm has additional fieldslong tm_gmtoff;           /* Seconds east of UTC */
const char *tm_zone;      /* Timezone abbreviation */

That's where you extra bytes come from (probably).


Question:
I want to add the ascii values of a string, say "hello".
What is the best way to do that in c? is There a way without looping the string?

Answer:
Of course, you can do it without looping:

```
#include <stdio.h>

int sum(const char *s) { return *s == 0 ? 0 : *s + sum(s + 1); }

int main()
{
    printf("%d\n", sum("hello"));
    return 0;
}
```


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

Possible Duplicate:C/C++ line number

I want to display the line number where the printf is triggered?

It may look like this:

```
printf("the line number is: %d",SOME_LIBC_MACRO);
```

How to do it?

Answer:
Use the__LINE__macro

```
printf("the line number is: %d", __LINE__);
```

Lists of other pre-defined macros are available forGCCandVisual Studio


Question: I printed sizeof(struct tm) in C using sizeof() operator it gives me 44 bytes.But in man page of ctime it has 9 int variables for time.then its size should be 36. How it is giving 44?

Answer:
http://linux.die.net/man/3/ctime

The glibc version of struct tm has additional fieldslong tm_gmtoff;           /* Seconds east of UTC */
const char *tm_zone;      /* Timezone abbreviation */

That's where you extra bytes come from (probably).


Question:
I'm a beginner in C.

Is there any datatype for dates?In C we have  for working with time, is there one for dates too?How can I calculate difference between two dates?

Answer: Yes,the standard libraryC Time Librarycontains structures and functions you want.You can usestruct tmto store date anddifftimeto get the difference.


Question:
I have a data structure:

```
typedef struct{
    int a;
    int b;
    int c;
}EVENTS;

EVENTS newone[20];
```

Then I use newone somewhere.
Now, I want to reset all values of newone[20] to 0.
Is there a short way to do this?

Thanks

Answer:
The shortest way is to usememset

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


Question:
I have tried googling this but all I get is results on how to compile a basic program.
Is it possible to compile code to a specific C++ standard using Clang++ and G++ by specifying that code should be compiled to say, C89, C99, C++98, etc?

Answer:
You can use the -std flag.  For example, to compile to C99, use-std=c99

The documentation for it ishere


Question:
I know the meaning of this statement

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

But what does this statement do

```
scanf("%2d",&x);
```

I tried searching for this, but could not find an answer. I want to know what happens internally also.

Answer:
That's two digits number:

```
int n = 0;
scanf ("%2d", &n);
printf ("-> %d\n", n);
```

12
-> 12

88657
-> 88


Question:
This question already has an answer here:Closed10 years ago.

Possible Duplicate:What is the rationale in allowing `?` to be escaped?

If I can do this:

```
string i = "'";
```

Why do this:

```
string i = "\'";
```

Answer:
You need it if you want a character literal:

```
char apos = '\'';
```


Question:
I know the meaning of this statement

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

But what does this statement do

```
scanf("%2d",&x);
```

I tried searching for this, but could not find an answer. I want to know what happens internally also.

Answer:
That's two digits number:

```
int n = 0;
scanf ("%2d", &n);
printf ("-> %d\n", n);
```

12
-> 12

88657
-> 88


Question:
This question already has an answer here:Closed10 years ago.

Possible Duplicate:What is the rationale in allowing `?` to be escaped?

If I can do this:

```
string i = "'";
```

Why do this:

```
string i = "\'";
```

Answer:
You need it if you want a character literal:

```
char apos = '\'';
```


Question:
I am creating a .so file with a C code. I need to link some other .so files to the .so file am creating. how to do it?

I tried this-L{path to file containing library} -l${library name}is it right?

Answer:
If your library file is called/path/to/libfile.so, then typically you'd need to specify the following arguments to the linker:

```
-L/path/to -lfile
```

Note that we only include the directory in-L, and omit both thelibprefix and the.sosuffix from-l.


Question:
In Visual C 2010 how do you do a string comparison to check for equality between a char* and a LPWSTR? For example, do something to the extent of

```
LPWSTR *str;
if (*str == "fileName") //...
```

Answer:
I believe the wsccmp function should do what you are looking to do.

http://msdn.microsoft.com/en-us/library/e0z9k731(v=vs.80).aspx


Question:
I want to copy the screen buffer of the command/powershell window to a text file using C/C++/Powershell.

Is there any way to do it?

Answer:
Use the Host console API:-

```
$rec = new-object System.Management.Automation.Host.Rectangle 0,0,($host.ui.rawui.BufferSize.Width  - 1),$host.ui.rawui.CursorPosition.Y
$buffer = $host.ui.rawui.GetBufferContents($rec)
```

Write buffer to file using >> or |


Question:
I wonder whether Timer created with

```
int eloop_register_timeout  (unsigned int   secs,
                             unsigned int   usecs,
                             eloop_timeout_handler  handler,
                             void *     eloop_data,
                             void *     user_data
                             )
```

in hostapd runs asynchronously.

Answer: No, the timer is run in the event loop thread when it expires.


Question:
Which is the plug in I need to install to program C in my eclipse
How I install it?

Answer: You need to install eclipseCDT(C Development Kit). You can choose which compiler you want to use with CDT. You can read morehere.


Question: Hello I'm trying to convert a decimal value to a hex using C in order to store it on my variablechar data[]and use the data later for something else. Does any one know how I can do it? I'm new to C

Answer:
You can use the%xformat specifier and asprintf. Passdataas the first parameter, and the value to be printed as the last parameter:

```
int value = 12345;
char data[16];
sprintf(data, "%x", value); // This produces 3039
```

Link to ideone.


Question:
I want a command that will completely ignore a function. Somebody once showed me the command, but I can't find it in the manual.

```
void a()
{
return;
}
#pragma gcc_disable
void a ()
{
return q09w8uifsdf
}
#include <stdio.h>
int main ()
{
  a();
}
```

Answer:
Umm... you mean this?

```
void a()
{
return;
}
#if 0
void a ()
{
return q09w8uifsdf
}
#endif
#include <stdio.h>
int main ()
{
  a();
}
```


Question:
Which is the plug in I need to install to program C in my eclipse
How I install it?

Answer: You need to install eclipseCDT(C Development Kit). You can choose which compiler you want to use with CDT. You can read morehere.


Question: Hello I'm trying to convert a decimal value to a hex using C in order to store it on my variablechar data[]and use the data later for something else. Does any one know how I can do it? I'm new to C

Answer:
You can use the%xformat specifier and asprintf. Passdataas the first parameter, and the value to be printed as the last parameter:

```
int value = 12345;
char data[16];
sprintf(data, "%x", value); // This produces 3039
```

Link to ideone.


Question:
How can I in my make-file use option-std=c99or-std=gnu99to compile my C code?

```
-include ../../../Common/C/Make.cfg

### target ###

TARGET_NAME   = myRec

### Objects, sources ###

# C source files

CSRCS = \
    myRec.c

LDLIBS ?= -lNBiometrics -lNMedia -lNCore

include ../../../Common/C/Make.rules
```

Answer: You need to set theCFLAGSmakefile variable.


Question: I want to change some kernel source files for network stack testing so is there any way to get kernel source code for RHEL6 Enterprise edition and how to apply the changes to get results?

Answer:
Herefrom redhat ftp, you may get what you want.

Example:kernel-2.6.32-220.17.1.el6.src.rpm


Question:
Using

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

{
    double number1, number2;
    char operator;

    number1 =atof (argv[0]);
    operator =argv[1];        // line 29
    number2 =atof (argv[2]);
```

Compiler complains saying

29 warning: assignment makes integer from pointer without a cast
  [enabled by default]

Answer: argv[1] is a pointer to char, you can't assign it to a char. either transform operator to char * or try operator = *(argv[1]);


Question:
Using

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

{
    double number1, number2;
    char operator;

    number1 =atof (argv[0]);
    operator =argv[1];        // line 29
    number2 =atof (argv[2]);
```

Compiler complains saying

29 warning: assignment makes integer from pointer without a cast
  [enabled by default]

Answer: argv[1] is a pointer to char, you can't assign it to a char. either transform operator to char * or try operator = *(argv[1]);


Question:
I need a condition for a do-while loop that means the loop is repeated (asking user to enter data again) until it is an integer number and between 1 and 25.

```
while (!isdigit(data) || data < 1 || data > 25);
```

This just throws out a runtime error and I'm not sure why.

Answer:
Try this:

```
do {

   /* Read from input and store it in data */

} while( !isdigit(data) || !( data > 1 && data < 25 ) );
```


Question:
I need a condition for a do-while loop that means the loop is repeated (asking user to enter data again) until it is an integer number and between 1 and 25.

```
while (!isdigit(data) || data < 1 || data > 25);
```

This just throws out a runtime error and I'm not sure why.

Answer:
Try this:

```
do {

   /* Read from input and store it in data */

} while( !isdigit(data) || !( data > 1 && data < 25 ) );
```


Question:
I need a condition for a do-while loop that means the loop is repeated (asking user to enter data again) until it is an integer number and between 1 and 25.

```
while (!isdigit(data) || data < 1 || data > 25);
```

This just throws out a runtime error and I'm not sure why.

Answer:
Try this:

```
do {

   /* Read from input and store it in data */

} while( !isdigit(data) || !( data > 1 && data < 25 ) );
```


Question:
I declared an array:

char * words[1000] = {NULL};

And now I have a series of forked child processes adding words to that array, but they are not affecting the parent program. How can I change that?

Answer: Hmm, for your edit-case: Dont use fork, use threads, because then everything runs in one address-space...And of course, then use mutexes to protect your words-array...


Question:
I'm making a Mac OSX program where I need to take a snapshot (image file) the currently active window in Photoshop.

How would I go about this?

Answer: I ended up using Applescript inside Xcode to find photoshop and saving a copy of the current file. Not the best solution but it works.


Question:
I declared an array:

char * words[1000] = {NULL};

And now I have a series of forked child processes adding words to that array, but they are not affecting the parent program. How can I change that?

Answer: Hmm, for your edit-case: Dont use fork, use threads, because then everything runs in one address-space...And of course, then use mutexes to protect your words-array...


Question:
I'm making a Mac OSX program where I need to take a snapshot (image file) the currently active window in Photoshop.

How would I go about this?

Answer: I ended up using Applescript inside Xcode to find photoshop and saving a copy of the current file. Not the best solution but it works.


Question:
I declared an array:

char * words[1000] = {NULL};

And now I have a series of forked child processes adding words to that array, but they are not affecting the parent program. How can I change that?

Answer: Hmm, for your edit-case: Dont use fork, use threads, because then everything runs in one address-space...And of course, then use mutexes to protect your words-array...


Question:
I'm making a Mac OSX program where I need to take a snapshot (image file) the currently active window in Photoshop.

How would I go about this?

Answer: I ended up using Applescript inside Xcode to find photoshop and saving a copy of the current file. Not the best solution but it works.


Question:
Specifically I am doing this

```
Word32 x = 18653184;
Word32 y;
Word16 shift = 269;
y = x >> shift;
```

I'd expect the result of this logical shift to be 0, but I am instead getting 2277.  How does C define this type of operation?

Answer:
Yes, it is undefined behavior, according to section 6.5.7 paragraph 3

... If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.


Question:
Specifically I am doing this

```
Word32 x = 18653184;
Word32 y;
Word16 shift = 269;
y = x >> shift;
```

I'd expect the result of this logical shift to be 0, but I am instead getting 2277.  How does C define this type of operation?

Answer:
Yes, it is undefined behavior, according to section 6.5.7 paragraph 3

... If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.


Question: I'm debugging a thread impersonating a currently logged on user in a Windows service process running underSYSTEMaccount. How could I determine the current impersonation level (as in whetherimpersonationordelegationwas used) either programmatically, or using Visual Studio debugger or other tools?

Answer: Simplest way is via Visual Studio$userpseudo variable.


Question: I'm debugging a thread impersonating a currently logged on user in a Windows service process running underSYSTEMaccount. How could I determine the current impersonation level (as in whetherimpersonationordelegationwas used) either programmatically, or using Visual Studio debugger or other tools?

Answer: Simplest way is via Visual Studio$userpseudo variable.


Question:
With this struct

```
typedef struct tNode_t {
    struct tNode_t **a;
} tNode;
```

I want to be able to haveapoint to an array to 5 pointers to tNodes

example main:

```
int main()
{
    tNode t;
    tNode (*alpha)[5];
    t.a = alpha;
}
```

why doesn't this work?

Answer:
This defines a pointer to an array of tNodes:

```
tNode (*alpha)[5];
```

This defines an array of pointers to tNodes:

```
tNode *alpha[5];
```


Question:
when running my code in borland c 3.1 it works fine, but when running it on c-free it crashes at this line:while(ptr1->pright)
       {
       ptr1=ptr1->pright;
       }giving SIGSEGV, any logical reasons?

Answer: You're probably accessing memory outside the bounds of an array or which you didn't allocate. As such, you triggeredundefined behaviour, so pretty much anything can happen, including crashing or evenapparentlyworking fine.


Question:
when running my code in borland c 3.1 it works fine, but when running it on c-free it crashes at this line:while(ptr1->pright)
       {
       ptr1=ptr1->pright;
       }giving SIGSEGV, any logical reasons?

Answer: You're probably accessing memory outside the bounds of an array or which you didn't allocate. As such, you triggeredundefined behaviour, so pretty much anything can happen, including crashing or evenapparentlyworking fine.


Question:
when running my code in borland c 3.1 it works fine, but when running it on c-free it crashes at this line:while(ptr1->pright)
       {
       ptr1=ptr1->pright;
       }giving SIGSEGV, any logical reasons?

Answer: You're probably accessing memory outside the bounds of an array or which you didn't allocate. As such, you triggeredundefined behaviour, so pretty much anything can happen, including crashing or evenapparentlyworking fine.


Question:
How would I make a pointer to:

```
char * values [x];
```

I'm trying to pass an array ofchar *to a pointer from outside the block of code, where x can by anything.

Answer:
Pointer to a pointer can do what you want.

```
char ** val ;
```

In the function definition :

```
return_type func(char ** val) {...}
```

In the function call :

```
func(&values)
```

You need to pass the address of the pointer to the function.


Question:
I have already compilelamefor android as static library.

How can I use lame for convert awavfile tomp3?

What I have to call? There is some tutorial of how use lame as library?

Answer:
You can see thisdeveloper.samsung.comtutorial for porting or how we use LAME on Android with JNI

Porting and using LAME MP3 on Android with JNI


Question:
Is the compound operator '&=' logical or bitwise AND ?

In other words, isa &= bthe same as:

a = a & ba = a && b

Answer:
a &= bis using the bitwise AND operator. Think of the+=operation:

```
a += 5;
```

is the same as:

```
a = a + 5;
```

It's just a combination of two operations:&and=.


Question:
Are there any c compilers for ms-dos that support some C99 features?
I have trouble searching for recent compilers that I can run on my system.
Actually, I need this to have a compiler on my Playbook via Dos Box, while I am away from home and wihout internet access.

Answer:
This compiler should work on MSDOS (gcc adapation)

http://personal.ee.surrey.ac.uk/Personal/R.Bowden/C/dos-gcc/index.htm


Question:
Win32 has the winmm library, which allows joystick events to be captured in the regular event loop (alongside the general window events, keyboard events, and mouse events).

Is there a similar setup in Xlib? Is my only choice to do raw input?

Answer: Sounds like the answer is no (until someone smarter than me comes along and corrects me). I need to do raw input. I have to poll at a reasonable interval and convert deltas into my own events.


Question:
Win32 has the winmm library, which allows joystick events to be captured in the regular event loop (alongside the general window events, keyboard events, and mouse events).

Is there a similar setup in Xlib? Is my only choice to do raw input?

Answer: Sounds like the answer is no (until someone smarter than me comes along and corrects me). I need to do raw input. I have to poll at a reasonable interval and convert deltas into my own events.


Question:
I installed GNAT 2012 a while back when I was working with Ada and it came with a version of GCC. I can compile C files from the command prompt using gcc fine, but "make" apparently wasn't included.

How would I go about getting make working? Should I just install the newest version of GCC instead?

Answer: Make is not part of GCC. On Windows, you can useMSYS. It includes make and other useful tools.


Question:
I installed GNAT 2012 a while back when I was working with Ada and it came with a version of GCC. I can compile C files from the command prompt using gcc fine, but "make" apparently wasn't included.

How would I go about getting make working? Should I just install the newest version of GCC instead?

Answer: Make is not part of GCC. On Windows, you can useMSYS. It includes make and other useful tools.


Question:
I have problems to jump to an label.

My Code:

```
asm{
keypress:
    ...
    cmp ax,0000
    jz keypress
}
```

Borland says: Undefined Label "keypress"

Answer:
Try moving the label to outside of the asm block (i.e., just above the "asm{" line).  This is per thislinkand thislink.

Also note that evidently you may not be able to jump to a forward label (perhere), but that's of course not your problem in this example.


Question:
I'm stuck with my code for 20 minutes.

What's wrong with this simple C code?

```
void function (char & reference_to_something) {}
```

error:

```
expected ';' , ',' or ')' before '&' token
```

Answer: C does not have references; C++ does.


Question: Is there a way to open a full screen window withSFMLon a 2nd monitor?

Answer:
I'm afraid the answer is no. Here's a quote from a different part of that site:

SFML doesn't explicitely manage multiple monitors. As a consequence, you won't be able to choose which monitor a window appears on, and you won't be able to create more than one fullscreen window. This should be improved in a future version.


Question: When I include mysql.h in my source file, I get all sorts of syntax errors. I'm using the cygwin gcc compiler and MysQL Windows Connector 6.0.2. I added an image of my IDE. What can I do to fix this?Click here for larger image

Answer: You need to includewinsockright before mysql.


Question: If I keep incrementing aCvariable, does it saturate or wrap around?

Answer:
For signed integer types, it'sundefinedas to what happens.

For unsigned integer types, it will wrap around (i.e. back to 0).


Question:
I have a question regarding to reset array in c,
I define a array like this:

```
static int hello[5][6] = {{1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6}};
```

then how to reset all the element on each row and line as 0?

Answer:
```
memset (hello, 0, sizeof(hello));
```


Question:
What do i need to to do to print the contents of a memory provided that it can have null characters in between.
suppose i have an address 0X123.i want to print some 100 characters before this address in the memory and there can be some NULL characters in between and i want to print those NULL characters too.

Answer:
Use unformatted output:

```
cout.write(address, count);
```

Or for C:

```
fwrite(address, 1, count, stdout);
```


Question: When I include mysql.h in my source file, I get all sorts of syntax errors. I'm using the cygwin gcc compiler and MysQL Windows Connector 6.0.2. I added an image of my IDE. What can I do to fix this?Click here for larger image

Answer: You need to includewinsockright before mysql.


Question: If I keep incrementing aCvariable, does it saturate or wrap around?

Answer:
For signed integer types, it'sundefinedas to what happens.

For unsigned integer types, it will wrap around (i.e. back to 0).


Question:
I have a question regarding to reset array in c,
I define a array like this:

```
static int hello[5][6] = {{1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6}};
```

then how to reset all the element on each row and line as 0?

Answer:
```
memset (hello, 0, sizeof(hello));
```


Question:
What do i need to to do to print the contents of a memory provided that it can have null characters in between.
suppose i have an address 0X123.i want to print some 100 characters before this address in the memory and there can be some NULL characters in between and i want to print those NULL characters too.

Answer:
Use unformatted output:

```
cout.write(address, count);
```

Or for C:

```
fwrite(address, 1, count, stdout);
```


Question: When I include mysql.h in my source file, I get all sorts of syntax errors. I'm using the cygwin gcc compiler and MysQL Windows Connector 6.0.2. I added an image of my IDE. What can I do to fix this?Click here for larger image

Answer: You need to includewinsockright before mysql.


Question: If I keep incrementing aCvariable, does it saturate or wrap around?

Answer:
For signed integer types, it'sundefinedas to what happens.

For unsigned integer types, it will wrap around (i.e. back to 0).


Question:
I have a question regarding to reset array in c,
I define a array like this:

```
static int hello[5][6] = {{1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6}};
```

then how to reset all the element on each row and line as 0?

Answer:
```
memset (hello, 0, sizeof(hello));
```


Question:
What do i need to to do to print the contents of a memory provided that it can have null characters in between.
suppose i have an address 0X123.i want to print some 100 characters before this address in the memory and there can be some NULL characters in between and i want to print those NULL characters too.

Answer:
Use unformatted output:

```
cout.write(address, count);
```

Or for C:

```
fwrite(address, 1, count, stdout);
```


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

Possible Duplicate:Recommended way to initialize srand?

I have the following problem when using srand() in c.

I call srand(time(NULL))in a loop, but the loopfinishes before 1sec and every time I call the rand() I get the same value.

How can I solve this?

Answer: Why are you callingsrandin a loop? Just call it once at the start of your program and then callrandany number of times.


Question:
When is it appropriate to include a type conversion in a symbolic constant/macro, like this:#define MIN_BUF_SIZE ((size_t) 256)Is it a good way to make it behave more like a real variable, with type checking?When is it appropriate to use theLorU(orLL) suffixes:#define NBULLETS 8U
#define SEEK_TO 150L

Answer: You need to do it any time the default type isn't appropriate.  That's it.


Question:
I have three ints.
Fx:20121121

I want to convert them into a single int20121121

Can this be done?
I have tried messing around withatoi()without results.

Answer:
Well, to answer directly the question that you asked, you would do it like this:

```
int combined = year*10000 + month*100 + day;
```

But your approach is quite possibly not the best solution to your actual problem.


Question:
I have three ints.
Fx:20121121

I want to convert them into a single int20121121

Can this be done?
I have tried messing around withatoi()without results.

Answer:
Well, to answer directly the question that you asked, you would do it like this:

```
int combined = year*10000 + month*100 + day;
```

But your approach is quite possibly not the best solution to your actual problem.


Question: I need to parse a HTTP request in C. I've been previously using std::regex for C++ but now I have to use C. What would be the best method to parse a HTTP request with C?

Answer: Apache recommends cgic, you can find it athttp://www.boutell.com/cgic/and its very simple to use


Question:
I'm designing an editor in GTK+ and wanted to add a feature of the gedit text editor to represent the line number at the left side of the text. I've added animage of gedit showing the line number at the left of each line. I require guidance of which widget I should use and how to use it.

Thanks in advance :).. !

Answer: To get line numbering, useGtkSourceViewinstead ofGtkTextView.


Question:
I am trying to reallocate memory to my table using the below expression.But I always keep getting the below error.Please kindly advise me.

```
typedef char *OFAttribs[6];
 OFAttribs *tmp = realloc(pTable, sizeof(*tmp) * (nTableLen+1));

Error: invalid conversion from âvoid*â to âchar* (*)[6]â
```

Answer:
Try this:

```
OFAttribs *tmp = (OFAttribs*) realloc(pTable, sizeof(*tmp) * (nTableLen+1));
```


Question:
Im trying to figure out what the function declarations mean:

```
int *f();
```

and

```
int (*g)();
```

Answer:
```
int *f();
```

The above line is the declaration of a functionfthat has an unspecified number of parameters and that returns anint *.

```
int (*g)();
```

The above line is the declaration of a pointergto a function that has an unspecified number of parameters and that returns anint.


Question: I'm developing a note-taking utility and want to add a feature for voice-recording and playback in full duplex asynchronous mode.What cross-platform c/c++ libraries/API's can I evaluate for my purpose? Google isn't much help in this case and the existing QA's on SO doesn't quite cover this.

Answer: PortAudiocan accomplish what you want. It has lots of backends for different technologies like ALSA, ASIO, DirectSound etc.


Question:
I am trying to reallocate memory to my table using the below expression.But I always keep getting the below error.Please kindly advise me.

```
typedef char *OFAttribs[6];
 OFAttribs *tmp = realloc(pTable, sizeof(*tmp) * (nTableLen+1));

Error: invalid conversion from âvoid*â to âchar* (*)[6]â
```

Answer:
Try this:

```
OFAttribs *tmp = (OFAttribs*) realloc(pTable, sizeof(*tmp) * (nTableLen+1));
```


Question:
Im trying to figure out what the function declarations mean:

```
int *f();
```

and

```
int (*g)();
```

Answer:
```
int *f();
```

The above line is the declaration of a functionfthat has an unspecified number of parameters and that returns anint *.

```
int (*g)();
```

The above line is the declaration of a pointergto a function that has an unspecified number of parameters and that returns anint.


Question: How to make sure, that my code is compatible with every gcc compiler set to the most strict level? Is there any tester tool or do I need to test it manually somehow? Thanks

Answer:
Every gcc compiler is easy, just use an old one and it will compile for sure with the newer ones.

If you want it to compile with any compiler it's a bit more hard. As suggested you might use the -ansi switch to disable gcc extensions.


Question:
How can I open a.txtfile usingexecl()function? Is there any other function in c to open a file ingeditin Ubuntu.

Regards

Answer:
Is there any other function in c to open a file in gedit

Th easiest would be

```
system("gedit file.txt");
```

As a side-note you might want to look intoxdg-open.


Question: How to make sure, that my code is compatible with every gcc compiler set to the most strict level? Is there any tester tool or do I need to test it manually somehow? Thanks

Answer:
Every gcc compiler is easy, just use an old one and it will compile for sure with the newer ones.

If you want it to compile with any compiler it's a bit more hard. As suggested you might use the -ansi switch to disable gcc extensions.


Question:
How can I open a.txtfile usingexecl()function? Is there any other function in c to open a file ingeditin Ubuntu.

Regards

Answer:
Is there any other function in c to open a file in gedit

Th easiest would be

```
system("gedit file.txt");
```

As a side-note you might want to look intoxdg-open.


Question: If I chdir within a thread, will that affect the cwd of the parent program?

Answer:
Yes.

If you need relative paths in a multithreaded application, it's safest to use theat()versions of functions.  For example,openat()is likeopen():

```
int openat(int dirfd, const char *pathname, int flags);
```

The first parameter is the fd to a directory.  The path is relative to that directory.


Question: Say I want to create a folder myFolder, and I want it to be hidden. I'm having trouble finding the answer to this for Unix.

Answer:
Seeman 2 mkdirfor creating a folder in C. To make it hidden you must prefix the name with a dot. It's just a one-liner:

```
mkdir(".myFolder", 0755);
```


Question: Say I want to create a folder myFolder, and I want it to be hidden. I'm having trouble finding the answer to this for Unix.

Answer:
Seeman 2 mkdirfor creating a folder in C. To make it hidden you must prefix the name with a dot. It's just a one-liner:

```
mkdir(".myFolder", 0755);
```


Question:
I just have a simple question, I cannot find what the key code is for space bar in curses.h.
ex. I know the code for down is KEY_DOWN.
can anyone help?

Answer:
There is no macro for the space key. Just use ' ' to represent a space. You can find a complete list of curses key macroshere.

Ex.

```
char mychar = ' ';
if (mychar == ' ') {//Do this...}
```


Question:
What should I do if I want to use identifierNULLingdb's call statement?

Is it because I didn't include stdio.h in gdb?

I have tried :call #include <stdio.h>but this doesn't seem to work.

Answer: Just use0or(void*)0. Nothing fancy.


Question: I have long value  of 12 digits as output from an arithmetic operation. So i want only the middle 4 value. for example i got 823954957346 and i only want 5495 to store in a variable. can i do this in C or C++ ?

Answer:
You can use something like:

```
main() {
    unsigned long i = 823954957346;
    printf ("%lu\n", i);
    printf ("%lu\n", i / 10000 % 10000);
}
```

Output:

```
823954957346
5495
```


Question:
hi i have this function

```
int printofarray(int *j,double *n)
{
int x,k;
k=*j;
if(n==NULL) {
printf("array was not created\n");
return 1;}

for(x=0;x<k;x++){
printf("%.2lf\n",*(n+x));}

return 0;
}
```

when i use it the output is like this

```
34.77
6114.05
410.70
```

but i want to write them this way

```
34.77
6114.05
 410.70
```

idea how?

Answer: Offhand, try %f instead of %lf for f1.   Edit:  %lf is for double.


Question:
What I was always doing is:

```
int arr[] = {2, 3, 4};
```

and it always worked.

I've heard of a better way to initialize new array, using the pointer:

```
int *arr = {2, 3, 4};
```

However, it doesn't work in any IDE, it throws some errors likeint differs in levels of indirection from int, ortoo many initializers. How should I do this?

Answer:
```
int arr[] = {2, 3, 4};
```

is just fine, and completely correct. No need to change.


Question: How do I programmatically get the core a given thread is running on? Something like Unix'sgetcpuid. This is for Linux, and C.

Answer: Doessched_getcpu()not give you a different value for the cores?


Question:
I can't reproduce this with a simple program, but somewhere in my program I have something like:

```
float e = f(...);
if (e > 0.0f) {
    ...
```

printf("%f", e)shows thateis0.000000, yete > 0.0fis true... So ise > 0ande > 0.0. What am I missing?

Answer: The floating point value is larger than zero, but less than 1e-7. It's printing issue. Use scientific notation printf("%e", value); or "%g" for shortest notation.


Question: Can I use pipe between two process without using fork and share file descriptors with for example socket ? I don't need another solution, I need pipe between two process that not forked.

Answer:
You could use a named pipe (FIFO):

if you domkfifo <common path>, you an use this path in both processes, one for reading and one for writing. Then you have the same behaviour as with a normal pipe.


Question: I am working with Ubuntu 12.04. I want to use the AUX library for OpenGL. Can anybody tell me what steps are involved in getting the AUX library for my system?

Answer:
I want to use the AUX library for OpenGL.

No, you don't! GlAux is unmaintained and a most annoying PITA.

You want to use GLFW, SDL, SMFL, or maybe FreeGLUT.


Question:
I'm going to write a code which will extensively execute other programs. I don't want it to have root privileges if someone set a set-user-id bit(and root is an owner). So I'm going to drop privileges at startup.

My question is:
How can I understand from within the program whether it run inset-user-idmode?

Answer:
You can compare result ofgetuid()andgeteuid()library calls.

Ifgeteuid()returns 0 (root), butgetuid()returns not 0, you can say that suid is active.


Question: I usually get a warning from the compiler if I tell it to return anything else.

Answer: This is the exit code provided to whoever called your program. Non-zero value usually signifies error.


Question: I usually get a warning from the compiler if I tell it to return anything else.

Answer: This is the exit code provided to whoever called your program. Non-zero value usually signifies error.


Question: I want to write a C++ wrapper for the Linux Socket API. In the socket() ctor the adress family (AF) is requested. I dont want to require the AF in the connect() signature again, becuase it has been already given in the constructor of socket. So how do I get the AF from an existing socket?

Answer:
Damn. Searched about half an hour. Now after posting this question I found immiediately the answer.

getsockopt([...])with option SO_DOMAIN (seesocket options)


Question: I need to make a rule in my lex file that will identify the start of a newline and a sequence of  spaces I did this^( )*but the compiler says it is wrong what is the right way to define it?

Answer:
Try something like this:

```
^[\n\t ]+
```


Question: So all I need is simple: if object color is (255, 10, 10) then each visible point of it shall be rendered as (255, 10, 10). No lights, no shadows, no shades, no reflections/refractions and no transparency. I only want to provide vertex meshes and colors for them and see them rendered. Can such thing be implemented with OpenGL (on Renderer setup level - not via post/pre shading)?

Answer:
You need to disable the lighting :

```
glDisable(GL_LIGHTING);
```


Question:
Could you post some examples how to read list of meanings from/procfiles?

```
list_head* get_from_proc_file()
{
   struct file* file = fopen("example","r");
   seq_open(file, &seq_ops);
   struct seq_file *p = file->private_data;
   READ LIST OF DATA?????
}
```

Answer:
You can't usefopenas this is a libc function. The example bellow shows how to read a file from the kernel.

http://www.wasm.ru/forum/viewtopic.php?pid=467952#p467952


Question:
Is there any way to extrude gluPartialDisk in OpenGL - have been looking around
but cant seem to find one.  If there isn't any way is there something similar I can
look at.

Answer: There is no function in OpenGL to do this (note: gluPartialDisk is not an OpenGL function. It's a GLU function, which is not part of OpenGL itself). So if you want to do extrusion, you'll have to compute the vertices yourself.


Question: I know that JPG, BMP, GIF and others formats compress image. But can I get snapshot of display and save it without compressing(in binary file) in programming way (using c/c++ for example or other stuff)?

Answer: BMP files aren't compressed by default.  See here:https://en.wikipedia.org/wiki/BMP_file_format


Question:
I declared a variable in this way:

```
int i = 0;
```

I get the warning:

ISO C90 forbids mixed declarations and code

How can I fix it?

Answer:
I think you should move the variable declaration to top of block. I.e.

```
{
    foo();
    int i = 0;
    bar();
}
```

to

```
{
    int i = 0;
    foo();
    bar();
}
```


Question:
I'm expecting h here.But it is showing g. Why?

```
char *c="geek";
printf("%c",++*c);
```

Answer:
You are attempting to modify a string literal, which isundefined behaviour. This means that nothing definite can be said about what your program will print out, or indeedwhetherit will print anything out.

Try:

```
char c[]="geek";
printf("%c",++*c);
```

For further discussion, see theFAQ.


Question:
Can if defined (XX) be placed inside a struct/union in aheader file?

```
struct
{
 int i;
 #if defined(xx)
 int j;
 #endif
}t;
```

I am dealing with a large file base of .c and .h files and I need to know the possible cons of this type of usage.

Answer: While completely valid, a definite con to using this is any time you need to uset.jyou would also have to surround it with your#if defined(xx)otherwise you will invoke compiler errors


Question:
I have a struct like this:

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

then I declare it in this way:

```
Hello hello[6] = {};
```

Then I got this warning: ISO C forbids empty initializer braces, anyhow I think I need to initialize it, how to do it in the right way?

Answer: That's not valid C. The universal zero initializer in C is{0}, not{}.


Question: I know that JPG, BMP, GIF and others formats compress image. But can I get snapshot of display and save it without compressing(in binary file) in programming way (using c/c++ for example or other stuff)?

Answer: BMP files aren't compressed by default.  See here:https://en.wikipedia.org/wiki/BMP_file_format


Question:
I declared a variable in this way:

```
int i = 0;
```

I get the warning:

ISO C90 forbids mixed declarations and code

How can I fix it?

Answer:
I think you should move the variable declaration to top of block. I.e.

```
{
    foo();
    int i = 0;
    bar();
}
```

to

```
{
    int i = 0;
    foo();
    bar();
}
```


Question:
I'm expecting h here.But it is showing g. Why?

```
char *c="geek";
printf("%c",++*c);
```

Answer:
You are attempting to modify a string literal, which isundefined behaviour. This means that nothing definite can be said about what your program will print out, or indeedwhetherit will print anything out.

Try:

```
char c[]="geek";
printf("%c",++*c);
```

For further discussion, see theFAQ.


Question:
My registry.arm.bin is 600 KB large, and every time my application starts, it takes  ~ 0.25 seconds to read and parse it.
The problem is that i don't need all the plugins that are located there.
I only want almost all of the plugins for AUDIO, and none for VIDEO.

How can i trim down my registry, so i reduce it size and loading time ?

Answer: Just remove the plugins you don't need from your system. They are in /usr/lib/gstreamer-0.10 (or -1.0).


Question:
How are called these "widgets" in Gtk+: the widget with blue border and the widgets inside on it? is there equivalent in Gtk+?

Note: I'm calling "widget" by following Gtk terminology, because I don't know what its real nomenclature in the KDE environment.

Answer:
That is called aTreeView, inside it you will findTreeViewColumnandCellRenderer.

The documentation ishere.


Question:
Does anyone know where can I find a simple client/server WinAPI message queue example?

I'd like to create a program that sends data from a client to a server using message queues and I can't find anything useful on the web.

Thank you.

Answer: TheWM_COPYDATAmessage can be used, but only synchronously. Without usingMSMQ, you'd have to implement your own message queue using named shared memory & named semaphores for asynchronous queues.


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

Possible Duplicate:C and C++ : Partial initialization of automatic structure

I'm looking for a fast way to init local array with zeros. (By "Fast", I mean "Fast to type.") When I do the following:

```
HANDLE hHandles[32] = {0};
```

does it zero out the first element or all 32?

Answer: It initializes all the 32 elements to zero.


Question:
Let's say I have astructwith a fieldxthat is also astruct(not a pointer to astruct).

If I sayobject.x = 0, what is actually happening under the hood?

Answer:
You'll get a compile error.

```
error: incompatible types in assignment
```

You can't assign anintto a struct variable.


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

Possible Duplicate:C and C++ : Partial initialization of automatic structure

I'm looking for a fast way to init local array with zeros. (By "Fast", I mean "Fast to type.") When I do the following:

```
HANDLE hHandles[32] = {0};
```

does it zero out the first element or all 32?

Answer: It initializes all the 32 elements to zero.


Question:
Let's say I have astructwith a fieldxthat is also astruct(not a pointer to astruct).

If I sayobject.x = 0, what is actually happening under the hood?

Answer:
You'll get a compile error.

```
error: incompatible types in assignment
```

You can't assign anintto a struct variable.


Question:
Real short and simple:

saycol = 10,size = 8. Then the following is executed:

```
col -= size--;
```

So does size get subtracted to 7 before doing the subtraction on col (so col = 3)? Or col = 2?

Thanks

Answer:
size--yields the previous value ofsize, so this is equivalent to:

```
col -= size;
-- size;
```


Question:
I'm not fairly familiar in C++ stream API and I want to convert a C code using stream in C++,

```
char sHex[20] = {0};
int numid = 2;

snprintf( sHex, sizeof(sHex) - 1, "%X", numId );
```

Answer:
```
stringstream ss;
ss << uppercase << hex << numId;
string res = ss.str();
```


Question: Problem is - I have to implement my own exit(status) with setjmp and longjmp. Maybe someone could give some pointers?

Answer: The only solution I think of right now, is to callsetjmpearly inmain, and then create aMyExitfunction which does alongjmpto thesetjmpinmainand does areturnwith some value (provided from thelongjmpcall).


Question:
I need to print 2 vector in openGL but I cannot sent a pointer with the functionglutDisplayFunc.

glutDisplayFunc(graphfunct)I have this once the window is created but I need send the 2 pointers with the address of vector to set the coordinates.

Answer: You cannot pass parameters to the function you register withglutDisplayFunc. You must use a globally-accessible variable instead.


Question:
I need to print 2 vector in openGL but I cannot sent a pointer with the functionglutDisplayFunc.

glutDisplayFunc(graphfunct)I have this once the window is created but I need send the 2 pointers with the address of vector to set the coordinates.

Answer: You cannot pass parameters to the function you register withglutDisplayFunc. You must use a globally-accessible variable instead.


Question:
How do I find a substring from the string path "/user/desktop/abc/post/" using C/C++? I want to check if folder "abc" is present or not in that path.

Path is character pointerchar *ptr = "/user/desktop/abc/post/";

Answer:
Usestd::stringandfind.

```
std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;
```


Question: I'm opening several files , and want to add to my struct the creation time of the file and the  last write time. Is there a way I can do it?

Answer:
You can usefstatto read the last write time (seestat.st_mtime).

I'm not aware of a portable way to read creation time.  On Windows you could useGetFileTime


Question:
```
void func(char a, int num)
{
    printf("%c",a);
}

int main()
{
     func("a", 6); //not func('a',6);
     printf("\n");
     func("b", 2); //not func('b',6);
}
```

I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?

Answer: It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.


Question:
```
void func(char a, int num)
{
    printf("%c",a);
}

int main()
{
     func("a", 6); //not func('a',6);
     printf("\n");
     func("b", 2); //not func('b',6);
}
```

I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?

Answer: It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.


Question:
```
void func(char a, int num)
{
    printf("%c",a);
}

int main()
{
     func("a", 6); //not func('a',6);
     printf("\n");
     func("b", 2); //not func('b',6);
}
```

I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?

Answer: It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.


Question:
Does the C11 standard (note I don't mean C++11) allow you to declare variables at any place in a function?

The code below is not valid in ANSI C (C89, C90):

```
int main()
{
  printf("Hello world!");
  int a = 5; /* Error: all variables should be declared at the beginning of the function. */
  return 0;
}
```

Is it valid source code in C11?

Answer: Yes. This was already valid in C99 (see the second bullethere).


Question:
Does the C11 standard (note I don't mean C++11) allow you to declare variables at any place in a function?

The code below is not valid in ANSI C (C89, C90):

```
int main()
{
  printf("Hello world!");
  int a = 5; /* Error: all variables should be declared at the beginning of the function. */
  return 0;
}
```

Is it valid source code in C11?

Answer: Yes. This was already valid in C99 (see the second bullethere).


Question:
I want to declare character array and later want to fill it. But getting error:

```
char line[BUFSIZE+1];
strcpy(line,"Memory is Full", sizeof(line));
```

Error is:

```
wrong number of arguments in call to strcpy.
```

Is there any alternative to achive this?

Answer:
If you have it, usestrlcpy(). It does what you might expectstrncpy()to do.

Failing that, I would recommend usingsnprintf(), if you have it.


Question:
I want to declare character array and later want to fill it. But getting error:

```
char line[BUFSIZE+1];
strcpy(line,"Memory is Full", sizeof(line));
```

Error is:

```
wrong number of arguments in call to strcpy.
```

Is there any alternative to achive this?

Answer:
If you have it, usestrlcpy(). It does what you might expectstrncpy()to do.

Failing that, I would recommend usingsnprintf(), if you have it.


Question: Is there any way (or a useful function) to know whether interrupts are disabled or not?

Answer:
You can useirqs_disabled()function:

```
#include <linux/irqflags.h>

int i = irqs_disabled();
```


Question: Is there any way (or a useful function) to know whether interrupts are disabled or not?

Answer:
You can useirqs_disabled()function:

```
#include <linux/irqflags.h>

int i = irqs_disabled();
```


Question: I know that in winapi existReadFile()function for reading data from file, but I don't know how can I set the position of reading from file. Can I do this using WinAPI?

Answer: Yes, you can do that withSetFilePointerEx.  However, unless you have a good reason for using the raw WinAPI, it's generally a better idea to use a cross-platform I/O library, such as C's stdio library or C++'s iostream library.  That way, your code is portable to any platform.


Question:
Is there any way to identify if a buffer was allocated by 'malloc'? like a function with the following signature:

```
bool is_malloced(void *buf);
```

Does such a mechanism exist in posix?

Answer: Nope. Neither C11 nor POSIX provide any such mechanism.


Question:
I have the following code:

```
volatile unsigned int * address;
char * array="0x10000008";
```

Please tell me, what is a correct way of writing the "array" value to "address" variable?

Answer:
You could usesscanf:

```
#include <stdio.h>

sscanf(array, "%p", &address);
```

orstrtoull:

```
#include <stdlib.h>

address = (unsigned int *)strtoull(array, NULL, 0);
```


Question:
I have the following code:

```
volatile unsigned int * address;
char * array="0x10000008";
```

Please tell me, what is a correct way of writing the "array" value to "address" variable?

Answer:
You could usesscanf:

```
#include <stdio.h>

sscanf(array, "%p", &address);
```

orstrtoull:

```
#include <stdlib.h>

address = (unsigned int *)strtoull(array, NULL, 0);
```


Question:
I want to know howls -Rimplemented in C language.
Is it use the  recursion algorithm?

Answer:
"ls" (at least the implementations that I know of) usefts_open,fts_read... to traverse a file hierarchy. These are "non-recursive" methods which maintain a list of the visited directories internally.

Use "man fts_read" orhttp://linux.die.net/man/3/fts_readto get more information about these functions.


Question:
I want to know howls -Rimplemented in C language.
Is it use the  recursion algorithm?

Answer:
"ls" (at least the implementations that I know of) usefts_open,fts_read... to traverse a file hierarchy. These are "non-recursive" methods which maintain a list of the visited directories internally.

Use "man fts_read" orhttp://linux.die.net/man/3/fts_readto get more information about these functions.


Question:
How can I get a version of language C/C++(downloaded??) where the functions sound, nosound, delay are present in the library DOS.H?
For example it doesn't exist in the version c/c++ on code::blocks. What have I to do in order to use/find the functions sound/nosound/delay?
thank you for your help !

Answer: download (sigh) a copy of TurboC/TurboC++.


Question: Is it possible to verify the type and number of arguments supplied to a variable length argument?(...)?

Answer:
At runtime? The type, no. The number, only if the caller places a NULL (or something recognisable) at the end, which is unreliable.

At compile time, you can get the compiler to check the arguments in the same way that it will check the args to printf. Google for gcc __attribute__ format


Question: I write simple console functions and use freopen to redirect printf statements to a file. Can the output to the file be "turned off" and the printf outputs redirected back to the console window later in the code?

Answer:
fprintflets you to print to a specific file stream. For example,

```
fprintf(stdout, "message");
```

printmessagein the standard output (the console), so... as you see,printfis just an specialization offprintf.

I hope this help.


Question:
I see two option to assign a pointer

1.

```
int p=5;
int *r=&p
```

2.

```
int p
int *r;
r=&p;
```

Why do they use in 1 with asterisk
and in two without?

Answer:
You should read this:

```
int *r [...]
```

as:

```
(int *) r [...]
```

The type ofrisint *. If you look at it that way, you'll see that both versions are identical.


Question:
I need my program go to some specific directory then run

system( ... );there and get me back where I was before. How can I do it?

Answer:
Just do thecdin yoursystemcall:

```
system("cd wherever; command");
```

The whole string gets passed tosh(1), so you can do any normal shell things in there.  Since it's in a subshell, the working directory of your program won't be changed.


Question:
Is it guaranteed that this piece of code print always values from 0 to 15 on any platform?

```
#include <stdio.h>

typedef struct UI4{
    unsigned value: 4;
} ui4;

int main(void)
{
    ui4 u;

    u.value = 0;
    while (1) {
        printf("%u\n", u.value++);
    }
    return 0;
}
```

Answer: Yes, unsigned integer overflows are guaranteed to "wrap around" by the standard.


Question: What are the correct JNA mappings of the C types uint8_t and int8_t? Thank you!

Answer: The only 8-bit integer data type in Java isbyte, so you would use that. Unfortunately it is signed, souint8_tvalues over 127 will be seen as negative when converted into Javabyte. This is not really a problem because the stored bits are the same.


Question:
So I was looking at some c++ source code and wanted to know just what the heck this meant. I think it means call tmp as a function but I'm not sure.

```
char* tmp;
///stuff filling tmp with values
((void (*)())tmp)();
```

Answer:
Yes, it's castingtmpas pointer to a function that accepts no arguments and returns nothing, then calling it.

Looks like a recipe for disaster, if you ask me.


Question:
I am getting an error when trying to call the method:

```
int box(int rows, int cols, int [rows][cols])
```

from the main method using this call:

```
box(arrayDimensions, arrayDimensions, array);
```

But i am not sure what the problem is.

Thanks.

Answer:
```
int box(int rows, int cols, int [rows][cols])
```

needs to be

```
int box(int rows, int cols, int something[rows][cols])
```


Question: What are the correct JNA mappings of the C types uint8_t and int8_t? Thank you!

Answer: The only 8-bit integer data type in Java isbyte, so you would use that. Unfortunately it is signed, souint8_tvalues over 127 will be seen as negative when converted into Javabyte. This is not really a problem because the stored bits are the same.


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

Possible Duplicate:Postfix to Infix conversation

What would be the prefix notation of this expression? I can not solve this expression

```
6 a b 7 * + - c d g / + e ^ f * +
```

Any suggestion will be appreciated.

Answer:
The in-order expression will be

```
[6-(a + b*7)] + [(c + d/g) ^ e]*f
```

from that you can find the pre-order, which is
    + -6 + a * b 7 * ^ + c / d g e f


Question:
I find myself typing

```
double foo=1.0/sqrt(...);
```

a lot, and I've heard that modern processors have built-in inverse square root opcodes.

Is there a C or C++ standard library inverse square root function that

uses double precision floating point?is as accurate as1.0/sqrt(...)?is just as fast or faster than the result of1.0/sqrt(...)?

Answer: No. No, there isn't. Not in C++. Nope.


Question: I am using bool datatype in C std99 whose definitions are defined in<stdbool.h>. Now I want the user to give me input. What format specifier I must use in scanf to input the boolean value of 1 byte from the user and then manipulate it afterwards in my program.

Answer:
There is none.

Use a temp object as the size of_Boolis implementation dependent.

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

bool b;
int temp;

scanf("%d", &temp);
b = temp;
```


Question:
I find myself typing

```
double foo=1.0/sqrt(...);
```

a lot, and I've heard that modern processors have built-in inverse square root opcodes.

Is there a C or C++ standard library inverse square root function that

uses double precision floating point?is as accurate as1.0/sqrt(...)?is just as fast or faster than the result of1.0/sqrt(...)?

Answer: No. No, there isn't. Not in C++. Nope.


Question: I am using bool datatype in C std99 whose definitions are defined in<stdbool.h>. Now I want the user to give me input. What format specifier I must use in scanf to input the boolean value of 1 byte from the user and then manipulate it afterwards in my program.

Answer:
There is none.

Use a temp object as the size of_Boolis implementation dependent.

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

bool b;
int temp;

scanf("%d", &temp);
b = temp;
```


Question:
I get this error in a C header file in this line :

```
char * getFechaHora(time_t & tiempoPuro);
```

In a C source code file i am including the header file and giving the function an implementation

```
char * getFechaHora(time_t &tiempoPuro){...}
```

also in my header file i am including correctly the "time.h" library.

Answer:
```
char * getFechaHora(time_t & tiempoPuro);
```

This is not C. C has no reference (&).


Question:
I am using functiongetopt_longto get command line options.
I want to ignore error when a invalid option is given.
Currently it printing  error to stderr like:

```
invalid option -- 's'
```

Answer:
There's variableopterrin getopt.h which will avoid printing the the error tostderrif you set it to 0.

Just set it to 0:

```
extern int opterr;

opterr = 0;
```


Question:
I get this error in a C header file in this line :

```
char * getFechaHora(time_t & tiempoPuro);
```

In a C source code file i am including the header file and giving the function an implementation

```
char * getFechaHora(time_t &tiempoPuro){...}
```

also in my header file i am including correctly the "time.h" library.

Answer:
```
char * getFechaHora(time_t & tiempoPuro);
```

This is not C. C has no reference (&).


Question:
```
char* output= (char*) argv[2];
 92     fp = fopen(output, "w");
 93     if( fp = NULL )
 94     {
 95         printf("writing output failed");
 96         return 0;
 97     }
 98     fprintf(fp,"hello");
```

This is causing seg fault exc bad memory at line 98.
What am I missing??

Answer:
Your line

```
if( fp = NULL)
```

is assigning the value ofNULLtofp, instead of comparing.

You should be using

```
if( fp == NULL)
```


Question:
For example if my program name istest.c

Then for the following run command theargc = 2instead of4.

$test abc pqr* *xyz*

Answer:
Try to run:

```
$ echo abc pqr* *xyz*
```

and you will understand why you don't get theargcvalue you were expecting


Question:
I have this matrix:

```
1 2 3 4 5
6 7 8 9 A
B C D E F
0 1 2 3 4
```

And I want it printed in one line as following:

```
1 6 2 B 7 3 0 C 8 4 1 D 9 5 2 E A 3 F 4.
```

How is the easiest way to do that?

Answer:
use a nested loop.
outer loop is over the distance from (0,0)

inner loop over all valid combinations of i and j that sum up to the distance.


Question:
I wonder why when I try to declare the array using#defineI get errors from compiler, while using literal instead of the size allows me to do so.

some_name.h:

```
#define size 10;

int* waitingBench[size];
```

Answer:
What you have will be pre-processed to:

```
int* waitingBench[10;];
//                  ^ notice this guy!
```

Remove the semicolon from the#define.

(Andsizeis a really bad identifier to#define.)


Question: I have a program with 2 threads. I want the first thread to be run under user permissions of USER_1, and the second under USER_2 of Windows. When I log in as USER_1, both threads have USER_1 permissions. How can I change the user of the thread!?

Answer: You need to assign an impersonation token to a thread usingSetThreadToken(). It may not be very trivial to do, though.


Question:
Can somebody please explain to me why the below code got the "invalid operands to binary ==" error?

```
typedef int (*func_t)(int);
#define NO_FUNC ((func_t) 0)
struct {
    const char *name;
    func_t func;
} table[] = { {"func1", NO_FUNC} };

if (table[0] == NO_FUNC) { // invalid operands to binary ==

}
```

Answer:
And you should refer to the correct member in the struct:

```
if (table[0].func == NO_FUNC)
```


Question: I need to discover name of audio device by ID. I use WaveOut functions. please help me

Answer:
This is an example on how to enumerate waveIn and waveOut devices on your system:

http://blogs.msdn.com/b/matthew_van_eerde/archive/2012/03/13/sample-how-to-enumerate-wavein-and-waveout-devices-on-your-system.aspx

So, you can just compare dev id you need and get name of the device.


Question: I need to discover name of audio device by ID. I use WaveOut functions. please help me

Answer:
This is an example on how to enumerate waveIn and waveOut devices on your system:

http://blogs.msdn.com/b/matthew_van_eerde/archive/2012/03/13/sample-how-to-enumerate-wavein-and-waveout-devices-on-your-system.aspx

So, you can just compare dev id you need and get name of the device.


Question:
Is there a replacement forpiconst on OS X 10.8?

When I use it I get the following warning:

```
'pi' is deprecated: first deprecated on Mac OS X 10.8
```

It works but I want to get rid of that warning.

Answer: Try includingmath.h, which defines the C standard library macroM_PI.


Question:
Is there a replacement forpiconst on OS X 10.8?

When I use it I get the following warning:

```
'pi' is deprecated: first deprecated on Mac OS X 10.8
```

It works but I want to get rid of that warning.

Answer: Try includingmath.h, which defines the C standard library macroM_PI.


Question:
This question already has an answer here:Closed10 years ago.

Possible Duplicate:How would you convert from ASCII to Hex by character in C?

I like to convert a hex value, represented in ascii code to the number represented by the hex value.

As an example:

A5should convert to0xA5(which is 165)

ButA5is represented inASCII(so something like0x4135I guess)

Any ideas?
Thx!

Answer:
Usestrtol.

```
long x = strtol("A5", 0, 16)
// x is now 165
```


Question:
I'm having problems with applesexamplesfor vDSP. I tried all of them but i need the convolution sample in the end.
I can't even get it through the linker:

```
Undefined symbols for architecture i386:
  "_conv", referenced from:
      _ConvTiming in main.o
ld: symbol(s) not found for architecture i386
```

Is the error message (no matter what architecture i build for or).

Answer: You need to include the Accelerate framework in the build.


Question:
I have the followingcharinside an Arduino sketch:

```
char inData[80];
```

When I print to the serial console:

```
Serial.print(strlen(inData) - 1);
```

I'm expecting to see:79instead I see:655356553501234567

Can someone shed some light as to why this is happening?

Answer: strlenis looking for a terminating nul. Calling it on an uninitialized array or pointer results in undefined behavior. You wantsizeof(inData)instead.


Question:
How do I cut off decimal places in C without rounding?

For example if the number is4.48

it will just show4.4

%.1frounds to4.5

Answer:
You can (ab)use the fact that integer division truncates and doesn't round:

```
float original = 4.48;

int tmp = original * 10; // 44.8 truncated to 44

float truncated = tmp / 10.0; // 4.4
```


Question:
I have a code like:

```
int contains(LPCTSTR name)
{
   char * data = "test.txt";
}
```

How can i check whethernamecontains 'data'? Thanks!

Answer:
Since you are using Windows andTCHAR, a more idiomatic solution would be:

```
BOOL contains(LPCTSTR lpName) {
    return _tcsstr(name, _T("data"));
}
```

Unless yourdatais deliberately achar *, in which case the answer changes.


Question:
I have a string being moved and i want to print it based on the register.

I did the following:

```
gdb x $esp
0xbffff110:  "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267"

{then I copied the address}

>> x *0xbffff110
0x80485bc <__dso_handle+12>:     "test1"
```

Is there any way to do this in one step?

Answer:
Is there any way to do this in one step?

```
(gdb) print *(char**)$esp
```


Question:
I have a code like:

```
int contains(LPCTSTR name)
{
   char * data = "test.txt";
}
```

How can i check whethernamecontains 'data'? Thanks!

Answer:
Since you are using Windows andTCHAR, a more idiomatic solution would be:

```
BOOL contains(LPCTSTR lpName) {
    return _tcsstr(name, _T("data"));
}
```

Unless yourdatais deliberately achar *, in which case the answer changes.


Question:
I have a string being moved and i want to print it based on the register.

I did the following:

```
gdb x $esp
0xbffff110:  "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267"

{then I copied the address}

>> x *0xbffff110
0x80485bc <__dso_handle+12>:     "test1"
```

Is there any way to do this in one step?

Answer:
Is there any way to do this in one step?

```
(gdb) print *(char**)$esp
```


Question:
I have a string being moved and i want to print it based on the register.

I did the following:

```
gdb x $esp
0xbffff110:  "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267"

{then I copied the address}

>> x *0xbffff110
0x80485bc <__dso_handle+12>:     "test1"
```

Is there any way to do this in one step?

Answer:
Is there any way to do this in one step?

```
(gdb) print *(char**)$esp
```


Question: We found that C will compile the log function when used with magic numbers, but not with a variable.  Any ideas?

Answer:
Because you didn't link your program to the math library and with a literal your compiler is probably using a builtin function.

Withgccyou will get the same error with-fno-builtinwith a literal.

Link with lib math this way:gcc bla.c -o bla -lm


Question:
In C/C++, what's the difference between the following two line code:

```
char *str1="hello";
char *str2={"hello"};
```

Answer:
Per the 2011 C standard, clause 6.7.9 Initialization, paragraph 11: “The initializer for a scalar shall be a single expression, optionally enclosed in braces…”

That is it. There is no semantic difference; the braces simply may be present or may be absent, with no change to the meaning.


Question: I run into a code:printf("\tout:\t%-14.14s\n", (sprintf(tmpbuf[0], "[%s]", mystring), tmpbuf[0]));What does those sentence in () with sprintf mean?

Answer:
It is an expression involving the comma operator, to put the following into a single line:

```
sprintf(tmpbuf[0], "[%s]", mystring);
printf("\tout:\t%-14.14s\n", tmpbuf[0]);
```

The comma operator evaluates both arguments and returns its right argument, i.e.tmpbuf[0].


Question:
```
#define START ((void (**)(int)) 0x0fff)

*START = &fun_foo();
```

I haven't seen this before. What is happening here? Is void (**)(int) a function pointer?

Answer:
void (**)(int)is a pointer to a pointer to a function that takes anintand returns nothing.

SoSTARTis apointer to a function pointer, and*STARTis the actual function pointer which is set to point tofun_foo.


Question:
```
#define START ((void (**)(int)) 0x0fff)

*START = &fun_foo();
```

I haven't seen this before. What is happening here? Is void (**)(int) a function pointer?

Answer:
void (**)(int)is a pointer to a pointer to a function that takes anintand returns nothing.

SoSTARTis apointer to a function pointer, and*STARTis the actual function pointer which is set to point tofun_foo.


Question:
In JavaScript i would usually do..

```
var myObject = { "Name" : "Liam", "Address" : "UK"};
```

How do i make something similar in C?

Preferably something of the structure

```
myObject { CHAR : INT}
```

Answer:
```
struct myObj
{
 char* string;
 int num;
};
```

that's the most basic. you should learn c if you want to use this.


Question:
```
int age;
char name[10];

scanf("%d", &age);
scanf("%s", name);
```

In firstscanffunction we use'&'symbol before age, but in secondscanfwe don't use'&'as it is a char array. Can anybody tell me why is so?

Answer: Because the array is already passed as an address, whereas the integer variable is not (and thus explicitly needs its address passed via the&address-of operator).


Question: If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?

Answer:
Initialisers can be nested for nested structs, e.g.

```
typedef struct {
    int j;
} Foo;

typedef struct {
    int i;
    Foo f;
} Bar;

Bar b = { 0, { 0 } };
```


Question: Say I have two variables x and y, and I want to align the most significant 1s, how would I write this in C? For example, I have x=11 and y = 1011, and I want to align x with y by making it 1100. How could I do this?

Answer: Run aBitScanReverse(or appropriate intrinsic for you compiler, like__builtin_clzfor GCC), subtract the smaller from the larger and shift the smaller to the left by the difference.


Question: If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?

Answer:
Initialisers can be nested for nested structs, e.g.

```
typedef struct {
    int j;
} Foo;

typedef struct {
    int i;
    Foo f;
} Bar;

Bar b = { 0, { 0 } };
```


Question: Say I have two variables x and y, and I want to align the most significant 1s, how would I write this in C? For example, I have x=11 and y = 1011, and I want to align x with y by making it 1100. How could I do this?

Answer: Run aBitScanReverse(or appropriate intrinsic for you compiler, like__builtin_clzfor GCC), subtract the smaller from the larger and shift the smaller to the left by the difference.


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

Possible Duplicate:C String literals: Where do they go?

If I have the following code

```
char *str = "Tryout" ;
```

where is the string going to be stored? Stack? If stack, does the pointer point to a stack location then?

Answer: The string has a static storage class, (likely in read only data) andstris a local variable with automatic storage. This is why it is better declared asconst char *.


Question:
I have a linux based OS with a lot of system libraries compiled as static libraries.

How can I use such libraries in my application, andlinkthem to my final binary?

Answer: You use them as you do use shared libraries, except that you link against statically.An introduction to GCC - shared libraries and static librariesarticle will get you started.


Question: Is it possible to know the CPU usage of a running/idle process programatically (in any language) in Windows?

Answer:
If you don't care on support old Windows versions (earlier than Windows XP SP1) you could useGetSystemTimes Win32 API function.

Otherwise you have to usePerformance Counters.


Question:
How can I get the number of channels used by my video before initiating a capture?
I thought I could usecvGetCapturePropertybut there is no property_id I could set to get the number of channels.

Answer: Yes, you're right - there are noproperty_idfor number of channels. You can get number of channels only from single frame of capture.


Question:
I am currently building 3.1 kernel for android (tegra/goldfish branch). I would like to write a program in C that gets the sensor values. I do have inc/hardware/sensors.h and some relevant files but I keep getting an error when trying to open the sensor device.

Thanks

Answer: Take a look at the samples that are packed with the NDK,native-activityin particular.


Question: Is it possible to know the CPU usage of a running/idle process programatically (in any language) in Windows?

Answer:
If you don't care on support old Windows versions (earlier than Windows XP SP1) you could useGetSystemTimes Win32 API function.

Otherwise you have to usePerformance Counters.


Question:
How can I get the number of channels used by my video before initiating a capture?
I thought I could usecvGetCapturePropertybut there is no property_id I could set to get the number of channels.

Answer: Yes, you're right - there are noproperty_idfor number of channels. You can get number of channels only from single frame of capture.


Question:
I am currently building 3.1 kernel for android (tegra/goldfish branch). I would like to write a program in C that gets the sensor values. I do have inc/hardware/sensors.h and some relevant files but I keep getting an error when trying to open the sensor device.

Thanks

Answer: Take a look at the samples that are packed with the NDK,native-activityin particular.


Question:
I am looking for a way to know how much time will my C program use, preferably before I run it, but if this cannot be known before, then after it has ended.

Is there a way?

Answer:
After, yes. On most (all?) UNIX-y systems, you can use this:

```
time ./myprog
```

Before, no, because the program could depend on external input.The halting problemmight also be an obstacle to finding the amount of time a program would take to execute beforehand.


Question:
I am looking for a way to know how much time will my C program use, preferably before I run it, but if this cannot be known before, then after it has ended.

Is there a way?

Answer:
After, yes. On most (all?) UNIX-y systems, you can use this:

```
time ./myprog
```

Before, no, because the program could depend on external input.The halting problemmight also be an obstacle to finding the amount of time a program would take to execute beforehand.


Question:
i have a code like this:

```
int i = 123;
char myString[100];
strcpy(myString, "my text");
```

and how i want to add the 123 after "my text". how to do this in c/c++?

at the endmyStringsould bemy test123

Answer:
In C++:

```
std::stringstream ss;
ss << "my text" << i;
std::string resultingString = ss.str();
```

There's no such thing as C/C++.


Question:
Im new to Pro*C coding. is there any difference between VARCHAR and char? can i select a
VARCHAR data into an character array? will there be any side effects?

Answer: TheVARCHARis a special type added by the Pro*C pre-compiler, it doesn't exist in the base C language. However, in C you can access aVARCHARvariable as a structure if I'm not mistaken.


Question:
Im new to Pro*C coding. is there any difference between VARCHAR and char? can i select a
VARCHAR data into an character array? will there be any side effects?

Answer: TheVARCHARis a special type added by the Pro*C pre-compiler, it doesn't exist in the base C language. However, in C you can access aVARCHARvariable as a structure if I'm not mistaken.


Question: I'm trying toexecvea process that reads from stdin. I want to prepare stdin with some data so it can execute successfully. How can I do that?

Answer:
You will need to fork the execve call into a child process and then create a pipe from the parent process to the child's stdin.

Take a look at this link for a detailed example on how to use pipes:http://tldp.org/LDP/lpg/node11.html


Question:
How do I get the contents from one character buffer into another? For instance I have

```
char buffer[SMALLVALUE];
char new_buffer[BIGGERVALUE];
```

I'd like to copy the contents ofbufferintonew_buffer. What's the shortest way to do this?

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

memcpy(new_buffer, buffer, sizeof buffer);
```


Question:
Here is the thing,1024 = 0x400, and I assume its binary representation (little endian) is\\x00\\x4\\x00\\x00. And I try to do something like this,

```
int main()
{
    const char *str = "\\x00\\x4\\x00\\x00";
    const int *p = (const int *)str;
    printf("%d\n", *p);
}
```

But why the above code can't give me1024?

Answer:
Because you escaped\. Unescape them:

```
const char *str = "\x00\x4\x00\x00";
```


Question: Can anybody tell how to write a program which when compiled withgccprintsc, and withg++printsc++?

Answer:
```
#ifdef __cplusplus
    printf("c++\n");
#else
    printf("c\n");
#endif
```

You may run into issues if your file extension isn't right.


Question:
What is the order of evaluation in C in the case ofx<<y>>z? Is it(x<<y)>>z, because of the Left to Right associativity ?

EDITNeed to know what the standards tell about it, and not guess what's going on by inspection for a particular compiler.

Answer: Yes,>>and<<are left associative and of the same precedence, sox << y >> zis equivalent to(x << y) >> z.


Question:
moin-moin,

I need the MS Visual C (6.0) equivalent for the functions "DosEnterCritSec()" and "DosExitCritSec()", which garantees, that no two threads are executing the enclosed code at the same time.

Can anybody please point me into the right direction?

Thanks a lot,
Peter

Answer:
EnterCriticalSection() / LeaveCriticalSection()

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


Question:
I am having this problem whenever I try to debug my project:

It's in French, here is my translation:

"Error while trying to run project: Failed Loading assembly "DBZ buu's
  Fury Text Editor" or one of it's dependencies. The given assembly name
  or codebase was invalid. (Exception from HRESULT: 0x80131047)"

Can anyone help me please?

Answer: If you are usingAssembly.Load()to load file try to change it withAssembly.LoadFile()instead.


Question: I'm dealing with some code written in manner that is really, honestly, ugly. Is there a way to auto enforce proper tabs and remove all of the random multi-line white space entries?

Answer: Old Unix people have a solution for everything, including lazy programmers. EnterGNU indent.


Question: I am readingGoogletest doc, and I am learning that there is one syntax for comparing string, and another for comparing C string. I dont see what is referred to as C string and as string. How are these different?

Answer: If you try to useASSERT_EQto C-Strings, you only compare two pointers, but not really null-terminated C-Strings. For that existsASSERT_STREQsyntax.


Question: How can I check if a directory exists on Linux in C?

Answer:
You can useopendir()and check ifENOENT == errnoon failure:

```
#include <dirent.h>
#include <errno.h>

DIR* dir = opendir("mydir");
if (dir) {
    /* Directory exists. */
    closedir(dir);
} else if (ENOENT == errno) {
    /* Directory does not exist. */
} else {
    /* opendir() failed for some other reason. */
}
```


Question:
I want to convert an array ofuint8_tto auint32_tinNesC.

Does anyone know how I can do this?

Answer:
The solution that i were found is the use of the function :

```
void * memcpy ( void * destination, const void * source, size_t num );
```

There is also the function :

```
void * memset ( void * ptr, int value, size_t num );
```

In my code i use memcpy and it works fine. Thanks to all people that answer my question


Question:
How can I find all words with at least one non latin letter (arabic, chinese...) in them using regex.h library?

cityدبي

Answer:
How about:

```
(?=\pL)(?![a-zA-Z])
```

This will match a letter in any alphabet that is not a latin letter:

```
not ok - cityدبي
ok - city
not ok - دبي
```


Question: Are there any generally-applicable tips to reduce the accumulation of floating-point roundoff errors in C or C++?  I'm thinking mainly about how to write code that gets compiled into optimal assembly language instructions, although strategies on overall algorithm design are also welcome.

Answer: Numerical analysisis a whole field of mathematics and it isn't reduced to some tips one can apply blindly.


Question:
I want to convert an array ofuint8_tto auint32_tinNesC.

Does anyone know how I can do this?

Answer:
The solution that i were found is the use of the function :

```
void * memcpy ( void * destination, const void * source, size_t num );
```

There is also the function :

```
void * memset ( void * ptr, int value, size_t num );
```

In my code i use memcpy and it works fine. Thanks to all people that answer my question


Question:
How can I find all words with at least one non latin letter (arabic, chinese...) in them using regex.h library?

cityدبي

Answer:
How about:

```
(?=\pL)(?![a-zA-Z])
```

This will match a letter in any alphabet that is not a latin letter:

```
not ok - cityدبي
ok - city
not ok - دبي
```


Question: Are there any generally-applicable tips to reduce the accumulation of floating-point roundoff errors in C or C++?  I'm thinking mainly about how to write code that gets compiled into optimal assembly language instructions, although strategies on overall algorithm design are also welcome.

Answer: Numerical analysisis a whole field of mathematics and it isn't reduced to some tips one can apply blindly.


Question:
I have something like this:

```
DIR *dir = opendir(curdir);
struct dirent *de = readdir(dir);
struc stat st;
lstat(de->d_name, &st);
```

I would like to know ifdeis a directory or a file, what should I do with st?

Answer:
The correct and simple way is to checkif (de->d_type == DT_DIR).
You don't have to uselstatfor that.


Question:
I have something like this:

```
DIR *dir = opendir(curdir);
struct dirent *de = readdir(dir);
struc stat st;
lstat(de->d_name, &st);
```

I would like to know ifdeis a directory or a file, what should I do with st?

Answer:
The correct and simple way is to checkif (de->d_type == DT_DIR).
You don't have to uselstatfor that.


Question:
Having a C or C++ source code how i can convert those statements in x86 and ARM assembly?
And with that i mean a plain text file containing assembly written source code from my C/C++ equivalent source code.

edit:

i use GCC/CNU toolchains

Answer:
You will need a cross compiler that can do both then just use

```
g++ -S [Plus all you other switch's and cross compile ones]
```

This will save the intermediate assembler for you


Question:
I saw this one in one of the .h files provided by my professor for a project, but I'm  not too sure what this means.

```
int (*get_console_dev)(void);
```

Is it the same as

```
(int*) get_console_dev(void);
```

(a function named get_console_dev, which returns a pointer to anint?)

Thanks

Answer: It's a function pointer that can point to a function returningintand taking 0 parameters; it's not equivalent to the second line you posted.


Question:
Having a C or C++ source code how i can convert those statements in x86 and ARM assembly?
And with that i mean a plain text file containing assembly written source code from my C/C++ equivalent source code.

edit:

i use GCC/CNU toolchains

Answer:
You will need a cross compiler that can do both then just use

```
g++ -S [Plus all you other switch's and cross compile ones]
```

This will save the intermediate assembler for you


Question:
I saw this one in one of the .h files provided by my professor for a project, but I'm  not too sure what this means.

```
int (*get_console_dev)(void);
```

Is it the same as

```
(int*) get_console_dev(void);
```

(a function named get_console_dev, which returns a pointer to anint?)

Thanks

Answer: It's a function pointer that can point to a function returningintand taking 0 parameters; it's not equivalent to the second line you posted.


Question:
In C the following is valid code:

```
if ((a, a+b, a*b) >= 0) {
    ....
}
```

Does the(a, a+b, a*b)part have a special name?

Answer:
x, yis called a comma expression.

,is called the comma operator in C and(x, y, z)is the same as((x, y), z).

It must not be confused with the comma that separates function arguments and which is not the comma operator.


Question:
In C the following is valid code:

```
if ((a, a+b, a*b) >= 0) {
    ....
}
```

Does the(a, a+b, a*b)part have a special name?

Answer:
x, yis called a comma expression.

,is called the comma operator in C and(x, y, z)is the same as((x, y), z).

It must not be confused with the comma that separates function arguments and which is not the comma operator.


Question:
This question already has answers here:What is the easiest way to make a C++ program crash?(31 answers)Closed9 years ago.

I'm trying to set up the way my server handles core dumps. In order to test it, I'd need a program that always segfaults.

Is there a simple example program that always segfaults?

Answer: main() { *(int *)0xdeadbeef = 37; }should do it.


Question:
This question already has answers here:What is the easiest way to make a C++ program crash?(31 answers)Closed9 years ago.

I'm trying to set up the way my server handles core dumps. In order to test it, I'd need a program that always segfaults.

Is there a simple example program that always segfaults?

Answer: main() { *(int *)0xdeadbeef = 37; }should do it.


Question:
This question already has answers here:What is the easiest way to make a C++ program crash?(31 answers)Closed9 years ago.

I'm trying to set up the way my server handles core dumps. In order to test it, I'd need a program that always segfaults.

Is there a simple example program that always segfaults?

Answer: main() { *(int *)0xdeadbeef = 37; }should do it.


Question: I have an animated png that I want to load in my MFC project to show it animated. I need this because it's a loading animation, and I would love to know how to do it. Would love if you can tell me how this works for png files.

Answer:
Maybe this is what you want:

http://www.codeproject.com/Articles/1427/Add-GIF-animation-to-your-MFC-and-ATL-projects-wit


Question:
I have a MFC Dialog Application. I add a Edit Control in the Dialog and turn the autoSuggestion on by using following code

```
SHAutoComplete(txtPath.m_hWnd, SHACF_FILESYS_DIRS);
```

things work fine. But when I Scroll the Suggestion list and press Enter, The list does not close. How Can I do this? Thanks

Answer: Take a lookhere: How To Use the ENTER Key from Edit Controls in a Dialog Box


Question:
I have a MFC Dialog Application. I add a Edit Control in the Dialog and turn the autoSuggestion on by using following code

```
SHAutoComplete(txtPath.m_hWnd, SHACF_FILESYS_DIRS);
```

things work fine. But when I Scroll the Suggestion list and press Enter, The list does not close. How Can I do this? Thanks

Answer: Take a lookhere: How To Use the ENTER Key from Edit Controls in a Dialog Box


Question: How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?

Answer: Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.


Question: How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?

Answer: Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.


Question: How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?

Answer: Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.


Question:
I want to find "\r\n\r\n" in a HTTP header.
I know it's at the end of the packet, so if I reverse search "\r\n\r\n" I'll get good performance.

Is there a  function implement reverse search in C or C++ ?
If so, which one?
Thanks.

Answer: Reverse searching for "\r\n\r\n" might give you wrong result. It is not correct logic, because the HTTP body might contain "\r\n\r\n".


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

Possible Duplicate:2GB limit on file size when using fwrite in C?

I realized that for my C compiler, the fread function can only correctly read a file smaller than 2GB (2147483648). I am wondering whether we could read >2GB file at all. Thanks

Answer: You need to compile withlarge file support.  Alternatively, on some platforms you can usefopen64.


Question:
I have achar buf[3];array where I need to put:buf[0] = chwherechis anint. But the compiler give the following warning:

conversion to ‘char’ from ‘int’ may alter its value

How do I remove this? I tried cast tounsigned charbut no luck.

Answer:
Use an explicit cast:

```
buf[0] = (char)ch;
```


Question: In GNU-GCC with Linux this is working#define sprintfc(string, ...) sprintf(string+strlen(string), ##__VA_ARGS__)Is there definition with same effect for Visual Studio 2010?

Answer:
Microsoft Visual C compilerdoes support variadic macros. However, the problem isthe GCC extension ##, which removes the leading comma if no arguments are passed.

Because sprintf() is never called without a second argument, your code should work fine if you just remove the ##.


Question:
Where can we write code like

```
struct Foo
{
    int bar;
    int baz;
} foo()
{

}
```

C89/C90? C99? C11? Or maybe it's K&R only?

And what about this

```
void foo(bar, baz)
int bar;
int baz;
{
}
```

Answer: It's standard since C89. In K&R C, it was not possible to return structs, only pointers to structs.


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

Possible Duplicate:Writing GUI applicatins on Mac OS X with c++

I am looking for an easy to use program/framework for making c++ GUI on a mac.

Answer:
Qt is a very popular C++ GUI framework that targets Mac (and Windows and Linux and mobile)

http://qt.nokia.com/


Question:
I use to define multi-line stuff, something like a help message, like this:

```
#define HELP_MSG "blabla\r\n" \
                 "Some other line"
```

Is there a way that I can avoid putting "\r\n" here, since I already have it defined in multiple line.

Answer: No,\is merely used as a linecontinuationmarker. If you need a line break, you need to include it explicitly in the string, as you're doing.


Question:
I have the following code. Why its undefined to derefrence union pointers in the following way ?

```
extern union MyUn *P1;
extern union MyUn *P2;

extern void myfunc(void)
{
      *P1 = *P2;
}
```

Answer:
If you haven't also defined the union in this source file, the compiler doesn't know how much to copy.

What is the size of the union?


Question: Why if I callRSA_size()on an RSA object do I obtain a value less than the return value ofi2d_RSAPublicKey(the size of the public key) called on the same RSA object?

Answer:
Becausei2d_RSAPublicKeygives you a PKCS#1 encoded version of the key, including public exponent and DER elements.

RSA_size()gives you just the size in bytes of the pure modulus (which is also the size of any unencoded signature or ciphertext for that key).


Question:
Does ~0 mean its flipping 000000000 to 1111111111?

```
printf("Check: %i", ~0);
```

The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?

Answer:
Does ~0 mean its flipping 000000000 to 1111111111?

Yes, it does.

Does -1 essentially mean the same thing as 11111111111111111 bits?

In2s complementrepresentation, it does.


Question: Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?

Answer:
No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code.

It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.


Question:
I use to define multi-line stuff, something like a help message, like this:

```
#define HELP_MSG "blabla\r\n" \
                 "Some other line"
```

Is there a way that I can avoid putting "\r\n" here, since I already have it defined in multiple line.

Answer: No,\is merely used as a linecontinuationmarker. If you need a line break, you need to include it explicitly in the string, as you're doing.


Question:
I have the following code. Why its undefined to derefrence union pointers in the following way ?

```
extern union MyUn *P1;
extern union MyUn *P2;

extern void myfunc(void)
{
      *P1 = *P2;
}
```

Answer:
If you haven't also defined the union in this source file, the compiler doesn't know how much to copy.

What is the size of the union?


Question: Why if I callRSA_size()on an RSA object do I obtain a value less than the return value ofi2d_RSAPublicKey(the size of the public key) called on the same RSA object?

Answer:
Becausei2d_RSAPublicKeygives you a PKCS#1 encoded version of the key, including public exponent and DER elements.

RSA_size()gives you just the size in bytes of the pure modulus (which is also the size of any unencoded signature or ciphertext for that key).


Question:
Does ~0 mean its flipping 000000000 to 1111111111?

```
printf("Check: %i", ~0);
```

The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?

Answer:
Does ~0 mean its flipping 000000000 to 1111111111?

Yes, it does.

Does -1 essentially mean the same thing as 11111111111111111 bits?

In2s complementrepresentation, it does.


Question: Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?

Answer:
No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code.

It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.


Question:
Does ~0 mean its flipping 000000000 to 1111111111?

```
printf("Check: %i", ~0);
```

The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?

Answer:
Does ~0 mean its flipping 000000000 to 1111111111?

Yes, it does.

Does -1 essentially mean the same thing as 11111111111111111 bits?

In2s complementrepresentation, it does.


Question: Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?

Answer:
No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code.

It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.


Question: Has any C guru ever implemented a Epoll Non-blocking selector in C that I can call from Java so I don't have to use Java's NIO Epoll implementation?

Answer: You can find epoll sample program written in C by me. I hope that will help youCould you recommend some guides about Epoll on Linux