Question:
I want an equivalent forprintf("%2.2x", var);tocerr<<in C++.code:

```
typedef unsigned char byte;
static byte var[10];
for(i=1; i<10; i++)
   printf("%2.2x", var[i]);
```

The idea is to redirect the debugging to a file like this:./myprog 2>out.txt.If I don't ask too much I would like to receive explanations too.Thanks!

Answer:
Usefprintf(stderr, ...), e.g.:

```
fprintf(stderr, "%2.2x", var[i]);
```


Question: I installed a windows service with cygwin cygrunsrv. That service is writing something to a file every 5 seconds. After I tried it, I removed service with "cygrunserv -R service_name". Now, service is removed from services list but it is still running. How can I remove it for real.

Answer: Restarting Windows is solving that issue.


Question:
I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace withistringtreamand bysingle delimiterwithgetline. How can I connect them all.

For instance:

input:This -is-a!,string;output:

```
This
is
a
string
```

Answer: Why not just#include <cstring>and usestd::strtok()in your C++ program?


Question: I installed a windows service with cygwin cygrunsrv. That service is writing something to a file every 5 seconds. After I tried it, I removed service with "cygrunserv -R service_name". Now, service is removed from services list but it is still running. How can I remove it for real.

Answer: Restarting Windows is solving that issue.


Question:
I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace withistringtreamand bysingle delimiterwithgetline. How can I connect them all.

For instance:

input:This -is-a!,string;output:

```
This
is
a
string
```

Answer: Why not just#include <cstring>and usestd::strtok()in your C++ program?


Question:
I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace withistringtreamand bysingle delimiterwithgetline. How can I connect them all.

For instance:

input:This -is-a!,string;output:

```
This
is
a
string
```

Answer: Why not just#include <cstring>and usestd::strtok()in your C++ program?


Question:
What would be an alternative for Microsoft C++ compiler's#importdirective in a C (notC++) source code?

Are there any tools which automatically produce C interfaces from a given type library?

Answer: The closest I know is using the OLE/COM object viewer (OLEVIEW.EXE) to get part of the IDL back, correcting a few missing things, and then running that through MIDL again.


Question:
Is it possible to write a message on assert error?

For example, using#include <assert.h>, I can only write:

```
void foo(int a, int b) {
  assert (a != b);
}
```

However, on an error I want to see the value ofaandb. How can I do that?

Answer: I usually simply useassert(a != b && "This is my error message"). This works becausechar*can be converted to bool and that it never will be false (since the address is not 0).


Question:
What would be an alternative for Microsoft C++ compiler's#importdirective in a C (notC++) source code?

Are there any tools which automatically produce C interfaces from a given type library?

Answer: The closest I know is using the OLE/COM object viewer (OLEVIEW.EXE) to get part of the IDL back, correcting a few missing things, and then running that through MIDL again.


Question:
Is it possible to write a message on assert error?

For example, using#include <assert.h>, I can only write:

```
void foo(int a, int b) {
  assert (a != b);
}
```

However, on an error I want to see the value ofaandb. How can I do that?

Answer: I usually simply useassert(a != b && "This is my error message"). This works becausechar*can be converted to bool and that it never will be false (since the address is not 0).


Question:
I want to know if there is a way to read date from console in format dd.mm.yyyy in C. I have a structure with information for the date. I tried with another structure just for the date with  day, month and year in it:

```
typedef struct
{
    int day;
    int month;
    int year;
} Date;
```

but the dots are a problem. Any idea?

Answer:
Try:

```
Date d;
  if (scanf("%d.%d.%d", &d.day, &d.month, &d.year) != 3)
    error();
```


Question:
Considering the following definition:

```
struct
{
    int x;
    int y;
} point;

void main()
{
    ...
}
```

You're declaring the variable "point" of "anonymous struct" type, is there any way to declare another variable of the same type outside the struct definition (maybe in main function)?

Answer: No, there isn't, at least not in standard C. If you want to use the type, you have to give it a name.


Question: I want to get the IP address of the client who’s just connected into my server running WinSock2. I’m using C.

Answer:
You could get the client's IP-address and port via the call toaccept().

Just pass in the appropriate data into the last two parameters.

```
struct sockaddr_in sa = {0}; /* for TCP/IP */
socklen_t socklen = sizeof sa;
... = accept(..., (struct sockaddr *) &sa, &socklen);
```

For detailsplease read here.


Question: I am studying the FAT32 manual, now i want to write a program to browse the device. How to read a specific sector of the device, i do not want to load the entire device as a file into memory, please suggest some system call's to get started.

Answer: Find the block device in/dev/, then your system calls areopen,lseek, andread. Higher level stuff likefopen,fseek, andfreadwill work too.Everything is a file.


Question: I am studying the FAT32 manual, now i want to write a program to browse the device. How to read a specific sector of the device, i do not want to load the entire device as a file into memory, please suggest some system call's to get started.

Answer: Find the block device in/dev/, then your system calls areopen,lseek, andread. Higher level stuff likefopen,fseek, andfreadwill work too.Everything is a file.


Question:
This question already has answers here:Accessing arrays by index[array] in C and C++(2 answers)Closed10 years ago.

I am dealing pointers in c and when i run the following code i get "l" as the output! Why?

```
char *s = "Hello, World!";
 printf("%c", 2[s]);
```

What does 2[s] signify?

Answer:
2[s]is same ass[2]because compiler convert both into*(2 + s)

here is a good link for you:why are both index[array] and array[index] valid in C?


Question:
The PIC is a16F630

```
#FUSES NOWDT, INTRC_IO, PROTECT, NOBROWNOUT, MCLR, CPD, NOPUT
#use delay(clock=4000000)
#use fast_io(A)
```

later, in a function:

```
#asm   nop nop nop nop nop   #endasm
```

Which C compiler could have been used to compile this code?

Answer:
Looks like theCCS PIC MCU C compiler.

As you can see at the link its pre-processor supports#FUSES,#USE,#ASMand#ENDASM.


Question: What's the simplest way to copy the unix file permissions of a file and set them to another file? Is there a way to store a file's permissions to a variable and then use that variable to set those permissions to another file?

Answer:
Sure. Usestat()andchmod()(may need root).

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

struct stat st;
stat("/foo/bar.txt", &st);
chmod("/baz/quirk.jpg", st.st_mode);
```


Question:
In Dennis Ritchie I found this,

```
struct rect r , *rp = r;
```

then these four expressions are equivalent :

r.pt1.xrp->pt1.x(r.pt1).x(rp->pt1).x

because operators associate left to right.Shouldn't it be struct rect *rp = &r?

Answer:
Absolutely -- the address operator is required,otherwise you get a compile-time error:

```
incompatible types when initializing type ‘struct rect *’ using type ‘struct rect’
```


Question: Is it possible to check which db2 code page is used in communication between ODBC connector and db2 database from c program using ODBC api?

Answer:
It's indicated by the connection attribute SQL_ATTR_CLIENT_CODEPAGE.

Here's the function to obtain it:SQLGetConnectAttr


Question:
What does a number argument inprintfwithout quotes do?

e.g.printf( 3 + "goodbye");results in output dbye.  Why do I get this output?

Answer: 3 + "goodbye"is equivalent to&"goodbye"[3]- in other words it's just a pointer to the fourth element of "goodbye" and so your example will print "dbye".


Question:
What does a number argument inprintfwithout quotes do?

e.g.printf( 3 + "goodbye");results in output dbye.  Why do I get this output?

Answer: 3 + "goodbye"is equivalent to&"goodbye"[3]- in other words it's just a pointer to the fourth element of "goodbye" and so your example will print "dbye".


Question:
What does a number argument inprintfwithout quotes do?

e.g.printf( 3 + "goodbye");results in output dbye.  Why do I get this output?

Answer: 3 + "goodbye"is equivalent to&"goodbye"[3]- in other words it's just a pointer to the fourth element of "goodbye" and so your example will print "dbye".


Question:
In all of the gtk examples I've read, callbacks are always static functions. I think I remember reading somewhere that there is a reason for that, but I can't find it now.

Must GTK callback functions be static? How come? What would go wrong if I defined them in a different control unit?

Answer: No. Nothing bad will happen if you make your callback functions not static.


Question:
```
printf("Hello%cWorld\n", '\r');
```

Outputs:

```
World
```

Because'\r'moves the cursor to the beginning of the line

Can I trust that all terminals have this behavior?

Answer: lib curses will tell you the capabilities of your terminal.


Question:
```
printf("Hello%cWorld\n", '\r');
```

Outputs:

```
World
```

Because'\r'moves the cursor to the beginning of the line

Can I trust that all terminals have this behavior?

Answer: lib curses will tell you the capabilities of your terminal.


Question:
Is there any C function to check if string s2 exists in s1?

s1: "CN1 CN2 CN3"
s2: "CN2"  or  "CG2"

s1 is fixed, and I want to check whether variants of s2 exists in s1 or not.

I am using C not C++.

Answer:
You can usestrstr:

```
#include <string.h>

if (strstr(s1, s2) != NULL)
{
    // s2 exists in s1
}
```


Question:
This question already has answers here:What does an assignment return?(5 answers)Closed4 years ago.

In the following code:

```
int c;
while((c=10)>0)
```

What doesc = 10evaluate to? Is it 1 which indicates that the value 10 is assigned to variable c successfully, or is it 10? Why?

Answer: c = 10 is an expression returning 10 which also assigns 10 to c.


Question:
I tried

```
printf("%s %15s", string1, string2);
```

and I found out that this kind of left padding depends the distance from the first string, what if I want an absolute left padding counting from the left most?

Answer:
You want to pad the first string on the right,  instead of padding the second sting on the left:

```
printf("%-15s %s",string1,string2);
```


Question:
the assert() function can print the error and where the error happens, but it will also abort the function.

I want to have a assert() function without aborting. I only hope to print the error, the name of the file where error happens, etc.

is there such a API or source snippets in C?

thanks!

Answer:
Cunit has an assert that will either be fatal (quits) or not (will continue).

http://cunit.sourceforge.net/doc/writing_tests.html#tests


Question:
Is there a stable and portable way to make use of PostGIS-functions in my own PostgreSQL extension?
I would like to process the geometry type with functions like intersects in my c code by directly calling this functions from the postgis-$version.so (in PostgreSQL's $libdir).

Answer:
You should generally do this by invoking the SQL-level PostGIS functions via either theSPIor viafmgrfast-path calls.

Seethis related question about using hstore from C.


Question: I'm making a wrapper for a C library. There is a method that changes 2 ints by the user giving 2 int pointers to the method. So if I havevoid changenums(int* a, int* b)what is a safe way to access this method in c#?

Answer:
Declare the p/invoke like this:

```
[DllImport(@"mydll.dll")]
static extern void changenums(ref int a, ref int b);
```

And call it like this:

```
int a = 0;
int b = 0;
changenums(ref a, ref b);
```


Question: I'm making a wrapper for a C library. There is a method that changes 2 ints by the user giving 2 int pointers to the method. So if I havevoid changenums(int* a, int* b)what is a safe way to access this method in c#?

Answer:
Declare the p/invoke like this:

```
[DllImport(@"mydll.dll")]
static extern void changenums(ref int a, ref int b);
```

And call it like this:

```
int a = 0;
int b = 0;
changenums(ref a, ref b);
```


Question: I'm making a wrapper for a C library. There is a method that changes 2 ints by the user giving 2 int pointers to the method. So if I havevoid changenums(int* a, int* b)what is a safe way to access this method in c#?

Answer:
Declare the p/invoke like this:

```
[DllImport(@"mydll.dll")]
static extern void changenums(ref int a, ref int b);
```

And call it like this:

```
int a = 0;
int b = 0;
changenums(ref a, ref b);
```


Question:
Simple code, eg:

```
void* print_my_address() {
    printf("%p\n", .../* get the execution address of print_my_address */)
}
```

Thanks!

PS: gcc v4.7
Can I get the address by compiler?

Answer:
The same way you'd do it for any other regular variable:

```
void print_my_address()
{
    printf("%p\n", &print_my_address);
}
```


Question:
char label[10] = "Me"works, and to change the value oflabel, I'd have to do something like:

```
char * temp = "Not Me";
strcpy(label,temp);
```

My question is why is this invalid?

```
char label[] = "Me";
label = "Not me";
```

Answer: Because arrays are not assignable. You can create them, you can change theircontent, but the array itself cannot be modified to refer to a new chunk of memory.


Question:
I am running a C program using DEVC++ and CodeBlocks in Windows and the code is not updating.
I just added a single printf message and it is not shown in the output.
I tried clean,rebuild,recompile, everything.

Please tell me what's going wrong.

Answer:
Try adding a newline to your printf. Sometimes (with certain compilers), the output isn't flushed to screen until a newline is printed.

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


Question:
I need to make a function using just~and|,
such that functionf(6, 5)will return4as the answer.

Answer: By De Morgan's law,~(a | b)equals~a & ~b. By the same law,a & bequals~(~a | ~b).


Question:
I need to make a function using just~and|,
such that functionf(6, 5)will return4as the answer.

Answer: By De Morgan's law,~(a | b)equals~a & ~b. By the same law,a & bequals~(~a | ~b).


Question:
I have a simple Opengl programm where I draw triangles by calling glVertex3f and the mode GL_LINE_LOOP

here's what I get:

You can see in the square that apparently some triangles that are at the base of my model (in blue) are drawn above what is in the foreground.

Do you know what is causing it? Is there a way to avoid it?

Answer:
gluPerspective(60., Width/Height,0,1000);

The near-z cannot be 0 or less. It must be a positive number greater than zero.


Question:
I am working with eclipse, jni, c, CentOS6.

I really want to see some logs from C code, but in eclipse console, it does not show printf Message which happens in C.

Is there any way to print C logs in eclipse console?

Answer: @Ozan Deniz  Thanks for sharing your knowledges. to summarize that link, eclipse has C console problem itself. so if someone print C msg in eclipse console, has to use fprintf(stderr, "")... Thanks again.


Question:
I am working with eclipse, jni, c, CentOS6.

I really want to see some logs from C code, but in eclipse console, it does not show printf Message which happens in C.

Is there any way to print C logs in eclipse console?

Answer: @Ozan Deniz  Thanks for sharing your knowledges. to summarize that link, eclipse has C console problem itself. so if someone print C msg in eclipse console, has to use fprintf(stderr, "")... Thanks again.


Question: I have not been able to find any information with a web-search. Where should I be looking?

Answer:
```
char myString[256]; // Input string
char dest[256];     // Destination string

strncpy(dest, myString, 10);
dest[10] = 0; // null terminate destination
```


Question:
ARCforbidsObjective-Cobjects instructs orunions.

Unless you add__unsafe_unretainedwhich means its not managed.

I was wonder what people are using in place ofstructs now if anything?

Or are you retaining everything manually?

Answer: It's very simple - if you want to add an object inside a struct, you are doing it wrong. Whenever you need a struct to hold an obj-c object, convert the struct into an obj-c object.


Question:
(UNIX) I have 2 programs in C in which I use a named pipe (created by mkpipe, fopen etc.) to communicate. There is one writer and multiple readers for that pipe.
Is there any way to set a maximum possible number of readers, in writer's code?

Answer: No there is no such way to do that.


Question:
I am using C.

Say I have a pointer to a integer called *myptr

int *myptr;

What would then be the difference between:

```
*myptr++
```

and...

```
*(myptr++)
```

Thanks
Dan

Answer: Since++has higher precedence than*, there isno differencebetween the two.


Question:
I am using C.

Say I have a pointer to a integer called *myptr

int *myptr;

What would then be the difference between:

```
*myptr++
```

and...

```
*(myptr++)
```

Thanks
Dan

Answer: Since++has higher precedence than*, there isno differencebetween the two.


Question: In windows I can callLogonUserWor on linuxpam_authenticateto check whether a given username/password is correct. How do I do this on OS X (for c/c++)?

Answer:
Take a look atthis:

PAM is a pluggable authentication and authorization library for *nix
  based systems – think Linux, FreeBSD and evenMac OS X....


Question: This is more just a question of interest - I'm not sure how it would actually be applicable. Anyways - is it possible using bit-checks to see if a number is equal to 1?

Answer: I am not sure what exactly the questions is, but you can use either!(x ^ 1)orx == 1or!(x-1)or(x & 1) && !(x & ~1)or one of many other ways.


Question: This is more just a question of interest - I'm not sure how it would actually be applicable. Anyways - is it possible using bit-checks to see if a number is equal to 1?

Answer: I am not sure what exactly the questions is, but you can use either!(x ^ 1)orx == 1or!(x-1)or(x & 1) && !(x & ~1)or one of many other ways.


Question: I am creating an alarm clock for my project in C. I am using mgp123 command(in package mpg321) to run the alarm sound. It is only for UBUNTU users.I need the program to check whether mpg321 is installed or not. How can i find using C if the package mpg321 is installed using C program?

Answer:
you can usesystem()

```
system("mpg321 -h");
```

if the command return error than thempg321is not installed


Question: I want to translate my GTK+ application written in C++. I don not have any ideas where to start, I heard about gettext(), but I don't know, how should I use it.

Answer: Take a look athttps://developer.gnome.org/gtk3/stable/gtk-question-index.htmlpage, in 1.7. paragraph they explain how you can translate your applications usingGNU gettext.


Question:
I can't find out why crt0.o or crt1.o are not provided for i386 targets by newlib as it is the case for powerpc, arm, etc. targets.

ld requires it (and so do I to call static constructors).

Answer: Question directly asked on newlib's mailing list:http://sourceware-org.1504.n7.nabble.com/Question-i386-s-crt0-tp229290p229999.html


Question:
```
Display *display;
display = XOpenDisplay(NULL);
Window window;
XGetInputFocus(display, &window, RevertToNone);
```

in XGetInputFocus segmentation fault happen; anything wrong ?
(program compile with xlib and don't any problem with compiling)

Answer: int revert; XGetInputFocus(display, &window, &revert);should fix it.


Question:
```
Display *display;
display = XOpenDisplay(NULL);
Window window;
XGetInputFocus(display, &window, RevertToNone);
```

in XGetInputFocus segmentation fault happen; anything wrong ?
(program compile with xlib and don't any problem with compiling)

Answer: int revert; XGetInputFocus(display, &window, &revert);should fix it.


Question:
I am getting some errors. Any clues where I am going wrong? I think I am applying the right logic.

```
int* adderFunction(int a, int b)
{
    int result;
    int *pResult;
    pResult = &result;
    result = a + b;
    return (pResult);
}
```

Answer: No. You are trying to return pointer on local variable, which is destructed after return from function.


Question:
What are the equivalent for java byte in C,C++

```
byte[]  itemsArray;
itemsArray = new byte[items *no];
itemsArray[x] = (byte) xyz;

unsigned char * itemsArray;
itemsArray = (unsigned char*) malloc (items*no);
```

How to assign bytes toitemsArray(likeitemsArray[x] = (byte) xyz) in C++ with endianess to ensure the proper byteorder.

Are the above things equivalent to byteArray in C ?

Answer: Usememcpy()to copy buffers between memories inC.


Question: I am trying to disable sse and sse2 instructions. I am cross compiling for x86 in a x64 system. I am also using -static to statically link with libc. Although I use -mno-sse and -mno-sse2, when I disassemble the binary I still see a call to strcpy_sse2, any solution?

Answer: For 64 bit Use -mno-sse gcc option


Question: I am trying to disable sse and sse2 instructions. I am cross compiling for x86 in a x64 system. I am also using -static to statically link with libc. Although I use -mno-sse and -mno-sse2, when I disassemble the binary I still see a call to strcpy_sse2, any solution?

Answer: For 64 bit Use -mno-sse gcc option


Question:
I have a program that need to read one line from file everytime when it receives a signal SIGUSR2. I made everything except how to read exactly one line.

The content of the file:

```
one
two
three
four
five
...
ten
```

Answer: usefgets()function....it will read until newline come...or else u can read one char by one char by using fgetc  when u get /n then u can end ur operation of reading


Question:
I have a program that need to read one line from file everytime when it receives a signal SIGUSR2. I made everything except how to read exactly one line.

The content of the file:

```
one
two
three
four
five
...
ten
```

Answer: usefgets()function....it will read until newline come...or else u can read one char by one char by using fgetc  when u get /n then u can end ur operation of reading


Question:
How can compare a string for matching a special format in c?

I want to check whether a string match to  "PCn.Value".

ie. It must match PC1.value, PC2.value,...

Answer:
sscanf()could help

```
char S[32];
if (sscanf(str, "PC%[0-9].Valu%1[e]%c", S, &S[30], &S[30])==2)
```


Question:
How can compare a string for matching a special format in c?

I want to check whether a string match to  "PCn.Value".

ie. It must match PC1.value, PC2.value,...

Answer:
sscanf()could help

```
char S[32];
if (sscanf(str, "PC%[0-9].Valu%1[e]%c", S, &S[30], &S[30])==2)
```


Question:
Some apps on the gnome desktop like the image viewer use a dark variation of the theme.
What code is required to make my own gtk program use this dark variation of the theme?

Answer:
Use thegtk-application-prefer-dark-themesetting. This ought to do it:

```
g_object_set(gtk_settings_get_default(),
    "gtk-application-prefer-dark-theme", TRUE,
    NULL);
```

You may need to make sure you do it before you create any widgets.


Question: chdir("~/")doesn't seem to work.  Am I expected to look at the string and substitute tilde by hand, or is there some better way?

Answer: POSIX provideswordexp(3)to perform shell-like expansion, including tilde expansion.


Question:
```
#include <stdlib.h>
int main(void)
{
    int* x;
    int* y;
    x = malloc(sizeof(int));
    *x = 42;
    *y = 13;
    y = x;
    return 0;
}
```

Where is the Error  in which line and why.. ? Can't I assign pointer to another pointer. Yes nothing is being printed out in this .. Actually its my homework question...

Answer:
You need to allocate memory forybefore assigning value to it.

```
y = malloc(sizeof(int));
 *y = 13
```


Question: Is there any c library that deals with utf8, usingchar*?In particular, for all thechar*, we will use utf8 compatible functions to deal with them:counting length, comparing, find & replace, concatenation, toupper tolower etc.There is no need to deal with conversion.

Answer: ... then theICU libraryis just what you need.


Question: Can I use the msleep() function to sleep for a specified amount of time in kernel space? If so, which header files do I need to include?#include <linux/time.h>doesn't seem to be the right one. Is there perhaps a better function for this purpose?

Answer: I needed to include<linux/delay.h>to use msleep in kernel space.


Question: chdir("~/")doesn't seem to work.  Am I expected to look at the string and substitute tilde by hand, or is there some better way?

Answer: POSIX provideswordexp(3)to perform shell-like expansion, including tilde expansion.


Question:
```
#include <stdlib.h>
int main(void)
{
    int* x;
    int* y;
    x = malloc(sizeof(int));
    *x = 42;
    *y = 13;
    y = x;
    return 0;
}
```

Where is the Error  in which line and why.. ? Can't I assign pointer to another pointer. Yes nothing is being printed out in this .. Actually its my homework question...

Answer:
You need to allocate memory forybefore assigning value to it.

```
y = malloc(sizeof(int));
 *y = 13
```


Question: This is purely out of interest. I searched around a bit, knowing that instances ofclassesare calledobjects, but I couldn't find what the correct word is for an instance of astructin C, C++, C#, etc. Do we even have a word for this?

Answer:
It is perfectly valid to call it an object even in C.

C99 Standard §3.15:Para 1:

objectregion of data storage in the execution environment, the contents of which can represent
  values


Question: This is purely out of interest. I searched around a bit, knowing that instances ofclassesare calledobjects, but I couldn't find what the correct word is for an instance of astructin C, C++, C#, etc. Do we even have a word for this?

Answer:
It is perfectly valid to call it an object even in C.

C99 Standard §3.15:Para 1:

objectregion of data storage in the execution environment, the contents of which can represent
  values


Question:
Let's say I have achar*called code, and it has"0x41"in it.

```
char *code = "0x41";
```

How can I convert that into anunsigned int? (To be exact, I need aWORD, but that's just anunsigned int).

Answer:
```
unsigned int h;
sscanf(code, "%x", &h);
```

EDITtaking account of the remark ofExP:%xcould catch the value in the string"0x41"


Question:
Let's say I have achar*called code, and it has"0x41"in it.

```
char *code = "0x41";
```

How can I convert that into anunsigned int? (To be exact, I need aWORD, but that's just anunsigned int).

Answer:
```
unsigned int h;
sscanf(code, "%x", &h);
```

EDITtaking account of the remark ofExP:%xcould catch the value in the string"0x41"


Question: I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not on iOS.Is there another way to hook C functions?

Answer: If youlook closely, you can find out that MobileSubstrate runs on OS X as well.


Question:
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program?

I have tried using\x25and%, but they do not work.

Answer:
You should be able to escape the%with an extra%:

```
%%
```


Question: I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not on iOS.Is there another way to hook C functions?

Answer: If youlook closely, you can find out that MobileSubstrate runs on OS X as well.


Question:
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program?

I have tried using\x25and%, but they do not work.

Answer:
You should be able to escape the%with an extra%:

```
%%
```


Question: I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not on iOS.Is there another way to hook C functions?

Answer: If youlook closely, you can find out that MobileSubstrate runs on OS X as well.


Question:
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program?

I have tried using\x25and%, but they do not work.

Answer:
You should be able to escape the%with an extra%:

```
%%
```


Question:
What is the difference between the devices "default" vs "hw:0,0" ? Are they the same ?

(Background: I faced some trouble to play audio when I configured hw:0,0 , but "default" worked. Could not find what caused this)

Thanks

Answer: Thedefaultdevice uses theplugplugin to automatically convert sample formats and rates, and typically alsa uses thedmixplugin to allow multiple applications to access the device at the same time.


Question:
What is the difference between the devices "default" vs "hw:0,0" ? Are they the same ?

(Background: I faced some trouble to play audio when I configured hw:0,0 , but "default" worked. Could not find what caused this)

Thanks

Answer: Thedefaultdevice uses theplugplugin to automatically convert sample formats and rates, and typically alsa uses thedmixplugin to allow multiple applications to access the device at the same time.


Question:
My project contains c++ files and c files and I want to build my project with autotools.

So I create theMakefile.am. and I m wondering if it's possible to put bothcppfiles andcfiles together into the_SOURCEvariable

```
myprogram_SOURCES = \
  file1.c   \
  file2.c   \
  file3.cpp
```

Answer: Yes, you can add C and C++ files to_SOURCES.


Question:
As the question said. In Xcode 4.6.

Want to print ints, chars, arrays, custom structs etc etc.

Possible?

With Objective-C I could do something like:

int three = 3;

po [NSString stringWithFormat:@"%i", three];

Thanks.

Answer:
postands for Print Object, which essentially calls thedescriptionmethod on the object.

Usepto print an integer. For example:

```
p three
```


Question:
My project contains c++ files and c files and I want to build my project with autotools.

So I create theMakefile.am. and I m wondering if it's possible to put bothcppfiles andcfiles together into the_SOURCEvariable

```
myprogram_SOURCES = \
  file1.c   \
  file2.c   \
  file3.cpp
```

Answer: Yes, you can add C and C++ files to_SOURCES.


Question: I have an old program that I want to read the mesh data from, is there a way I can access all the faces/triangle strips that any program(not just the one doing the reading) is sending to OpenGL's buffer.

Answer:
Check outglintercept

```
GLIntercept is a OpenGL function call interceptor for Windows that will intercept and log all OpenGL calls.
```


Question:
For example, is

```
static int a[1+1];
```

valid standard C? For some or all versions of the standard?

I'm not interested in whether compilers can handle it, but whether it is part of standard C.

Answer:
C11, §6.6:

A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.

So yes, simple constant folding is mandatory and this snippet is valid standard C.


Question:
I have a C code that I'm analizing and there is something like this:

```
variable = (unsigned long)rx;
```

Ifrxis an array of hex numbers and variable is ofunsigned long, what will variable hold? The first element inunsigned longformat?

Answer: Remember that arrays decays to pointers. So what will happen is that the cast will convert the pointer (i.e. memory address) to anunsigned longand assign that tovariable.


Question: I want to know if there is some open source projects (I prefer C projects) that use the cppUnit for the unit tests.

Answer:
Xnor midi,tadaandnkbaseuse CppUnit. I believegnuradioalso uses CppUnit.
A quick search on github goes a long way.


Question: I want to know if there is some open source projects (I prefer C projects) that use the cppUnit for the unit tests.

Answer:
Xnor midi,tadaandnkbaseuse CppUnit. I believegnuradioalso uses CppUnit.
A quick search on github goes a long way.


Question:
I want to implement logging functionality in C and log messages to both stdout and some file.
I would like to write something like fprintf(logout, "msg"); with somehow declared FILE* logout which will redirect strings to both stdout and some file. Is it possible?

Answer:
If this is on Linux, you can open a pipe to theteecommand:

```
FILE *logout = popen("tee logfile", "w");
```


Question:
I want to split the string "abc 123 456" into the string ("abc") and 2 numbers (123,456). What is the format should I put in the below code?

```
char *s;
int a,b;
sscanf("acb 123 456", format, s, &a, &b);
```

Answer:
You want:

```
"%s%d%d"
```

But you also need to allocate buffer space for the string you extract:

```
char s[100];
int a,b;
sscanf("acb 123 456", "%s%d%d", s, &a, &b);
```


Question:
I want to split the string "abc 123 456" into the string ("abc") and 2 numbers (123,456). What is the format should I put in the below code?

```
char *s;
int a,b;
sscanf("acb 123 456", format, s, &a, &b);
```

Answer:
You want:

```
"%s%d%d"
```

But you also need to allocate buffer space for the string you extract:

```
char s[100];
int a,b;
sscanf("acb 123 456", "%s%d%d", s, &a, &b);
```


Question:
Is there difference in C if I declare function like this:

```
Type * AK_init_observer();
```

and like this:

```
Type* *AK_init_observer();
```

Answer: Yes, the return types are different. The first returns a pointer toType, whereas the second returns a pointer to pointer toType.


Question:
Is there difference in C if I declare function like this:

```
Type * AK_init_observer();
```

and like this:

```
Type* *AK_init_observer();
```

Answer: Yes, the return types are different. The first returns a pointer toType, whereas the second returns a pointer to pointer toType.


Question:
When you open a file withCreateFileyou can set its sharing mode (the third parameter).

Is there a way to set the sharing mode when using_open? Possibly by a call to_setmodeor something equivalent? I need to use theFILE_SHARE_DELETEmode.

Answer: _fsopen,_sopenand similar functions can take a share mode parameter however this does not supportFILE_SHARE_DELETE. If you want this share mode useCreateFile


Question: How can I capture packet of applications, including Hotspot Shield and other free proxy applications?

Answer:
If I understand your question, you're looking for a tool that allows you to capture network packets on your machine and examine them.

You can use tools likeWiresharkthat allows you do that.


Question: I wrote a program in which I found the area of cylinder using a functionareawith a return-type and without parameters.answerwas returned tomainfunction. However, I am getting different output inmainand a different output inarea. The decimal places seem to be replaced by 0 in themainfunction. Why is it so?

Answer: Change the return type of area from int to float


Question:
If I have a condition like this:

```
if (X && Y) {}
```

Will the compiler checkYifXis false? Is it compiler dependent?

Answer:
In C andmost other languagesshort-circuit evaluation is guaranteed. SoYis only evaluated ifXevaluates to true.

The same applies toX || Y- in this caseYis only evaluated ifXevaluates to false.

SeeMike's answerfor a reference to the C specification where this behavior is mentioned and guaranteed.


Question:
Multiple markers at this line
    - previous definition of 'type' was here
    - redefinition of parameter 'type'

int parseLine(char* line, int* day, float* amount,char* type, char* type);

That's the error I'm getting in a header C file in Eclipse

Answer: The error tells you that you definedchar* typetwice


Question:
Anybody knows, how to get real value of clock per sec?clock()fromtime.hreturns clocks from start of my process, so it need to be divided byCLOCKS_PER_SEC, but this constant has always value1000000.

Is there some POSIX standard for this?

Answer:
That's how it specified in the C specification.

If you want to measure elapsed time, there are other (and better) functions, likegettimeofdayfor example.


Question:
How to play a sound file specified by user in an array using the PlaySound()? I'm using Windows7 and VC++ 2010.

Suppose I use thegets(song);statement to input the complete path of the song from user.

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

```
PlaySound( song, NULL, SND_FILENAME );
```


Question:
Everything I've seen says to uselsof -p, but I'm looking for something that doesn't require a fork/exec.

For example on Linux one can simply walk/proc/{pid}/fd.

Answer: You canuseproc_pidinfowith thePROC_PIDLISTFDSoption to enumerate the files used by a given process. You can then useproc_pidfdinfoon each file in turn with thePROC_PIDFDVNODEPATHINFOoption to get its path.


Question:
Everything I've seen says to uselsof -p, but I'm looking for something that doesn't require a fork/exec.

For example on Linux one can simply walk/proc/{pid}/fd.

Answer: You canuseproc_pidinfowith thePROC_PIDLISTFDSoption to enumerate the files used by a given process. You can then useproc_pidfdinfoon each file in turn with thePROC_PIDFDVNODEPATHINFOoption to get its path.


Question:
What is the best way to execute this command: "sudo cat /var/log/auth.log | grep Accepted" inside my C program ?
I tried to use:

```
sprintf(command_result,"sudo cat /var/log/auth.log | grep Accepted");
```

But it didn't work obviously.

Answer:
You cannot execute the command withsprintf()you needsystem()atleast

fix:

```
sprintf(command_result, "sudo cat /var/log/auth.log | grep Accepted");
system(command_result);
```


Question:
all:

Is there any good open source C library which provides sending email function? I don't want use mailx command in Solaris.Thanks very much in advance!

Answer:
I just searched on google and found these few link..hope this will help.

http://sourceforge.net/projects/jwsmtp/?source=dlp

http://www.stafford.uklinux.net/libesmtp/download.html


Question: Does anyone know how to turn an integer array into a float array?

Answer:
Your question is not worded well; however, assuming you have already declared your integer array, you could try something like this:

```
// instantiate float array
float fArray[sizeOfIntArray];

// step through each element of integer array, and copy into float array as float
for(int i = 0; i < sizeOfIntArray; ++i) {
    fArray[i] = (float)iArray[i];
}
```


Question:
I was trying to implementgetchar()function usingreadfunction in unistd.h.

I knowread(0,buffer,1)is equivalent togetchar(), however, it takes too many system calls.

Is there a way to implementgetchar()function using less system calls?

Answer: Yes -- read a larger buffer (e.g., at least a few kilobytes) full of data. When the user calls getchar, return a char from the buffer unless it's empty. If it is empty, refill the buffer first, then return a char.


Question:
```
#define Map(From, To, val)          \
        Map__##From__##To(val)

Map(TYPEA, TYPEB, 22);
```

In the above code I am wondering whyMap(TYPEA, TYPEB, 22);is getting expanded toMap__From__TYPEB(22);and notMap__TYPEA__TYPEB(22);

I used gcc -E for expansion.

Answer:
BecauseFrom__is not a token inMapand hence, preprocessor does not look it up.. fix is :

```
#define Map(From, To, val) \
        Map__##From##__##To(val)
```


Question:
I am trying to use a macro in sprintf statement. It is like this :

```
#define MACR 6

....
int Number= 5;
char Formatted[30];
sprintf( Formatted, "%06d", Number );
```

Here I would like to use MACR instead of 6. Can anyone help me please?

Answer:
Use the*format specifier to pass the width as argument. Something like this should work:

```
sprintf( Formatted, "%0*d", MACR, Number );
```

But please use a constant not a MACRO.


Question:
currently I search achar *withstrstrbut I dont want to search in the complete one, only from the 42. char to the end.
How can I achieve this?

Answer:
Just providestrstr()with a pointer to the first character to include in the seach:

```
if(strstr(the_haystack + 42, "the needle") != NULL)
  printf("found needle at end of haystack!\n");
```

Of course, this assumes thatthe_haystackreally is at least 42 characters long.


Question:
This question already has answers here:What is the difference between const int*, const int * const, and int const *?(23 answers)Closed10 years ago.

```
char const*const variablename = " ";
```

what does it mean?

is it same as pointer declaration?

Please anyone explain.

Thank you in advance!

Answer: It's aconstpointer to aconstC string. This means that neither the contents of the string, nor the pointer itself, can be changed.


Question:
```
tempValue = input2[0] << 8;
```

I can't figure out what the<<does in this line of code.  What is this used for?

Answer:
It assignstempValuethe value ininput2[0]shifted to the left by 8 bits.

Here is a link about bit shifting in C:http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/bitshift.html


Question:
I am using

unistd.hsys/stat.h

and what is interesting is thatst_sizeis bigger than the value returned afterread()?st.st_sizereturns644-read()returns606,
Any thoughts?

Answer: Size of file and size of stream may not match. For example, when you open file in text mode, OS can translate multi-byte EOL sequences into single char. This is usually visible on Windows, but if you have a Windows file on Linux, the effect can be the same.


Question:
I want to pass Unix file descriptor from one local (same machine processes) process to another process. Which are the IPCs mechanism useful from below?

```
PIPE/FIFO/Message Queue/ Shared Memory/ Socket / TLI / stream/ RPC**
```

Answer: The canonical way of passing a file descriptor from one process to the other is using Unix domain sockets, via the ancillary data ofsendmsgandrecvmsg.


Question:
I want to pass Unix file descriptor from one local (same machine processes) process to another process. Which are the IPCs mechanism useful from below?

```
PIPE/FIFO/Message Queue/ Shared Memory/ Socket / TLI / stream/ RPC**
```

Answer: The canonical way of passing a file descriptor from one process to the other is using Unix domain sockets, via the ancillary data ofsendmsgandrecvmsg.


Question:
Usuallylseekdoesn't work onstdin.

But, what if I run my program like this:

./a.out < filename

Nowstdinis a file and not keyboard.

Willlseekwork there?

Can I do

lseek(0, -1, SEEK_CUR)

and get the same effect like

ungetc()?

Answer:
Yes,lseekwill change the seek pointer. No, it is not equivalent toungetc().

fseek(stdin, -1, SEEK_CUR)comes closer toungetc(), but still isn't identical.


Question:
When I intuitively try to run such command

```
cc -c source.c header.h -o a_name_different_than_source.o
```

the following error is thrown

cc: cannot specify -o with -c, -S or -E with multiple files

Answer:
Do not putheader.hin your command line:

```
cc -c source.c -o a_name_different_than_source.o
```

will work.


Question:
Usuallylseekdoesn't work onstdin.

But, what if I run my program like this:

./a.out < filename

Nowstdinis a file and not keyboard.

Willlseekwork there?

Can I do

lseek(0, -1, SEEK_CUR)

and get the same effect like

ungetc()?

Answer:
Yes,lseekwill change the seek pointer. No, it is not equivalent toungetc().

fseek(stdin, -1, SEEK_CUR)comes closer toungetc(), but still isn't identical.


Question:
When I intuitively try to run such command

```
cc -c source.c header.h -o a_name_different_than_source.o
```

the following error is thrown

cc: cannot specify -o with -c, -S or -E with multiple files

Answer:
Do not putheader.hin your command line:

```
cc -c source.c -o a_name_different_than_source.o
```

will work.


Question:
When I intuitively try to run such command

```
cc -c source.c header.h -o a_name_different_than_source.o
```

the following error is thrown

cc: cannot specify -o with -c, -S or -E with multiple files

Answer:
Do not putheader.hin your command line:

```
cc -c source.c -o a_name_different_than_source.o
```

will work.


Question:
If I was to write a tiny C or C++ application (on Linux) and call "native" Linux functions, such as select() and poll() when profiling, would I be able to see the assembler being used for these functions too, its not just user-written code which can be profiled?

I would be interested to see the assembly produced for various "native" Linux functions.

Answer: Almost. They are kernel calls, so you would see a bit of code up to kernel level.


Question: In libc's malloc(x), the function is said to return a pointer to a memory region of at least x bytes and the pointer is aligned to 8 bytes. What does this alignment mean? THank you.

Answer:
It means that the pointed address mod 8 is 0:

```
pointer % 8 == 0
```

This can be important for low level operations where it may impact correctness or efficiency. See alsothis answer.


Question:
I am using gnu gcc and armcc to compile a few C files. How can I get the information about which compiler compiled which file?

Ex: test.cpp is being compiled by armcc or gnu gcc.

The makefile is very complicated and I am looking out for a command by which I can check which compiler compiled which file.

Any ideas?

Answer: Sometimes you can look at the file with a hex editor and tell if the compiler wrote its name into the file.


Question: I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!

Answer:
```
struct B {
   //your struct..
};
struct A {
    B b;
};

void foo(struct A a)
{
   a.b + ???....
   //you function
}
```


Question: I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!

Answer:
```
struct B {
   //your struct..
};
struct A {
    B b;
};

void foo(struct A a)
{
   a.b + ???....
   //you function
}
```


Question: I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!

Answer:
```
struct B {
   //your struct..
};
struct A {
    B b;
};

void foo(struct A a)
{
   a.b + ???....
   //you function
}
```


Question:
Basically I want to do the following:

```
#define TYPE float

int main()
{
  if (TYPE==float)...;
}
```

Of course it wont' work, and not sure how to achieve it.

Answer:
You can use the C preprocessor'sstringificationoperator.

```
#define xstr(s) str(s)
 #define str(s) #s

 if (strcmp(xstr(TYPE), "float") == 0) ...
```

For an explanation of this, seehere


Question:
I have data for which using cin/in is too slow.
There are three integers per line :

```
1 2 2
3 4 1
5 6 122
6 4 7
```

How to read-in each line in loop, to achive result (for first iteration) :

```
x==1;
y==2;
z==2;
etc.
```

?

How to to do it using cstdio::scanf ?

Answer:
Use this:

```
while(scanf("%d %d %d", &a, &b, &c) != EOF) {
   ... do stuff ...
 }
```


Question:
I have data for which using cin/in is too slow.
There are three integers per line :

```
1 2 2
3 4 1
5 6 122
6 4 7
```

How to read-in each line in loop, to achive result (for first iteration) :

```
x==1;
y==2;
z==2;
etc.
```

?

How to to do it using cstdio::scanf ?

Answer:
Use this:

```
while(scanf("%d %d %d", &a, &b, &c) != EOF) {
   ... do stuff ...
 }
```


Question: I am currently working in C multi-threading on server having multiple hexa-core cpus. I want to set affinity of some of my threads to respective cores of a single CPU. I have used pthread_setaffinity_np() and also  sched_setaffinity() but i guess the set affinity on the cpus not the cores. am I right?

Answer: pthread_setaffinity_np()et al operate in terms of logical CPUs (i.e. cores), not physical ones (i.e. CPU sockets).


Question:
I have this part of code in C class:

```
int i;
    for (i=0;i<val;i++)
        mdl_print ("%u ", rec->payload[i]);
    mdl_print ("\n");
```

Variable rec->payload is uint8_t type. I would print it in hexadecimal notation.

How can I do? Thanks.

Answer:
Quick and easy:

```
print("%x", (int)(rec->payload[i]));
```

To display in the format 0x05 then use:

```
print("0x%02x", ...)
```

instead.


Question:
I have this part of code in C class:

```
int i;
    for (i=0;i<val;i++)
        mdl_print ("%u ", rec->payload[i]);
    mdl_print ("\n");
```

Variable rec->payload is uint8_t type. I would print it in hexadecimal notation.

How can I do? Thanks.

Answer:
Quick and easy:

```
print("%x", (int)(rec->payload[i]));
```

To display in the format 0x05 then use:

```
print("0x%02x", ...)
```

instead.


Question: Is it possible to make a data type which can take integer values from 0 to 9 only? If yes, please tell How?

Answer: No, it is not possible to make a custom-ranged integer in C. You'll have to maintain such an invariant yourself.


Question: Is there native support for a data type for storing Unicode strings in C. I'm writing a toy compiler and would like to parse Unicode strings.

Answer:
Is there native support for a data type for storing Unicode strings in C.

Yes. Since Unicode strings can bestoredas sequences of bytes using an encoding scheme, one can use arrays ofcharfor this purpose.

Note that supporting storage says nothing about the ability to interpret or manipulate the data.


Question:
Why is the value of n changing to garbage inside the for-loop? (I'm new to C language, I come from a C++ background)

```
float n = 3.0;
printf ("%f\n", n);
for (; n <= 99.0; n += 2)
    printf ("%f\n", &n);
```

Answer: You are printing the address of n (&n) inside the for-loop. Get rid of the&


Question:
I wrote a small rgrep function and I'll have another text file with words that I am checking a pattern against.
My text file will be in the following format.

```
a
because
cat
7.*
```

How do i write a loop that will call a function for each of those words in the file? Thanks!

Answer: Make a state machine for that pattern first, then every char drives that state machine to next state. Check state to check pattern match.


Question:
i wanna know what is the difference between

```
void fct1(int *p)
```

and

```
void fct1(int p[])
```

i know that both are pointers but are there any differences

Answer: There is absolutely no difference when used as a function parameter like that. The compiler treats both forms identically.


Question:
Using the Mongodb C Driver, how can I issue shell commands like db.mydb.remove()?

The API seems pretty limited:http://api.mongodb.org/c/current/api/annotated.html

Answer:
To drop collection usemongo_cmd_drop_collection(…), to drop DBs usemongo_cmd_drop_db(…). Most commands are insidemongo.h.

Edit: To perform the requestedremove(…)usemongo_remove(…).


Question:
How can I assign non-ASCII characters to a wide char and print it to the console? This code down doesn't work:

```
#include <stdio.h>
int main(void)
{
    wchar_t wc = L'ć';
    printf("%lc\n", wc);
    printf("%ld\n", wc);
    return 0;
}
```

Output:

```
263
Press [Enter] to close the terminal ...
```

I'm using MinGW GCC on Windows 7.

Answer:
You should usewprintfto print wide-character strings:

```
wprintf(L"%c\n", wc);
```


Question:
Using the Mongodb C Driver, how can I issue shell commands like db.mydb.remove()?

The API seems pretty limited:http://api.mongodb.org/c/current/api/annotated.html

Answer:
To drop collection usemongo_cmd_drop_collection(…), to drop DBs usemongo_cmd_drop_db(…). Most commands are insidemongo.h.

Edit: To perform the requestedremove(…)usemongo_remove(…).


Question:
What is the value of0x1.921fb82c2bd7fp+1in a human readable presentation?
I got this value byprintfusing%a.

Answer: The mantissa is hexadecimal and the exponent is a decimal value representing the power of 2 the mantissa is scaled by.


Question:
```
#define power(a) #a
  int main()
  {
    printf("%d",*power(432));
     return 0;
  }
```

can anyone explain the o/p??the o/p is

52

Answer:
It is equivalent to:

```
printf("%d",*"432");
```

which is equivalent to:

```
printf("%d", '4');
```

and the ASCII value of'4'is52.


Question:
I get this error.

```
error: warning: incompatible implicit declaration of built-in function ‘memcpy’ [enabled by default]
```

This is the code:

```
int arr[ 12] = {1,0,0,0,0,0,0,0,0,0,9370, 0};
void *a = &arr;
memcpy(machine->mem, a,12*4);
```

What I am doing wrong?

Answer:
You likely forgot to include<string.h>.

Add#include <string.h>to the top of your file.


Question: I am learning cmocka unit testing framework. I am a bit puzzled at use of mock() function. Can somebody explain it clearly why and how it is used with suitable examples? Also please explain when it should be used.

Answer: You should readhttps://lwn.net/Articles/558106/to understand the mock() feature.


Question:
Hi I have a question about double pointers. For example in this code:

```
int a, b=2;
int *iPtr1, **iPtr2;

iPtr1  = &a;
iPtr2  = &iPtr1;
*iPtr1 = b+3;
*iPtr2 = iPtr1;
```

On the last line*iPtr2 = iPtr1;It that just tellingiPtr1to point back to itself since dereferencing a double pointer just once is like usingiPtr1?

Answer: It makes*iPtr2point to whateveriPtr1points to. And asiPtr2points toiPtr1it's the same asiPtr1 = iPtr1.


Question:
I have the code:

```
#DEFINE NEW = 1;
```

And a Struct:

```
typedef struct PCB
{

 /*Process state:new, ready, running, waiting, terminated*/
 int state;
 }PCB;
```

How can I assign NEW, such that state=1?

More info, I get the error:

```
expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
```

Answer:
Remove both semicolon and the=

#DEFINE NEW 1


Question: What is the practical difference, if any, betweenstdinandSTDIN_FILENOin C?

Answer: The interface.  Like everyone else has said,stdinis aFILE *as defined by the standard c library.  You can use some of the higher level interfaces likefread,fwrite, andfprintf.  On the other hand,STDIN_FILENOis just a file descriptor (almost certainly 0).  This uses a slight lower level interface through the likes ofreadandwrite.


Question:
Is there a difference between

```
const char* name = "name";
```

and

```
const char *name = "name";
```

Thank you.

Answer:
no.

But there is a difference between

```
const char* name = "hello", something = "else";
```

which will not work, while

```
const char *name = "hello", *something = "else";
```

should


Question:
I am doing assignment in which I am using POSIX named semaphore, but it is not showing me list when I enteripcs -scommand.

Please help me to get entry of named semaphore. Where will I get that?

Answer: ipcsis for System V semaphores, you are using POSIX semaphores. For the differences, seehere.


Question:
followed the steps mentioned in the following thread,

Attaching a process to a debug session: empty process list

Now I am able to get the process list. But Process list is missing "javaw.exe" which is shown in the task manager.

any help?

Answer:
Enter the process id of the process you want to attach to.

You can get the process id by looking for the process's image name in the task manager.


Question: What is the practical difference, if any, betweenstdinandSTDIN_FILENOin C?

Answer: The interface.  Like everyone else has said,stdinis aFILE *as defined by the standard c library.  You can use some of the higher level interfaces likefread,fwrite, andfprintf.  On the other hand,STDIN_FILENOis just a file descriptor (almost certainly 0).  This uses a slight lower level interface through the likes ofreadandwrite.


Question:
Is there a difference between

```
const char* name = "name";
```

and

```
const char *name = "name";
```

Thank you.

Answer:
no.

But there is a difference between

```
const char* name = "hello", something = "else";
```

which will not work, while

```
const char *name = "hello", *something = "else";
```

should


Question:
Uncrustify is great, and does an excellent job of tidying code.
However, I have some C code within a file that I don't want Uncrustify to change. Is there any way I can prevent Uncrustify from touching this, maybe by putting specific tags in comments around the code or something?

Answer:
```
/* *INDENT-OFF* */
int i = 0; // No uncrustify action here
/* *INDENT-ON* */
```


Question:
Is there a way for abashshell program, that takes a command-line argumentx, that will makex(C program) processes start?

.

Answer:
It's fairly simple:

```
#!/bin/bash
$1
```

If you want to pass the rest of the parameters as parameters to the function, do this:

```
$@
```

(i.e.foo.sh echo hiexecutesecho hi)

If you want to steal some parameters and pass others, useshift:

```
param1=$1
shift
echo $@ # contains parameters 2+
```


Question:
I can't find relevant information about this. For lua, if you want to execute a test.lua file from the main() C function, you calllua_dofile("test.lua").
What is the python equivalent?

Answer:
If you are embedding Python, usePyRun_SimpleFile:

```
FILE *fp = fopen("test.py", "r");
int ret = PyRun_SimpleFile(fp, "test.py");
if(ret < 0) {
    /* exception occurred */
}
```


Question:
I need to do some socket programming on Mac OS X but I'm missing the library for it?
This is what happens when I compile:

```
gcc ser.c -o ser -lsocket -lnsl
ser.c: In function ‘main’:
ser.c:41: warning: format ‘%.24s’ expects type ‘char *’, but argument 6 has type ‘int’
ld: library not found for -lsocket
collect2: ld returned 1 exit status
```

How do I get this library?

Answer: You don't need-lsocketon OS X.


Question:
I wish to change this popup for every program calling

```
public class OpenFileDialog : FileChooserDialog {
```

Ideally it would involve removing desktop and changing search etc. I was just hoping somebody knew where the underlying files are?

Answer:
The UI layout for the file chooser dialog is in gtk/gtkfilechooserwidget.c

http://git.gnome.org/browse/gtk+/tree/gtk/gtkfilechooserwidget.c


Question:
```
$arr['key1'] = "";
$arr['key2'] = "";
echo json_encode($arr);
```

I get{"key1":"","key2":""}. How could I add just a key element without a value? So it would be{"key1","key2"}?

Answer:
Your desired output is notvalid JSON. If you want to create a list, then use:

```
$arr[0] = 'key1';
$arr[1] = 'key2';
echo json_encode($arr);
```

Output:

```
["key1","key2"]
```


Question: How does one trackKEY_ENTERin ncurses?  I have tried tracking\nusinggetch(),KEY_ENTER, andraw(), to no avail.

Answer:
Seems like to use those key abbreviations like KEY_ENTER, you have to make a call to:

```
keypad(win, true);
```

before using them. Take a look at this:http://osr600doc.sco.com/en/man/html.CURSES/keypad.CURSES.html


Question: How does one trackKEY_ENTERin ncurses?  I have tried tracking\nusinggetch(),KEY_ENTER, andraw(), to no avail.

Answer:
Seems like to use those key abbreviations like KEY_ENTER, you have to make a call to:

```
keypad(win, true);
```

before using them. Take a look at this:http://osr600doc.sco.com/en/man/html.CURSES/keypad.CURSES.html


Question:
It completely stops reading in code after it sees a space. How do I change my code so it reads in white space

```
char line[300];

printf("Enter a string to be checked: ");
scanf("%s", line);
```

the string I'm trying to input via redirection is:

( ( a a ) < > [ [ [ { [ x ] ]]] <>)

Answer:
You can use fgets intsead of scanf. For example:

```
fgets(line, 1024, stdin);
```


Question:
Where is gethostbyaddr and netdb.h functions implemented? I can only find the header file where it is extern'ed (netdb.h)

Thanks

Answer:
It is implemented in glibc.

BTW, use getnameinfo() and getaddrinfo().  gethostbyaddr() is obsolete, mostly because of IPv6.


Question:
I have the following code

```
long x;
scanf("%ld",&x)
if(x==-1) // does this comparison is allowed
    printf("just test\n");
```

doeslongparameters need any casting before comparison?

Answer:
-1is a decimalint. There's an implicit conversion (promotion) frominttolong, so-1is automatically "casted" tolong.

Also, both-1andxare signed types. No need from any additional casts.


Question:
Hi I am using a C compiler(GCC) where I cannot use a vector like in C++. So how can I create similar kind of data structure/dynamic array with c which will work like a vector? It might be very easy but I don't have any idea how can I do it.

thanks

Answer: Start with a struct holding a pointer to the correct type the currently used size, and the current allocation size. Allocate space with malloc. If you run out of space, use realloc to increase it.


Question:
This question already has answers here:How to check if a string contains spaces/tabs/new lines (anything that's blank)?(5 answers)Closed10 years ago.

Lets say we havechar *str = "123 467";Is there something like isdigit() for numbers to return a boolean value?

Answer:
How about isspace()?  This will tell you if a char is a white space character.

It is included in ctype.h


Question:
This question already has answers here:How to check if a string contains spaces/tabs/new lines (anything that's blank)?(5 answers)Closed10 years ago.

Lets say we havechar *str = "123 467";Is there something like isdigit() for numbers to return a boolean value?

Answer:
How about isspace()?  This will tell you if a char is a white space character.

It is included in ctype.h


Question: I was wondering if it's possible to determine if a virtual address (pointer) belongs to a previousVirtualAlloccall or not (if possible without writing to the page). SinceVirtualFreecan automatically set thedwSizevalue if you use it withMEM_RELEASE.

Answer:
Something like this or I don't understand the question?

```
MEMORY_BASIC_INFORMATION mbi;
void* p = NULL;
VirtualQuery(p, &mbi, sizeof(mbi));
BOOL bWasUsed = (mbi.State==MEM_FREE)? FALSE: TRUE;
```


Question: I want to have my text horizontally aligned to the center in the terminal. How can I do this in C?

Answer:
To expand on @eyalm's answer: if you got theCOLUMNSvar, you can center strings like this:

```
int columns = strtol(getenv("COLUMNS"), NULL, 10);
int fwidth = strlen(s) + (columns - strlen(s)) / 2;
printf("%*s\n", fwidth, s);
```


Question:
I'm writing a function in C (using Eclipse) which has a integer calledalpha, and its assigned value is077.

But when I print it out, it prints63instead of77or077.

In fact, it's not just077butanyinteger with a leading0is printing an unexpected value. When I remove0from077, itdoesprint the correct value77.

What effect does this leading0have?

Answer:
A number starting with a0is an octal number.

077is7 x 8 + 7 == 63


Question:
I need to calculate an angle in C programm. Here is a method from JAVA that I need to convert to C.

```
private static double calculateDirection(double x, double y)
{
    return Math.toDegrees(Math.atan2(y, x));
}
```

Is there a function like toDegrees in C language so I don't have to write all the code by myself?
Thank you

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

inline double to_degrees(double radians) {
    return radians * (180.0 / M_PI);
}
```


Question: I want to have my text horizontally aligned to the center in the terminal. How can I do this in C?

Answer:
To expand on @eyalm's answer: if you got theCOLUMNSvar, you can center strings like this:

```
int columns = strtol(getenv("COLUMNS"), NULL, 10);
int fwidth = strlen(s) + (columns - strlen(s)) / 2;
printf("%*s\n", fwidth, s);
```


Question:
I'm writing a function in C (using Eclipse) which has a integer calledalpha, and its assigned value is077.

But when I print it out, it prints63instead of77or077.

In fact, it's not just077butanyinteger with a leading0is printing an unexpected value. When I remove0from077, itdoesprint the correct value77.

What effect does this leading0have?

Answer:
A number starting with a0is an octal number.

077is7 x 8 + 7 == 63


Question:
I need to calculate an angle in C programm. Here is a method from JAVA that I need to convert to C.

```
private static double calculateDirection(double x, double y)
{
    return Math.toDegrees(Math.atan2(y, x));
}
```

Is there a function like toDegrees in C language so I don't have to write all the code by myself?
Thank you

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

inline double to_degrees(double radians) {
    return radians * (180.0 / M_PI);
}
```


Question:
In C language code, if I have a bunch of variables that will be used only for logical operations, what is the data type that will yield the fastest execution time?

Also, does it depend if I'm using an ARM or Intel processor, 32-bit or 64-bit system?

Answer: If the compiler allows, include<stdbool.h>, usebool, and trust the compiler/RTL vendor to do the right thing. Otherwise useint.


Question: Are there any open source libraries or standard functions that allow a C program to interact with other command line programs (that for example may request user input).

Answer: expectis a popular library for programmatically interacting with interactive programs (e.g.ssh). There's a port of it to C calledlibexpectwhich may do what you want.expectemulates a terminal, so it is particularly useful for applications that won't talk to simple pipes.


Question:
I need to read the text and find if there is more than one space between the words.

If there is change it to one.

For example if I have a text:

```
My         name     is      Lukas
```

Program should change it to:

```
My name is Lukas
```

Any ideas?

Answer:
```
while (*str) {
  if (*str != ' ' || str[1] != ' ') *newstr++ = *str;
  str++;
}

*newstr = 0;
```


Question:
crypt (const char *key, const char *salt)

I saw it in code, but i could not find the implementation of this function. Is it some of the conventions of C?

Answer:
It's specified byPOSIXbut not by any version of the C standard. Careful though:

The crypt() function is a string encoding function.The algorithm is
  implementation-defined.


Question:
Why is there a number added to the name of a local static variable in the symbol table?

```
int main(void) {
    static stat_var = 20;

    return 0;
}
```

8: 0000000000000008     4 OBJECT  LOCAL  DEFAULT    2 stat_var.1604

Answer: There can be many local static variables with the same name (across different functions). The compiler is giving them disambiguating suffixes to avoid a potential name collision.


Question:
I am creating a public key generator and I do c= p*q; Where p and q are large prime numbers, but I keep getting this for C  11875820813;

```
long unsigned int c= p*q;
printf("C is: %d\n", c);
```

I know I has something to do with my numbers, but I don't know how to fix this.

I am trying to multiply:

872017*533297

Answer: You might be overflowing the value. Remember that on a 32-bit platform anunsigned longcan be at most a little over 4 billion.


Question:
I get the error: warning: format argument is not a pointer (arg 2)

with this line:printf("%s \n", *(group_list->name));

I don't understand why this is a problem considering thatnameis a pointer to a char. Is it a problem with usings? Do I have to use a different specifier?

Answer:
Use this instead:

```
printf("%s \n", group_list->name);
```

sconversion specifier expects achar *not achar.


Question:
printf("%d, ", packet[i]);

How to display variable correctly. It should be from 0 to 255
but if I use%dit prints:

-1 as 255

up to the number 128 is displayed correctly, larger are negative.

when I use%uit prints 4294967295 instead of 255.

Answer:
Use%hhuconversion specification:

```
printf("%hhu, ", packet[i]);
```


Question:
My simplified code looks like something below:

```
char decrypted[64] = "P@ssw0rd                ";
 int realsize = 8;
  realloc(decrypted, realsize);

  char *dec2 = (char *) malloc(realsize+1); // Exe crashes at this point
```

I am guessing it has to do withchar *dec2, but this only crashes Win XP for some reason.

Answer: You cannotrealloc()what hasn't been allocated withmalloc()orcalloc()orrealloc().


Question:
Withfopen()I read the file line by line withfgets().

Are there a function likefgets()inorder to read stream opened byopen()?

Answer:
There is no such function. The problem is, unless you do buffering in userspace (likeFILE*routines do), there is no way to implement it efficiently: you'll have toreadcharacters one-by-one.

On POSIX systems you can usefdopento wrap aFILE*structure around a file descriptor, and then usefgets.


Question:
I've been asked to create this for loop for my C Programming class but I do not know how to alternate the positive and negative values. Thank you in advance!

sum2=1-x+x^2-x^3+⋯+/-x^n

Answer:
Hint: consider the expression as sum of (-1*x)^i, with i = 1, 2, 3, ..., n.
If n is even then (-1*x)^i is positive, if odd then negative.


Question:
I've to link libcurl to a project compiled on Windows XP with VS 2010 (MSVC 10).

The dependencies found at urlhttp://windows.php.net/downloads/php-sdk/deps/are only for VC 2008 (MSVCR 9) and VS 2012 (MSVCR 11).

Does anybody know where to find compiled libcurl binaries or its dependencies (for building by its makefiles) with VS 2010 (MSVCR 10)?

Thank you very much!

Answer: Problem solved : open and convert the root DSW file, then compile with VS!


Question:
Linux C program:

What function call can check if running in X Window?

If not in X Window, then printf.

Answer:
Do you mean something like this:

```
#include <X11/Xlib.h>

  // ...

  char *display_name = NULL;

  /* connect to X server */
  if ( (display=XOpenDisplay(display_name)) == NULL )
  {
    //printf or whatever
  }
```


Question:
I have to read from standard input two numbers as strings, in C. How can I print their sum as a string too? I have:

```
char a[10],b[10];
printf("enter the two numbers");
scanf("%s%s",&a,&b);
char sum[20];
sum=?
```

A little tip,please?
Thank you!

Answer:
Just do it like in elementary school

Let's say the input was "...69 + ...63"

```
9 + 3     = 2 and 1 to go
6 + 6 + 1 = 3 and 1 to go
...
```


Question: On SDL 2, there is the functionSDL_GL_MakeCurrent, is there any thing like that for SDL 1.2?

Answer:
Not in the public API, no.

Theprivate video backend interfacehas a function pointer for it though.


Question: On SDL 2, there is the functionSDL_GL_MakeCurrent, is there any thing like that for SDL 1.2?

Answer:
Not in the public API, no.

Theprivate video backend interfacehas a function pointer for it though.


Question:
I am trying to build WildMagic 5.9 on Visual Studio 2012 but here are error:

```
Error   3   error C2039:
'greater' : is not a member of 'std'
c:\wildmagic5\libmathematics\intersection\wm5intrellipsoid3ellipsoid3.cpp 142 1
LibMathematics_VC100
```

Why? What to fix to get this to compile?

Answer:
Need include:

```
include <functional>
```


Question:
How do I open an external EXE file from inside C?  I'm trying to write a C program that opens Notepad, and some other applications and I am stuck.
Thanks for putting up with my noob level of C ;p

Answer: Please trysystem("notepad");which will open the notepad executable. Please note that the path to the executable should be part ofPATHvariable or the full path needs to be given to thesystemcall.


Question:
How do I open an external EXE file from inside C?  I'm trying to write a C program that opens Notepad, and some other applications and I am stuck.
Thanks for putting up with my noob level of C ;p

Answer: Please trysystem("notepad");which will open the notepad executable. Please note that the path to the executable should be part ofPATHvariable or the full path needs to be given to thesystemcall.


Question:
Is there a way to remove the last number from an integer in C? For example, if the user entered the number: "123" is there a way to change that to just "12"?

Thanks

Answer:
Divide that integer number by 10.

123 / 10 == 12.


Question:
This question already has answers here:How do you initialise a dynamic array in C++?(10 answers)Closed10 years ago.

Is there a way in c++ to fill an array allocated like this

```
int **a = new int[4][2];
```

so that it's filled with values in one line like this

```
int a [4][2] = {{2,3,4},{5,6,7}};
```

Answer:
You can do it in C++11 withuniversal initialization notation:

```
int(*a)[2] = new int[2][2]{{1,2},{3,4}};
```


Question: I have downloaded both programs, but I see no instructions on google for getting Cilk to work on Cygwin.  Is there a Cygwin package that would work?  I'm programming in C and have gcc installed.

Answer:
Build it from source.

That will link thecygwin32.dllwith the binaries which are essential for it to work with cygwin.

Here is a guide:http://groups.csail.mit.edu/sct/wiki/index.php?title=Cilk_Plus_Installation_Guideto build it from source withgcc.


Question:
This question already has answers here:What does 'sizeof (function name)' return?(4 answers)Closed10 years ago.

I triedsizeof(printf),sizeof(foobar)etc. where foobar is a user defined function. It returns 1 without any warning or error. Why 1?

Answer: The size of functions is not well defined in C, so the value is meaningless.


Question:
everytime we write a program we need something like #include or any other #include things...

Is there anyway to create alias for this, so that when I type inc in vim and press some key, then inc changes to #include

Answer:
Read:h abbreviationsor try one ofthe many snippet expansion plugins available.

I use the originalSnipMate, but there isa modern forkand a modern alternative calledUltiSnips.


Question:
everytime we write a program we need something like #include or any other #include things...

Is there anyway to create alias for this, so that when I type inc in vim and press some key, then inc changes to #include

Answer:
Read:h abbreviationsor try one ofthe many snippet expansion plugins available.

I use the originalSnipMate, but there isa modern forkand a modern alternative calledUltiSnips.


Question:
I came across a code that looks like this:

```
asm volatile (
    # [...]
    "movl $1200, %%ecx;"
    # [...]
);
```

I know whatmovl $1200, %ecxdoes in x86. but I was confused by why there are two percent signs.

Answer:
GCC inline assembly uses %0, %1, %2, etc. to refer to input and output operands.  That means you need to use two %% for real registers.

Check thishowtofor great information.


Question:
There isfilenoto get the file descriptor of a FILE*.

How do you get the address for the FILE* given a file descriptor number, e.g. as returned frompipe?

filenopipe

Answer:
You want to use thefdopen()function:

```
FILE * file = fdopen(fd, "r");
```

so you could use it in combination withpipelike this:

```
FILE * file = fdopen(pipe(..,..), "r");
```


Question:
I have two bytes containing a 14-bit left-justifiedtwo's complementvalue, and I need to convert it to a signed short value (ranging from -8192 to +8191, I guess?)

What would be the fastest way to do that?

Answer:
Simply divide by 4.

(Note, right-shift leads to implementation/undefined behaviour.)


Question:
There isfilenoto get the file descriptor of a FILE*.

How do you get the address for the FILE* given a file descriptor number, e.g. as returned frompipe?

filenopipe

Answer:
You want to use thefdopen()function:

```
FILE * file = fdopen(fd, "r");
```

so you could use it in combination withpipelike this:

```
FILE * file = fdopen(pipe(..,..), "r");
```


Question:
I have two bytes containing a 14-bit left-justifiedtwo's complementvalue, and I need to convert it to a signed short value (ranging from -8192 to +8191, I guess?)

What would be the fastest way to do that?

Answer:
Simply divide by 4.

(Note, right-shift leads to implementation/undefined behaviour.)


Question:
I have known this problem is compiler-dependent. So I want a reliable method to determine.

For example:

```
const wchar_t str[] = L"飞流直下三千尺";
```

How should I know whetherstris little-endian or big-endian?

Is there a compiler's guarantee that the endianness of a wide string literal is the same one as the target architectures?

Answer: There's no compiler guarantee thatwchar_tevenhasan endianness (or that it's Unicode, for that matter).


Question:
I am trying to add a null termination to my buffer with the following code. But I don't seem to be able to pass my null terminator in.Is this the correct way to do it? When I strlen my buffer the value is 10 but I only keyed in 9 chars.

```
char buffer[256];
int n;

bzero(buffer,256);
fgets(buffer,255,stdin);
buffer[n-1]="\0";
```

Answer: You are assigning a string not a char withbuffer[n-1] = "\0";.Trybuffer[n-1] = '\0';instead.


Question: How would i find out the length of a string without using loop and String class function like strlen() ?

Answer:
```
int length (const char* p)
{
    return *p == 0 ? 0 : 1 + length(p+1);
}
```

Any iterative function can theoretically be implemented recursively and vice versa.


Question:
I'd like to do something likeprintf("?", count, char)to repeat a charactercounttimes.

What is the right format-string to accomplish this?

EDIT: Yes, it is obvious that I could callprintf()in a loop, but that is just what I wanted to avoid.

Answer:
You can use the following technique:

```
printf("%.*s", 5, "=================");
```

This will print"====="It works for me on Visual Studio, no reason it shouldn't work on all C compilers.


Question:
This question is pure teoretical, and not about the right way of doing it, but do we need to convert char 'x' to network format? I'm intressted in all cases: always / sometimes / never
I personally think I should but i need to be sure, than you.

Answer: No, char is a single byte value so endianess doesn't matter


Question:
In CMakeLists.txt, I would like to check that bzlib.h exists:

```
include(CheckIncludeFiles)
check_include_file(bzlib.h HAVE_BZLIB_H)
if(NOT HAVE_BZLIB_H)
    # How can I exit cmake with an error message if bzlib.h does not exists?
endif()
```

Answer: It's quite easy:message( FATAL_ERROR "Your message" )


Question:
I have a unix time_t , is there any easy way to convert this to a time_t so it:

Represents midnight of the day of the time_t ?Represents the start of the hour of the time_t ?

Answer:
Something like this:

```
time_t t = time(NULL);

t -= (t % 86400);
```

The constant 86400 = 24 * 60 * 60 - a useful number to remember, I think... ;)


Question:
I was wondering how does autility like this oneredirects a folder to a driver letter?

PS. I need this done with C/C++/MFC.

Answer: It probably usesDefineDosDevice, as an ordinarysubstcommand does.


Question:
I have a unix time_t , is there any easy way to convert this to a time_t so it:

Represents midnight of the day of the time_t ?Represents the start of the hour of the time_t ?

Answer:
Something like this:

```
time_t t = time(NULL);

t -= (t % 86400);
```

The constant 86400 = 24 * 60 * 60 - a useful number to remember, I think... ;)


Question:
Consider a functionfoo()that might never exit:

```
int foo(int n) {
    if(n != 0) return n;
    else for(;;); /* intentional infinite loop */

    return 0; /* (*) */
}
```

Is it valid C to omit the final return-statement? Will it evoke undefined behavior if I leave out that final statement?

Answer: Even if it does return without a return statement there is no UB unless you use the return value.


Question:
In this piece of code, why in my testing the result is always1,2, and3?

```
#include <stdio.h>

void test() {
    int a;
    a++;

    printf("%d",a);
}

int main(int argc, char *argv[]) {
    test();
    test();
    test();
}
```

I think the variable intest()is static, isn't it? And Why?

Answer: The variable is not static. You're accessing an uninitialized variable. The behavior is undefined.


Question:
In this piece of code, why in my testing the result is always1,2, and3?

```
#include <stdio.h>

void test() {
    int a;
    a++;

    printf("%d",a);
}

int main(int argc, char *argv[]) {
    test();
    test();
    test();
}
```

I think the variable intest()is static, isn't it? And Why?

Answer: The variable is not static. You're accessing an uninitialized variable. The behavior is undefined.


Question:
I find myself always appending the name of the enum, to its values, because else I often have conflicts with other enums, for example:

```
typedef enum
{
    A_ONE,
    A_TWO,
} A;

typedef enum
{
    B_ONE,
    B_TWO,
} B;
```

Is there a nicer way to do this in C?

Answer: No, there is not.  C++ has namespaces, or enums existing in classes (IIRC), but C is extremely primitive in this regard.


Question:
When I call:

```
write_byte((uint8_t*)0);
```

It passes a null-pointer. How can I modify it to pass a pointer to the literal value 0?

Answer:
It passes a NULL pointer.

You cannot take the address of a constant (&0). If you want to pass a pointer to the value0, you must assign0to a variable first.

```
uint8_t i = 0;
write_byte(&i);
```


Question:
Let

```
const char cstring[] = "cstringline";
```

How can the above code be altered, to append CRLF in compile time aka declaration?

Answer:
Unix line ending:

```
const char str[] = "foobarbaz\n";
```

Legacy Mac line ending:

```
const char str[] = "foobarbaz\r";
```

Windows line ending:

```
const char str[] = "foobarbaz\r\n";
```

(But really, google...)


Question:
```
int main(void){
    float f=0,ff=0;
    if (scanf("%f %f",&f,&ff) == 2){
        printf("True\n%f %f",f,ff);fflush(stdout);
    } else{
        printf("False\n%f %f",f,ff);fflush(stdout);
    }

    getchar();
    return 0;
}
```

If my input is "6.81 7.kj" it returns true!!

Answer: 7.is a valid float. The fact that there's more input left is irrelevant to the success of the call.


Question:
I wanted to know like where does the stderr dumps its content.
I have a question like whether it dumps to syslog?
Please explain.

Answer:
stderris just another output stream, just likestdout.

Where it's hooked up depends on how the application is called.

For example if I runfoo.exe 2> errors.txtthenstderrwill write to the specified file.


Question: I need to get file type without using file extensions on linux. There is "file" utility, which can do this. How can I do the same using C/C++? Not 'system(const char *)', of course... Thanks)

Answer:
AFAIKfileis implemented overlibmagic. For more reference see:

filesourcesand maybe this link:http://linux.die.net/man/3/libmagic.


Question:
Good day,

I set up Eclipse with MinGW and my project compiles fine:

However when I try to run it via creating aRun ConfigurationI have the problem that there is noC/C++ Local Applicationlike here:

Mine looks like this:

What is missed? What do I need to do?

Answer: Select Help → Install New SoftwareType this url:http://download.eclipse.org/tools/cdt/releases/indigoTick the CDT Main Features witch includes c++ sdkRestart eclipse done!


Question:
Good day,

I set up Eclipse with MinGW and my project compiles fine:

However when I try to run it via creating aRun ConfigurationI have the problem that there is noC/C++ Local Applicationlike here:

Mine looks like this:

What is missed? What do I need to do?

Answer: Select Help → Install New SoftwareType this url:http://download.eclipse.org/tools/cdt/releases/indigoTick the CDT Main Features witch includes c++ sdkRestart eclipse done!


Question: Suppose defined:int a[100]Typeprint athen gdb will automatically display it as an array:1, 2, 3, 4.... However, ifais passed to a function as a parameter, then gdb will treat it as a normal int pointer, typeprint awill display:(int *)0x7fffffffdaa0. What should I do if I want to viewaas an array?

Answer:
Seehere.In short you should do:

```
p *array@len
```


Question:
There must be some logic behind this calculation. But I am not able to get it.  The normal mathematics does not result in such behavior.  Can anyone help me out in explaining why

printf ("float %f \n", 2/7 * 100.0);results in printing 1.000000

Why so?  I am not understanding the reason

Answer:
Integer division.2/7 = 0as an integer,0 * 100.0 = 0.0as a float.

Do2.0/7 * 100.0to get the answer you're looking for.


Question: I was just curious by default does Microsoft's C/C++ Optimizing Compiler compile down to machine language or byte code?

Answer:
It compiles down to machine language (microprocessor opcodes) by default, orCIL, using the/clrswitch.

For comparison, C# and Visual Basic compile toCIL, and Visual Basic 6 can compile to either P-code (a form of byte code) or native code (machine language).


Question:
I have been using msgsend and receive from

```
#include <sys/ipc.h>
#include <sys/msg.h>
```

for quite a while now.

I just came up with the question whether it is possible to join the communication from a python program.

Thank you

Answer: sysv_ipcmodule provides API for using System V IPC message queues as well as other IPC primitives (semaphores and shared memory).


Question: I have a flac file and I need to analize its waveform, so I need to have the pcm data in an array. Is there some library which does this for me without converting the file with commandline tools? I can use both Python and C.

Answer: I suggest you use libFLAC to decode.http://flac.sourceforge.net/


Question: I'm trying to ping6 an address. If there's a response it's fine. If there's no response, the ping takes anywhere between 100-300ms to return. Is there a way to set the no response time? What's the default no response time?

Answer:
If there is no response, ping6 will time out, i.e. it will wait for a response for a duration t and then report "destination unreachable".

To change the default duration, use the -W option: -W timeout

http://man.he.net/man8/ping6


Question: I have a flac file and I need to analize its waveform, so I need to have the pcm data in an array. Is there some library which does this for me without converting the file with commandline tools? I can use both Python and C.

Answer: I suggest you use libFLAC to decode.http://flac.sourceforge.net/


Question:
```
CvMat* nextimg = 0;
int firstframe;

firstframe=nextimg==0;
```

if I don't put "==0" returns the following warning:

```
[Warning] assignment makes integer from pointer without a cast
```

Answer:
Its a shortened equivalent of

```
int firstframe;
if (nextimg == 0) {
    firstframe = 1;
}
else {
    firstframe = 0;
}
```


Question:
I would like to return+INFbut instead, I am only returning "inf":

```
int main(void)
{
    double dubb = HUGE_VAL;
    printf("%f \n", dubb);
}
```

Am I overlooking something here? Or it is just compiler semantics?

Answer:
Useprintf("%+F\n", dubb);instead

'+' makes printf display the sign
'F' makes inf/nan uppercase


Question:
I would like to return+INFbut instead, I am only returning "inf":

```
int main(void)
{
    double dubb = HUGE_VAL;
    printf("%f \n", dubb);
}
```

Am I overlooking something here? Or it is just compiler semantics?

Answer:
Useprintf("%+F\n", dubb);instead

'+' makes printf display the sign
'F' makes inf/nan uppercase


Question:
Consider the following code.

```
char message[]="foo";

void main(void){
    message[] = "bar";
}
```

Why is there a syntax error in MPLAB IDE v8.63? I am just trying to change the value of character array.

Answer:
You cannot use character array like that after declaration. If you want to assign new value to your character array, you can do it like this: -

```
strcpy(message, "bar");
```


Question: Whenever NaN is returned, I would like for the value returned to instead be 0. What is the best way to go about achieving this end?

Answer:
You can use this function

```
float zero_nan(float n)
{
  return n == n ? n : 0;
}
```

you can inline the function and wrap any return values you think may be nans.


Question:
I haveuint8_t  orig[ETH_ALEN];

How can I print it using__printf(3, 4)

which is defined as#define __printf(a, b)                  __attribute__((format(printf, a, b)))

the Orig should be ethernet hardware address.

Answer:
Use C99 format specifiers:

```
#include <inttypes.h>

printf("%" PRIu8 "\n", orig[0]);
```


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

#define d 10+10

int main()
{
    printf("%d",d*d);
return 0;
}
```

I am new to the concept of macros.I found the output for the above program to be 120.What is the logic behind it?

Thanks.

Answer:
```
10+10*10+10 == 10 + 100 + 10
```

Is that clear?


Question:
I wan to define enum with non constant step. I want that the step between 2 enum variables looks like that:

```
enum test {
   a1 = 1,
   a2 = 1<<2,
   a3 = 1<<3,
   a4, // a4 deduced automatically as 1<<4
   a5 // a5 deduced automatically as 1<<5
}
```

Are there a way to define it as indicated in the above example?

Answer: You must do this manually, or possibly with macro chicanery.


Question:
I wan to define enum with non constant step. I want that the step between 2 enum variables looks like that:

```
enum test {
   a1 = 1,
   a2 = 1<<2,
   a3 = 1<<3,
   a4, // a4 deduced automatically as 1<<4
   a5 // a5 deduced automatically as 1<<5
}
```

Are there a way to define it as indicated in the above example?

Answer: You must do this manually, or possibly with macro chicanery.


Question:
In my C program, I am printing a string to the command terminal usingprintf("%d %s %s\n", node->id, node->date, node->input);but I need to now use the write functionwrite(STDOUT_FILENO, cmdline, strlen(cmdline));...

How can I format the string like I did using printf?

Answer: Usesprintf/snprintfto format the string into a character buffer, and thenwritethat.


Question:
How do I run an executable file likea.outusing the standard C library functionsexec().

Thanks in advance.

Answer:
Whatever isexec, it is not C standard.

If you are speaking aboutexecve(POSIX), look at the documentation.

```
int execve(const char *filename, char *const argv[], char *const envp[]);
```

So:

```
#include <unistd.h>

char *args[] = { "./a.out", /* other arguments */, NULL };

execve("a.out", args, NULL);
```


Question:
I am trying to set flag tcp_nodelay on a unix domain socket. Can we set it or does it even make sense to set tcp_nodelay for UNIX domain sockets, specifically on Linux?

please advise.

thanks

Answer: Unix domain sockets don't use Nagle (and obviously don't use TCP either). Also, the fact that it's calledtcp_nodelayindicates it's a TCP-only thing.


Question:
In my C program, I am printing a string to the command terminal usingprintf("%d %s %s\n", node->id, node->date, node->input);but I need to now use the write functionwrite(STDOUT_FILENO, cmdline, strlen(cmdline));...

How can I format the string like I did using printf?

Answer: Usesprintf/snprintfto format the string into a character buffer, and thenwritethat.


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

int main()
{
    int a=5,*b,*c;

    b=&a;
    c=b;

    *b++=*c++;

    printf(" %d %d %d\n",&a,b,c);
}
```

Here if adress of a is x, then value of b and c is both becoming x+4.  But shouldn't two ++ operator increase atleast one value by 8

Answer:
No.  Don't confuse the value of a pointer with the value that it pointsto.

The expression*b++means: retrieve the value that b pointsto, and then increment the value of b.


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

int main()
{
    int a=5,*b,*c;

    b=&a;
    c=b;

    *b++=*c++;

    printf(" %d %d %d\n",&a,b,c);
}
```

Here if adress of a is x, then value of b and c is both becoming x+4.  But shouldn't two ++ operator increase atleast one value by 8

Answer:
No.  Don't confuse the value of a pointer with the value that it pointsto.

The expression*b++means: retrieve the value that b pointsto, and then increment the value of b.


Question: For C/C++ applications in Windows(non GUI), what should be the proper list of error codes for different failures? I have seen various lists such as from IBM and others, but I was wondering if there was some consensus on typical error codes given to the user when the program exits.

Answer: There are three portable values for the argument toexit:0,EXIT_FAILURE, andEXIT_SUCCESS.0is equivalent toEXIT_SUCCESS.


Question:
I have 3 console programs (.exe), and I want to run them from one console application without showing the windows of the 3 console programs.
All programs are written in VC++.
Any suggestions about how I can do this?

Answer: You can use ShellExecute command to run the other application


Question:
If I have something like this

```
if(pointer!=NULL&&(*pointer)==x) { ... }
```

Will it segfault if pointer is NULL? If it is compiler specific, I'd like to know how it is in GCC.

Answer:
No, because ofshort circuit evaluation.

If the LHS isfalse, then the RHS won't be evaluated. Therefore, if it's aNULLpointer, it will never hit the RHS and attempt to dereference it.


Question:
If I have something like this

```
if(pointer!=NULL&&(*pointer)==x) { ... }
```

Will it segfault if pointer is NULL? If it is compiler specific, I'd like to know how it is in GCC.

Answer:
No, because ofshort circuit evaluation.

If the LHS isfalse, then the RHS won't be evaluated. Therefore, if it's aNULLpointer, it will never hit the RHS and attempt to dereference it.


Question:
I need to know what it means when a function has avoid *parameter. For example:

```
function(void * param){}
```

Answer:
It is a function that receives avoid*. This may be used to pass any kind of pointer in C.

A good example is thepthread_createfunction, and the pthread start routine.

Note, however, that if no return type is specified, it defaults to return anint, which it does not in your example.


Question:
I need to encode a few instructions like

```
mov eax, edx
inc edx
```

to the corresponding x86_64 opcodes. Is there any library (not an entire asm compiler) to accomplish that easily?

Answer: You could take open sourceFASMorNASMand use their parser.


Question: I have a code, that is split into multiple files, and which has to use a lot of constant strings(hundreds), and many of them have to be accessed from functions located in several files, what is the most convenient way to do this?

Answer: You can make a header called e.g.,global.hand put your constants on it and include where the constants is needed(in fact,you will include for context,because you need to useinclude guardsfor avoid redefinition error)


Question:
I want to block the user to backup files to optical discs, so I have to determine if a CDROM drive is writable.

How to do under Windows?

Answer: The drive index (0 = A, 1 = B, etc) for the Windows CD burner can be found in the registry atHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CD Burning\DriveIndex.


Question:
I was going through the linux kernel sources and found this function definition.

```
function(struct net * const *pnet)
```

Can somebody explain what does this mean. Is it a net* or net** or const net* or const net**?

Thanks

Answer: pnet is a pointer to a const point to a struct net (in a case like this, you just read from right to left from the name of the variable to the name of the type, reading*as "pointer).


Question: I write a server/client  TCP application in C .Many clients can be connected to the server at the same time. How can a client be disconnected after 10 seconds he called close()?

Answer: Callcloseon the socket 10 seconds after youacceptit.


Question:
I recently updated Ubuntu from 10.04 to 12.04 this changed the linux Kernel from 2.6.35-30-server to 3.0.0-29-server. After the update I am currently getting an error when I am compiling my driver code.

error: implicit declaration of function 'semaphore_init' [-Werror=implict-function-declaration].

How do I resolve this ?

Answer: Unlesssemaphore_initis a function of your own making, I think you'll wantsema_initinstead.


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

Possible Duplicate:What does “-1L” mean in C?

What does "0L", "1L" mean in C ?
How is it different from "0" and "1" ?
Is there other literals than "L" with similar function in C ?

Answer:
It's an integer constant that has along inttype instead ofint.

C11, § 6.4.4.1 Integer constants #1long-suffix: one oflL


Question:
What is the meaning of:

```
printf("%c", **++argv);
```

in a C command line program?

Answer:
Print the first character of the first argument passed. i.e.argv[1][0]

argvis a pointer to pointer passed tomain().

**++argv:

First it is incremented (due to pre-increment) to point to the next pointer which isargv[1]and then dereferences that pointer to pointer using which isargv[1][0].


Question: Where do i find the definition/body of the printf/scanf & other similar predefined commonly used functions (getch, clrsr ...etc) of "Borland C" ?

Answer:
You cannot.. You can just see the prototype ofprintf/scanfin the header file<stdio.h>

You can find it in the standard library which comes with whatever compiler you are using..


Question:
What is the meaning of:

```
printf("%c", **++argv);
```

in a C command line program?

Answer:
Print the first character of the first argument passed. i.e.argv[1][0]

argvis a pointer to pointer passed tomain().

**++argv:

First it is incremented (due to pre-increment) to point to the next pointer which isargv[1]and then dereferences that pointer to pointer using which isargv[1][0].


Question: Where do i find the definition/body of the printf/scanf & other similar predefined commonly used functions (getch, clrsr ...etc) of "Borland C" ?

Answer:
You cannot.. You can just see the prototype ofprintf/scanfin the header file<stdio.h>

You can find it in the standard library which comes with whatever compiler you are using..


Question: Which roles are used when i call a function with pointer argument unless declare the function before? I know that float are promoted to double and that are executed the integral promotion, but what happens at the pointers?

Answer: Nothing. Default argument promotions don't apply to arguments of pointer type so they are left unchanged in type and value.


Question: I want to store 5 names without wasting  1byte , so how can allocate memory using malloc

Answer: That's for all practical purposesimpossible,mallocwill more often than not return blocks of memory bigger than requested.


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

Possible Duplicate:Passing two-dimensional array via pointer

```
int table[20][20];
int** table1 = table;
int a;
table[0][0] = 4;
a = table1[0][0];
```

the last line gives me Access violation, and i dont get it ..

thanks in advance!

Answer: The short answer is that a pointer to a pointer is not the same as an array of arrays.