Question: I have a small problem. I have numbers from 00000001 to 99999999, and they have to be divided into 000 00001 and 999 99999, respectively, and put them in different variables. Who knows elegant solution for this?

Answer:
Use division to get the first part and modulus to get the second part:

```
void splitter(int number) {
    printf("First part: %i", number / 100000);
    printf("Second part: %i", number % 100000);
}
```


Question:
Very basic question (I am a total noob in C...)

I have a piece of code written:

```
if(!_a[_item[i]] || _b[_item[i]])
```

Does this mean the next line should be run if:

item[i] isnot present in a or in b

or does it mean it should be run if:

item[i] isnot present in aoris present in b?

Thanks

Answer: It meansitem[i]is not present inaor is present inb


Question: I'm writing a program in C using Code::Blocks 13.12 on Windows 8 (the C compiler is mingw32-gcc). I would like to use the "getline" function but it seems to be missing from the stdio.h. Is there any way to get it except for writing own implementation?

Answer:
getlineis a POSIX function, and Windows isn't POSIX, so it doesn't have some POSIX C functions available.

You'll need to roll your own. Or use one thathas already been written.


Question:
I was wondering if there is a shorthand way to initialise a 2D or 3D array in C similar to the following syntax:

```
int array[1024] = {[0 ... 1023] = 5};
```

Answer:
The initialization you use isn't standard C, it's aGCC extension (Designated Initializers).

To initialize a 3d array, use:

```
int array[10][10][10] = {[0 ... 9] [0 ... 9] [0 ... 9] = 42};
```

Demo.


Question:
I can't understand what the following code is doing ons:

```
if(!s--)
```

sis anint

Answer:
Actually, it's misleading.

You are testing issis different from 0 (withif (!s)). And then, afterward, whatever the result is, you're decreasing it.

So, it's two different operations.
It could be written this way :

```
if (!s)
{
     s--;
     //...
}
else
{
     s--;
}
```


Question:
I was wondering if there is a shorthand way to initialise a 2D or 3D array in C similar to the following syntax:

```
int array[1024] = {[0 ... 1023] = 5};
```

Answer:
The initialization you use isn't standard C, it's aGCC extension (Designated Initializers).

To initialize a 3d array, use:

```
int array[10][10][10] = {[0 ... 9] [0 ... 9] [0 ... 9] = 42};
```

Demo.


Question:
I can't understand what the following code is doing ons:

```
if(!s--)
```

sis anint

Answer:
Actually, it's misleading.

You are testing issis different from 0 (withif (!s)). And then, afterward, whatever the result is, you're decreasing it.

So, it's two different operations.
It could be written this way :

```
if (!s)
{
     s--;
     //...
}
else
{
     s--;
}
```


Question:
I upgraded to Yosemite, and now all my compilers (from the command line—gcc and icc) are giving me errors like: cannot open source file “ctype.h"

Does anyone know how to fix this? Do I need to reinstall the compilers?

Answer: OK, not sure what’s going on here, but after updating to Xcode 6.1.1 and installing the associated command line tools, icc seems like it can now find the system headers. Now having a separate issue with gcc, will post separately…


Question:
When I execute the following code on Linux, the output is 32. Why is that so?

```
#include <stdio.h>
#define m 10+2

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

Answer:
Macro expansion doesn't heed the surrounding syntax, soi=m*mgets expanded intoi=10+2*10+2, rather thani=(10+2)*(10+2). This why one should always parenthesize macro definitions and arguments:

```
#define m (10+2)
```


Question:
I upgraded to Yosemite, and now all my compilers (from the command line—gcc and icc) are giving me errors like: cannot open source file “ctype.h"

Does anyone know how to fix this? Do I need to reinstall the compilers?

Answer: OK, not sure what’s going on here, but after updating to Xcode 6.1.1 and installing the associated command line tools, icc seems like it can now find the system headers. Now having a separate issue with gcc, will post separately…


Question:
```
unsigned char x=0;
//int num is some random integer
x=num;
```

How to get 2 least significant bytes?

Answer:
Since you want the two least significant bytes, you will need two unsigned chars to hold the two bytes since unsigned char is just a byte in length.

```
unsigned char x, y;
x = 0x00FF & num; // Get the first least significant byte.
y = (0xFF00 & num) >> 8; // Gets the second least significant byte and store it in the char.
```


Question:
```
unsigned char x=0;
//int num is some random integer
x=num;
```

How to get 2 least significant bytes?

Answer:
Since you want the two least significant bytes, you will need two unsigned chars to hold the two bytes since unsigned char is just a byte in length.

```
unsigned char x, y;
x = 0x00FF & num; // Get the first least significant byte.
y = (0xFF00 & num) >> 8; // Gets the second least significant byte and store it in the char.
```


Question:
Say I have these binary numbers:

0011100000000and

```
0000111000000
```

How would I go about checking to see if these binary numbers have a 1 in the same bit?

Answer:
Yes, as punned by Martin, you want AND.

(0011100000000 & 0000111000000) will result in 0000100000000

Also read up on OR (|) and XOR (^)


Question:
Considering the following:

```
#define SIZE 5

/* ... */

int oxen[SIZE] = {5,3,2,8};
int yaks[SIZE];
yaks[SIZE] = oxen [SIZE];   /* -->Out of range */
```

Can someone explain why its out of range?

Answer:
Arrays indices in C start at 0, so youroxenandyaksarrays range from0toSIZE-1.
You're outside the allowed boundaries, as the compiler rightly warns you about.


Question:
The C system() call runs a program and forwards both stdout and stderr of the command that is run to the stdout and stderr streams of the calling program.

Is it possible to redirect stdout from the command inside the system() call to the stderr stream of the calling program?

Answer:
Just append1>&2to the command executed in your system call:

Example:

```
system("ls 1>&2");
```

will executelsand redirect stdout (1) to stderr (2).


Question:
Kindly help me with this error:

error: storage class specified for 'interrupt_save_disabled'#define TX_INTERRUPT_SAVE_AREA                  register unsigned int interrupt_save_disabled;

This is a header file in which it is used:

```
#if defined (WIN32) || defined (LINUX)
#define register
#endif
  TX_INTERRUPT_SAVE_AREA
```

Answer: You can't haveregisteron a global variable. Remove the specifier.


Question:
Kindly help me with this error:

error: storage class specified for 'interrupt_save_disabled'#define TX_INTERRUPT_SAVE_AREA                  register unsigned int interrupt_save_disabled;

This is a header file in which it is used:

```
#if defined (WIN32) || defined (LINUX)
#define register
#endif
  TX_INTERRUPT_SAVE_AREA
```

Answer: You can't haveregisteron a global variable. Remove the specifier.


Question:
I found in the doc the function :gtk_entry_set_input_purpose()to set the input-method of a gtkentry,
but when using it, gcc didn't recognize it,  it gives me this error

```
implicit declaration of function ‘gtk_entry_set_input_purpose’ [-Wimplicit-function-declaration]
undefined reference to `gtk_entry_set_input_purpose'
```

where is the problem?

Answer:
i think it was a linking problem ,
compiled successfully with windows after linking all libs ,


Question:
I have managed to configure, compile, and install some C source code into a Linux machine.

Now I know that my library (saymylib.so) is available at/usr/local/bin

I would like to write my C program with a main in it, that will access one of the methods inmylib.sothat returns a struct defined in there.

Can somebody help me with this?

Answer:
Something like this should give you the result:

```
gcc -o prog prog.o -L/usr/local/bin -mylib
```


Question: I am trying to use C API to connect my C code to my SQL. I was wondering if anyone has any good beginner  resources so I can get up to speed. All I am trying to do is just store data in tables I made in SQL. If it helps I am using MySQL on my Mac. Thank you!

Answer:
You can find a good MySQL tutorial here:MySQL C API programming tutorial

Here is the official documentation:

20.6.6 C API Function Overview20.6.3 Example C API Client Programs


Question:
```
static void fubar(int a)
{
  void (*b) (int) = fubar; // <---
  static int c;
}
```

http://cdecl.org/says syntax error.

My guess is that b is a pointer to a function returning int. Is this correct?

Answer:
There has to be some return type,

```
void (*b) (int) = fubar;
```

or

```
int (*b) (int) = fubar;
```

Then itbwould be, pointer to function which returnvoid/intand takesintas parameter.


Question:
When I doing my assigment , I am string to use this formatscanf("%[^\n]%*c",s);in putty but it said

```
writing into constant object (argument 2) [-Wformat=]
scanf("%[^\n]%*c",s);
```

I want to input string with white space:

```
const s[10000];
```

Answer:
Changeconst char s[10000]-->char s[10000]

Code cannot write to aconstarray.  It is not a format issue forscanf().


Question:
```
int num = 65537;
char p = (char)num; //char = 1;
```

Whats going on here?
Is itp=num%(127+128)-1orp=num%256or something else?
I need to know why p is equal to 1.
thanks!

Answer: since 65537 is00000000 00000001 00000000 00000001in binary, but the char type has only 1 byte, the last byte is considered for the char value, wich is00000001 = 1


Question:
```
function(void * p)
```

pis an address containing an address to a struct. I cannot get from the given address to the address within to display the data that it points to. There is a really simple solution to do this, however I do not know how to dereference from the given address, and use the information I get as a new address.

Answer:
Just cast to the type you're looking for.

```
MyStruct **pps = (MyStruct**)p;
(**pps).Member = ...
```


Question:
```
function(void * p)
```

pis an address containing an address to a struct. I cannot get from the given address to the address within to display the data that it points to. There is a really simple solution to do this, however I do not know how to dereference from the given address, and use the information I get as a new address.

Answer:
Just cast to the type you're looking for.

```
MyStruct **pps = (MyStruct**)p;
(**pps).Member = ...
```


Question:
Specifically, I'm storing URLs and ports and storing them in a table. A pair would be ("www.beej.us", 80) or ("8.8.8.8", 22). Does it make sense to append the integer onto the string and hash on the final string?

Thanks for the help!

Answer:
For better performance and minimizing collisions, you would better write a hash function as follows:

```
hash(host) * prime_greater_than_65536 + port
```


Question:
This question already has answers here:String literals: Where do they go?(8 answers)Closed8 years ago.

For example this code here:

```
char *s = "Hello";
```

Where is "Hello" being stored? Is it stored the same in memory just anonymously?

Answer: String literals have static storage duration and are allocated in the static memory that is neither on the stack nor in the heap. For example they can be allocated in a read only data segment.


Question:
This question already has answers here:String literals: Where do they go?(8 answers)Closed8 years ago.

For example this code here:

```
char *s = "Hello";
```

Where is "Hello" being stored? Is it stored the same in memory just anonymously?

Answer: String literals have static storage duration and are allocated in the static memory that is neither on the stack nor in the heap. For example they can be allocated in a read only data segment.


Question: Q:Could someone give a hint, why inside my program here are conflicting types, even if its the same?

Answer: If you call a function before it is defined (i.e. earlier in the file than the definition), the compiler won't know the argument types and return type.  You need to have a function prototype before the function is called.  Usually people put function prototypes in header files, but you could just add one near the top of your file.


Question: Q:Could someone give a hint, why inside my program here are conflicting types, even if its the same?

Answer: If you call a function before it is defined (i.e. earlier in the file than the definition), the compiler won't know the argument types and return type.  You need to have a function prototype before the function is called.  Usually people put function prototypes in header files, but you could just add one near the top of your file.


Question: Hi I program in c and I like using clion. Is there a way to change how the default files it creates in a new project? I would like it to create a main.c and the make file to reflect that.

Answer: ReadHow to create a C project with CLion. It's not possible to create a C project by default, but you could use the info of that post to prepare CMakeLists.txt.


Question:
I have a server program running.
I want to connect 1000 clients to it and observe how the server is working. I also want to save the output to a file for analyzing.
My server is just an echo server.

Answer:
You can use netcat:

```
for ii in {1..1000}; do
  (echo "testing"; sleep 5; echo "goodbye") | nc localhost 12345 > out.$ii &
done
wait # for all to finish
```


Question: In Linux I can do this by checking the /proc/pid/status file and looking for a line: Threads: 1 (or any number). How can I achieve the same in FreeBSD? I am not interested in any interactive tool. Is there any C function, or a system file? I have tried BSD's procfs and and linprocfs and I could not find any similair feature there.

Answer:
You want:

procstat -t <pid>

This answer is short, but I'm typing more to get the answer up to the minimum length.


Question: Is the memory lost until a reboot or does VS have some safe-mechanism to handle that? I've always wondered...

Answer: The leaked memory will be freed when the process leaking the memory is closed and the operating system cleans up.


Question: I have achar *p = "abcd", how can I access the elements'a','b','c','d'using only C(not C++)? Any help would be appreciated .

Answer:
You can use indexing:

```
char a = p[0];
 char b = p[1];
 /* and so on */
```

Equivalently you can use pointer arithmetic, but I find it less readable:

```
char a = *p;
char b = *(p+1);
```

If you really want to surprise someone you can also write this:

```
char a = 0[p];
 char b = 1[p];
 /* and so on */
```


Question:
```
typedef struct A
{
    int* whatever;
} A;

int main(void)
{
    A* foo = (A)malloc(sizeof(A));
    foo->whatever = (int)malloc(sizeof(int));
    free(A); // leak? (foo->whatever)
    return 0;
}
```

Do I have to free each component of a struct / composite data type, or can I just free the struct?

Answer: Anything that is malloc'd needs to be freed


Question: I want to test my c code for big endian on Windows (On x86-64). How can we do this?

Answer:
Assuming that you don't have any actual big-endian hardware to hand, your best bet is to use a virtual machine such asQEMUto emulate a big-endian architecture such asSPARCorPowerPC.

You'll then need to install a suitable operating system on your VM - perhapsDebianwould suit your needs.


Question: I want to test my c code for big endian on Windows (On x86-64). How can we do this?

Answer:
Assuming that you don't have any actual big-endian hardware to hand, your best bet is to use a virtual machine such asQEMUto emulate a big-endian architecture such asSPARCorPowerPC.

You'll then need to install a suitable operating system on your VM - perhapsDebianwould suit your needs.


Question:
```
int i=0;
int array[1000]={0};
srandom(23523);
a0=random();
a1=random();
a2=random();
....
a999=random();   //a0,a1,...a999 are some random numbers
for(i=0;i<999;i++){
   ....
   //array[0]=a0 array[1]=a1 array[2]=a2....array[999]=a999
}
```

My goal is to change the values in array to a0, a1...a999.
How to do it by using for loop in C?

Answer:
If you already know the values you don't need a loop.

```
int array[3]= { 0, 14, 22 };
```


Question:
Using C in a Windows in a Kernel Mode Driver using KMDF, how do I determine the owner a of file?

I searched high and low but could not find any hint. Only C++ and of course Csharp.

Answer: After opening a handle to a file, you can use the kernel-modeZwQuerySecurityObjectto get the owner information (and full DACL).


Question:
I'm learning on how to use signals in C with POSIX threads.
I know how to signal threads from main, but how to signal my main from the thread to notify it that it has finished some job? I need the PID of my main. How should I go about doing it?

How can I let my threads know mains PID to send a signal to it?

Answer: In the main threadgetpid() == gettid(), so, you can usegetpid()orgettid()to get PID of main thread.


Question:
I'm learning on how to use signals in C with POSIX threads.
I know how to signal threads from main, but how to signal my main from the thread to notify it that it has finished some job? I need the PID of my main. How should I go about doing it?

How can I let my threads know mains PID to send a signal to it?

Answer: In the main threadgetpid() == gettid(), so, you can usegetpid()orgettid()to get PID of main thread.


Question:
Is there anyway to open an sqlite database in c without having to have the sqlite exes and dlls.
Is there a lib to do this.
I only want to read the database, not write.

Answer:
Have you taken a look at theSQLite3 C/C++ interface?

(See the second bulletpoint of the section titled "Write Programs that use SQLite" at the bottom ofthis pagefor a quick example on how to use it.)


Question: I want to know how to get all data from a gtk treeview (row and column) and put it in a logfile, I know how to create the log, my problem is getting all data, I already know how to get the selected row, but not all rows at once.

Answer: gtk_tree_model_foreach is your friend.


Question:
If I have this code block

```
char *array[] = {"element1" , "eLement2"};
char *p ;
char *pc;
```

How can I point*pto the first String"element 1"andhow can I point*pcto the second character of the second StringLand then print those two using printf

Answer:
p = array[0]
pc = array[1]+1

This should do the trick


Question:
If I have this code block

```
char *array[] = {"element1" , "eLement2"};
char *p ;
char *pc;
```

How can I point*pto the first String"element 1"andhow can I point*pcto the second character of the second StringLand then print those two using printf

Answer:
p = array[0]
pc = array[1]+1

This should do the trick


Question:
If I have this code block

```
char *array[] = {"element1" , "eLement2"};
char *p ;
char *pc;
```

How can I point*pto the first String"element 1"andhow can I point*pcto the second character of the second StringLand then print those two using printf

Answer:
p = array[0]
pc = array[1]+1

This should do the trick


Question:
I want to pack the lowest two bytes of an integer into another in integer, an stuck at this

```
for ( int i = 0; i < 8 ; i ++){
         if ((bitmask & ( 1 << i)))
             result |= 1 >> i;
     }
```

Answer:
Endian-independent solution:

```
x = ((y >> 0) & 0xFF) |
    ((y >> 8) & 0xFF);
```


Question:
I am using a macro defined in the same source file as:

```
#define MY_MACRO (a, b,...) (...)
```

The macro is being used later in the file.

However, the compiler complains:

error: a undeclared (first use in this function).

It's really weird.. am I missing something obvious?

Answer:
I think the problem is that there is a SPACE betweenMY_MACROand(a, b, ...). It should be like this:

```
#define MY_MACRO(a, b,...) (...)
```


Question:
I am writing some C code with Eclipse + CDT + MinGW.

The compilation output always shows:

```
Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o Math.o "..\\Math.c"
```

How can I change the command line parameters such as -O0, -Wall?

(I am new to Eclipse IDE.)

Answer: For GCC, the setting is in project properties => C/C++ Build => Settings => GCC C Compiler => Optimization.


Question:
I am writing some C code with Eclipse + CDT + MinGW.

The compilation output always shows:

```
Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o Math.o "..\\Math.c"
```

How can I change the command line parameters such as -O0, -Wall?

(I am new to Eclipse IDE.)

Answer: For GCC, the setting is in project properties => C/C++ Build => Settings => GCC C Compiler => Optimization.


Question:
Suppose I want to generate a very long, repetitive string, such as

```
"foo bar bar bar bar ... bar"
```

wherebaroccurs 1,000 times in the final result. What would be the easiest way to do this without having memory leaks?

Answer:
The first thing that came to my mind is:

```
char *string = malloc(4004);
int i;
strcpy(string, "foo");
for(i = 0; i < 1000; i++)
    strcat(string, " bar");
```


Question:
I need to initialize a typedef struct pointer

in header file,

```
typedef struct {
    DWORD RxBuf[4];
    DWORD Tr0c;
} t, *p_t;
```

In the cpp file,

```
static p_t p1
    = {
    {0x00,0x00,0x00,0x00},
    0
};
```

Answer:
Just a guess, I believe you want to do:

```
static t tNull
    = {
    {0x00,0x00,0x00,0x00},
    0
};

static p_t p1 = &tNull;
```


Question:
I need to initialize a typedef struct pointer

in header file,

```
typedef struct {
    DWORD RxBuf[4];
    DWORD Tr0c;
} t, *p_t;
```

In the cpp file,

```
static p_t p1
    = {
    {0x00,0x00,0x00,0x00},
    0
};
```

Answer:
Just a guess, I believe you want to do:

```
static t tNull
    = {
    {0x00,0x00,0x00,0x00},
    0
};

static p_t p1 = &tNull;
```


Question:
Now, when I print each element in my block array, each one has the same address.  For example:

```
ints:   20 bytes stored at 0xbffa84fc
doubles:   80 bytes stored at 0xbffa84fc
chars:   8 bytes stored at 0xbffa84fc
Students:   1008 bytes stored at 0xbffa84fc
```

Answer:
```
blk->addr = &blk;
```

The address of the allocated memory actually isblkitself. But here, you are using&blk, i.e, the address ofblk.


Question:
So far, I can print in one column quite nicely :

```
for (i = 0 ; i < *lengthOfFile ; i++)
{
    fprintf(myFile, "%d\n", thisArray[i]);
}
```

Easy enough.  However, how would I go about printing in columns of ten if say I have 20 or 100 or 10000 or more numbers?

Anything would help very much, thank you!

Answer: You can print "%d\t" instead of "%d\n", and move the "\n" into its own print statement that only occurs when (i % 10) == 0.


Question:
If I have an array declared as

```
char arr[1] = "";
```

What is actually stored in memory? What will a[0] be?

Answer:
Strings are null-terminated. An empty string contains one element, the null-terminator itself, i.e,'\0'.

```
char arr[1] = "";
```

is equivalent to:

```
char arr[1] = {'\0'};
```

You can imagine how it's stored in the memory from this.


Question:
If I have an array declared as

```
char arr[1] = "";
```

What is actually stored in memory? What will a[0] be?

Answer:
Strings are null-terminated. An empty string contains one element, the null-terminator itself, i.e,'\0'.

```
char arr[1] = "";
```

is equivalent to:

```
char arr[1] = {'\0'};
```

You can imagine how it's stored in the memory from this.


Question:
Why does this hang without first printing?

```
#include <stdio.h>

void main() {
    printf("hello world");
    while (1) {}
}
```

Answer:
Because you haven't flushed the standard output.  Tryfflush.  Even better, for C++ use...

```
std::cout << "hello world" << std::endl;
```

Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.


Question:
Why does this hang without first printing?

```
#include <stdio.h>

void main() {
    printf("hello world");
    while (1) {}
}
```

Answer:
Because you haven't flushed the standard output.  Tryfflush.  Even better, for C++ use...

```
std::cout << "hello world" << std::endl;
```

Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.


Question:
Why does this hang without first printing?

```
#include <stdio.h>

void main() {
    printf("hello world");
    while (1) {}
}
```

Answer:
Because you haven't flushed the standard output.  Tryfflush.  Even better, for C++ use...

```
std::cout << "hello world" << std::endl;
```

Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.


Question: I'v been use some module manager like npm for node.js or apt-get in ubuntu, I find it's really easy to build more. And I just want to know is there a cpm for module manage in c programming?

Answer: clibmay be the answer.https://github.com/clibs/clibit is proposed to offer some stand-alone "micro c libraries".


Question: Is there an option that I can use to separate parts of my GUI with lines in Glade 3? I want some widgets to be separated from the others; for example I would like to put them in a box.

Answer: Use GtkSeparator; its icon is the vertical line in the Control and Display section of the tool palette.


Question:
I developed a program in which I use a http client with libcurl.

I want to find out the source tcp port used by libcurl in a tcp session.

How can I do that ?

Answer: curl_easy_getinfowith theCURLINFO_LOCALPORToption!


Question:
Glibc provides the very handybacktrace()andbacktrace_symbols()functions, which can help getting the stack trace of the current function programmatically (see here).

Does the Windows API provide any similar functions?

Answer: Yes, take a look at the functionCaptureStackBackTrace(). UseSymFromAddr()and its counterparts to get meaningful symbol names.


Question:
Given an API like this :

write_data(uint32_t address,uint8_t *data)

how can I transmit a constant to my embedded device, like 0x001 ?

Answer: You create a variable and assign the constant to it. Then you pass a pointer to the variable.


Question:
This question already has answers here:What does void mean in C, C++, and C#?(15 answers)Closed8 years ago.

What is the value that is stored in void()? Basically it is used before a function which doesnot return anything. But does simply void holds any value?

Answer:
Void is an incomplete type which, by definition, can't be an lvalue.
That means it can't get assigned a value.

So it also can't hold any value.


Question:
This is my program :

```
#include<stdio.h>
int main()
{
    int *n;
    int var;
    scanf("%d",n);
    printf("%d",*n);

}
```

asscanfstores the value at specified address I am giving the address .Then I am trying to print value at address but its giving segfault.

Answer:
You should allocate memory for pointers like this:

```
int* n = (int*)malloc(sizeof(int))
```


Question: I am working on a project in which If I could include a header file at runtime, it would save some programming effort. I google'd about it, but all in vain. My question is :Can we include header files in a C program at runtime ?If yes, how?If not, why?

Answer: In C the source files are only read compile-time, so the answer to your question isnot. Runtime there is only the executable binary, which has nothing to do with your source code headers.


Question:
i have created macro as following

```
#define log printf("(%s):(%d)  ",__FUNCTION__, __LINE__);printf
```

And i am using it in main function for logging

```
log("Hello world\n");
```

it is resulting in run time error as "lldb".
Error in IDE is displaying "called object type 'int' is not a function or function pointer in x code"

Answer:
Try:

```
#define LOG( s ) printf( "(%s):(%d)%s\n", __FUNCTION__, __LINE__, s );
```


Question:
I see many programmers that include "utils.h" to their program.
Tried to search for what it is exactly and what is the proper use of utils.h, but all I found was different versions of the file.
So what is it exactly?

Answer:
Many programmers define common functionalities inutils.cand declare them inutils.h. You could implement for example command line parsing methods in utils.h / utils.c.

But utils.h is no standard file to be included.


Question:
I see many programmers that include "utils.h" to their program.
Tried to search for what it is exactly and what is the proper use of utils.h, but all I found was different versions of the file.
So what is it exactly?

Answer:
Many programmers define common functionalities inutils.cand declare them inutils.h. You could implement for example command line parsing methods in utils.h / utils.c.

But utils.h is no standard file to be included.


Question:
How do I write nothing inifpart if the condition is true?

For example:

```
if(true)
   // I want to keep this space blank or want compiler to do nothing here
else
   break;
```

How do I do this?

Answer:
Typically, this is written by negating the condition:

```
if (not true)
   break;
```


Question:
How can I write three different matrices of different sizes say A, B and C using C?

The doubt being that once a particular row is printed the cursor is in the bottom most position, now how do we bring it back up?

Answer:
You don't. you plan in advanced the rows and then print each row (one you go down - you can't go up....)

If you can't handle the logic - use a 2d array to store everything and then print it.


Question:
How do I write nothing inifpart if the condition is true?

For example:

```
if(true)
   // I want to keep this space blank or want compiler to do nothing here
else
   break;
```

How do I do this?

Answer:
Typically, this is written by negating the condition:

```
if (not true)
   break;
```


Question:
How can I write three different matrices of different sizes say A, B and C using C?

The doubt being that once a particular row is printed the cursor is in the bottom most position, now how do we bring it back up?

Answer:
You don't. you plan in advanced the rows and then print each row (one you go down - you can't go up....)

If you can't handle the logic - use a 2d array to store everything and then print it.


Question:
What is the unary-& doing here?

```
int * a = 1990;
int result = &5[a];
```

If you were to printresultyou would get the value 2010.

You have to compile it with-fpermissiveor it will stop due to errors.

Answer: In C, x [y] and y [x] are identical. So &5[a] is the same as &a[5].


Question:
Is it possible to intercept primitive operations (+,-,% etc.) like this one, with LD_PRELOAD?

```
int64_t endWhenNsec = startWhenNsec + gTimeLimitSec;
```

If not, any way to achieve something similar?

Answer: No.  Primitive operators are compiled directly to machine code.  There is no library involved, so preloading libraries cannot alter their behavior.  What a mess if it could!


Question:
Is there any way to do this withstrtokfunction? or any suggestions ?

Example :

```
Insert "hello world" to dbms
```

Result:

```
Insert
"hello world"
to
dbms
```

Answer: strtokor any other function in the standard C library can't do this for you. To get it, you have to write code for it yourself, or you have to find some existing code in some external library.


Question:
According to the man page for pause, it returns -1 and sets errno to EINTR.

Why does it do this? I understood -1 to mean a failure, not something operating as normal.

Answer: The only timepause()stops pausing is when it is interrupted, and that is a return on failure (to continue pausing).  So, correctly, it returns -1 to indicate that it failed to continue pausing.


Question:
Is it possible to clear the output at the command prompt using C on windows?

For example, on linux I could do

```
printf("\033[2J");
```

But as far as I know windows doesn't recognise the ANSI escape codes
Thanks.

EDIT: I guess I'll also need to get the cursor back to 0,0 fo r the next output after the clear...

Answer:
There are many way to do that on windows.

You includeconio.hand call_clrscr();

Or you can callsystem("cls");


Question:
I have the following function in assembly, but I need it in C. The code is:

```
push    ebp
mov ebp, esp
mov eax, DWORD PTR [ebp+8]
add eax, 1667940388
pop ebp
ret
```

Could anybody translate this into C for me. Thanks.

Answer:
Sorry for the silly mistake on theeaxreturn value ... its' fixed now ... my assembly is a little rusty :)

```
int function(int value)
{
    return value + 1667940388;
}
```


Question:
I have the following function in assembly, but I need it in C. The code is:

```
push    ebp
mov ebp, esp
mov eax, DWORD PTR [ebp+8]
add eax, 1667940388
pop ebp
ret
```

Could anybody translate this into C for me. Thanks.

Answer:
Sorry for the silly mistake on theeaxreturn value ... its' fixed now ... my assembly is a little rusty :)

```
int function(int value)
{
    return value + 1667940388;
}
```


Question:
I have the following function in assembly, but I need it in C. The code is:

```
push    ebp
mov ebp, esp
mov eax, DWORD PTR [ebp+8]
add eax, 1667940388
pop ebp
ret
```

Could anybody translate this into C for me. Thanks.

Answer:
Sorry for the silly mistake on theeaxreturn value ... its' fixed now ... my assembly is a little rusty :)

```
int function(int value)
{
    return value + 1667940388;
}
```


Question: How do I create a soft link programmatically in C/C++? link() system call in freebsd will create a hard link.

Answer:
The system call you want issymlink(2).

```
#include <unistd.h>

int symlink(const char  *name1, const char *name2);
```

A symbolic linkname2is created toname1


Question:
What could be the simplest way to split strings in an array and put it to array of array of strings in C.

For example

```
["this is a test", "this is also a test"]
```

into

```
[["this", "is", "a", "test"], ["this", "is", "also", "a", "test"]]
```

Answer:
Usestrtokfunction from the C library. The function splits a string into a serie of tokens.

http://man7.org/linux/man-pages/man3/strtok.3.html


Question:
How can I set the socket buffer size for a UNIX socket file descriptor in C?
I understand setsockopt is probably the system call involved...
Can anyone give an example of how to use it, the one's I have found do not explain how to set the buffer size?

Answer: On Ubuntu 14.04 Linux check outman 7 socket, and specifically look atSO_RCVBUFandSO_SNDBUF.


Question: Is there a way using the OpenLDAP API to set a particular network interface address to be used for socket bind on the LDAP client on a multi homed machine; like you do with the LDAP_OPT_SOCKET_BIND_ADDRESSES option with Microsoft's LDAP client.

Answer: You can do it by creating and binding and connecting the socket yourself and then calling ldap_init_fd() to turn it into an LDAP connection.


Question:
I'm developing in c, using visual studio 2013.
I wonder if there is a way in visual studio, or a plugin, that enable to refactor names of variable/functions ...

If not, Is there any other recommended IDE that enables refactoring with C?
Thanks.

Answer: Visual Assist(commercial) andVisual C++ Refactoring(free) extensions for VS 2013 support the rename refactoring for C.


Question: How to generate random numbers with rand() and srand() without time.h in C ?

Answer:
You could try givin another seed to the random generator like the program's pid.

```
srand(getpid());
int num = rand();
```


Question:
```
for (int i = 0; i< n; i++)
    arr[arr[i]%k] += k;
```

I'm new to programming and I came across this piece of codehere. Can anyone explain what it does?

Answer:
Translate to:

```
for (int i = 0; i< n; i++) {
    int temp1 = arr[i];
    int temp2 = temp1%k;
    int temp3 = arr[temp2];
    arr[temp2] = temp3+k;
}
```

Edit: thanks for the correction @R Sahu


Question:
Does K&R 2nd edition explain the usage of typedefs to make declaration and use of function pointers easier? I lost my copy and can't recollect of it does or it does not.

Thanks.

Answer: Yes, this is explained in section 6.7, "Typedefs".


Question:
How can I tell what version of the C library python's zlib module was built with?

Specifically, I want to tell whether it was a new enough version to support ZLIB_RSYNC=1

This is different than the version of the zlib pythonmodule, but instead the version of the underlying C library

Answer:
It iszlib.ZLIB_VERSION:

```
>>> import zlib
>>> zlib.ZLIB_VERSION
'1.2.7'
```


Question:
How can I tell what version of the C library python's zlib module was built with?

Specifically, I want to tell whether it was a new enough version to support ZLIB_RSYNC=1

This is different than the version of the zlib pythonmodule, but instead the version of the underlying C library

Answer:
It iszlib.ZLIB_VERSION:

```
>>> import zlib
>>> zlib.ZLIB_VERSION
'1.2.7'
```


Question: From which file ifconfig command takes input for displaying ip address, inet addr and h/w addr ?. I want this information for my presentation. Any file apart from /etc/network/interfaces is there ?  Looking foreword for help.

Answer:
It's in the manual man. just run commandman ifconfigin your terminal and at bottom it says
it comes from these three files:

```
FILES
       /proc/net/socket
       /proc/net/dev
       /proc/net/if_inet6
```

Hope it works.


Question:
If the following array contained shell code in a C program on a LINUX machine

```
char buf [100]
```

then how does the following execute this shell code :

```
((void(*)())buf)()
```

Answer:
Simple. It castsbufto a pointer-to-function taking no arguments and returningvoid, and then invokes that function.

However, that probably won't work since the page containingbufis highly unlikely to be marked as executable.


Question:
I am reading the current directory and printing it out using

```
printf("%s\n", file->d_name);
```

but it also prints out "." and ".." files. How can I exclude them?

Answer:
The simple way:  just make sure the file name isn't"."or".."before you display it.  :P

```
if (strcmp(file->d_name, ".") && strcmp(file->d_name, "..")) {
    printf("%s\n", file->d_name);
}
```


Question:
I'm trying to create a game for my CS assignment and I'm stuck with this for loop that won't end my game even though the lives are already at zero.

```
for(life = 3, ai_life = 3; ai_life != 0, life != 0; --ai_life, --life)
```

Answer:
Please read up what thecomma operatordoes

```
for(life = 3, ai_life = 3; ai_life != 0 && life != 0; --ai_life, --life)
```


Question:
Lets say I am in /home/myuser

there are 90,000 files there inside 3000 directories.

How can I write a bash function or with linux commands to get one random file?

It could be C as well I suppose

Answer:
You can list all your files and then pick a random line between them:

```
find /home/myuser | sort -R | head -n1
```

However this is not very efficient, and could take a while, but is easy to understand. You can work from here.


Question:
I am reading the current directory and printing it out using

```
printf("%s\n", file->d_name);
```

but it also prints out "." and ".." files. How can I exclude them?

Answer:
The simple way:  just make sure the file name isn't"."or".."before you display it.  :P

```
if (strcmp(file->d_name, ".") && strcmp(file->d_name, "..")) {
    printf("%s\n", file->d_name);
}
```


Question:
I'm trying to create a game for my CS assignment and I'm stuck with this for loop that won't end my game even though the lives are already at zero.

```
for(life = 3, ai_life = 3; ai_life != 0, life != 0; --ai_life, --life)
```

Answer:
Please read up what thecomma operatordoes

```
for(life = 3, ai_life = 3; ai_life != 0 && life != 0; --ai_life, --life)
```


Question:
```
int gcd(int x, int y) {
    int t;
    while (y) {
        t = x;
        x = y;
        y = t % y;
    }
    return x;
}
```

Does it stop when y = 0? I thought the loop stops when y isn't defined.

Answer:
Yes, it stops when y is 0, what you have

```
while (y)
```

is short hand for

```
while (y != 0)
```


Question:
```
int foo(int n)
{
    int sum = 0;
    for(int k=1; k <= n; k = k * 2)
    {
        sum += k;
    }
    return sum;
}
```

I have the following function.
Now, according to me the runtime complexity of foo(n) should be big-o(logn).
Now, I am asked to find out the run time complexity of foo(n*n*n*n). What should it be?
According to me, it should be, big-o(logn) only.
Am I right in saying this?

Answer: It is O(log n4) → O(4 log n) → O(log n)


Question:
```
int foo(int n)
{
    int sum = 0;
    for(int k=1; k <= n; k = k * 2)
    {
        sum += k;
    }
    return sum;
}
```

I have the following function.
Now, according to me the runtime complexity of foo(n) should be big-o(logn).
Now, I am asked to find out the run time complexity of foo(n*n*n*n). What should it be?
According to me, it should be, big-o(logn) only.
Am I right in saying this?

Answer: It is O(log n4) → O(4 log n) → O(log n)


Question:
```
int main()
{
int a,i;
 char b;
for(i=0;i<3;i++)
 scanf("%c %d",&a,&b);
```

}

The program only scans twice (each for char and int) and then terminates.

OUTPUT

r

3

4

t

Now program is terminating rather than scanning two more times(one char and one int)

Answer:
```
scanf(" %c %d",&a,&b);
```

solves the problem


Question:
```
int main()
{
int a,i;
 char b;
for(i=0;i<3;i++)
 scanf("%c %d",&a,&b);
```

}

The program only scans twice (each for char and int) and then terminates.

OUTPUT

r

3

4

t

Now program is terminating rather than scanning two more times(one char and one int)

Answer:
```
scanf(" %c %d",&a,&b);
```

solves the problem


Question:
please could you help me understand what's __format in printf prototype for?

extern int printf (const char *__restrict __format, ...);

How can I find set of these in documentation?

Thanks!

Answer:
as per the ISO/IEC 9899:1999 declaration,

int printf(const char * restrict format, ... );

using the__is a variable nomenclature.


Question:
This question already has answers here:!! c operator, is a two NOT?(4 answers)Closed9 years ago.

While going over infrastructure code, I found this:

```
return !!(fin.flags & FIN_ACCEPT);
```

Does this has a meaning other than two logical nots in succession?

Answer:
!is logical negation.!!is logical negation applied twice.

It is typically used to normalise a boolean expression value to be either0or1.


Question:
```
struct tree{
#ifdef A
   #define TREE_GET(x,y)        &x->y
#else
   #define TREE_GET(x,y)        x->y
#endif
};
```

I want to know whether macro A  was defined . Is there any command I can use in gdb .

Answer:
In compilation time we pass the -gdwarf-2 and -g3 flags to ensure the compiler includes information about preprocessor macros in the debugging information.

For example,g++ -gdwarf-2 -g3 program.cpp -o program

C Preprocessor Macros


Question:
```
struct tree{
#ifdef A
   #define TREE_GET(x,y)        &x->y
#else
   #define TREE_GET(x,y)        x->y
#endif
};
```

I want to know whether macro A  was defined . Is there any command I can use in gdb .

Answer:
In compilation time we pass the -gdwarf-2 and -g3 flags to ensure the compiler includes information about preprocessor macros in the debugging information.

For example,g++ -gdwarf-2 -g3 program.cpp -o program

C Preprocessor Macros


Question:
```
int main()
{

  static int fun(){}
  return 0;
}
```

** If we define a function into another then why this code is giving following error:**

Error: invalid storage class for function ‘fun’

Answer: This is called "nested function". It's not supported in C. Some compilers, such asgcc, offer it as language extension. You do not need thestatickeyword though.


Question: What happens if you callopendir(argv[i])andargv[i]is the name of atextfile, not adirectory?

Answer:
Fromman opendir:

Return ValueTheopendir()andfdopendir()functions return a pointer to the directory stream. On error,NULLis returned, anderrnois set appropriately.

In this case,errnowould beENOTDIR: name is not a directory.


Question:
I initialized my array like this:char x[]={'m'};

It worked.
But for the following lines i got error:Size of the type is unknown or zero

```
char x[][]={{'m'},{'m'}};
```

or

```
char x[][]={{'m'}};
```

I am unable to find the reason of the error.

Answer:
While defining a 2D array, specifying the column size is mandatory.

```
char x[][1]={{'m'}};
```


Question:
I initialized my array like this:char x[]={'m'};

It worked.
But for the following lines i got error:Size of the type is unknown or zero

```
char x[][]={{'m'},{'m'}};
```

or

```
char x[][]={{'m'}};
```

I am unable to find the reason of the error.

Answer:
While defining a 2D array, specifying the column size is mandatory.

```
char x[][1]={{'m'}};
```


Question:
I would like to initialize an array of strings with \0.
Is it right to do it like this?

```
char first[1024][1024] = {'\0'};
```

Answer:
For a 2d array is better to use:

```
char first[1024][1024] = {{'\0'},{'\0'}};
```

or better yet (as suggested by @haccks):

```
char first[1024][1024] = {{'\0'}};
```

in order to avoid warnings.


Question:
i need to put many symbols in one array of char.

This is my code, I have problem with the single quote symbol, "'" :

```
int main()
{
    int i, j;
    int a;
    char alph[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','.',',',':','?','=','-','(',')','"',''','/','%','@','!'};
}
```

Answer: You can escape the quote with a backslash, i.e.'\''


Question:
I have a simple program like :

```
#include <stdio.h>

int main(void){
*(int*) 1 = 1;
return 0;
}
```

but why it is giving me Segmentation fault?

Answer:
This will most likely crash no most systems. The assignment

```
*(int*)1 = 1;
```

tries to assign 1 to the location in memory with address 1. This is very undefined behaviour, and in most of systems the memory protection mechanism raises an error when you try it.


Question: I want to remove or hide some components from my window (button, combobox, etc). How can I do that?

Answer:
So, I've found answer on pelles-c forum:http://forum.pellesc.de/index.php?topic=6382.0

```
ShowWindow(hWnd, SW_HIDE);
// where hWnd - is some component
```


Question:
I have a simple program like :

```
#include <stdio.h>

int main(void){
*(int*) 1 = 1;
return 0;
}
```

but why it is giving me Segmentation fault?

Answer:
This will most likely crash no most systems. The assignment

```
*(int*)1 = 1;
```

tries to assign 1 to the location in memory with address 1. This is very undefined behaviour, and in most of systems the memory protection mechanism raises an error when you try it.


Question: I want to remove or hide some components from my window (button, combobox, etc). How can I do that?

Answer:
So, I've found answer on pelles-c forum:http://forum.pellesc.de/index.php?topic=6382.0

```
ShowWindow(hWnd, SW_HIDE);
// where hWnd - is some component
```


Question:
This question already has answers here:Command-line Parameters in C program?(5 answers)Closed9 years ago.

How can I send parameters to main in C(Linux):
first one is -c or -d
second is a string like file.

How I'm doing that?

Answer:
First, send data to your program using command line argument Like @haccks said

Second, get the arguments in your code using :

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

Tutorial Here


Question:
I need to know if there is 3 d array say :

```
int a[2][3][2]={{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}};
```

How And what does the expression a[1]-a[0] calculate?

Answer:
what does the expression a[1]-a[0] calculate?

It calculates the difference between the pointers to whicha[1]anda[0]decay if use as operators to the arithemtic operator-.


Question:
I have some arrays that are declared like this:

```
static double covalent_radius[256] = {
    [ 0 ] = 0.85,
    [ 1 ] = 0.37,
    ...
};
```

C++ doesn't allow this kind of declaration. Is there any way to achieve this?

Answer:
```
static double covalent_radius[256] = {
    0.85, /* ?,  Unknown    */
    0.37, /* H,  Hydrogen   */
    ...
};
```

It's C89, not C99 so I suppose it should work.


Question:
I have some arrays that are declared like this:

```
static double covalent_radius[256] = {
    [ 0 ] = 0.85,
    [ 1 ] = 0.37,
    ...
};
```

C++ doesn't allow this kind of declaration. Is there any way to achieve this?

Answer:
```
static double covalent_radius[256] = {
    0.85, /* ?,  Unknown    */
    0.37, /* H,  Hydrogen   */
    ...
};
```

It's C89, not C99 so I suppose it should work.


Question:
Can someone explain why this expression produces 1 as result?

```
i = 1 && 2 + 3 | 4;
```

What is exactly the order of the operations here?

Answer:
```
i = (1 && ((2 + 3) | 4)))
```

Boolean expression in C always evaluates to 0 or 1. Anything that's not 0 is considered true.

1 != 02 + 3 == 55 | 4 == 5 (| is the bitwise or operator)5 != 01 && 5 == 1


Question:
I was wondering if it's possible to use a regex.replace in flex BEFORE the parsing starts.
Is there a predefined variable representing the whole input string?

Answer:
No, there is no variable representing the whole input string.

Think about it, this would not be possible for a generic scanner as Flex which must be able to handle very large file sizes, and can be used for a virtually infinite input in an interactive command parser.


Question:
I'm compiling a C program for an embedded application using eclipse, but I need the code to know (at runtime) where exactly it ends in flash. What is the simplest way of doing this?
Thanks

Answer: You will need to go into the linker command file and create some labels that mark the start and end of the .text section in memory then in the code take the difference.


Question:
I'd like to fork and exec and program as a non root user while the parent retains root permissions.

pseudo code:

```
pid = fork();

  if (pid == 0) {
      if (RunAsUser(ConvertStringToUserId("John")) == false) {
          stop();
      }
      if (RunAsUser(ConvertStringToUserId("admin")) == true) {
          stop();
      }
      CreateProcess();
  }
```

Answer: If you want to drop privileges in C code, use the functionsetuid.


Question:
I was wondering if it's possible to use a regex.replace in flex BEFORE the parsing starts.
Is there a predefined variable representing the whole input string?

Answer:
No, there is no variable representing the whole input string.

Think about it, this would not be possible for a generic scanner as Flex which must be able to handle very large file sizes, and can be used for a virtually infinite input in an interactive command parser.


Question:
I am writing a C code which reads from a file and generates an intermediate.cfile.
To do so I usefprintf()to print into that intermediate file.

How can I print"?

Answer:
You can use escape symbol\"For example

```
puts( "\"This is a sentence in quotes\"" );
```

or

```
printf( "Here is a quote %c", '\"' );
```

or

```
printf( "Here is a quote %c", '"' );
```


Question: Suppose I have a number liken = 1462. When I performi = n%10, the value ofi = 2. After this operation, I want the value ofn = 146, i.e., remove the2from the number. How do I do this in C? Sorry I am very new to C programming. Thanks guys!

Answer:
Afteri=n%10usen=n/10. then you will getn=146

```
i = n%10;
n = n/10; // Solution
```


Question: I was taking a look at some code for a microcontroller when I came across this cast:(void (*) (void))ROM_FPUTABLE[8]I was wondering what it actually does. Any ideas?

Answer:
void (*) (void)specifies a pointer to a function, which returns nothing, and takes no arguments.

Therefore(void (*) (void))casts something to a pointer to a function, which returns nothing, and takes no arguments.


Question: I was taking a look at some code for a microcontroller when I came across this cast:(void (*) (void))ROM_FPUTABLE[8]I was wondering what it actually does. Any ideas?

Answer:
void (*) (void)specifies a pointer to a function, which returns nothing, and takes no arguments.

Therefore(void (*) (void))casts something to a pointer to a function, which returns nothing, and takes no arguments.


Question:
I'm writing program, that can send emails through SMTP, on C/C++ using cURL library.

I have got problem - I can't start new line in email.

I tried using'\0'and'\n'symbols.

Answer:
It should be\r\nnot/n.

Same goes to\0


Question:
In C, I have a header filefile1_0.hwhich is included by onlyfile1.handfile1.c.

file1.his included by many other files say,file2.c,file3.candfile4.c

If I make any change infile1_0.hI know that I need to re-compilefile1.cbut do I also need to recompilefile2.c,file3.candfile4.c?

Answer:
Yes.

All your other files depend onfile1_0.hsincefile1.hdepends on it and all the others depend onfile1.h. So you need to recompile "to be safe".


Question:
How does~operator work in c?

can anyone explain the following code?

```
main()
{
   printf("%d",~5);
}
```

output is-6

Answer:
5is (probably) a 32-bit signed integer with bit representation0x00000005, or in binary:

```
0b00000000000000000000000000001010
```

~5is the bitwise NOT of5, which will be0xFFFFFFFA, or in binary:

```
0b11111111111111111111111111110101
```

Usingtwo's complement, that is-6.


Question:
I was solving C programming Questions and I came across this

```
#include<stdio.h>
int main()
{
   int x=100,y=200,z=300;
   printf("%d..%d..%d");
}
```

I expected an error but the output was300..200..100

Can anyone explain this output?

Answer: %dinprintfexpectsinttype argument. You are passing no arguments. Its a constraint violation and ultimately your program invokesundefined behavior.


Question:
I was solving C programming Questions and I came across this

```
#include<stdio.h>
int main()
{
   int x=100,y=200,z=300;
   printf("%d..%d..%d");
}
```

I expected an error but the output was300..200..100

Can anyone explain this output?

Answer: %dinprintfexpectsinttype argument. You are passing no arguments. Its a constraint violation and ultimately your program invokesundefined behavior.


Question:
Is there any C or C++ function which can produce the same output of this python code (SHA512 with salt)?

```
import crypt;
crypt.crypt('test', '$6$Salte2Ck$')
```

Answer: Hereare some explanations to Python'scryptfunction.So I think what you are looking for is the C functioncryptfromunistd.h.


Question:
Currently, I have an application that does:

execlp(java_exec, java_args, etc, etc);

to launch a jar file.

Is there a way to also have it prependLD_PRELOAD="mylib.so"?

I couldn't find a way to tellexeclpto do:LD_PRELOAD="mylib.so" java -jar foo.jar

Any ideas how I can achieve this in C or C++ on Linux?

Answer: You should probably addLD_PRELOAD=mylib.soto*envp,execlpe()'s fourth arg.


Question: I was wondering if  there is a ALSA function that can tell which sample frequencies are supported by the recording using ALSA?

Answer:
That would be thesnd_pcm_hw_params_get_rate_maxfunction.

For an example, seehw_params.c.


Question: I was wondering if  there is a ALSA function that can tell which sample frequencies are supported by the recording using ALSA?

Answer:
That would be thesnd_pcm_hw_params_get_rate_maxfunction.

For an example, seehw_params.c.


Question:
Is there a function to return a keysym from a string representation of the key?

for example,SDL_GetKeySym("d") == SDLK_d

I need this to read a keysym from a config file, and of course I'm usingSDL_GetKeyNameto get a string representation of the key and then saving it to the config file.

Answer: SDL2 adds theSDL_GetKeyFromNamefunction, which does the inverse ofSDL_GetKeyName.


Question:
How do you store a 16 bit binary in an array in C? What data type would I have to make the array? long int, float, char?
ex. data = {'1001111101110010', '1001101011010101','1000000011010010'}

Answer:
Withinstdint.his the followingtypedef:

uint16_t

This integer type is exactly 16 bits in width.  You can use it for your needs like this:

```
#include <stdint.h>

uint16_t arr[NUM_ELEMENTS] = {...};
```


Question:
the output of the function would be 4, but i am unable to understand why is this so. Its much appreciated if you can reason to what happens when for  x%y, when y > x

```
int main()
{
 int x=4%5;
 printf("x=%d\n",x);
 return 0;
}
```

Answer:
4 / 5 = 0and0 * 5 + 4 = 4, so the remainder is4.

C defines%, the remainder operator, as (in c11, 6.5.5p6):

```
(a/b)*b + a%b shall equal a.
```


Question: I have code written in C but I need to see the Assembly file so I can optimize the code and figure out how long certain functions will take. Does anyone know of a quick way to pull up the Assembly code?

Answer:
I also had the same problem as you. Here is what worked for me.

Debug the main program, when finished, choose

```
" Window >> Debugging >> Disassembly ".
```

Then you would see the corresponding assembly code.

Hope it could help you out.


Question: I am usinggtk_overlay_new ()to create an overlay in gtk, is there any way i can add some background color to it? so far i have not been successful in finding anything in the documentation.

Answer: Use:void gtk_widget_override_background_color();https://developer.gnome.org/gtk3/unstable/GtkWidget.html#gtk-widget-override-background-color


Question:
I build Clang from sources to ensure I get the latest analysis tools and sanitizers. The tarballs I download are Clang Source Code, LLVM Source Code, Compiler-RT Source Code and LLDB Source Code. TheLLVM Download Pagealso lists aClang Tools Extradownload.

What is in Clang Tools Extra tarball?

Answer: You can check it in the official documentation:extra clang tools documentation


Question: I am usinggtk_overlay_new ()to create an overlay in gtk, is there any way i can add some background color to it? so far i have not been successful in finding anything in the documentation.

Answer: Use:void gtk_widget_override_background_color();https://developer.gnome.org/gtk3/unstable/GtkWidget.html#gtk-widget-override-background-color


Question:
I build Clang from sources to ensure I get the latest analysis tools and sanitizers. The tarballs I download are Clang Source Code, LLVM Source Code, Compiler-RT Source Code and LLDB Source Code. TheLLVM Download Pagealso lists aClang Tools Extradownload.

What is in Clang Tools Extra tarball?

Answer: You can check it in the official documentation:extra clang tools documentation


Question:
```
int t[ ] = { 0x0203, 0x4 };
char *p=t;
printf(" *p = %d; *(p+1) = %d ",*p,*(p+1));
```

Why does *(p+1) always return 2, regardless of the second element in t?

Answer:
You're running this program on alittle endiancomputer. This means your int array is stored in memory as bytes in the following order:

0x03 0x02 0x00 0x00 (first integer)
0x04 0x00 0x00 0x00 (second integer)

Try to print out*(p+i)for p between 0 and 7, it should verify this.


Question:
```
int t[ ] = { 0x0203, 0x4 };
char *p=t;
printf(" *p = %d; *(p+1) = %d ",*p,*(p+1));
```

Why does *(p+1) always return 2, regardless of the second element in t?

Answer:
You're running this program on alittle endiancomputer. This means your int array is stored in memory as bytes in the following order:

0x03 0x02 0x00 0x00 (first integer)
0x04 0x00 0x00 0x00 (second integer)

Try to print out*(p+i)for p between 0 and 7, it should verify this.


Question:
For the sake of readability, I like to write boolean conditions "in full" in C/C++, e.g.:

if (foo == true)instead ofif (foo)andif (foo == false)instead ofif (!foo).

Does this compromise performance?

Answer:
Assuming foo is a bool, it does not. It can be trivially optimized by the compiler.

However, this may not be the case if foo is a class, which can overload operators to do whatever it wants.


Question: Is there a way to use asterisk AMI in c language? I want to get information about asterisk in its module using C language. I have configured manager.conf file.

Answer:
AMI is simple interface using tcp socket.

Sure you can use it from c.

You can get libs from this page:

http://www.voip-info.org/wiki/view/Asterisk+manager+Examples


Question: Is there a way to use asterisk AMI in c language? I want to get information about asterisk in its module using C language. I have configured manager.conf file.

Answer:
AMI is simple interface using tcp socket.

Sure you can use it from c.

You can get libs from this page:

http://www.voip-info.org/wiki/view/Asterisk+manager+Examples


Question:
For example:

```
if(mvwinch(win,y,x=(oldx-1))=='X')
```

Is the value of the variable 'x' now changed?

Answer: Before comparison, both expressions will be evaluated and any side effect could take place during the evaluation. So, yesxwould be modified.


Question:
For example:

```
if(mvwinch(win,y,x=(oldx-1))=='X')
```

Is the value of the variable 'x' now changed?

Answer: Before comparison, both expressions will be evaluated and any side effect could take place during the evaluation. So, yesxwould be modified.


Question:
If I typeint xis it usingsizeof(int)bytes of memory now? Is it not until x has a value?

What ifx = b + 6...is x given a spot in memory before b is?

Answer:
Yes, as soon as you declare a variable like:

```
int x;
```

memory is, generally, allocated on the stack. That being said, the compiler is very smart. If it notices you never use that variable, it mayoptimize it away.


Question:
Are the following twostaticvariable declarations equivalent?

1.

```
static int var1;
    static int var2;
    static int var3;
```

2.

```
static int var1, var2, var3;
```

More specifically, in case 2, will all variables bestatic, or justvar1?

Answer:
They're equivalent.

In case 2, all the variables will be static.

The storage class specifierstaticapplies to all the declared variables in the declaration.


Question: Literally, does(char *) 0mean a pointer to some location that contains a zero? Does the system create such an address with value 0 for each such declaration?

Answer:
No, it's a cast of0to typechar *.  That is, anull pointer.  A0in any pointer context refers to thenull pointer constant.

Whatexactly it points to doesn't matter - dereferencing it would cause undefined behaviour.

For more, check out theC FAQ Part 5: Null Pointers.


Question: Literally, does(char *) 0mean a pointer to some location that contains a zero? Does the system create such an address with value 0 for each such declaration?

Answer:
No, it's a cast of0to typechar *.  That is, anull pointer.  A0in any pointer context refers to thenull pointer constant.

Whatexactly it points to doesn't matter - dereferencing it would cause undefined behaviour.

For more, check out theC FAQ Part 5: Null Pointers.


Question:
What is this code doing exactly:

```
char* pointer=0;
*pointer=0;
```

Every time I run this code, the programme crashes!

Answer:
First line: You create apointervariable to a char, then you initialize it to address zero (NULL pointer).

Second line: you try to write a zero to the address wherepointeris pointing to.
Address zero is outside of your process' writable virtual memory area, so you get a segmentation fault.


Question:
What is this code doing exactly:

```
char* pointer=0;
*pointer=0;
```

Every time I run this code, the programme crashes!

Answer:
First line: You create apointervariable to a char, then you initialize it to address zero (NULL pointer).

Second line: you try to write a zero to the address wherepointeris pointing to.
Address zero is outside of your process' writable virtual memory area, so you get a segmentation fault.


Question:
How can I create a mutex in linux that will work with different processes and will have string name?

I want something similar toCreateMutexin Windows OS.

Answer:
Use a semaphore - seehttp://man7.org/linux/man-pages/man7/sem_overview.7.html.

This will give you the same as a mutex and you can name them


Question:
How can I create a mutex in linux that will work with different processes and will have string name?

I want something similar toCreateMutexin Windows OS.

Answer:
Use a semaphore - seehttp://man7.org/linux/man-pages/man7/sem_overview.7.html.

This will give you the same as a mutex and you can name them


Question: My C++ multi threaded application hangs in pthread_spin_lock in valgrind versions 3.8.0 and latest. But it is not happening in 3.6.0, 3.6.1 and 3.7.0. Anyone knows any workaround for this?

Answer: This is cause the internal problems of thread managing in valgrind. I had same problem and it was fixed in 3.10 version of valgrind.


Question:
is control-d a default stop sign for stdin?

In our homework, it says command-d will be stop inputting.

Is it a default ?

Answer:
Ctrl-Don Linux terminal with default settings is an end-of-file marker for stdin.

See alsothe tty demystifiedand thestty(1)command (andtermios(3)...). Use e.g.feof(3)aftersome stdio operation, or compare the result ofgetc(3)withEOF(etc....) to detect end-of-file conditions!


Question:
This question already has an answer here:What does the following for loop syntax mean in C?(1 answer)Closed9 years ago.

For example,

```
for (;;)
{
//do something
}
```

How is this different from

```
{
//do something
}
```

Answer:
It's an infinite loop.  Pretty much the same as writing

```
while (true)
{
    // do something
}
```


Question:
This question already has an answer here:What does the following for loop syntax mean in C?(1 answer)Closed9 years ago.

For example,

```
for (;;)
{
//do something
}
```

How is this different from

```
{
//do something
}
```

Answer:
It's an infinite loop.  Pretty much the same as writing

```
while (true)
{
    // do something
}
```


Question:
How can I codetest al,alin c language?

I've triedif((n & 0xFF) & 0){}but this is not correct.

Thanks.

Answer:
I'm guessing that you're checking the zero flag next, i.e.jzor similar. In that case you'd want

```
if ((n & 0xFFFF) != 0) {
```

Note that

AX is 16-bit not 8 bit (as e.g. AL and AH are) so you want 0xFFFF not 0xFF (if you even need this restriction)& 0can only ever give= 0and so false.


Question:
Say I have a python script that opens a file to write:

The python modules also call C modules that change the directory with

```
chdir()
```

Will the python script still have the file open and be able to write?

Answer: Files are tracked by file handles, and once open for a particular file, stays open to that file until closed.


Question: Given aSecKeyRefloaded usingSecItemImportfrom an RSA private key is there a way to obtain or create aSecKeyReffor only the public key components? In OpenSSL this could be done by copying the modulus and public exponent to a new struct, butSecKeyRefis opaque and I've been unable to find a function that performs this operation.

Answer: As of macOS 10.12, iOS/tvOS 10, and watchOS 3 the functionSecKeyCopyPublicKeynow exists to do this.


Question: Hello I am writing a program and dynamic loadable modules. Those modules are loaded using 'dlopen'. How do I use a program function in the module? Are function pointers the right way? Thank you

Answer: Yes you need function pointers and have to calldlsym()to get them


Question: Hello I am writing a program and dynamic loadable modules. Those modules are loaded using 'dlopen'. How do I use a program function in the module? Are function pointers the right way? Thank you

Answer: Yes you need function pointers and have to calldlsym()to get them


Question:
```
char foo[] = "something";
char *p = foo;
```

Is there a way to change the value pointed and increment the pointer to the next element using only one ;?

I mean, make the effect of these 2 lines below in a single statement?

```
*p = 'S';
 p++;
```

Answer:
I think you want

```
*p++ = 'S'; // as good as -->   *(p++) = 'S';
```

Sample run.


Question:
I have a struct that declared as follow:

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

How to declare a variable ofboutsidea? In C++ I can usea::b x;. But, in C it required to specifiesstructkeyword before struct name.

Answer:
C has a flat layout; when you declare a struct within another struct, the former is just being put into the global namespace.

So, in your example, it is juststruct b.


Question:
```
unsigned char endian[2] = {1, 0};
short x;

x = *(short *) endian;
```

I don't understand the value held in x. If I have a little-endian system, x is 1.

But if I have a big-endian system, x is 256.

Why is the value 256 rather than 128 ?

Thanks for your help.

Answer: Because the bytes01 00, in big-endian, are the value0x0100, which equals1 << 8 == 2**8 == 256(Recall there are 8 bits in a byte).


Question:
```
unsigned char endian[2] = {1, 0};
short x;

x = *(short *) endian;
```

I don't understand the value held in x. If I have a little-endian system, x is 1.

But if I have a big-endian system, x is 256.

Why is the value 256 rather than 128 ?

Thanks for your help.

Answer: Because the bytes01 00, in big-endian, are the value0x0100, which equals1 << 8 == 2**8 == 256(Recall there are 8 bits in a byte).


Question: I have a pre-built static library (.a) and the source code for it. How do I attach the source so so I can step through it while debugging in Eclipse with gdb?

Answer: You can't step through the source code if your library has not been compiled with the debug option (gcc -g, assuming you are using gcc). The easiest thing would be to compile the library yourself in Eclipse, in debug mode, then link your program against the newly-compiled library.


Question: I have a pre-built static library (.a) and the source code for it. How do I attach the source so so I can step through it while debugging in Eclipse with gdb?

Answer: You can't step through the source code if your library has not been compiled with the debug option (gcc -g, assuming you are using gcc). The easiest thing would be to compile the library yourself in Eclipse, in debug mode, then link your program against the newly-compiled library.


Question:
Is this legal in C?

```
struct Doubles
{
  double a,b,c;
};

void foo(struct Doubles* bar)
{
  double* baz = (double*)bar;
  baz[0]++;
  baz[1]++;
  baz[2]++;
}
```

I know that it "works" on MSVC 2010, but I don't know if it's legal, or if different layouts could cause UB.

Answer: This leads to undefined behaviour. The layout of the struct is not totally prescribed by the standard.  For instance, there may be padding.


Question: strlen() is terminated by null right? So how come both char c[]={'1','1'} and char d[]={'1','1','\0'} gives the same output 2 when strlen(c) and strlen(d) is used?

Answer: The former is undefined behavior; it could output 2, it could also output 500, terminate your program or destroy your computer.


Question: I have a portable library that in one place needs to do X if compiled under Visual Studio or just with Microsoft's C/C++ compiler, and Y otherwise. What#defineshould I look for?

Answer: Aquick Google searchleads topredefined macros on MSDNwhich lists all macros predefined by MSVC. Out of these,_MSC_VERis likely the best candidate.


Question:
I need to check string values and if a string with value 0d0a in hex comes i need to break while loop.

How to check this since those are unprintable characters ?

Answer:
To check if a string consists of just those two characters:

```
if ( 0 == strcmp(my_string, "\x0d\x0a") )
{
    // action to take if it matches
}
```

If your intent is to look for CR-NL pairs then"\r\n"is equivalent (in ASCII encoding) and documents that a bit more clearly.


Question:
I need to check string values and if a string with value 0d0a in hex comes i need to break while loop.

How to check this since those are unprintable characters ?

Answer:
To check if a string consists of just those two characters:

```
if ( 0 == strcmp(my_string, "\x0d\x0a") )
{
    // action to take if it matches
}
```

If your intent is to look for CR-NL pairs then"\r\n"is equivalent (in ASCII encoding) and documents that a bit more clearly.


Question:
I need to check string values and if a string with value 0d0a in hex comes i need to break while loop.

How to check this since those are unprintable characters ?

Answer:
To check if a string consists of just those two characters:

```
if ( 0 == strcmp(my_string, "\x0d\x0a") )
{
    // action to take if it matches
}
```

If your intent is to look for CR-NL pairs then"\r\n"is equivalent (in ASCII encoding) and documents that a bit more clearly.


Question:
This is my little program:

```
#include <unistd.h>
#include <stdio.h>
int main() {
  printf("1");
  fork();
  printf("2");
  fork();
  return 0;
}
```

The output of this code is12121212and I ask:Why does it print more than122?

Answer: Because printf is buffered and the text is printed only when program exits. Try to flush stdout after each print.


Question:
Dogccandclhave an equivalent forifortreal-sizecompiler flag? If not, what should I use instead? MACRO?

```
#ifdef DOUBLE_PRECISION
  #define REAL double
#else
  #define REAL float
#endif
REAL myvar;
```

Answer: gfortran has compile-time option-fdefault-real-8.   But not gcc.


Question:
This is my little program:

```
#include <unistd.h>
#include <stdio.h>
int main() {
  printf("1");
  fork();
  printf("2");
  fork();
  return 0;
}
```

The output of this code is12121212and I ask:Why does it print more than122?

Answer: Because printf is buffered and the text is printed only when program exits. Try to flush stdout after each print.


Question:
Dogccandclhave an equivalent forifortreal-sizecompiler flag? If not, what should I use instead? MACRO?

```
#ifdef DOUBLE_PRECISION
  #define REAL double
#else
  #define REAL float
#endif
REAL myvar;
```

Answer: gfortran has compile-time option-fdefault-real-8.   But not gcc.


Question:
I have an int that I need to round down to the nearest 100.

As an example:

91 would be rounded down to 0

101 would be rounded down to 100

199 would be rounded down to 100

Answer:
```
main()
{
    int a=0;
    scanf ("%d", &a)
    a= ( a/100) * 100;
    printf ("Result:%d", a);
}
```

The above code will satisfy your requirement.


Question:
I need an event which handles clicks on main window of my program.
I usedbutton-press-eventbut when i click on my window nothing happens.

I'm designing my GUI usingGlade Interface Designer.
please explain for me whenbutton-press-eventwill be called in gtk+ & is it the event i need or not?

Answer:
Check you've got the button press event mask set for the window under the
Window Properties - Common tab in glade


Question:
I need an event which handles clicks on main window of my program.
I usedbutton-press-eventbut when i click on my window nothing happens.

I'm designing my GUI usingGlade Interface Designer.
please explain for me whenbutton-press-eventwill be called in gtk+ & is it the event i need or not?

Answer:
Check you've got the button press event mask set for the window under the
Window Properties - Common tab in glade


Question:
```
int main() {
int i,j=6;
for(;i=j;j-=2)
printf("%d",j);
   return 0;
}
```

This piece of code gives output 642
please explain me why this loop doesn't run infinitely and stops when j is non-positive

Answer:
Whenjbecomes0the expressioni=jevaluates to0. Hence, the loop terminates.

Note that ifjwere to start as negative number ( e.g.-1)or as an odd number (e.g.5), then the condition will never evaluate to0and will result in an infinite loop.


Question:
Why is this bad?

```
if (true)
    int stuff = 10;
else
    int stuff = 5;

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

Is it because of scope?

Answer:
Yes.stuffonly exists in the scope of theifandelseblocks (where they are two different variables). You have to declare it outside the if-else to work.

```
int stuff;

if (true)
    stuff = 10;
else
    stuff = 5;

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


Question:
Why is this bad?

```
if (true)
    int stuff = 10;
else
    int stuff = 5;

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

Is it because of scope?

Answer:
Yes.stuffonly exists in the scope of theifandelseblocks (where they are two different variables). You have to declare it outside the if-else to work.

```
int stuff;

if (true)
    stuff = 10;
else
    stuff = 5;

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


Question:
```
main() {

       unsigned int a=-9;
       printf("%d",a);//gives output -9

       cout<<a;// gives output 9429967287
       getch();

   }
```

Why it gives different output in both cases?

Do 'printf' and 'cout' treat bit pattern in a different way?

Why is 'printf' not giving the positive answer?

Answer: Because you told it to:%dis for printing an argument as asignedint. To print an unsigned int, you should have used%u.


Question: I'm experienced with Objective C and easily know how to use NSScanner. I have a project I need to write in either C or Python that needs to use similar functionality to NSScanner(such as scanUpToString). Are there any standard or non-standard libraries that could provide similar functionality?

Answer:
In Python take a look at thefindmethod ofstr.

You could combine it like so:

```
foo ="barbazzapp"
foo[:foo.find("zapp")] # Returns 'barbaz'
```


Question:
If y is of integer type, then the expressions:

```
3*(y-8)/9
```

and

```
(y-8)/9*3
```

Will yield different result always or is it possible for them to yield same result?

What does it depend on?

Explanation with an example will be helpful.

Answer:
May yield different or same result, it is depend on 'y' value. The operations will be carried from left to right.
Ex: for y=11:
3*(y-8)/9: 1 (y-8)/9*3: 0

for y = 10
3*(y-8)/9: 0 (y-8)/9*3: 0


Question: In my C program I am using void* pointers. Is there anyway to check in an if statement if the void* pointer is pointing to an int* or a char*?

Answer:
Nope. There is no run-time type information in C.  Avoid*is just an address. That's it. It's completely up to the programmer to know / keep track of what information avoid*points to.

With more information about how/why you're usingvoid*, a workaround could possibly be suggested.


Question:
I am using LDA algorithm to classify a signal, how can i do that with multiple classes ? I have read some references but don't get the result.
I I've looked example code atlink

but it doesn't have explicit classifier part for me!

Answer: You can use OpenCV to keep doing this.


Question:
I have stored an int in a void * variable in a struct

```
void * data = &ID;
```

and now I want to print it. How would I do this? I tried to dereference it but the compiler complained about dereferencing void*. Thanks!

Answer:
You should castdatatoint *first, then derefer it:

```
printf("%d\n", *(int *)data);
```


Question:
I have stored an int in a void * variable in a struct

```
void * data = &ID;
```

and now I want to print it. How would I do this? I tried to dereference it but the compiler complained about dereferencing void*. Thanks!

Answer:
You should castdatatoint *first, then derefer it:

```
printf("%d\n", *(int *)data);
```


Question:
Working on this little piece of code, but for some reason it keep crashing the whole time.

Anyone got an idea what i'm doing wrong

```
char *str;
printf("Enter a string\n");
gets(str);
printf("The size of the string is %d", strlen(str));
system("PAUSE");
return 0;
```

Answer: You have not allocated any memory forstr. Declare a buffer, for examplechar str[50], but be aware ofbuffer overflows.


Question:
If on linux I try to compile c code in the standard way

```
gcc -myprog.c
```

the generated binary uses only the base CPU features, since the modern CPUs have a lot of special features to increase the performances, like AVX, AVX2, SSE3, SSE4 etc. according the model

Since I want targeting only a specific CPU type (i7 Sandy Bridge), Is there a way to set the copiler to take advantage of these features?

Answer: Look at the -march and -mtunegcc flags


Question:
If on linux I try to compile c code in the standard way

```
gcc -myprog.c
```

the generated binary uses only the base CPU features, since the modern CPUs have a lot of special features to increase the performances, like AVX, AVX2, SSE3, SSE4 etc. according the model

Since I want targeting only a specific CPU type (i7 Sandy Bridge), Is there a way to set the copiler to take advantage of these features?

Answer: Look at the -march and -mtunegcc flags


Question:
I'm sure this has been asked many times before but this kind of thing is pretty difficult to search for.Say foo and bar are both pointers to separate arrays, what does this line do?

```
*foo++ = *bar++;
```

At what point does each pointer get incremented, and is it an assignment of pointers or values?Thank you

Answer:
```
*foo++ = *bar++;
```

copies whatbarpoints at over whatfoopoints at.  Then it increments both pointers to the next element.


Question:
I am a beginner to Linux console and start write some code in C.

I try to compile code and hope to see messages using command

gcc foo.c -o foo -v | less

But the result text cannot be paged. Any wrong I do? Thanks.

Answer:
The|pipe command just redirects stdout.  To redirect stderr as well as stdout use|&:

```
gcc foo.c -o foo -v |& less
```


Question:
There is any api in c which can set multicast ip address in route table in linux.

like
through command it can be like this

ip route add multicast  dev

there is any c api which will same as above command is doing.

thanks in advance

Answer:
You might want to look at the documentation forrtnetlink

This is the userspace api to interact with the kernel routing rules.


Question: Is there anyway to emit the llvm-ir bytecode from inside my pass, into a file? I want the same format that I am getting by using the opt tool, so I can pass this file to the opt later.

Answer: To print a module in the textual representation (whichoptcan parse just file) to stdout, useModule::dump(). To save it to a file, useModule::print(and just pass null as the 2nd argument).To dump it to a bitcode file, usellvm::WriteBitcodeToFile.


Question: Is there anyway to emit the llvm-ir bytecode from inside my pass, into a file? I want the same format that I am getting by using the opt tool, so I can pass this file to the opt later.

Answer: To print a module in the textual representation (whichoptcan parse just file) to stdout, useModule::dump(). To save it to a file, useModule::print(and just pass null as the 2nd argument).To dump it to a bitcode file, usellvm::WriteBitcodeToFile.


Question:
I'm trying to make a simple c-shell like program on C (for Linux) that will execute scripts.

I need to read a script file in order to execute it, but how can I read it if it has only execute permission, and no read permission?

Answer:
In short,

A binary file you can execute with only execute permissions.A script is a text file, so you need read permissions.

So, you would need to play some games with group ownership, sudo, or similar.


Question:
This question already has answers here:Are empty macro definitions allowed in C? How do they behave?(3 answers)Closed9 years ago.

I encountered some codes as the following:

```
#define MY_IDENTIFIER
void someCode()
{
    ...
    MY_IDENTIFIER
    ...
}
```

What's the upper code doing ?

Answer: Absolutely nothing. The pre-processor is simply replacingMY_IDENTIFIERwith nothing wherever it encounters it.


Question:
I have the following c code:

```
int argv = 2;
char **argv = {"test arg 1",
          "test arg 2"};
```

When I compile it, I get teh following warning:

warning: initialization from incompatible pointer type [enabled by default]

Can you please tell me what's wrong for my initialization?

Thank you.

Answer:
char **is a pointer type not an array type.

Use an array type:

```
char *argv[] = {"test arg 1", "test arg 2"};
```


Question:
Can anybody tell me how to useitoafunction in C?

The prototype is:

```
char*itoa(int_Val,char*_DstBuf,int_Radix)
```

I think thatint_Valis the value that I want to convertchar*_DstBuf, is the string where I want to store the result
But what isint_Radix?

Answer:
It is the base to convert to

10 - Decimal
16 - Hexidecimal
8 - Octal

A per the manual pagehttp://www.cplusplus.com/reference/cstdlib/itoa/


Question:
I'm writing an multithreaded application and I'm wondering about following:
When using-D_REENTRANTmacro, do I need to explicitly use_rsuffixed functions?

e.g. Shall I usestrtok_reverywhere in the code or can I usestrtokand make sure I pass-D_REENTRANTmacro to the compiler?

Thanks a lot

Answer: Defining_REENTRANTwon't change the semantics ofstrtok(). You'll need to usestrtok_r().


Question:
How do I convert the following macro into a function?

```
#define xtime(x)   ((x<<1) ^ (((x>>7) & 1) * 0x1b))
```

Answer:
```
template<typename T>
T xtime(T x)
{
    return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
}
```


Question:
is there some way to define static structure that is already one and only instance of itself?
Like the way you can do it with the struc keyword in nasm?

Answer:
You can use an anonymous structure, like this:

```
struct {
   int memberA, memberB;
} my_struct;

my_struct.memberA = 1;
my_struct.memberB = 2;

printf("%d %d\n", my_struct.memberA, my_struct.memberB);
```


Question: Basically it's all in the title.  I'm calling C code from R via .Call().  The C code is throwing an error, but using traceback() or options(error=recover), the .Call() function is the farthest I can drill down to.  Is there a way to view the C call stack when an error is thrown in the C code?

Answer: Use gdb (or lldb under clang) to debug C code, perhaps as outlinedhere


Question: By using c language I need to create a text file in/tmpdirectory, but I don't know how to do this. Is there anyone who knows how to create a text file in/tmpfolder?

Answer: There'smkstempfunction for this


Question: By using c language I need to create a text file in/tmpdirectory, but I don't know how to do this. Is there anyone who knows how to create a text file in/tmpfolder?

Answer: There'smkstempfunction for this


Question:
Sayais my number.

And I wanta1to be a with all bits on even positions inverted.

This is my current solution

```
int a1 = ((a & 0xaaaaaaaa)  | (~(a) & 0x55555555));
```

How can I make this faster?

Answer:
Use the bitwise xor (^) operator:

```
a1 ^= 0x55555555;
```

this will invert bits 0, 2, 4, and so on.


Question:
Sayais my number.

And I wanta1to be a with all bits on even positions inverted.

This is my current solution

```
int a1 = ((a & 0xaaaaaaaa)  | (~(a) & 0x55555555));
```

How can I make this faster?

Answer:
Use the bitwise xor (^) operator:

```
a1 ^= 0x55555555;
```

this will invert bits 0, 2, 4, and so on.


Question: There are several basic MPI datatypes however, what if it is needed to send/receive an instance of a class. If this is possible, could you give an example?

Answer:
To send astruct, you may useMPI_Type_create_structhttp://www.mpich.org/static/docs/v3.1/www3/MPI_Type_create_struct.html

Here is an example of how to do so :

http://mpi.deino.net/mpi_functions/MPI_Type_create_struct.html

Bye,


Question: could we reallocated a shared memory ? by passing it's address toreallocfunction , if NO , how I can reallocate the shared memory ?

Answer: You can callmremap(). Alternatively, you can callmmap()again, copy the data, andmunmap()the original.


Question: could we reallocated a shared memory ? by passing it's address toreallocfunction , if NO , how I can reallocate the shared memory ?

Answer: You can callmremap(). Alternatively, you can callmmap()again, copy the data, andmunmap()the original.


Question: Is it for ipv6? If ipv4 is s_addr just the dotted quad reinterpreted as a 32 bit integer?

Answer: unsgined longguarantees that the size of the variable is at least 4 bytes, thus holding the entire ip. An unsigned int can be smaller.


Question:
I want to write a function which would redirect the standard output to a file where the name of the file is "name".log where "name" is the argument to the function

```
void redirect(char *name) {
```

I don't know where to begin.

Answer:
You can usefreopen()

```
// code copied from the link
#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);
...
```


Question: Is it for ipv6? If ipv4 is s_addr just the dotted quad reinterpreted as a 32 bit integer?

Answer: unsgined longguarantees that the size of the variable is at least 4 bytes, thus holding the entire ip. An unsigned int can be smaller.


Question:
I want to write a function which would redirect the standard output to a file where the name of the file is "name".log where "name" is the argument to the function

```
void redirect(char *name) {
```

I don't know where to begin.

Answer:
You can usefreopen()

```
// code copied from the link
#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);
...
```


Question:
I want to know how to use gettext in C with dynamic message id in the argument.

For example,

```
char *var = fun();   //where fun returns char * type.

char *val = gettext(var);
```

Answer: Your code is fine, but you will of course also need to make sure thatfun()returns a static string, that's going to stick around. Alsovalshould beconst char *, you cannot change the strings owned by gettext.


Question:
What is the fastest way to make the last 2 bits of a byte zero?

```
x = x >> 2 << 2;
```

OR

```
x &= 252;
```

Is there a better way?

Answer:
Depends on many factors, including the compiler, the machine architecture (ie processor).

My experience is that

```
x &= 252; // or...
x &= ~3;
```

are more efficient (and faster) than

x = x >> 2 << 2;


Question:
I'm studying C and TCP/UDP.
As the title... Is there any difference between inet_aton() and gethostbyname() in C? From what I know, both convert an IP address from a string to a number.

Answer:
gethostbyname() is obsolete. You should usegetaddrinfo().

inet_aton() only works for IPv4.

Also,inet_aton() only convert a IPv4 notion (0.0.0.0) to int,getaddrinfodoes DNS resolution.


Question:
What is the version of C used in GCC? C99, C11 or C90? I thought was the GCC use C99 but I was mistaken:

```
for(int i = 0; i < 100; i++){
  ...
}
```

error: ‘for’ loop initial declarations are only allowed in C99 mode.

Answer:
According to2 Language Standards Supported by GCC:

The default, if no C language dialect options are given, is-std=gnu90; this is intended to change to-std=gnu11in some future release.


Question:
In my current program I am having an issue where, when I divide a number by a larger number I am just given 0. For example if I divide -272 by 400 I receive 0.

```
y=x/400;
printf("%f\n", y);
```

This is the only piece of code causing issues. x is a negative integer 1-500 and y is initialized as a float.

Where am I going wrong?

Answer: Write something like this y = x/400.0f or y = (float)x / 400


Question:
In my current program I am having an issue where, when I divide a number by a larger number I am just given 0. For example if I divide -272 by 400 I receive 0.

```
y=x/400;
printf("%f\n", y);
```

This is the only piece of code causing issues. x is a negative integer 1-500 and y is initialized as a float.

Where am I going wrong?

Answer: Write something like this y = x/400.0f or y = (float)x / 400


Question:
I think i may be losing it but can anyone double check my sanity? This is the only code i wrote in a new file to see my project file is not messed up.

Error: This declaration has no storage class or type specifier

Error: Expected a ";"

Answer: On a global level you can only have declarations and definitions, not statements (likeg.a = 1;is) or expressions.


Question: I'm trying to write an extension for php using swig. I need to know the absolute path of the current php file in my extension code. I used __ FILE __ in my C code but it returns current c file name.

Answer:
finally i found the solution. to access __ FILE __ in your php extension, you can use like this:

```
char *file_name = zend_get_executed_filename();
```


Question: As the title says, would all the pointers be freed after the child dies or do I have to free them manually?

Answer:
Yes,

The OS is a good housekeeper and tidys up for you.

But being a good guest it is better to do it yourself.

Perhaps files need to be closed, network connections tidied up


Question: Is there any way to call category or test name from code in MSTest during test run?

Answer:
I don't now if it's possible for the test category but you can call the test name using theTestContext.

```
[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod1()
    {
        Assert.AreEqual("TestMethod1", TestContext.TestName, "Something went really wrong...");
    }

    public TestContext TestContext { get; set; }
}
```


Question: As the title says, would all the pointers be freed after the child dies or do I have to free them manually?

Answer:
Yes,

The OS is a good housekeeper and tidys up for you.

But being a good guest it is better to do it yourself.

Perhaps files need to be closed, network connections tidied up


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

int main(){

        int main =22;
        printf("%d\n",main);
        return 0;
}
```

output:22
I am defining main as function and variable both even though compiler is not giving error. It should give error "error: redefinition of ‘main’ " . I am not able to understand why this code is working.

Answer: It will not give you an error becausemainis not a keyword.but main is define 2 times- Scoping rules come into play.


Question: I have complied and run the code on a single machine , If I want to run the code on multiple machines in a client server architecture , which file do I place on server and which file do I place on client ?

Answer:
I'm assuming green indicates an executable file and that the file names follow normal naming practices.

Putint_clienton the clients.

Putint_serveron the server(s).


Question:
Can someone help me convert this line to an if-else statement?

temp = head->left ? head->left : head->right;

Thanks!

Answer:
```
if ( head->left )
    temp = head->left;
else
    temp = head->right;
```


Question: I have an input text in a single line of the form "part1 part2". How can i get in 2 different variables part1 and part2 if they have been input in the same line?

Answer:
You can use two different format specifiers :

```
#include <stdio.h>

int main(void)
{
    char part1[100],part2[100];
    scanf("%99s%99s",part1,part2);
    printf("%s,%s\n",part1,part2);
    return 0;
}
```


Question:
I have my main C file, another C file (which I'm using as a library) and two header files containing the function prototypes for each C file.

How can I compile and link them into one executable file with GCC? I'd like to use the-oand-gflags too.

Answer:
```
gcc -g -c first_file.c
gcc -g -c second_file.c
gcc -o executable first_file.o second_file.o
```

In general though, try googling for agcctutorial first.


Question:
I want to initialise a 2d array having all its elements are 0.
I have tried this:

```
scanf("%d",&n);
int arr[n][n]={0};
```

but i got the [Error]:"variable-sized object may not be initialized"

So,how to do this?

Answer:
Be explicit.

```
#include <string.h>

const int got = scanf("%d", &n);
int arr[n][n];
memset(arr, 0, sizeof arr);
```

Note that ifgotisn't 1, the above has undefined behavior. This is pretty dangerous.


Question: I saw that MinGW has a makefile too which is not supported in NetBeans/Eclipse. Why? And why MSYS? I also heard MSYS is Unix like env, so why do I need it for Windows programming?

Answer: Simply put msys is a unix/linux like enviorenment on windows. means you can run your program in unix/linux which you're making on windows


Question:
Im writing a hexdump function in C.

How can I truncate a given address (void* start) to the greatest multiple of 16 that's less than the given start argument?
Is there a simple way to do this?
Thanks

Answer:
```
uintptr_t rounded = ((uintptr_t)start) & ~0xF;
```


Question: I was wondering how to include files like LUA scripts, dlls, ect in a code:blocks build (debug and release) or would I just have to copy over all the files manually to the folders?

Answer: As far as I know, it is done by manual organization


Question:
Ok, so I have an array of srings

```
char array[4][20];

//initialized
strcpy(array[0], "PERSON1");
strcpy(array[1], "PERSON2");
...
```

My question is how would I use shmget, and shmat to turn this array into shared memory?
Any help appreciated!

Answer:
```
int segment_id = shmget(IPC_PRIVATE, sizeof(array),0660 | IPC_CREAT);

char** shared = shmat(segment_id,NULL,0);
```

This is a possible solution.


Question: From the kernel 3.4code,I could not make out that where the UART Base address is mapped ?As far as I know for mapping the base address we should userequest_mem_regionandio_remapfunction.But I could not find this in the code.Base address for UART4 is 0x4806E000

Answer: This should be defined in the dts file in arch/arm/boot/dts/omap4.dtsi file. I'm not sure if DT is enabled for your kernel.If enabled, it reads in the probe function


Question: I was wondering how to include files like LUA scripts, dlls, ect in a code:blocks build (debug and release) or would I just have to copy over all the files manually to the folders?

Answer: As far as I know, it is done by manual organization


Question:
Ok, so I have an array of srings

```
char array[4][20];

//initialized
strcpy(array[0], "PERSON1");
strcpy(array[1], "PERSON2");
...
```

My question is how would I use shmget, and shmat to turn this array into shared memory?
Any help appreciated!

Answer:
```
int segment_id = shmget(IPC_PRIVATE, sizeof(array),0660 | IPC_CREAT);

char** shared = shmat(segment_id,NULL,0);
```

This is a possible solution.


Question:
I'm trying to use the hardware instructions to compute some mathematical functions. For example the square root (sqrtpd instruction). I'm compiling my C code with GCC.

Does Anybody know what are the gcc options to force to compile with the hardware instructions and not to use the libc? Or if I need to do something special on my source code? (Without writing asm code).

Answer: On gcc you should use__builtin_ia32_sqrtpd.


Question:
I am aware of what the ceil function does, it rounds numbers up.
So; 1.3 to 2.0 and 5.9 to 6.0.
But I want it to round up with steps of 0.5.
So; 1.3 to 1.5 and 5.9 to 6.0.
Is this possible?
Thanks!!!

Answer:
```
y = ceil(x * 2.0)/2.0;
```

should do what you need:

```
x     x*2.0   ceil(x*2.0)  y
------------------------------
1.3    2.6     3.0         1.5
1.6    3.2     4.0         2.0
5.9   11.8    12.0         6.0
```


Question:
on page 23 in the K&R second edition, there is some code

```
if (c >= '0' && c <= '9')
       ++ndigit[c-'0'];
```

It goes on. My question is, why do the integers have the ' on each side?
and what is the c-'0'?

Answer: '0'is a character. It has the integer value 48.'9'has the value 57. The value ofc - '0'is equal toc - 48, and will be the integer value of the corresponding character.'0'will be0,'1'will be1, etc.


Question:
on page 23 in the K&R second edition, there is some code

```
if (c >= '0' && c <= '9')
       ++ndigit[c-'0'];
```

It goes on. My question is, why do the integers have the ' on each side?
and what is the c-'0'?

Answer: '0'is a character. It has the integer value 48.'9'has the value 57. The value ofc - '0'is equal toc - 48, and will be the integer value of the corresponding character.'0'will be0,'1'will be1, etc.