Question:
I have an function address stored in anunsigned int, and a function pointer.

Now i want thatfunction_pointerwill contain the value offunction_address

```
unsigned int function_address = 0xdeadbeef;
void(*function_pointer)(void) = function_address; // not valid
```

how to do that in C ?

Answer:
Perform an explicit cast.

```
void(*function_pointer)(void) = (void (*)(void))function_address;
```


Question:
Is there any doc i can read about this kind of function?

```
// return the capital of char c
char a(char c){
    return c >= 'a' && c<='z' ?
           c +'A' - 'a':c;
}
```

Answer:
Read up on the ternary operator.  :)  And then it will be clear the code is doing:

```
if (c >= 'a' && c<='z') {
   return(c +'A' - 'a');
} else {
    return c;
}
```

So basically it is capitalizing the Latin alphabet in ASCII.


Question:
Just curious, why below code is not equivalent to forever loop? Instead application crashes.

```
unsigned short i;
for (i = 1; i >= 0; i++)
{
    printf("%d\n", i);
}
```

Answer: The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.


Question:
Just curious, why below code is not equivalent to forever loop? Instead application crashes.

```
unsigned short i;
for (i = 1; i >= 0; i++)
{
    printf("%d\n", i);
}
```

Answer: The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.


Question:
How can we do transaction signing in mozilla firefox by loading PKCS#11 library to database.
after some research i found about capicom library. but the thing is this library does not support with windows7 and higher versions.

Answer: you cannot use c code but you can do the same by java applets which are to be signed. Please referhttp://www.nakov.com/books/signatures/Java-for-Digitally-Signing-Documents-in-Web-book-Nakov.html


Question:
What happens in the follwing code, does program executes 'return 1' or exits before?

```
int cmd_quit(tok_t arg[]) {
  printf("Bye\n");
  exit(0);
  return 1;
}
```

Answer:
exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of

```
exit(main(argc, argv));
```

to execute your program.

(meaning:ifmain()returns,exit()will be called automatically with its return value)


Question: How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.

Answer:
Try this:

```
#include<stdio.h>

int main()
{
    double a = 1.2345666;
    printf("%05.2lf\n", a);
    return 0;
}
```

Here,05says "print 5 columns with leading zeros"..2says "print decimal digits untill 2 columns". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.


Question:
What happens in the follwing code, does program executes 'return 1' or exits before?

```
int cmd_quit(tok_t arg[]) {
  printf("Bye\n");
  exit(0);
  return 1;
}
```

Answer:
exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of

```
exit(main(argc, argv));
```

to execute your program.

(meaning:ifmain()returns,exit()will be called automatically with its return value)


Question: How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.

Answer:
Try this:

```
#include<stdio.h>

int main()
{
    double a = 1.2345666;
    printf("%05.2lf\n", a);
    return 0;
}
```

Here,05says "print 5 columns with leading zeros"..2says "print decimal digits untill 2 columns". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.


Question:
I have the following:

```
char rank[100][100];
int score = 5;

strcpy(rank[0], "%d" score);
```

However,strcpy()does not accept these arguments. Is there any way to append a formatted string into my array?

Answer:
You could usesprintf:

```
char rank[100][100];
int score;

sprintf(rank[0], "%d", score);
```

Note however thatsnprintfis the buffer overflow-safe alternative.


Question:
For example there is a method dog:

```
void dog(char C,int N)
{
//here if I want to print the value of C with a print statement,how do I do that?
}
```

Answer:
What about a

```
printf("the value of c = %c\n", C);
```


Question:
How can I remove opened file in linux?

In shell I can do this:

```
rm -rf /path/to/file_or_directory
```

But how can I do it in C?

I don't want to usingsystem()function.

I have seen unlink and remove method but it's haven't any flags to set force deletion.

Answer: Theunlinkandremovefunctions force deletion. Thermcommand is doing extra checksbeforeit calls one of those functions. But once you answery, it just uses that function to do the real work.


Question:
How can I remove opened file in linux?

In shell I can do this:

```
rm -rf /path/to/file_or_directory
```

But how can I do it in C?

I don't want to usingsystem()function.

I have seen unlink and remove method but it's haven't any flags to set force deletion.

Answer: Theunlinkandremovefunctions force deletion. Thermcommand is doing extra checksbeforeit calls one of those functions. But once you answery, it just uses that function to do the real work.


Question:
please i can't understand the while loop , why the loop show A two time and not one

```
char *s,*t;
s="ABC";
t="AA";
do {printf("A");}
while(*s++==*t++);
printf("%d %d",*s-*t);
```

Answer:
In your code

```
printf("%d %d",*s-*t);
```

invokes undefined behavior as you're not supplying enough argument to sate the supplied format specifiers.


Question:
I am using the source file fromhttps://github.com/contiki-os/contikiI added a new directory (say/foo) that includes some .c and .h files

I need to use them onexamples/cc26xx, although I included the .h files (under/foo) to cc26xx-demo.c, it doesn't really include the files when I runmake

can anyone tell me how do I need to include them either onexamples/cc26xx/MakefileorMakefile.include

Answer: addingPROJECT_SOURCEFILES += mylib.cto Makefile solved the issue.


Question:
I am using the source file fromhttps://github.com/contiki-os/contikiI added a new directory (say/foo) that includes some .c and .h files

I need to use them onexamples/cc26xx, although I included the .h files (under/foo) to cc26xx-demo.c, it doesn't really include the files when I runmake

can anyone tell me how do I need to include them either onexamples/cc26xx/MakefileorMakefile.include

Answer: addingPROJECT_SOURCEFILES += mylib.cto Makefile solved the issue.


Question:
While I was looking for MMX functions, I noticed that two of them,_m_emptyand_mm_empty, haveexactly the same definition.

So why do they both exist ? Is one of them older than the other ? Is there a difference that is not mentioned in the manual ?

Answer:
Differences would/should be pointed out in the documentation. TheMSDNis more precise. They explicitly mention this:

A synonym for_mm_emptyis_m_empty.


Question:
I want to reduce the resolution of a video from 1024*768 to 800*600.
I found on the web ffmpeg, and the library swscale (I use  in C.

And I found some informations on the web, but nothing about how to reduce the resolution of a video nor about which functions to use

How can I do ?

Answer: Seethisorthisexample code. Usesws_getContext() to set up a scaler, andsws_scale() to convert one frame or slice.


Question: I just created new console application project byDev-C++ 4.9.9.2. But Project Options(Alt+P) not working andError: Access violation at address 0012F64B. Write of address 0012F64B. How to fix this problem.

Answer: Its Dev-C++ problem , update it .Details


Question: I just created new console application project byDev-C++ 4.9.9.2. But Project Options(Alt+P) not working andError: Access violation at address 0012F64B. Write of address 0012F64B. How to fix this problem.

Answer: Its Dev-C++ problem , update it .Details


Question:
According tothisquestion, gcc's-lcommand requires your library to be named libXXX.a.

Is there a way to link a static library using a different command with gcc? The goal is to avoid this lib- prefix.

Answer:
Just pass the library as in input file like so:

```
gcc main.c yourlibrary.a -o prog
```


Question:
In ubuntu I would do it by following command

```
./a.out < input.txt | cat > ouput.txt
```

how can I do this in Windows cmd?

Answer:
You can do it in two lines:

```
a.exe < input.txt >output.txt
type output.txt
```


Question:
In ubuntu I would do it by following command

```
./a.out < input.txt | cat > ouput.txt
```

how can I do this in Windows cmd?

Answer:
You can do it in two lines:

```
a.exe < input.txt >output.txt
type output.txt
```


Question:
I have a variable i:

```
int i;
if(b){
    i=1;
}
else{
    i=-1;
}
```

Isiundefined behavior because ofint i;exists?
Or Should we alwaysint i=0first?

Answer:
Absolutely fine.

You are initialisingion all program control paths, and not reading the value until initialisation is complete.

I prefer using the ternary operator in such instances.

int i = b ? 1 : -1;

as that's less vulnerable to accidental reference to an uninitialisedi.


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

int main()
{
   FILE * fp;

   fp = fopen ("file.txt", "w+");

   fclose(fp);

   return(0);
}
```

the above programs will create a file . i need that file needs to be placed in specific directory. please help

Answer:
Add path into the parameter offopen().

```
fp = fopen ("/path/to/file.txt", "w+");
```


Question:
What does this macro mean or what is the result?

```
#define MOD_TYPE_12 0x11, 0x20, 0x0C, 0x00, 0x02, 0x00, 0x07, 0x0F, 0x42, 0x40, 0x01, 0xC9, 0xC3, 0x80, 0x00, 0x02
```

Is this evaluated to an array?

I couldn't find anything... Maybe because I don`t know what I have to search for ^^

Answer:
All the

MOD_TYPE_12

in your program will be replaced with

0x11, 0x20, 0x0C

There is no specialty with commas


Question: I remember being constantly told that the C preprocessor does not know C. It doesn't know about types, doesn't remember declared symbols, etc. If that's the case, how can it possibly act differently based on the type of its parameter?

Answer: The_Genericfeature is not processed by the preprocessor. It is aprimary expressionthat is treated with higher preference than most other expressions.


Question: Is there anything similar to Java's Integer.MIN_VALUE in C, which gives the smallest possible value of a signed integer, or do I just have to hard code the value myself?

Answer:
You can uselimits.hhttp://en.cppreference.com/w/c/types/limits

I think this is what you're looking for:INT_MIN = minimum value for an int


Question:
My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way.

Is there a function with the effect ofscanfwhich takes a pointer to memory instead of input stream?

Answer: You'll be wantingsscanf. Note that it does expect a null-terminated string.


Question:
I have a string which captures details stored indata

User 6%, System 18%, IOW 0%, IRQ 0%

What i am doing is

sscanf(data,"User %d,System %d,IOW %d,IRQ %d",&user,&sys,&iow,&irq);

I am getting wrong output . why ?
Is is like i am missing something ?

Answer:
You left out the%symbols and some spaces - try:

```
sscanf(data,"User %d%%, System %d%%, IOW %d%%, IRQ %d%%",&user,&sys,&iow,&irq);
```


Question:
My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way.

Is there a function with the effect ofscanfwhich takes a pointer to memory instead of input stream?

Answer: You'll be wantingsscanf. Note that it does expect a null-terminated string.


Question: I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?

Answer: Yes, as long as the queue is initialized you are fine.


Question:
What does this expression mean:

```
typedef char foo [FOO];
```

I am just struggeling with the meaning of the expression between the squared brackets.

Answer:
It readsfoois the type of an array ofFOO-manycharelements. In this case,FOOis a constant, defined somewhere as#define FOO 100

```
typedef int pair[2]; // Pair is an array of two ints.
```


Question: I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?

Answer: Yes, as long as the queue is initialized you are fine.


Question:
A code snippet is as follows:

```
struct wer
{
unsigned int a:5;
unsigned int:0;
unsigned int b:3;
unsigned int c:2;
unsigned int:0;
}v;
```

I know that all of these are packed bit fields but how to find the storage which would be needed for v.

Answer: You can get the storage required forvusingsizeof(v).


Question:
A code snippet is as follows:

```
struct wer
{
unsigned int a:5;
unsigned int:0;
unsigned int b:3;
unsigned int c:2;
unsigned int:0;
}v;
```

I know that all of these are packed bit fields but how to find the storage which would be needed for v.

Answer: You can get the storage required forvusingsizeof(v).


Question:
I am trying to set a bit in a 8 bit variable.
Every time I print the variable after setting a particular bit , I always get the value as 1.

```
uint8 value;
value = (1<<1 || value)
printf(%x \n,value); //prints 1 instead of 2
value = (1<<2 || value)
printf(%x \n,value); //prints 1 instead of 4
```

Answer:
You're using boolean 'or'||. Bitwise 'or' is|.

Also you haven't initializedvalueso you can't expect it to be anything.


Question:
I have a struct that I want to zero and then set the members. I tried this:

```
cmdRequest_t cmdRequest = {0};
cmdRequest = {3, "d t"};
```

but that doesn't work. I have also tried several variants, but I always get a syntax error on that second line. How can I do this?

Answer:
Simply do:

```
cmdRequest_t cmdRequest = {3, "d t"};
```

There's no need to zero the structure if you're going to immediately fill in other values.


Question:
I have not really a programming issue but more like an IDE issue. My Eiffel Studio 15.01 won't start up because of this error shown on the picture in the link.https://i.stack.imgur.com/mCzrO.jpg

Can anybody help please?

Answer:
You can try to go to menu View > Tools Layout > Reset Tools Layout

Otherwise remove the files under
%LOCALAPPDATA%\Eiffel Software\.es\15.01\docking
(or ~/.es/15.01/docking  in linux)

And restart EiffelStudio.


Question:
I have not really a programming issue but more like an IDE issue. My Eiffel Studio 15.01 won't start up because of this error shown on the picture in the link.https://i.stack.imgur.com/mCzrO.jpg

Can anybody help please?

Answer:
You can try to go to menu View > Tools Layout > Reset Tools Layout

Otherwise remove the files under
%LOCALAPPDATA%\Eiffel Software\.es\15.01\docking
(or ~/.es/15.01/docking  in linux)

And restart EiffelStudio.


Question:
I need a regex that will match 24 time format.

Eg2300is valid2900is not valid

I was using this:

```
_[0-2][0-3][0-5][0-9]_
```

But this doesn't allow _1900_etc_

Answer:
You need to decompose thehourspart in two cases: from00to19and from20to23. This is done by using a(pattern1|pattern2)expression.

Hours: 00-23.

```
([01][0-9]|2[0-3])
```

Minutes: 00-59.

```
[0-5][0-9]
```

All together:

```
([01][0-9]|2[0-3])[0-5][0-9]
```


Question: Question speaks for itself. I have a program that used SHBrowseforfolder, but now they want me to upgrade it to IFileDialog which I made but is in C++, so is it even possible to get it to work with C since it's OOP?

Answer:
IFileDialog is part of Microsoft's Component Object Model (COM). COM programming can be done in C. Quite tedious though.

Here's a tutorial (can't vouch for it's quality)

http://www.codeproject.com/Articles/13601/COM-in-plain-C


Question: Question speaks for itself. I have a program that used SHBrowseforfolder, but now they want me to upgrade it to IFileDialog which I made but is in C++, so is it even possible to get it to work with C since it's OOP?

Answer:
IFileDialog is part of Microsoft's Component Object Model (COM). COM programming can be done in C. Quite tedious though.

Here's a tutorial (can't vouch for it's quality)

http://www.codeproject.com/Articles/13601/COM-in-plain-C


Question:
This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.

Taking the following example:

```
void foo(const int foobar);
```

Is the keywordconstmeaningful?

Answer: Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.


Question:
This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.

Taking the following example:

```
void foo(const int foobar);
```

Is the keywordconstmeaningful?

Answer: Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.


Question:
This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.

Taking the following example:

```
void foo(const int foobar);
```

Is the keywordconstmeaningful?

Answer: Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.


Question: Lets say I have achar[10]="1234567890. I want it to break it in two 5digits number. I want to ask two thing that do i need to convert it in int before spliting and how will i split it

Answer:
ex

```
char num10[]="1234567890";
int n1, n2;
sscanf(num10, "%5d%5d", &n1, &n2);
printf("%d, %d\n", n1, n2);
```


Question: I Want to get the username or SID from a session id value, how can I do that working from Window XP using the WinAPI?

Answer:
You can use theWTSQuerySessionInformationfunctionto get the Username and Domain (WTSUserNameandWTSDomainNamefromWTS_INFO_CLASS).

This function is available as far back as Windows 2000.


Question: I couldn't disable it even though by using-std=c89flag. How can I disable it?

Answer:
You can generate an error for variable length arrays using a compiler flag:

```
-Werror=vla
```


Question: I couldn't disable it even though by using-std=c89flag. How can I disable it?

Answer:
You can generate an error for variable length arrays using a compiler flag:

```
-Werror=vla
```


Question:
I want execute a code only one time. I used a solution based on a global varibale of bool type. My question, is it the best solution?

Remark: I use ucos-II.

```
if (TRUE == Lock)
{
 /*Code to execute one time*/
}

/*The reste of the code*/
```

Answer:
A simple code using a static variable.

```
static bool once = false;

if (once == false)
{
    once = true;
    // do your "once" stuff here
}
```


Question:
Is the memory allocation system of C completely random or does it use pseudo random generator ?
What is the actual algorithm for memory allocation that happens at the back ?

Answer: C doesn't do memory allocation.You, the programmer, have to do it yourself based on the simple primitivesmalloc()andfree(), which do nothing but ask the OS for free chunks of memory to give you.


Question: The problem is that on one platform (windows, mvsc2015)uint64_tis defined asunsigned long longand on another (ubuntu, clang) it'sunsigned longand there is the code which looks likesprintf(buffer, "%#llx", u64key);

Answer:
The solution is to use C99's format macros, in particularPRIu64for anuint64_t:

```
#include <inttypes.h>
…
sprintf(buffer, "%#" PRIu64 "\n", u64key);
```


Question:
What's the meaning of:

```
#include <stdio.h>

int main(){
  double bmax = 31.4159265;
  printf("%1.4e\n", bmax);
}
```

What is the meaning of%1.4e? I know%ffor double.

Answer:
```
%e specifier is used to print value of float\double in exponential format.
```

So here%1.4ewill print 1 digit before the decimal point and 4 digits after the decimal point.

So ifbmax=12.242then the output will be1.2242e+01.


Question: I'm trying to build vp8 for android armv6 but with no luckI tried to set --target=armv6-android-gcc but i get Unrecognized toolchain 'armv6-android-gcc' errorbut --target=armv7-android-gcc works just fine.how should i do it ?

Answer: There is no ARM6 Android ABI in the NDK. ARM6 Android devices use the ARM5 ABI (which is the plain androideabi).


Question:
What's the meaning of:

```
#include <stdio.h>

int main(){
  double bmax = 31.4159265;
  printf("%1.4e\n", bmax);
}
```

What is the meaning of%1.4e? I know%ffor double.

Answer:
```
%e specifier is used to print value of float\double in exponential format.
```

So here%1.4ewill print 1 digit before the decimal point and 4 digits after the decimal point.

So ifbmax=12.242then the output will be1.2242e+01.


Question: I'm trying to build vp8 for android armv6 but with no luckI tried to set --target=armv6-android-gcc but i get Unrecognized toolchain 'armv6-android-gcc' errorbut --target=armv7-android-gcc works just fine.how should i do it ?

Answer: There is no ARM6 Android ABI in the NDK. ARM6 Android devices use the ARM5 ABI (which is the plain androideabi).


Question:
what is __dirstream, where can we find the definition

So, I'm trying to get the sizeof DIR from opendir, which is a typedef of __dirstream. I understand it's hidden at compile-time, is there a defined max size?

Answer:
That__double-underscore in the name marks it as implementation-private. Nothing is defined about it except what the implementation documents.

is there a defined max size

Nope, sorry.


Question:
The below program redirects all my output to log file. I need to display all the output along with log file. How can this be achieved?

```
$ gcc test.c
$ ./a.out > log.txt
$
```

Answer:
You could usetee:

```
$ ./a.out | tee log.txt
```


Question:
The below program redirects all my output to log file. I need to display all the output along with log file. How can this be achieved?

```
$ gcc test.c
$ ./a.out > log.txt
$
```

Answer:
You could usetee:

```
$ ./a.out | tee log.txt
```


Question: Is it possible to develop applications for Roku inCorC++as the SDK is written inC? If yes, how?  If no, then which languages other thanBrightscriptcan apps be developed in?

Answer: My understanding is yes, at least with games and the Marmalade SDKhttps://www.roku.com/developer. I actually just downloaded the SDK and have not looked at it in much detail yet, but as it seems, developing for Roku involves a mix of Brightscript, C++ and Java (Android). Hope that helps!


Question: In Unix, C. After afork(), usually followed by await()orwaitpid()to wait thechildterminate. But can thechildexecute thewait()? Thechilddoesn't have a_child_, so when it execute thewait(), what will happen?

Answer:
There are no child proccess for the child proces sowait()will return -1. From the man page:

wait(): on success, returns the process ID of the terminated child;
         on error, -1 is returned.


Question:
I have a very simple macro for which I want to typecast its output tointonly. How to do that?

```
#define Numbits(A) (sizeof(A)*CHAR_BIT)
```

I tried:

```
#define int Numbits(A)({int val; val = sizeof(A)*CHAR_BIT; return val;})
```

but it also doesn't work

Answer: Are you saying that#define Numbits(A) (int)(sizeof(A)*CHAR_BIT)didn't work?


Question:
If I have program with a main thread and a function running in a separated detached thread. If something in the detached thread is returning something > 0
will only the child thread exit or the main thread too?

Answer:
A Posix thread returnsvoid *(ie. a pointer), so it cannot return anything less than zero since it's not an integer.

In any case, the return value from a detached thread is always ignored, and the process will not exit whatever the value.


Question:
Doesalignof(N) == sizeof(N)where N is an integral type?

I'm asking for both C and C++, hope this isn't a problem.

Answer: It's machine-specific.  On a 32-bit machine,alignof(int64_t)could easily be 4.  Too, assumptions that are widespread now won't be for so very long.


Question:
Doesalignof(N) == sizeof(N)where N is an integral type?

I'm asking for both C and C++, hope this isn't a problem.

Answer: It's machine-specific.  On a 32-bit machine,alignof(int64_t)could easily be 4.  Too, assumptions that are widespread now won't be for so very long.


Question: What combination of preorder,inorder and postorder Traversal generate a unique binary Tree?

Answer:
following combination can uniquely identify a tree.

Inorder and Preorder.
Inorder and Postorder.
Inorder and Level-order.

And following do not.
Postorder and Preorder.
Preorder and Level-order.
Postorder and Level-order.

For more infomation refer:Geeksforgeek


Question:
This question already has answers here:size of int variable(6 answers)Closed4 years ago.

Why in Turbo C compilersizeof(int)is 2 bytes and in gcc Linux compiler is of 4 bytes?

Answer:
sizeof(int)is not a constant across all platforms.

It varies from system to system.

PS: Only sizeof object which is constant across all platforms issizeof(char)


Question:
I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors.

https://msdn.microsoft.com/en-us/library/027c4t2s.aspx

Answer: CFLAGS+= -fdiagnostics-absolute-paths


Question:
I've asorted arraybut it'snot necessarily sequential, and I need to knowIF it contains any duplicates.

```
Array : | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 8 |
```

I know we can linearly traverse in O(n) check if it contains any duplicates, but I was wondering if it is possible using Binary Search.

Answer: No, You can't do it with binary search. All algorithms will take at least linear time.


Question:
I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors.

https://msdn.microsoft.com/en-us/library/027c4t2s.aspx

Answer: CFLAGS+= -fdiagnostics-absolute-paths


Question:
The code excerpt:

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

produces error message

error: cannot convert ‘char**’ to ‘wchar_t**’ for argument ‘2’ to ‘void PySys_SetArgv(int, wchar_t**)’

How do I convertargv?

Answer:
You could look into whether your compiler supportswmain. If so, you can replacemainwith:

```
int wmain(int argc, wchar_t *argv[])
{
    PySys_SetArgv(argc, argv);
```


Question: I am trying to convert from arduino to avr-c. I get the errorSREGis undeclared. Do you know whatSREGis?.

Answer: SREGis theStatusRegister. It is#define'd in one of the AVR headers, so you are probably missing an#include(perhapsavr/io.horavr/common.h).


Question:
As per my knowledge range of unsigned char in C is 0-255. but when I executed the below code its printing the 256 as output. How this is possible? I have got this code from "test your C skill" book which say char size is one byte.

```
main()
{
 unsigned char i = 0x80;
 printf("\n %d",i << 1);
}
```

Answer:
Because the operands to<<*undergointeger promotion.  It's effectively equivalent to(int)i << 1.

* This is true for most operators in C.


Question:
As per my knowledge range of unsigned char in C is 0-255. but when I executed the below code its printing the 256 as output. How this is possible? I have got this code from "test your C skill" book which say char size is one byte.

```
main()
{
 unsigned char i = 0x80;
 printf("\n %d",i << 1);
}
```

Answer:
Because the operands to<<*undergointeger promotion.  It's effectively equivalent to(int)i << 1.

* This is true for most operators in C.


Question: If file is opened using fopen() and in different mode then is it necessary to close it number of time or it can be closed once at end of code ?

Answer: Each time you open the file, you are going to receive different file descriptors or file handles. So you have to close each file handle usingfclose()if opened viafopen()orclose()if opened viaopen().


Question:
I saw someone doing this to have array index starting at 1 instead of 0 in C.

```
a = (int *) malloc(sizeof(int)*3) - 1
```

Is there any risk in this?

Answer:
Theoretical risk : only null pointers and pointers to, into, or right after an object are valid. Other pointers trigger undefined behaviour on use (if they're dangling) or when creating them through pointer arithmetic.

Practical risk : getting pelted by a random code reviewer.


Question:
I saw someone doing this to have array index starting at 1 instead of 0 in C.

```
a = (int *) malloc(sizeof(int)*3) - 1
```

Is there any risk in this?

Answer:
Theoretical risk : only null pointers and pointers to, into, or right after an object are valid. Other pointers trigger undefined behaviour on use (if they're dangling) or when creating them through pointer arithmetic.

Practical risk : getting pelted by a random code reviewer.


Question: If for example I usedLoadImage()to load a bitmap from file in Thread A, can I use the returnedHBITMAPin Thread B?

Answer: Yes you can, but remember a bitmap can only be selected into one DC at once. If you have two threads both drawing the same bitmap you'll need to coordinate access to it.


Question:
For example: when I round a float into an int, why should I use :

int i = (int) round(f);

Instead of :

int i = int round(f);

Answer:
What is the difference between int and (int) in C?

anintis the built-in type integer and(int)isType Casting.


Question:
```
Min Profile Cycles  [215914]
Max Profile Cycles  [934625]
Max Profile         [23]
Max Profile Count   [4]
```

How to print all these console output into some .txt file in c so that whenever i will call that function it will print in txt file instead of printing in console.

Answer: as your tag is C, you can fopen() in append-mode a file and instead of using printf() you use fprintf() (and fwrite() and similar) with this filehandle.


Question:
```
Min Profile Cycles  [215914]
Max Profile Cycles  [934625]
Max Profile         [23]
Max Profile Count   [4]
```

How to print all these console output into some .txt file in c so that whenever i will call that function it will print in txt file instead of printing in console.

Answer: as your tag is C, you can fopen() in append-mode a file and instead of using printf() you use fprintf() (and fwrite() and similar) with this filehandle.


Question:
How to I give the user the ability to name the output .txt file? Here is all I have right now.

```
FILE *f = fopen("output.txt", "a");
```

Answer:
You can read the input from user and append.txt

```
char fileName[30];
// ...
scanf("%25s", fileName); // max 25 characters because .txt have 4 (25+4 = 29)
strcat(fileName, ".txt"); // append .txt extension
// ...
FILE *f = fopen(fileName, "a");
```


Question: Actually, I know it's necessary to free the memory allocated with malloc(), but I wonder if I can know there is some memory left being not collected if I forget to collect it with free().

Answer:
Valgrind would be your best bet

http://valgrind.org/


Question: Actually, I know it's necessary to free the memory allocated with malloc(), but I wonder if I can know there is some memory left being not collected if I forget to collect it with free().

Answer:
Valgrind would be your best bet

http://valgrind.org/


Question:
How can I determine the length, in seconds, of the Ogg Vorbis stream with libvorbis and/or libvorbisfile?

As far as I can tell, there's nothing in thevorbis_infostructure that tells me the length of the stream.

Answer: Using the lower level API, you can do this withov_time_total.


Question:
I have a 16 bit address 0-15, I need to check at value of bit corresponding to their position in C

for example at 15 place i have 1, 14 has 0, and soo on!

|1|0|0|0|1|0|1|0|1|1|1|1|1|0|1|0|

I was thinking to create 16 new addresses with all zero and the position i am looking

Answer:
Use a macro similar to this:

```
#define CHECK_BIT(x, i) ( ((x) & (1 << (i)) != 0 ) )
```

CHECK_BIT(x, i)will returntrueif the i'th bit ofxis one, false otherwise.


Question:
I am confused about this example:

```
typedef int32_t voltage_dc_estimate_t[1];
```

Everything is OK but that[1]at the end of the type definition confuse me. Could someone please help me to understand that situation?

Answer:
[1]means an array of1element.

voltage_dc_estimate_tis a type of an array of1element of typeint32_t.


Question:
I'm trying to use #ifndef as below.

```
#ifndef MACRO1 || #ifndef MACRO2
....
#endif
```

I already tried:

```
#ifndef (MACRO1 || MACRO2)
..
#endif
```

But for both cases  am getting below error

error: extra tokens at end of #ifndef directive

Answer:
Use the#ifpreprocessor directive instead:

```
#if !defined(MACRO1) || !defined(MACRO2)
```


Question:
I have:

```
const char  *ptr = "int";
```

If I have to declare usingptr:

```
int a;
```

ptrcan point to anything arbitrarychar,string,<anythihg>.
I have to delcare a variable of that type whatptris pointing at.
Is it possible?

Answer: No. C++ is not an interpreted language."int"has a meaning to the compiler, but at runtime there's nothing which understands"int".


Question:
I have:

```
const char  *ptr = "int";
```

If I have to declare usingptr:

```
int a;
```

ptrcan point to anything arbitrarychar,string,<anythihg>.
I have to delcare a variable of that type whatptris pointing at.
Is it possible?

Answer: No. C++ is not an interpreted language."int"has a meaning to the compiler, but at runtime there's nothing which understands"int".


Question:
I have:

```
const char  *ptr = "int";
```

If I have to declare usingptr:

```
int a;
```

ptrcan point to anything arbitrarychar,string,<anythihg>.
I have to delcare a variable of that type whatptris pointing at.
Is it possible?

Answer: No. C++ is not an interpreted language."int"has a meaning to the compiler, but at runtime there's nothing which understands"int".


Question: I know how to find Big O for "for loops" and nested "for loops", but what happens when we have two for loops, not nested but two separate for loops in the same function.

Answer:
It just gets added.

See for e.g. :

```
for(i=0;i<n;i++)
    //statements

for(i=0;i<m;i++)
    //statements
```

So the total complexity is O(m+n).

lets say m=3n then
its O(4n) which is O(n) only .

let m = n^2

then its O(n^2+n) which is O(n^2)


Question:
How do I define a 2D array where the first dimension is already defined with MAX_VALUES. I wish to be able to allocate memory to the second dimension. Below is what I have attempted. I want an array with A[1000][mallocd]

```
#define MAX_VALUES 1000
int
main(){
    int n= 10;
    int *A[MAX_VALUES] = malloc(10 * sizeof(int));

}
```

Answer:
Try this

```
int (*A)[n] = malloc(MAX_VALUES * sizeof(*A));
```

It will allocate contiguous 2D array.


Question: I need to know what's the address from which/bin/lsprogram execution starts (after dynamic linker fix the environment, what address gets the control?) I need it in hexadecimal (0xNNN...) or decimal format

Answer: That would be platform dependent. For a recent system, that should actually be randomized.


Question: I have to insert uncompressed data in between the compressed data bytes. Type 0 header in zlib allows me to do that. But How can i do that ? any clues ?

Answer: There is no type 0 allowed in a zlib header.  There is a stored block type in the deflate format used within a zlib stream.  zlib will automatically use stored blocks if they are smaller than the same data compressed.


Question:
I have a question related to bit-fields in C. Here I have such a structure:

```
struct Register
{
  int bit:1;
};

int main(void)
{
  struct Register bit = {1};

  printf("\nbit = %d", bit.bit);
  return 0;
}
```

Can you please explain me why do I get:

bit = -1

Answer: If you're working with bitfields, you should useunsigned int.signed intis a problem for bit-fields.


Question: I need to know what's the address from which/bin/lsprogram execution starts (after dynamic linker fix the environment, what address gets the control?) I need it in hexadecimal (0xNNN...) or decimal format

Answer: That would be platform dependent. For a recent system, that should actually be randomized.


Question:
I am now starting to learn C.  I would like to know why I get the warning. I declared a bidimensional char array, but why the character"d"is not allowed?

```
char array[3][3] = {{1,"d",3},{3,2,1},{2,1,3}};
```

Answer:
Replace "d" with 'd'

'd' is a character

"d" is a string


Question:
I am now starting to learn C.  I would like to know why I get the warning. I declared a bidimensional char array, but why the character"d"is not allowed?

```
char array[3][3] = {{1,"d",3},{3,2,1},{2,1,3}};
```

Answer:
Replace "d" with 'd'

'd' is a character

"d" is a string


Question:
On the CPU, I have an array of positions and colors:

```
[ x0, y0, z0, col0, x1, y1, z1, col1 ...]
```

On the device, I have a 3D texture. Is there any efficient way to modify that texture so that positionx0, y0, z0's color becomes col0 and so on?

Answer:
glTexSubimage3d will work if you can arrange your data into cubes. Doing it one texel at a time would be miserable though.

https://www.opengl.org/sdk/docs/man3/xhtml/glTexSubImage3D.xml


Question:
I tried includingstring.handstdlib.h, but still get undefined reference compile errors.

This leads me to conclude that it is in a different library that I didn't include. Where is it?

I am using gcc compiler - the code is written in Windows, but is going to be compiled and run on a unix server.

Answer: strcat_scan be found instring.has of C 2011. Generally speaking, only microsoft has implemented these alternative functions.


Question:
On the CPU, I have an array of positions and colors:

```
[ x0, y0, z0, col0, x1, y1, z1, col1 ...]
```

On the device, I have a 3D texture. Is there any efficient way to modify that texture so that positionx0, y0, z0's color becomes col0 and so on?

Answer:
glTexSubimage3d will work if you can arrange your data into cubes. Doing it one texel at a time would be miserable though.

https://www.opengl.org/sdk/docs/man3/xhtml/glTexSubImage3D.xml


Question:
I tried includingstring.handstdlib.h, but still get undefined reference compile errors.

This leads me to conclude that it is in a different library that I didn't include. Where is it?

I am using gcc compiler - the code is written in Windows, but is going to be compiled and run on a unix server.

Answer: strcat_scan be found instring.has of C 2011. Generally speaking, only microsoft has implemented these alternative functions.


Question:
Consider the C code below:

```
#include <stdio.h>
int main()
{
    int i = 012;
    printf("%d", i);
}
```

On O/P the value ofiis printed as 10. I know (012)8= (10)10. But I'm confused about how C storesintvariable values. Can anybody explain it to me?

Answer: They are stored in binary, you can use many representations to define them, but in the end it's the binary representation that is used.


Question:
I have a set of points in a 2D plane. I need to detect only the points that belong to the shape that borns from the union of this subset of points in order to cover the largest area: that is, the boundary points.

The following figure is an example:

The red points are those ones I need to detect.

Answer: What you need is calledConvex hull.A lot of algorithms existto calculate it.


Question:
I have a set of points in a 2D plane. I need to detect only the points that belong to the shape that borns from the union of this subset of points in order to cover the largest area: that is, the boundary points.

The following figure is an example:

The red points are those ones I need to detect.

Answer: What you need is calledConvex hull.A lot of algorithms existto calculate it.


Question:
I disassembled the following C call

```
exit(EXIT_SUCCESS);
```

and found out that it calls the exit procedure at an assembly level

```
call    exit
```

Where can I find the source code for this procedure so that I can study it and find out exactly what is happening?

Answer:
In theC library of your system. Which then eventually invokes youroperating system.

The links are for linux with glibc, you forgot to mention your environment.


Question:
I disassembled the following C call

```
exit(EXIT_SUCCESS);
```

and found out that it calls the exit procedure at an assembly level

```
call    exit
```

Where can I find the source code for this procedure so that I can study it and find out exactly what is happening?

Answer:
In theC library of your system. Which then eventually invokes youroperating system.

The links are for linux with glibc, you forgot to mention your environment.


Question:
so I have a string with the following value

[7, 8]

Now I wan't to store each value (only the numbers) in a 2D array [1][2].I'm pretty sure using sscanf is the best way to do this, but how do I tell sccanf to only read the integers?

Thanks in advance

Answer:
```
sscanf("[%d,%d]", Array[a][b], Array[c][d]);
```


Question:
Whats difference in the working of

```
while(i++<100)
```

and

```
while(i++<100);
```

Is this correct that in 1st case,iincreases until its value reach to99but in 2nd case,;is an error that's why nothing is going to happen?

Answer:
No:

while(i++<100);is a loop with a empty command (does nothing untiliis 100), (there is no compilation error).

Andwhile(i++<100) {commands}is a same loop but does someting.


Question:
so I have a string with the following value

[7, 8]

Now I wan't to store each value (only the numbers) in a 2D array [1][2].I'm pretty sure using sscanf is the best way to do this, but how do I tell sccanf to only read the integers?

Thanks in advance

Answer:
```
sscanf("[%d,%d]", Array[a][b], Array[c][d]);
```


Question:
Whats difference in the working of

```
while(i++<100)
```

and

```
while(i++<100);
```

Is this correct that in 1st case,iincreases until its value reach to99but in 2nd case,;is an error that's why nothing is going to happen?

Answer:
No:

while(i++<100);is a loop with a empty command (does nothing untiliis 100), (there is no compilation error).

Andwhile(i++<100) {commands}is a same loop but does someting.


Question: How do I that? I don't want to use the Visual Studio IDE, yet I want to use the provided compiler (cl.exe) and the Developer Command Prompt for VS2013.

Answer:
I used to do it to via command line

```
cl /EHsc /MD  main.cpp /Fetest.exe /I F:\C++_Libraries\SDL2\SDL2-2.0.3\include /link /LIBPATH:F:\C++_Libraries\SDL2\SDL2-2.0.3\lib\x86 SDL2.lib SDL2main.lib /SUBSYSTEM:CONSOLE
```


Question:
Please explain the difference between

```
char* str = "Hello";
```

And

```
char* str = {"Hello"};
```

Answer:
ISO 9899-1990 6.5.7("Initialization") says :

An array of character type may be initialized by a character string
  literal, optionally enclosed in braces.


Question:
Please explain the difference between

```
char* str = "Hello";
```

And

```
char* str = {"Hello"};
```

Answer:
ISO 9899-1990 6.5.7("Initialization") says :

An array of character type may be initialized by a character string
  literal, optionally enclosed in braces.


Question:
Create file using C in Ubuntu.
I've tried that code and it doesn't work.

```
#include<stdio.h>
#include<string.h>
int main()
{
  char a[50];
  char command[150];
  printf("Enter The File's Name");
  gets(a);
  strcpy("touch ");
  strcat("a");
  system(command);
  return 0;
}
```

Answer:
Your strcpy should bestrcpy(command, "touch")and your strcat should bestrcat(command, a)

But there are much better ways to create an empty file...


Question:
Why doesn't this work?

```
printf("%d \n\n\n\n", atoi("11110010100"));
```

it outputs -1774891788... I just want it outputted as it is. It seems to work just fine if the number is a bit smaller.

Answer:
atoireturns anint. You pass a string which contains a number bigger than whatint(in your implementation) can hold. So, you have an integer overflow.

To print the maximum value anintcan hold, includelimits.hand printINT_MAX.


Question:
Newbie question: why can't I getprintfto output the binary number as it is, instead of converting it?

```
int gpa = 01011001;
printf("pure: %i \n", gpa);
```

gives the output: 266753

How can I get it to output 01011001 or just 1011001?

Answer: 0preceding an integer literal is hold for octa-decimal number. Decimal equivalent of01011001is266753. Remove that preceding0to print as it is.


Question:
Create file using C in Ubuntu.
I've tried that code and it doesn't work.

```
#include<stdio.h>
#include<string.h>
int main()
{
  char a[50];
  char command[150];
  printf("Enter The File's Name");
  gets(a);
  strcpy("touch ");
  strcat("a");
  system(command);
  return 0;
}
```

Answer:
Your strcpy should bestrcpy(command, "touch")and your strcat should bestrcat(command, a)

But there are much better ways to create an empty file...


Question: I am using linux Lite.  I have installed code Blocks. When i am creating any new project then it is working correctly. it compiling codes. But When any empty c file is creating and trying to compile then it is not working.Showing message that  permission denied.  I have checked the compiler setting for empty file. it is GNU GCC Compiler. How can i solve this?

Answer: It would be happen due to root access. run code-blocks as root user and try it would be work.


Question:
I need to edit the values of an existing ListView row (i.e change the values of an Item and its Subitems).

I need to do that programmatically and not by clicking on the ListView item at runtime to rename it.

Answer: just useLVM_SETITEMas documented.


Question:
```
#include<stdio.h>
void main ()
{
     int a=4;
     const int *p=&a;
     *p--;
}
```

in the above line it means that we can not change the value a via p, so in decrement statement it should give an error but it is not giving the error. can anyone explain why??

Answer:
*p--decrementspnot contents ofp.

If you do(*p)--you will get compilation error

```
error: decrement of read-only location ‘*p’
```


Question:
I know compiler does Structure padding because CPU can read one word at time ( Word size depends on architecture 16/32/64 ) but I am not able to understand padding behavior for below example.

```
struct pad
{
  char ch;
};
```

Size of "struct pad" comes as 1 Byte ( But According to padding concept I suspected 4 byte ( 32 bit architecture ).

Answer: A char type can be accessed efficiently on any address boundary, so no padding is necessary.


Question:
I'm trying to do thisswprintf(hexResult, L"%I64X", result);from javascript, is this possible? Such thatCityHash64('C:\Program Files (x86)\Mozilla Firefox')is encoded asE7CF176E110C211B.

Thanks

Answer: JavaScript numbers have atoStringmethod which takes a radix.  UsingtoString(16)will get you the number in hex.  Is this what you're looking for?


Question:
How can I delete the first digit of a given number using a user defined function (Suppose the function isDELTOP) ?

For Ex.,

```
x=DELTOP(1748);
```

I want the value ofxas748.

Would anybody tell me how to write this function easily ?

Answer:
A C++11 one-liner would be

```
int DELTOP(int x) {
    return std::stoi(std::to_string(x).substr(1));
}
```


Question:
Does something like TextBox exist in ncurses?

Requirements to TextBox:

ability to adequate handle KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_BACKSPACE, KEY_DC and other.adequate transfer lines.save, if you need, text in char* buffer.

Answer: ncursesitself provides lower-level functions from which a "textbox" can be built.  For instance, thedialogandcdklibraries use (n)curses to provide these features.


Question:
Does something like TextBox exist in ncurses?

Requirements to TextBox:

ability to adequate handle KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_BACKSPACE, KEY_DC and other.adequate transfer lines.save, if you need, text in char* buffer.

Answer: ncursesitself provides lower-level functions from which a "textbox" can be built.  For instance, thedialogandcdklibraries use (n)curses to provide these features.


Question:
At the third line I get "Expected a declaration" for instr[0xB8][256]

```
void funcB8 ();
void (*instr[256][257])();
instr[0xB8][256] = &funcB8;
```

Answer:
You can initialize the array at a specific index outside a function:

```
void (*instr[256][257])() = { [0xB8][256] = &funcB8 };
```

or assign a value to the array, but to do that you have to do that in a function


Question: So, I'm trying to write some JNA code to work with Unix sockets, and I'm trying to reference AF_UNIX for sockets. I looked through some of the gcc included files, but I couldn't find anything.

Answer: It may be platform-dependent, which is why you should use the define. It should be insys/socket.h.


Question: I'm writing a netfilter module and need to store current time value somewhere inside the module to calculate difference in time. What is the best way to do that?

Answer: I didn't understood your question properly. Because you are not provided any piece of code. Any way you can keep your variable either indevice structure of  module, or you can declare variable simply as aGlobal variable.


Question:
The following C code is apparently O(N) (according to my practice exam). However, I am not sure as to why it is O(N) and not O(Something*Something).

```
void doit(int N) {
    while (N) {
        for (int j = 0; j < N; j += 1) {
        }
        N = N / 2;
    }
}
```

Anyone care to give me some insight to this problem?

Thanks in advance!

Answer: Because N + N/2 + N/4 + ... = 2N.


Question:
I just started programming in C. And I don't really understand the following code:

```
printf("%zu",i);
```

or instead of%zuwhat are the other things that I can write (I know that they depend on the type of i) and which one is for what?

Answer:
It's a format modifier forsiz_tandsize_tis unsigned.

```
printf("%zu\n", x);  // print unsigned decimal
printf("%zx\n", x);  // print hexadecimal
printf("%zd\n", y);  // print signed decimal
```


Question:
I just started programming in C. And I don't really understand the following code:

```
printf("%zu",i);
```

or instead of%zuwhat are the other things that I can write (I know that they depend on the type of i) and which one is for what?

Answer:
It's a format modifier forsiz_tandsize_tis unsigned.

```
printf("%zu\n", x);  // print unsigned decimal
printf("%zx\n", x);  // print hexadecimal
printf("%zd\n", y);  // print signed decimal
```


Question:
I want to be able to do this in visual studio:

```
struct A
{
    int x;
};

struct B
{
    int y;
    struct A;
};

struct B b;
b.x //...
```

How can I do this? In gcc you use -fms-extensions to compile it

Answer: Youjust do it.MSVS supports this as an extension.


Question:
Basically, I can't figure this out, I want my C program to store the entire plaintext of a batch program then insert in a file and then run.

I finished my program, but holding the contents is my problem. How do I insert the code in a string and make it ignore ALL special characters like %s \ etc?

Answer: You have to escape special characters with a \, you can escape backslash itself with another backslash (i.e.\\).


Question:
Basically, I can't figure this out, I want my C program to store the entire plaintext of a batch program then insert in a file and then run.

I finished my program, but holding the contents is my problem. How do I insert the code in a string and make it ignore ALL special characters like %s \ etc?

Answer: You have to escape special characters with a \, you can escape backslash itself with another backslash (i.e.\\).


Question: In C, we can build a debug version or a release version of the binary files (the object files and the executable). How can we do this in Go?

Answer:
In Go, it isn't typical to have a debug version or a release version.

By default,go buildcombines symbol and debug info with binary files. However, you can remove the symbol and debug info withgo build -ldflags "-s -w".


Question: In C, we can build a debug version or a release version of the binary files (the object files and the executable). How can we do this in Go?

Answer:
In Go, it isn't typical to have a debug version or a release version.

By default,go buildcombines symbol and debug info with binary files. However, you can remove the symbol and debug info withgo build -ldflags "-s -w".


Question: Is it possible to load akernel extension(kext) through aC APIinstead of using thesystem()call?

Answer: Yes, you want theKextManagerAPI. In particular,KextManagerLoadKextWithIdentifier()is probably the function you'll want to use to load an installed kext, versusKextManagerLoadKextWithURL()if you want to load a kext that is not in /System/Library/Extensions or /Library/Extensions but e.g. in an .app bundle.


Question:
This question already has answers here:Fill with variable number of ones(2 answers)Closed8 years ago.

I have a number in range 1-8.

I want to convert it to

```
0b00000001  // 1
0b00000011  // 2
0b00000111  // 3
0b00001111  // 4
0b00011111  // 5
0b00111111  // 6
0b01111111  // 7
0b11111111  // 8
```

Can it be done without a switch or a for loop?
Ideally with a simple formula.

Answer:
What you are looking for is

```
(1 << v) - 1
```


Question:
This question already has answers here:Fill with variable number of ones(2 answers)Closed8 years ago.

I have a number in range 1-8.

I want to convert it to

```
0b00000001  // 1
0b00000011  // 2
0b00000111  // 3
0b00001111  // 4
0b00011111  // 5
0b00111111  // 6
0b01111111  // 7
0b11111111  // 8
```

Can it be done without a switch or a for loop?
Ideally with a simple formula.

Answer:
What you are looking for is

```
(1 << v) - 1
```


Question:
This is a piece of myCcode:

```
for (i=2; i<sequence_length+1; i++)
{
    int tab_length = Newton(sequence_length, i);
    start_tab[tab_length] = make_for_num(i, sequence_length, start_tab, tab_length);

}
```

My goal is to use updatedstart_tabvariable for every next step of forloop. Output of each iteration should be an input for the next one, but it isn't. How can I fix that?

Answer: You could use a recursive function.


Question:
This is a piece of myCcode:

```
for (i=2; i<sequence_length+1; i++)
{
    int tab_length = Newton(sequence_length, i);
    start_tab[tab_length] = make_for_num(i, sequence_length, start_tab, tab_length);

}
```

My goal is to use updatedstart_tabvariable for every next step of forloop. Output of each iteration should be an input for the next one, but it isn't. How can I fix that?

Answer: You could use a recursive function.


Question: Hello I am developing a simple protection for a Cocoa Mac Os X application for independent distribution. What would be the best place to store some secret hidden files on the user's disk to keep track of demo expiration ? also how to protect in case a user monitors the file system activity with tools such as FSEventer ? Thanks

Answer:
Store it as a generic password in the user's keychain.

Keychain Services Programming Guide


Question: I am wrapping c library for Python using Cython.I have pointers to callable Python objects in my C code to call them back later from C code.How to ensure a callback is not garbage collected or deleted if I only have address.

Answer: Just__Pyx_INCREF(obj)the object you're holding -- this ensures it won't go away!Doremember to__Pyx_DECREF(obj)once you're done with it -- and, seehttps://github.com/cython/cython/wiki/refcountingfor details!-)


Question:
I was going throughPthreads Programmingby Bradford Nichols, on Page number177I noticed this code:

```
static char work_buffer[100];
 void reverse_string(in_str)
 char *in_str;
 {
   ...
   ...
 }
```

What is the third line of code doing here?

Answer: Third line states that the parameterin_starofreverse_stringis of typechar *. Its an old K&R style of parameter declaration.


Question:
I was going throughPthreads Programmingby Bradford Nichols, on Page number177I noticed this code:

```
static char work_buffer[100];
 void reverse_string(in_str)
 char *in_str;
 {
   ...
   ...
 }
```

What is the third line of code doing here?

Answer: Third line states that the parameterin_starofreverse_stringis of typechar *. Its an old K&R style of parameter declaration.


Question: I'm studying operating systems and I encountered both the terms ISR and interrupt handler. Are they two words for the same mechanism? If not, what is the difference?

Answer:
There is no difference in Interrupt handler and ISR.Wikisays that:

In computer systems programming,an interrupt handler, also known as an interrupt service routine or ISR, is a callback function [...]


Question:
I'm telling other people thatcc -DFOOis just the same ascc -DFOO=1but I'm not quite confident if all compilers support this. So is it a standard for C compilers?

(As inspired by the accepted answer, found the recent POSIXc99standard, 2016 edition. Just for reference.)

Answer: It's not a standard for C compilers, though it is a standard for POSIX-compliant systems. Seethe cc manual.


Question: I have one Tcp/Ip with ssl server enabled with epoll so it can handle ten thousand connections simultaneously. When i tried to test the server,i created thousand clients using thread. when i tried to connect with the server,after certain time connect() return ETIMEOUT. How to overcome this error?

Answer: you could change the socket attributes for recv and xmit timeout values  Probably the same way you set the keepalive attribute


Question:
How could I modify the line bellow in ANSI C without using theunsignedmark?

```
unsigned int x, y, z; // unsigned variables should not be used
/*... some operations where x, y and z gets values between 0x0 and 0xFFFFFFFF ... */
x = (unsigned int)-(int)(y * z); // line to modify
```

Answer:
You can directly apply negation to an unsigned value. The result will be reduced modulo 2^N, which is what your existing code does anyway.

```
x = -(y * z);
```


Question: I have a big project. I want to find which all .cpp/.h files includefile1.hin them. Is there any shortcut key in Eclipse CDT to do this?

Answer: I'd suggest the Include Browser view. You can drag a file in there and you get a nice tree which shows all files that include your file, including indirect includes.


Question:
i have a functionisEmpty()and i want to replace it with with thisEmpty().

```
int isEmpty(char *s)
{   return s[0]=='\0';
}
```

Should i replace it like this?

```
#define isEmpty() Empty()
```

Answer:
Given you have a functionisEmptyas defined, you need to pass a parameter to it:

```
#define Empty(s) isEmpty(s)
```

But you might want to achieve it without any function:

```
#define Empty(s) ((s)[0]=='\0')
```


Question: I have a big project. I want to find which all .cpp/.h files includefile1.hin them. Is there any shortcut key in Eclipse CDT to do this?

Answer: I'd suggest the Include Browser view. You can drag a file in there and you get a nice tree which shows all files that include your file, including indirect includes.


Question: let's say there is a (void)function I define that prints some numbers and I want to check if it prints the correct content. I'm thinking writing the content to a file and read it back and check if it is what I wanted.  But I dont know how since the function is void and returns nothing.

Answer: I just found out I can use freopen() to write data into a file from stdout. My bad for not making the question more clear.


Question:
I want to test an element forstructureif he is empty or not
but when (ex.) theG[s].a=0andG[s].b=2he never go into theif,, any help ?

```
if (G[s].a != NULL && G[s].b != NULL)
```

Answer:
re write your logic with positive logic instead of using not null.

"not (A or B)" is the same as "(not A) and (not B)".


Question:
I saw some code like this:

```
enum
{
   FIRST_DAY = 0
};
```

I know the grammar allows only one member in the enum, but in which case we define it like this? and what is the reason?

Answer: I can only guess, but in C this was an idiom to define named integer constants without resorting to using #define.


Question: Suppose I write a program in C/C++ and create an array of certain size. I want to keep that permanently even if I switch off the computer and later access it. Is there a way to do that? If so do let me know and also after saving it, how to access it.

Answer: Save the data to a file and load it on programm start.


Question:
I saw some code like this:

```
enum
{
   FIRST_DAY = 0
};
```

I know the grammar allows only one member in the enum, but in which case we define it like this? and what is the reason?

Answer: I can only guess, but in C this was an idiom to define named integer constants without resorting to using #define.


Question: Suppose I write a program in C/C++ and create an array of certain size. I want to keep that permanently even if I switch off the computer and later access it. Is there a way to do that? If so do let me know and also after saving it, how to access it.

Answer: Save the data to a file and load it on programm start.


Question:
I want to quickly make a static linked list, with as little code as possible, which is very readable and without clutter. How do i accomplish this elegantly?

something like

1 -> 2 -> 3 -> 4 -> NULL

Answer:
```
struct node {int x; struct node *next;};
#define cons(x,next) (struct node[]){{x,next}}
struct node *head = cons(1, cons(2, cons(3, cons(4, NULL))));
```


Question:
Is there a way to compute the result of((UINT_MAX+1)/x)*x-1in C without resorting tounsigned long(wherexisunsigned int)?
(respective "without resorting tounsigned long long" depending on architecture.)

Answer:
It is rather simple arithmetic:

```
((UINT_MAX + 1) / x) * x - 1 =
((UINT_MAX - x + x + 1) / x) * x - 1 =
((UINT_MAX - x + 1) / x + 1) * x - 1 =
(UINT_MAX - x + 1) / x) * x + (x - 1)
```


Question:
Is there a way to compute the result of((UINT_MAX+1)/x)*x-1in C without resorting tounsigned long(wherexisunsigned int)?
(respective "without resorting tounsigned long long" depending on architecture.)

Answer:
It is rather simple arithmetic:

```
((UINT_MAX + 1) / x) * x - 1 =
((UINT_MAX - x + x + 1) / x) * x - 1 =
((UINT_MAX - x + 1) / x + 1) * x - 1 =
(UINT_MAX - x + 1) / x) * x + (x - 1)
```


Question:
So I declared a variable as an integer and initialized it to 0. When I tried printing the value of that variable, it gave me an incredibly high number. int

```
x=0;
printf("%d", &x);
```

This is what I did. Am I doing anything wrong? Thanks in advance.

Answer:
The operator '&' represent the address of that variable. we need, the actual value of that variable use like this...

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


Question: What is the reason to invoke theprepare handle callbackand thecheck handle callbackin the libuv event loop?

Answer:
The i/o operations happen between those 2, so you may want to perform some operation before blocking for i/o (prepare handles), and after i/o (check handles).

This diagram illustrates how the libuv event loop operates internally:http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop


Question: What is the reason to invoke theprepare handle callbackand thecheck handle callbackin the libuv event loop?

Answer:
The i/o operations happen between those 2, so you may want to perform some operation before blocking for i/o (prepare handles), and after i/o (check handles).

This diagram illustrates how the libuv event loop operates internally:http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop


Question: As the title suggests, what are names ofletoh16,letoh32,betoh16, andbetoh32on Linux? I have foundhtonl, but that doesn't let me choose 16 bit or 32 bit, and it is also only to big endianess.

Answer:
The functions are called the following on Linux:

letoh16is calledle16tohletoh32is calledle32tohbetoh16is calledbe16tohbetoh32is calledbe32toh


Question: how do I add Arduino libraries to Eclipse Project? I just started playing with Intel Edison and have a Grove developer kit with an LCD that I can't use, because the library is missing.

Answer:
If you go to Project->Properties->C/C++ Build->Settings
You can add a library under the appropriate compiler with -l and you can include directories for headers with -I under C/C++ General->Paths and Symbols under the includes tab.


Question: how do I add Arduino libraries to Eclipse Project? I just started playing with Intel Edison and have a Grove developer kit with an LCD that I can't use, because the library is missing.

Answer:
If you go to Project->Properties->C/C++ Build->Settings
You can add a library under the appropriate compiler with -l and you can include directories for headers with -I under C/C++ General->Paths and Symbols under the includes tab.


Question:
printf stops printing at the first \0 it meets.

Is there a way to force it to continue, for example if my string contains more characters after \0.

Answer:
If you know the length of your string asncharacters, you can output it usingfwrite:

```
if (n && fwrite(str, 1, n, stdout) != n) {
    /* Error handling. */
}
```


Question:
I am confused between theif/elseand#if/#else/#endifconstructs.

What are the differences between them?In which specific situations should I use each of them?

Answer: if(...)andelse(...)conditions are evaluated at runtime.#if,#elseare evaluated before compile time by the preprocessor.


Question:
Why won't this program run?

```
#include<stdio.h>
int main()
{
    printf("%f\n", log(36.0));
    return 0;
}
```

Answer:
You have to include

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

This is because math.h is a header file in the standard library of C programming language designed for basic mathematical operations.


Question:
Why won't this program run?

```
#include<stdio.h>
int main()
{
    printf("%f\n", log(36.0));
    return 0;
}
```

Answer:
You have to include

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

This is because math.h is a header file in the standard library of C programming language designed for basic mathematical operations.


Question:
Why won't this program run?

```
#include<stdio.h>
int main()
{
    printf("%f\n", log(36.0));
    return 0;
}
```

Answer:
You have to include

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

This is because math.h is a header file in the standard library of C programming language designed for basic mathematical operations.


Question:
I think that the C programming language should be more clear with regards to syntax for certain elements.

I have tried to solve this with an emulator but it was to slow.

```
typedef unsigned long into uli;
uli i, j;
unsigned long int x, y;
```

Answer: Yes they are. The C programming language contains various discrepancies but this question is relatively simple. The terms "uli" and "unsigned long int" are the exact same thing.


Question: I want to scan a file for 001.120 float or 220.550 or 123.125 etc., and floats with three digits, and three decimal digits, how do I do this, like is it %03.3f?

Answer: No, it's just%f. It doesn't need to know the specifics because it can deduce them.


Question:
I was debugging my syscall and I found that dmesg prints so many lines which made me couldn't see all of myprintk.

Is it possible toprintkto a file?

Answer:
Usetrace_printk()instead ofprintk()

And your prints should be in ftrace buffers.

```
$ cd /sys/kernel/debug/tracing
      $ cat trace
```

Referhttp://june-takeout.blogspot.dk/2010/01/debugging-kernel-using-ftrace-part-1.htmland see section "Using trace_printk()"


Question:
I was debugging my syscall and I found that dmesg prints so many lines which made me couldn't see all of myprintk.

Is it possible toprintkto a file?

Answer:
Usetrace_printk()instead ofprintk()

And your prints should be in ftrace buffers.

```
$ cd /sys/kernel/debug/tracing
      $ cat trace
```

Referhttp://june-takeout.blogspot.dk/2010/01/debugging-kernel-using-ftrace-part-1.htmland see section "Using trace_printk()"


Question:
I am studying pointers for c and this placement of*really really confuses me.

I understand whatint *ais..

But what is

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

I understand what above is doing but why is*in the middle of by itself?? This part really confuse me so please someone can explain to me?

Answer: unary*means dereferencing and binary*means multiplication.


Question:
I am studying pointers for c and this placement of*really really confuses me.

I understand whatint *ais..

But what is

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

I understand what above is doing but why is*in the middle of by itself?? This part really confuse me so please someone can explain to me?

Answer: unary*means dereferencing and binary*means multiplication.


Question:
Say I have a pointer to a struct which has an array field called arr: p

Isp->arr[i]equal to:

(p->arr)[i](which is what I was going for)

or

p->(arr[i])(which is an error)

Answer:
->operator has same precedence as[]operator.But it will be evaluated from left to right. So

```
p -> arr[i]
```

is equivalent to

```
(p -> arr)[i]
```


Question:
How do I create aarray containing multiple pointersin C?

e.g.If you have a data-set of sizenwhich you want to split intotchunks. So if you want to access an element in the range0-(n/t), you would need to access the array index and go to the corresponding pointer index.

Answer:
This will work forintdata

```
int *arr_of_ptr[t];
for(int i = 0; i < t; i++)
    arr_of_ptr[i] = malloc(sizeof(int) * n/t);
```


Question:
I want to make variable null in C in dev C.

This code isn't work

```
char a = '5';
a = '';
```

I don't know why this is not work. And I want to make characterabe empty. The error message is
"[Error] empty character constant"

Answer:
It depends what you mean by empty..

'\0' means the value 0 (NUL).


Question:
I want to make variable null in C in dev C.

This code isn't work

```
char a = '5';
a = '';
```

I don't know why this is not work. And I want to make characterabe empty. The error message is
"[Error] empty character constant"

Answer:
It depends what you mean by empty..

'\0' means the value 0 (NUL).


Question:
```
//function to copy string t to string s using pointers
void strcpy(char *s,char *t)
{
    while((*s++=*t++)!='\0');
    return;
}
```

i am confused how is the expression *s++==*t++ evaluated.I know associativity of increament operator is higher than assignment operator.

Answer:
*s++=*t++ is basically

```
*s = *t;
s++;
t++;
```


Question:
```
//function to copy string t to string s using pointers
void strcpy(char *s,char *t)
{
    while((*s++=*t++)!='\0');
    return;
}
```

i am confused how is the expression *s++==*t++ evaluated.I know associativity of increament operator is higher than assignment operator.

Answer:
*s++=*t++ is basically

```
*s = *t;
s++;
t++;
```


Question: This may seem to be a dumb question but I don't really have a good understanding offork()other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed viafork(), how to correctly assign tasks to parent process and child process?

Answer: Check the return value offork. The child process will receive the value of0. The parent will receive the value of the process id of the child.


Question: This may seem to be a dumb question but I don't really have a good understanding offork()other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed viafork(), how to correctly assign tasks to parent process and child process?

Answer: Check the return value offork. The child process will receive the value of0. The parent will receive the value of the process id of the child.


Question:
If I do

```
sum2=(((p/2)%m)*((p+1)%m))%m;
sum2=(sum2 * (p%m))%m;
```

I get the right answer but if I do

```
sum2=((p%m)*(((p/2)%m)*((p+1)%m))%m)%m;
```

I get the wrong answer. What is the reason?
All variables are of unsigned long long integer type and m<=10000000.
PS:Question updated because of typo.

Answer: sum2=((p%m)*((((p/2)%m)*((p+1)%m))%m))%m;This should work for you.There was a problem with parentheses.


Question:
How would I go about making an enum into a string using a case such as
enum {Ace,....King} face;
to a case that would convert it to say "Ace" rather than a 0 or 1.

Answer:
```
char const* faceToString(face f)
{
   switch (f)
   {
       case Ace:
          return "Ace";
       case Two:
          return "Two";

       ...

       case King:
          return "King"
   }
}
```


Question:
Every Ruby object is of typeVALUEin C. How do I print it in a readable way?

Any other tips concerning debugging of Ruby C extensions are welcome.

Answer:
You can callpon Ruby objects with the C functionrb_p. For example:

```
VALUE empty_array = rb_ary_new();
rb_p(empty_array); // prints out "[]"
```


Question:
In C, on any micro controller when we initialize a float variable to 0

```
float var = 0.0f;
```

Is 'var' exactly equal to zero or does it depend on the min & max float resolution of the processor?

Answer: Happily, zero is actually zero no matter what: IEEE-754 (the usual standard for floats) sets aside the all-zeroes bit pattern as meaning identically zero.


Question:
It´s possible using Macros in ironPython?
I have a dll with macros in C and I would like access it from IronPython.
Any ideas?
Thank you.

Answer: You can't access C macros from a DLL - they're handled by the C preprocessor, so they never reach the compiler and thus can't part of the DLL. You can access functions exported from the DLL in IronPython using the standard Pythonctypesmodule.


Question:
It´s possible using Macros in ironPython?
I have a dll with macros in C and I would like access it from IronPython.
Any ideas?
Thank you.

Answer: You can't access C macros from a DLL - they're handled by the C preprocessor, so they never reach the compiler and thus can't part of the DLL. You can access functions exported from the DLL in IronPython using the standard Pythonctypesmodule.


Question:
I just wrote a code in c

```
#include <stdio.h>

int main()
{
    int a=0;
    option1: a++=5;
    option2: ++a=5;
    printf("%d\n",a);

    return 0;
}
```

but it doesnt compiled with error

```
lvalue required as left operand of assignment
```

why its an error?
thanks!

Answer:
Because, like your compiler says,a++is not anlvalue, it's arvalue.
You will find more information aboutlvalueandrvaluehere.


Question:
For example:

```
void func1(){
    int i = 123;
    func2(&i);
}
void func2(int *a){
    *a = 456;
}
```

Whenfunc1callingfunc2, a pointer to local variable is passed tofunc2-- the pointer is pointed to the stack. Is this safe for the rules of C?

Thanks.

Answer: The scope ofiisfunc1and it outlives the call tofunc2. So it is perfectly safe.


Question:
```
void cleanup( command_t* p_cmd ){
}
```

Basically i need to find a way to free up space that has beenmallocin C. I am new to c and working on a basic shell.

Answer:
1) free (p_cmd);

2) p_cmd = NULL;

E.g.:

```
void cleanup( command_t* p_cmd )
  {
      if( p_cmd )
      {
          free (p_cmd);
          p_cmd = NULL;
      }
  }
```


Question:
```
void cleanup( command_t* p_cmd ){
}
```

Basically i need to find a way to free up space that has beenmallocin C. I am new to c and working on a basic shell.

Answer:
1) free (p_cmd);

2) p_cmd = NULL;

E.g.:

```
void cleanup( command_t* p_cmd )
  {
      if( p_cmd )
      {
          free (p_cmd);
          p_cmd = NULL;
      }
  }
```


Question: I've been told it is possible, but it seems every time I try I continuously get an error saying "No symbol tables have been loaded." Have I been tricked, or is it in fact possible?

Answer:
Assuming the address of the variable is0x7fffffffe51cand its type isint, here is how you do it in GDB:

```
(gdb) set {int}0x7fffffffe51c = 11
(gdb) p *0x7fffffffe51c
$5 = 11
```

To find local variables, refer to
"How to read local variables with gdb?".


Question: I have to get which exe use my dll at the moment. How to accomplish it from dll?

Answer:
DLLs are Windows shared object files, I assume you use C with the windows SDK and windows.h is available for you to include.

In that case, use the GetModuleFileName() function. Use 0 as the module handle and you'll get the executable name.

```
wchar_t buffer[MAX_PATH];
GetModuleFileName(0, buffer, MAX_PATH);
```


Question: I've been told it is possible, but it seems every time I try I continuously get an error saying "No symbol tables have been loaded." Have I been tricked, or is it in fact possible?

Answer:
Assuming the address of the variable is0x7fffffffe51cand its type isint, here is how you do it in GDB:

```
(gdb) set {int}0x7fffffffe51c = 11
(gdb) p *0x7fffffffe51c
$5 = 11
```

To find local variables, refer to
"How to read local variables with gdb?".


Question: I have to get which exe use my dll at the moment. How to accomplish it from dll?

Answer:
DLLs are Windows shared object files, I assume you use C with the windows SDK and windows.h is available for you to include.

In that case, use the GetModuleFileName() function. Use 0 as the module handle and you'll get the executable name.

```
wchar_t buffer[MAX_PATH];
GetModuleFileName(0, buffer, MAX_PATH);
```


Question: I have to get which exe use my dll at the moment. How to accomplish it from dll?

Answer:
DLLs are Windows shared object files, I assume you use C with the windows SDK and windows.h is available for you to include.

In that case, use the GetModuleFileName() function. Use 0 as the module handle and you'll get the executable name.

```
wchar_t buffer[MAX_PATH];
GetModuleFileName(0, buffer, MAX_PATH);
```


Question:
What is this use of the colon called?

The following code is taken from the bookLearn Core Audio.

```
int main(int argc, const char * argv[])
    {
    //...

    cleanup:
        AudioQueueDispose(queue, true);
        AudioFileClose(player.playbackFile);

        return 0;
    }
```

Answer:
That's a label. It's used along with agotostatement to control the flow of your program.

goto and Labeled Statements (C)


Question:
i was studying EOF character in c and came across a program :

```
#include <stdio.h>
main()
{
int c= 0;
while((c = getchar())!=EOF)
putchar(c);
}
```

its all good it is giving proper o/p but how do i come out of the loop by entering a EOF character which i entered and it did nothing.

Answer:
To stimulateEOFinstdin,

If you are on windows or DOS press CTRL+ZOr if you are running linux or some other OS, press CTRL+D


Question:
I have my structure set up like this

```
struct judges
{
    char surname[20];
    int id;
    struct judges *wsk;
}
```

How can I get random number from given IDs? Like for example, I add 3 judges with IDs 3, 7, and 253, is there a way to get random number only from these ones?

Answer: Pick a random item from an array of these structures and read its ID.


Question:
i was studying EOF character in c and came across a program :

```
#include <stdio.h>
main()
{
int c= 0;
while((c = getchar())!=EOF)
putchar(c);
}
```

its all good it is giving proper o/p but how do i come out of the loop by entering a EOF character which i entered and it did nothing.

Answer:
To stimulateEOFinstdin,

If you are on windows or DOS press CTRL+ZOr if you are running linux or some other OS, press CTRL+D


Question:
I have a very small amount of code:

```
int test = strcmp("Websecurity", "easily");
printf("%d\n", test);
```

The result is -1. Why? Clearly 'W' is greater than 'e'?

Answer: Capital letters come before lowercase letters in ASCII, and so'W' < 'e'.


Question:
When reading through some example codes for DMAs from Xilinx, I came across this piece of code:

```
value = (value + 1) & 0xFF
```

where value is an uint8_t.

What is the point of the& 0xFF? Why not simply writevalue = value + 1?

Answer: My guess is that this code was intended to work correctly even ifvalueisnota 1-byte (8-bit) type. The bitmask0xFFmakes sure that only the last byte of the value is kept.


Question:
When reading through some example codes for DMAs from Xilinx, I came across this piece of code:

```
value = (value + 1) & 0xFF
```

where value is an uint8_t.

What is the point of the& 0xFF? Why not simply writevalue = value + 1?

Answer: My guess is that this code was intended to work correctly even ifvalueisnota 1-byte (8-bit) type. The bitmask0xFFmakes sure that only the last byte of the value is kept.


Question:
I was debugging something since last two days and it seems on my linux m/c accept is returning me a socket ID of zero.

```
fd = accept(unix_domain_socket,
                   (struct sockaddr *) &new_connection,
                   &new_conn_length);
```

I see that fd is returning 0 -- Is this valid? Is 0 a valid socket fd number?

Answer: Yes. -1 means that it failed, but 0 is valid. Usually file descriptor zero is occupied by the standard input, though.


Question:
I have a project that be make all in terminal, in C and i am using ccpcheck file by file but i would like to used for check all files how a um project . I try used command with parameters :
cppcheck --enable=all  *.c  ,in the folder but show me less errors than check file by file.

There are better method for to do this ?
if you can help me

Answer:
try:

```
cppcheck --enable=all .
```

that scans all source files in current folder and in all subfolders


Question:
How would one go about using the pointer parameter if given a function like this:

```
int testFunction(int *){
}
```

I understand that a pointer is being passed as the parameter, but how do I use that pointer given that there is no variable name after the pointer?

Answer: You should name the argument. See this link for atutorial


Question: Given a size of buffer, I need to count how many new lines I have read using fread(). How to do that?

Answer: Count the number of newline characters (usually\n) in the buffer.


Question:
For library functions I useman <function>to find which header file I need to include. But for types likesize_t,uint32_t, etc. themanapproach doesn't work.

Is there any command to find the header file required?

Answer:
Another possible solution is to search locally using grep.

Something likegrep -r 'typedef\s.*\suint32_t;' /usr/includeshould work for you.


Question:
I want to print an error string with variables.

```
printf("Hi, %s", name);
perror-something("Error no: %d", number);
```

How do I add variables toperror?

Answer:
You can use the combination of strerror and the fprintf.

Consider,

```
fprintf(stderr,"%s:Error NO:%d\n",strerror(errno),number);
```


Question:
I want to print an error string with variables.

```
printf("Hi, %s", name);
perror-something("Error no: %d", number);
```

How do I add variables toperror?

Answer:
You can use the combination of strerror and the fprintf.

Consider,

```
fprintf(stderr,"%s:Error NO:%d\n",strerror(errno),number);
```


Question:
The following statements in C:

```
iONE >>= iShift;
iONE &= 0xffefffff;
iONE |= (((((long)(*temp & 0x7f) - 65) << 2) + iShift + 1023) << 20) | (iTWO & 0x80000000);
```

Is there something likeshr=,And=andOr=in Delphi.  Is there more appropriate way than literal porting, especially the third statement.

Answer: Those are basically two operations combined.x >>= ymeansx = x >> y.The same applies for&=and|=.And for the Delphi part:And,Or, andRight Shift.


Question:
How structs in C are saved in the memory?

Why sometimes the struct length in the memory is bigger
than expected?

Answer:
That's calleddata structure alignment.

Although not a perfect duplicate, you can find a good explanation of this in C atStructure padding and packing


Question:
```
short i = 1;
fwrite(&i, sizeof(i), 1, file);
fwrite(&i, sizeof(i), 1, file);
```

Is that proper? I want to write the sameitwice.

Answer: There's nothing wrong with it; just remember to check the return value.


Question:
While readinf MuPDF comes across the source code line

```
x = !x;
```

Want to know what does the above code do?

While compilation is also gives error as

```
assuming signed overflow does not occur when simplifying
condition to constant [-Werror=strict-overflow ]
```

Answer:
!xwill evaluate to either0or1, depending on the value ofx.

Ifxis0, it evaluates to1.Otherwise, it evaluates to0.


Question:
How structs in C are saved in the memory?

Why sometimes the struct length in the memory is bigger
than expected?

Answer:
That's calleddata structure alignment.

Although not a perfect duplicate, you can find a good explanation of this in C atStructure padding and packing


Question: I'm writing a C program and am exceeding the recursion limit via a segmentation fault. Is there any way to increase the program's recursion limit (perhaps via increasing the stack size), either via an option to GCC or via a command-line option? The program is running on Ubunutu.

Answer:
You can change the stack size withulimiton Linux, for example:

```
ulimit -s unlimited
```

On Windows with Visual Studio, use/Foption.


Question: If you are reading lines from a terminal in canonical mode, is there any way to tell the difference between a line terminated with EOL (Enter) and EOF (Ctrl-D)? My understanding is that both will return the number of bytes read from read().

Answer:
For EOL on an empty line, the byte count will be 1, for the newline.

For EOF on an empty line, the byte count will be 0, for 'there was no more data'.


Question: If you are reading lines from a terminal in canonical mode, is there any way to tell the difference between a line terminated with EOL (Enter) and EOF (Ctrl-D)? My understanding is that both will return the number of bytes read from read().

Answer:
For EOL on an empty line, the byte count will be 1, for the newline.

For EOF on an empty line, the byte count will be 0, for 'there was no more data'.


Question: Inthe tutorialfor erl_driver there seems to be no indication to where does the firstErlDrvPortobject comes from. Say I want to wrap libusb-1.0 to use it from erlang. There is no place in the API described byErlDrvEntryfor any index methods. How does one find a port to open?

Answer: Normally you obtain the first port using theerlang:open_port/2function, usage of which is shown in the code example in section 6.2 ofthe tutorialyou linked to in your question.


Question:
```
#include<stdio.h>
main()
{
    int c;
    c=getchar();

    while(c!=EOF)
    {
        putchar(c);
        c=getchar();
    }
}
```

Why this code is resulting in an infinite loop. It is from D.Ritchie's book.

Answer:
It results in an infinite loop becauseEOFis not a character that can be entered via keyboard.

Take a look at this:EOF in Windows command prompt doesn't terminate input stream


Question:
In C, suppose I have an unsigned char A which can be either 0 or 1.
I would like to find a bitwise logical operator that will convert
A to !A.

Note: I am using this code on a GPU, where bitwise operators are very cheap compared to logical operators. i.e. XOR is much cheaper than !

Answer: If by 'not' you mean send 1 to 0 and 0 to 1. you can use the XOR operator^to do that. If character is called c, you can writec = c ^ 1;.


Question: I came across a problem where _dl_resolve_conflicts was crashing. After a bit of search found it linked error while resolving pre-linked elfs. Can anyone throw some insight.

Answer: If you know in advance that some combination of object files will be referenced by a program, then pre-linking will fix up any references between that set of object files. The linker will still need to fix up references between your program and the object files.


Question:
As the title, is it possible to initialize a pointer in a struct to point to the first element of an array that is also in the same struct?

```
struct foo
{
    int barr[12];
    int* barr_itt;
};

struct foo f = {{0}, /*.?.*/}
```

Answer:
Yes, use the name of the variable

```
struct foo f = {{0}, f.barr} ;
```


Question:
I would like to increase the maximum pipe size in linux.
I am not talking about F_SETPIPE_SZ... but it seems there is 1MB limit to the pipe size(depends on the linux version I guess)

Can anyone let me know how I can increase the max limit?

Answer:
Changing the value in /proc/sys/fs/pipe-max-size, seems to do the trick :)... Thanks Joachim for your pointer in the right direction.

My current linux has the max value as 1048576


Question: Im using semaphore.h, what is happening if 5 child processes waiting onsem_waitwhile another child process unlocking the semaphoresem_post? Are they all going to be unlocked?

Answer:
No, only one will be unblocked. RTFM.

sem_wait

sem_post

If many processes are block, then one will be chosen to be unblocked, which one is up to OS. Scheduler will choose one.


Question:
How can I print an array without changing line? I have this array. I want to print its element in one single line, for example(a b c d).

```
char word[20][20];
for (j = 0; j < 10; j++)
{
    puts(word[j]);
}
```

Answer: putsplacees a\nafter writingchararray to standard output.  Useprintf("%s", word[j])instead.


Question:
I'm trying to create my own data type of string, could anyone tell me what I'm doing wrong with typedef and initialization.

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

typedef char string[10];

int main(){

    string myName;

    myName = "Tayyab";

    printf("This is %s", myName);

    getch();
}
```

Answer:
You cannot assign to an array but you can initialize it:

```
string myName = "Tayyab";
```


Question:
In C++ if you want to input a string and store it in a char array from index 1 you can do something like this:

```
ifstream f("data.in");
char a[100];
f.get(a+1,90);
```

Is there any way you can do this in C (like using fscanf)? Doing this:

```
fscanf(f,"%s",&a+1);
```

or this:

```
fscanf(f,"%s",&(a+1));
```

doesn't work.

Answer:
Yes there is, this way

```
fscanf(f,"%90s",a+1);
```


Question: We have an array:int p[100].Whyp[i]is equivalent to*(p+i)and not*(p+i*sizeof(int))?

Answer:
Why p[i] is equivalent to*(p+i)and not*(p+i*sizeof(int))?

Because*(p+i)is also the same as*((int *) ((char *) p + i * sizeof (int))). When you add an integerito a pointer, the pointer is moveditimes the size of the pointed object.


Question: We have an array:int p[100].Whyp[i]is equivalent to*(p+i)and not*(p+i*sizeof(int))?

Answer:
Why p[i] is equivalent to*(p+i)and not*(p+i*sizeof(int))?

Because*(p+i)is also the same as*((int *) ((char *) p + i * sizeof (int))). When you add an integerito a pointer, the pointer is moveditimes the size of the pointed object.


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

int main()
{
   char string[]="Programming Language";

    printf(string);

    printf("\n%s",string);

    return 0;
}
```

Output

Programming LanguageProgramming Language

Why is the output same?

Answer:
Whenprintfparses the format string it prints the characters that are not format specifiers as they are.

So when it parses"Programming Language"it just echoes each character.


Question:
Which are variable by " Uint "? is that there are " Uint8 ", " Uint16 ", etc ...

But what are they ?

Now I have some time using C ++ but I have never needed to use these variables and cause me curious.

Thanks in advance.

Answer:
uintis not a standard type. On some systemuintistypedefed as

```
typedef unsigned int uint ;
```


Question:
Is there a way to make getopt() or getopt_long() recognise double character option?

example:./a.out -my argumentwhere my is single command.

Answer:
You can usegetopt_long_only, which will try to process options as long ones even if there is only one-sign before them.

This function is GNU extension, as well asgetopt_long.


Question:
I'm trying to change the ECN mark in the tcp header of a specific packet in NS-2 but could not find the way.
Is there anyone who can give me a hand? Thanks a lot!

Answer:
I found it in ns2.35/tcp/tcp-full.cc , line 874. Below is the code that marks ECN(or we can say ECE here).

```
if (ecn_ && ect_ && recent_ce_ ) {
    // This is needed here for the ACK in a SYN, SYN/ACK, ACK
    // sequence.
    pflags |= TH_ECE;
}
```


Question:
Is there a way to make getopt() or getopt_long() recognise double character option?

example:./a.out -my argumentwhere my is single command.

Answer:
You can usegetopt_long_only, which will try to process options as long ones even if there is only one-sign before them.

This function is GNU extension, as well asgetopt_long.


Question:
I'm trying to change the ECN mark in the tcp header of a specific packet in NS-2 but could not find the way.
Is there anyone who can give me a hand? Thanks a lot!

Answer:
I found it in ns2.35/tcp/tcp-full.cc , line 874. Below is the code that marks ECN(or we can say ECE here).

```
if (ecn_ && ect_ && recent_ce_ ) {
    // This is needed here for the ACK in a SYN, SYN/ACK, ACK
    // sequence.
    pflags |= TH_ECE;
}
```


Question:
While generating c/c++ symbol table , when adding a new variable or a function name with its values to symbol table what is the key of that entry? name of the variable or address of the variable?
Then how it detect multiple declaraions for that variable according to the symbol table?

Answer:
The key is the name, of course. The linker never looks for address.

Duplicated symbols are symbols with external linkage and the same name, so it is easy to check.


Question:
I want to know how can I do something like this in a C program.

```
if wget -q www.someurl.com;
then echo OK;
else echo Not there;
fi
```

Answer: From the parent dofork().Inside the child created by 1. doexec*().From the parent or a signal handler listening toSIGCHLDdowait(&status).Finally useWEXITSTATUS(status)to get the equivalent tor=$?from your script.


Question:
While generating c/c++ symbol table , when adding a new variable or a function name with its values to symbol table what is the key of that entry? name of the variable or address of the variable?
Then how it detect multiple declaraions for that variable according to the symbol table?

Answer:
The key is the name, of course. The linker never looks for address.

Duplicated symbols are symbols with external linkage and the same name, so it is easy to check.


Question:
I use thecodeblock.

when the code is:

```
printf("%.1f", 1);
```

The program can run,and the output is0.0. I want to know why.
`

Answer:
Change it to:

```
printf("%.1f", 1.0);
```

fconversion  specifier requires an argument of typedoublebut you are passing anintvalue (1is of typeint). Passing an argument of the wrong type toprintfinvokes undefined behavior.


Question: I have one thread calling recvfrom() and another thread calling setsockopt() to add/leave multicast membership. Is that thread safe or both functions need to be called from the same thread?

Answer:
These are both system calls, not library functions, so it is safe to call them from different threads.

Whether a join/leave will affect a concurrentrecvfrom()that has already started is a moot question.


Question:
Is it fine to use sizeof operator with  "snprintf" ?
for example

```
char cstring[20];
   snprintf(cstring,sizeof(cstring),"%s","somestring......");
```

Answer: Yes, it's fine, the specific case you posted is good except that you don't check the return value, so you won't know if the string was truncated.


Question: I'm working on a micro controller with a serial terminal and I want to be able to backspace characters, I'm already handling it in the input buffer, but I don't know what to send through serial to delete it from the terminal emulator, sending \b only moves the cursor back. ¿Anyone knows how to handle this in VT100?

Answer:
FromHans Passant'scomment:

Use "\b \b" instead. –


Question: I'm working on a micro controller with a serial terminal and I want to be able to backspace characters, I'm already handling it in the input buffer, but I don't know what to send through serial to delete it from the terminal emulator, sending \b only moves the cursor back. ¿Anyone knows how to handle this in VT100?

Answer:
FromHans Passant'scomment:

Use "\b \b" instead. –


Question:
Is there a function that prints the graphical representation of a control character in C? For example "NULL" for 0, "DEL" for 127 and so on.
thanks

Answer: There is no standard function for this, but you can easily create your own array/string mapping them. Or you could simply add a constant to map them into the unicode range for pictorial representations of the ASCII control characters.


Question:
After compiling a project USING AMILIE SDK RTX4140_... by RTX how to deploy the hex file in the RTX dev kit[Board].

dev kit device imagehttp://www.rtx.dk/RTX41xx_Development_Kit-4020.aspx

Answer: we can use the RTX41xx_Platform_Firmware_Update_Pack to deploy hex file.


Question:
After compiling a project USING AMILIE SDK RTX4140_... by RTX how to deploy the hex file in the RTX dev kit[Board].

dev kit device imagehttp://www.rtx.dk/RTX41xx_Development_Kit-4020.aspx

Answer: we can use the RTX41xx_Platform_Firmware_Update_Pack to deploy hex file.


Question:
I came across this for loop what it is this use for

```
if(__builtin_popcount(mask) % 2 == K % 2) // Do somethings
```

What the__builtin_popcountfunction do ?

Answer:
Have you tried googling for it?Here'sthe first hit and the answer:

— Built-in Function: int __builtin_popcount (unsigned int x)Returns the number of 1-bits in x.


Question:
I came across this for loop what it is this use for

```
if(__builtin_popcount(mask) % 2 == K % 2) // Do somethings
```

What the__builtin_popcountfunction do ?

Answer:
Have you tried googling for it?Here'sthe first hit and the answer:

— Built-in Function: int __builtin_popcount (unsigned int x)Returns the number of 1-bits in x.


Question:
I came across this for loop what it is this use for

```
if(__builtin_popcount(mask) % 2 == K % 2) // Do somethings
```

What the__builtin_popcountfunction do ?

Answer:
Have you tried googling for it?Here'sthe first hit and the answer:

— Built-in Function: int __builtin_popcount (unsigned int x)Returns the number of 1-bits in x.


Question:
I have a ios application which has some C files. I would like it to printed in the console.

I would like to log messages and print the value of an unsigned int inside the C file in the console.

NSLog and printf doesn't work, is there a way to do this ?

Or is there any work around ?

Answer:
This works for OS X apps. It might work for iOS also.

```
#include <syslog.h>

syslog(LOG_WARNING, "Log me to console");
```


Question:
I'm checking a code written a long time ago.

I don't know what's the meaning of~symbol before the hexadecimal number.

It's like:

```
a = b & ~0xff;
```

Other parts of the code are like below, without the~symbol:

```
a = (b & 0xff00) >> 8;
```

Answer: The~operator is the bitwise NOT, it inverts the bits of a binary number.