Question:
The title is the exact error my compiler(geany on ubuntu) gives me when I try to compile. The part of code in question is the following:

```
for(int q=strlen(stringA)-1;q>0;q--)
{
//do stuff
}
```

I've already set the C99 mode and the initialization of variables in the 'for' header is accepted. Is what I did simply illegal in C?

Answer:
I assume you are missing an include. Try:

#include <string.h>


Question: I am usingfPointInput = fopen(fileName, "r");, when trying to access the data chunk inide the .WAV file but never getting any comprehensible results. (Data array is filled mostly with zeroes except the first few hundred indices). Can this be caused by the usage of inaccurate opening mode ?

Answer:
Thisarticleindicates that usingrbworks well.
Note that nothing in this answer isWindowsspecific. Just standardCIO.


Question:
The title is the exact error my compiler(geany on ubuntu) gives me when I try to compile. The part of code in question is the following:

```
for(int q=strlen(stringA)-1;q>0;q--)
{
//do stuff
}
```

I've already set the C99 mode and the initialization of variables in the 'for' header is accepted. Is what I did simply illegal in C?

Answer:
I assume you are missing an include. Try:

#include <string.h>


Question: I am usingfPointInput = fopen(fileName, "r");, when trying to access the data chunk inide the .WAV file but never getting any comprehensible results. (Data array is filled mostly with zeroes except the first few hundred indices). Can this be caused by the usage of inaccurate opening mode ?

Answer:
Thisarticleindicates that usingrbworks well.
Note that nothing in this answer isWindowsspecific. Just standardCIO.


Question:
I want to use interrupt handlers

```
void EXTI3_IRQHandler(void)
{
  //body
}
```

but when I build the project, I get the following error:

SymbolEXTI3_IRQHandlermultiply defined (by stm32f10x_it.o and
  main.o)

I have included library stm32f10x_exti.h

Answer:
Handlervoid EXTI3_IRQHandler(void)already defined in filestm32f10x_it.c.
You can replace code of your handler frommain.cto this special file or comment blank handler instm32f10x_it.c.


Question:
What would this translate to (in a more verbose way)?

```
local.sin_addr.s_addr = (!ip_address) ? INADDR_ANY:inet_addr(ip_address);
```

Trying to understand Ternary operators and I can't quite get it.

Answer:
A ternary is similar to anifstatement, but it can be used where an expression is required. So it's equivalent to:

```
if (!ip_address) {
    local.sin_addr.s_addr = INADDR_ANY;
} else {
    local.sin_addr.s_addr = inet_addr(ip_address);
}
```


Question:
I want to do an evented read on Serial port which will run only when the data is available.

I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.

So I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.

Answer:
The canonical equivalents for linux systems is to usepoll()orselect().

Workings are different of course.


Question:
I want to do an evented read on Serial port which will run only when the data is available.

I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.

So I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.

Answer:
The canonical equivalents for linux systems is to usepoll()orselect().

Workings are different of course.


Question:
If "Allow windows manager to decorate window" is on.
What is the function name in the wine source that knows a user click this X button and send the WM_CLOSE to the app?
Thank you

Answer: The window manager sends ClientMessage with type WM_PROTOCOLS and the protocol value WM_DELETE_WINDOW.  This is handled in dlls/winex11.drv/event.c: X11DRV_ClientMessage() -> handle_wm_protocols().


Question: While running a sample code from the internet, I am stuck at 'glutTimerfunc'. I cannot figure out what is this error.

Answer:
glutTimerFunctakes a pointer to a function that must have a signature of

```
void (*func)(int value)
```

YourframeTimerCallbackfunction doesn't take an integer parameter. Hence the error.

Refer tohttps://www.opengl.org/resources/libraries/glut/spec3/node64.html


Question:
This question already has answers here:Yosemite and Valgrind(12 answers)Closed6 years ago.

I am not sure if I can installvalgrinddebugger in my Macbook Pro. I searched online but most posts are related to Ubuntu. Can someone tell if this is possible? If so, can it be by brew for example?

Answer: you can use "brew install valgrind" to install valgrind.


Question:
Is there any way to roundsystemGuessup. In this case the outcome ofsystemGuessis 5.5 I want it to be 6 how do I do this?

See code below:

```
int main(void){

    int systemGuess = 0;
    stystemGuess = (10 - 1)/2 + 1;
    printf(" %d ", stystemmGuess);
}
```

Answer:
Use floating point division andceil:

```
stystemGuess = ceil((10 - 1)/2.0) + 1;
```

If you want to round 0.4 down, useroundinstead.


Question: Why we don't use extern when using function from one .c file in another .c file , but we must do extern for variables case? Is it related to linker?

Answer:
Functions are extern qualified by default (unless you change it to internal withstatic). For example,

```
int func(void) {
}

extern int func2(void) {
}
```

Bothfuncandfunc2are external. Theexternkeyword is optional for external functions.


Question:
```
int j=4;
(!j!=1)?printf("Welcome"):printf("Bye");
```

In the above code segment, according to me, firstj!=1will result in true and!trueis false which must result in printingByebut I getWelcomeas the output.

Can anyone explain this one?

Answer:
!executed first because unary operator!has a higher precedence than!=.

!4become0then0 != 1becometrue.

So, output isWelcome.


Question:
I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below

```
asm("MOV $00500A,#$3");
```

But I'm facing with following error

```
#error cpstm8 ..\app\sched.c:183(5) missing prototype
```

Can anyone help me in fixing this?

Answer:
For STM8 assembly instruction, you need to use_before the instruction as shown below

```
_asm("MOV $00500A,#$3");
```


Question:
I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below

```
asm("MOV $00500A,#$3");
```

But I'm facing with following error

```
#error cpstm8 ..\app\sched.c:183(5) missing prototype
```

Can anyone help me in fixing this?

Answer:
For STM8 assembly instruction, you need to use_before the instruction as shown below

```
_asm("MOV $00500A,#$3");
```


Question:
GDB is showing the content of a register as

```
rbp            0x604420 0x604420 <sval>
```

What does sval mean? Does it means string val?

Answer:
What does sval mean?

It means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol.

You can runnm your-binary | grep svaland see that symbol.

Does it means string val?

No,nothingof the sort.


Question:
I am learning C usingthissite.

Underfgetc()Function the author said:

This function reads a single character from a file and after reading increments the file position pointer.

```
FILE *fp;
fp = fopen(filename, "r");
```

What I want to ask is that thefile position pointeris different from the pointerfpor not?

Answer: It means your current offset in the file. It is the return value offtell.


Question:
GDB is showing the content of a register as

```
rbp            0x604420 0x604420 <sval>
```

What does sval mean? Does it means string val?

Answer:
What does sval mean?

It means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol.

You can runnm your-binary | grep svaland see that symbol.

Does it means string val?

No,nothingof the sort.


Question:
I'm trying define "ip_addr" from lwip. That's my code:

```
#include "lwip/tcp.h"
#include "ip_addr.h"
...
struct ip_addr ip;
```

But when i'm trying to compile this, compiler gives me error:

```
error: storage size of 'ip' isn't known
```

Answer:
Try:

```
ip_addr_t ip;
```

and your second #include line should it not be:

```
#include "lwip/ip_addr.h"
```


Question:
my code can be compiled with C or C++ compilers.
I'd like to know which one is doing the compilation

is there preprocessor define to tell me this ?

Answer:
The definition is__cplusplus.

```
#ifdef __cplusplus
// treated as C++ code
#else
// treated as C code
#endif // __cplusplus
```


Question:
my code can be compiled with C or C++ compilers.
I'd like to know which one is doing the compilation

is there preprocessor define to tell me this ?

Answer:
The definition is__cplusplus.

```
#ifdef __cplusplus
// treated as C++ code
#else
// treated as C code
#endif // __cplusplus
```


Question:
I want to create a socket connected directly to the gpu.
I would like to send data from a server to the gpu without spending a copy/moving time from host to device.
Is it possible?

Answer:
If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products.

But realistically, no.


Question: When writing a program (Unix-style), can it address and manage more than one stdout and stdin channels?

Answer: No; there is (at most) one standard input and one standard output at any given time.  Ultimately, since the question specifically mentions Unix, standard input is file descriptor 0 and standard output is file descriptor 1, and there is only one file descriptor with a given number.


Question:
I want to create a socket connected directly to the gpu.
I would like to send data from a server to the gpu without spending a copy/moving time from host to device.
Is it possible?

Answer:
If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products.

But realistically, no.


Question: How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.

Answer: You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.


Question: Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.

Answer:
It depends on yourRAMor the memory available for you.

i:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.


Question: How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.

Answer: You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.


Question: Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.

Answer:
It depends on yourRAMor the memory available for you.

i:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.


Question:
I came across this line of code written in C that confuses me coming from a JavaScript background.

```
short s;
if ((s = data[q]))
    return s;
```

Is this assigningstodata[q], and if it equals true/1, return s?

Answer:
Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false.

it would be the same as

```
if ((s = data[q]) != 0) return s;
```


Question:
Consider inline assembly like this:

```
uint64_t flags;
asm ("pushf\n\tpop %0" : "=rm"(flags) : : /* ??? */);
```

Nonwithstanding the fact that there is probably some kind of intrinsic to get the contents of RFLAGS, how do I indicate to the compiler that my inline assembly clobbers one quadword of memory at the top of stack?

Answer: As far as I am concerned, this is currently not possible.


Question: Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?

Answer: Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).


Question:
This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago.

I came across this code today:

```
for (i = 0; i < level; i++) {
    a[i] = b[i] = c[i] = 0;
}
```

What is the meaning of the code located inside the for loop?

Answer:
```
a[i] = b[i] = c[i] = 0;
```

is parsed as:

```
a[i] = (b[i] = (c[i] = 0));
```

and has the same effect as:

```
a[i] = 0;
 b[i] = 0;
 c[i] = 0;
```


Question:
Can I pass a character array tofopen? For example:

```
fopen(s, "r");
```

Wheresis declared as a character array and is null terminated.

Answer:
smust be a pointer to a null terminated character array.

Theman pagesconfirm this

```
FILE *fopen(const char *path, const char *mode);
```

You can see that it must be null terminated, since nosizeargument is given.


Question: Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?

Answer: Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).


Question:
This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago.

I came across this code today:

```
for (i = 0; i < level; i++) {
    a[i] = b[i] = c[i] = 0;
}
```

What is the meaning of the code located inside the for loop?

Answer:
```
a[i] = b[i] = c[i] = 0;
```

is parsed as:

```
a[i] = (b[i] = (c[i] = 0));
```

and has the same effect as:

```
a[i] = 0;
 b[i] = 0;
 c[i] = 0;
```


Question:
Can I pass a character array tofopen? For example:

```
fopen(s, "r");
```

Wheresis declared as a character array and is null terminated.

Answer:
smust be a pointer to a null terminated character array.

Theman pagesconfirm this

```
FILE *fopen(const char *path, const char *mode);
```

You can see that it must be null terminated, since nosizeargument is given.


Question:
```
void func(int num){
    if(num< 3){
        printf("%d ", num);
        func(num+ 1);
        printf("%d ", num);
    }
}
```

Suppose I call this function with func(0).
Why is the result 0 1 2 2 1 0 ?
I don't know why it's decreasing.

Answer:
Here's a stack trace

```
f(0)
    print 0
    f(1)
        print 1
        f(2)
            print 2
            f(3)  // 3 < 3 == false
            print 2
         print 1
     print 0
```


Question: Set PriorityWhat are all possible priorities in KPRIORITY in win kernel?

Answer:
From thedocumentation for KeQueryPriorityThread:

Thread priorities range from 0 to 31, where 0 is the lowest priority and 31 is the highest.


Question:
I've used OpenSSLBIGNUMto implement some cryptosystems and I am now wondering if it also offers big decimal support. I could not find anything in the documentation but perhaps there is an extension/add-on somewhere preferably in C (not C++)?

Note: I am aware of GMP and NTL, I am not looking for those.

Answer:
Does OpenSSL offer Big Decimal support?

No.


Question:
From this page:http://linux.die.net/man/2/mprotect

I understand the flags except for PROT_EXEC. What is the effect of calling

```
mprotect(ptr, size, PROT_EXEC);
```

Answer:
From the manual page you link to:

PROT_EXECThe memory can be executed.

It marks the memory as executable, meaning it can contain code you can call and run.


Question: I would like a check box to be automatically unchecked when a certain value is reached. But I can't find an option to set the state of a check box

Answer:
Send it aBM_SETCHECKmessage:

```
SendMessage(hWndOfCheckbox, BM_SETCHECK, BST_UNCHECKED, 0);
```

Alternatively, use theButton_SetCheckmacro, that expands to the same call toSendMessage(but doesn't expose unused formal parameters):

```
Button_SetCheck(hWndOfCheckbox, BST_UNCHECKED);
```


Question: I want to compile several c files and I want to have executables whose names are same as the c file's names i.e if I have trial1.c, how can I have trial1.out?

Answer:
Do you want something like this?

```
for i in *.c; do gcc ${i::1}.c -o ${i::1}.out; done
```

Or, if you are interested on just knowing if they compile successfully:

```
for i in *.c; do gcc $i 2>/dev/null && echo "$i : OK" || echo "$i : FAIL"; done
```


Question: I know * indicates it is a pointer, but what's the difference betweenint (* a)[2]and(int (*)[2]) ainC?

Answer: int (* a)[2];declaresaasa pointer to an array of twointwhile(int (*)[2]) acastsatoa pointer to an array of twoint.


Question: How can I useperf_event_open()to retrieve callchain? I do not want to use the callchains provided by oprofile and perf. I want to get them directly. It seems that I need tommap()the file descriptor returned byperf_event_open(). I do not know the size ofmmap()and how to read from it.

Answer: Chapter 8 ofthis bookdescribes, by example, how to useperf_event_open()for bothcountingandsamplingmodes.


Question: In C, if the array is initialised while declaration then the dimension is optional. Why?

Answer: Because if you tell it to create an array holding a1,2, and3, it can easily figure out the required size since you gave it 3 elements.


Question:
Given the following lines:

```
char szInline[80];
char szDescription[80] = { NULL };
float fCost = 0;
sscanf (szInline, "%80[^,], %f", szDescription, &fCost);
```

What does the %80[^,] do?

Answer:
Read at most 80 chars up to the next,comma.

Btw, theszDescriptionbuffer is too small by 1.


Question:
I know what a delimiter is, but what does the string" \t\r\n\a"stand for in the example below?

```
#define DELIMITER " \t\r\n\a"
```

Answer:
```
\t = tab
\r = carriage  return
\n = newline
\a = alert (bell)
```

Looks like the author was creating a preprocessor DEFINE containing these common delimiters.


Question: What is maximum length of user space APC queue to one thread in Windows? I read Windows Internals 6 Part 1 and didn't finded any information about this.

Answer: There is no fixed limit. KAPC structures are allocated fromnonpaged pooland linked to a thread by a singleLIST_ENTRYstructure. Nonpaged pool islimited by available system resources only.


Question:
As for System V messageint msgget(key_t key, int msgflg);,

Can syscallreadwork likemsgsndto send a message?Can syscallwritework likemsgrcvto receive a message?

Answer:
No, they can't. The message queue identifier (returned bymsgget) is not a descriptor.

Different sub-systems, different identifiers.


Question:
I have some operation like this C++ code that I want to convert in C89:

return reinterpret_cast<uint8_t *>(stream.buffer) - buffer;

How can I replace the reinterpret cast in C?

Answer:
Nothing very exciting, you've seen this before:

```
(uint8_t *)(stream.buffer)
```

That's the only way to cast something in C.


Question:
I've been programming in C for a while and i wondered why is important to separate this processes (Compile and Linking)?

Can someone explain please?

Answer: It is useful in order to decrease rebuilt time. If you change just one source file - it is often no need to recompile whole project but only one or few files.


Question:
This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago.

Does a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored?

```
#define NUMBER 10
```

Answer:
No, macros don't work like that.

They are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10.

In this respect, C and C++ are identical.


Question: I would like to close a socket but before notify all threads blocking onaccept/connect, therefore I am sending a user specific signal, however not knowing the tid of the signal receiving threads. I cannot use syscallkill(pid, signal)

Answer: Why not just shutdown the socket without notifying? Each thread that is blocked on accept or read from that socket will return with the corresponding error that you can parse to take the necessary actions


Question:
This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago.

Does a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored?

```
#define NUMBER 10
```

Answer:
No, macros don't work like that.

They are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10.

In this respect, C and C++ are identical.


Question:
```
#define HELPER(param) Wazz ##param

HELPER(hek)
```

Doing agcc -E filenameshows me

```
Wazzhek
```

How do I getWazz hek? How do I insert a space between the 2 tokens?

```
#define HELPER(param) Wazz ## ## ##param
```

Doesnt work either. Any suggestions?

Answer:
Just do not use token concatenation operator when you don't want to do token concatenation.

```
#define HELPER(param) Wazz param

HELPER(hek)
```


Question:
What is the quickest bit-hack to achieve the following result?

Let x be a 4 byte int, in a C program.

If x is0x00000000, then x should be0xFFFFFFFF, else x should be untouched.

Answer:
x |= -(x == 0);x |= -!x;x = x ? x : 0xFFFFFFFF;if (x == 0)
     x = 0xFFFFFFFF;...

Benchmark and choose what's appropriate for you


Question:
I know I can do this:

```
//With A = tax(x);
return tan(arctan(A)/2);
```

but I wanted something more efficient.

Answer:
Whenxis between -π/2 and π/2 you can use this formula:

```
t / (1 + sqrt(1 + t*t))
```

This is hardly an improvement on the original formula, but it uses one function call instead of two.

Note:I found this formulahere. The wikipedia page is in Russian, and the equivalent English page does not include the same formula.


Question:
I am reading lines from a file, the lines look like this:

```
89f81a03eb30a03c8708dde38cf:000391716
```

The thing is: I want to remove everything after the:(including the:).
I tried everything I could find online but they seem to useconst charand the lines arecharpointers.

Answer:
You can usestrchr:

```
char str[] = "89f81a03eb30a03c8708dde38cf:000391716";
char *ptr;

ptr = strchr(str, ':');
if (ptr != NULL) {
    *ptr = '\0';
}
```


Question:
I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it?

(Does it actually make sense?)

Answer:
Iffoois of typechar[n]for integraln, then you can use

&foo[0]

to give you the pointer to the zeroth element offoo. The type of this expression ischar*.


Question:
I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it?

(Does it actually make sense?)

Answer:
Iffoois of typechar[n]for integraln, then you can use

&foo[0]

to give you the pointer to the zeroth element offoo. The type of this expression ischar*.


Question:
I want to dynamically load library from SD card, with dlopen, but when I do it, get error:
dlopen failed: couldn't map "/storage/emulated/0/Documents/Tests/armeabi-v7a/libtest.so" segment 2: Operation not permitted

When i use it for internal storage it's work.
What can i do to solve this problem?

Answer: This is disallowed by Android's security policy. Anyone can write to that location, so loading code from it is an easily exploitable attack vector.


Question:
My code:

```
PGresult *res = PQexec(m_IConnection, "MOVE NEXT in my_cursor_name");

ExecStatusType status =  PQresultStatus(res);

if (status != PGRES_COMMAND_OK)
{
    PQclear(res);
    return;
}
```

But it does not fail after it reaches the last row.
I've searched all over and can find no reference for detecting the end of rows.

Answer:
Per the first comment,

if(!stricmp(PQcmdTuples(res), "0"))

works to check for the last row of the MOVE


Question:
I am building a C application that uses OpenCV.

when compiling, I get the following error:

```
fatal error C1189: #error :  core.hpp header must be compiled as C++
```

I did not find how to resolve this error.

How to use OpenCV from a C project?

Answer: Select the required file.Launch its properties windowGoto C/C++ -> Advanced, and changeCompile astoCompile as C++ Code (/TP)


Question:
I need to create a function in which there is a default argument:

```
void func ( int a, int b = 1 );
// and
func (1, 2);
func (1);
```

Answer:
C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor:

```
void func(int a, int b);
#define TWO_ARGS(A, B, ...)  A, B
#define func(...) func(TWO_ARGS(__VA_ARGS__, 1))

func(1, 2);  /* calls func(1, 2); */
func(1);     /* calls func(1, 1); */
```


Question:
I need to create a function in which there is a default argument:

```
void func ( int a, int b = 1 );
// and
func (1, 2);
func (1);
```

Answer:
C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor:

```
void func(int a, int b);
#define TWO_ARGS(A, B, ...)  A, B
#define func(...) func(TWO_ARGS(__VA_ARGS__, 1))

func(1, 2);  /* calls func(1, 2); */
func(1);     /* calls func(1, 1); */
```


Question:
```
#include <stdio.h>
int main()
{
int i;
i=0;
printf("%d\n%d\n%d\n", i, &i, &(&i));
return 0;
}
```

i think that &i is just a value of address, and assume that it's 0xFF so &(&i)should be the address of 0xFF but why it's not valid?

Answer: Unary&operator need an lvalue as its operand and returns an rvalue.&iis an rvalue, therefore&ican't be an operand of&.


Question:
if I have a pointer to an integer such as:

```
int num = 12;
int *p = #
```

and then print the address so

```
printf("%p\n", (void*)p);
```

What is the difference between the previous and this:

```
printf("%p\n", (void*)&p);
```

Answer:
Here,pcontains the address ofnum, so the firstprintfoutputs the address ofnum.

On the other hand,&pis the address ofp, so the secondprintfprints the address ofp.


Question:
I want to be able to do this:

```
typedef int a[2], b[2], c[2];
```

without having to type the[2]. One solution is to do:

```
typedef struct { int a[2] } a, b, c;
```

but then you have to always do stuff likea.a[0]and that's no good.

Answer:
For C or C++98, a simple typedef will do:

```
typedef int int2[2];
int2 a, b, c;
```


Question:
I have array defined like this

```
float array [1000][3]
```

I want to extract third column

```
float third[1000]
for (i = 0; i < 999,i++)
```

and then what?

Answer:
```
for (i=0; i<1000; i++)
{
    third[i]=array[i][2];
}
```

This should do it if I understood your question correctly.


Question:
I have array defined like this

```
float array [1000][3]
```

I want to extract third column

```
float third[1000]
for (i = 0; i < 999,i++)
```

and then what?

Answer:
```
for (i=0; i<1000; i++)
{
    third[i]=array[i][2];
}
```

This should do it if I understood your question correctly.


Question:
I have an array which is stored in my program memory

```
const char* const paragraph[] PROGMEM = {
    "First Line",
    "Second Line"
};
```

How do I read one string at a time so that it output

```
First Line
Second Line
```

Answer:
```
int i;
for (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {
    printf("%s\n", paragraph[i]);
}
```


Question:
I have an array which is stored in my program memory

```
const char* const paragraph[] PROGMEM = {
    "First Line",
    "Second Line"
};
```

How do I read one string at a time so that it output

```
First Line
Second Line
```

Answer:
```
int i;
for (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {
    printf("%s\n", paragraph[i]);
}
```


Question:
2d array declared by me.

```
static char daytab[2][13] =  {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
 };
```

I want address location of the element [1][5].

When I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p  = &(*(*daytab+1)+5);then it shows error?

Answer: That's becausea[i]is equivalent to*(a+i), not*a+i.


Question: Can you use a pipe to share threads between two processes in C? I am writing my own shell and want to know if this implementation would be more optimal, if it is even possible?

Answer:
Each thread is specific to a process and share memory of the calling thread.

If you want efficient inter process communication, you can use shared memory.

Seehttp://man7.org/linux/man-pages/man7/shm_overview.7.html


Question:
2d array declared by me.

```
static char daytab[2][13] =  {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
 };
```

I want address location of the element [1][5].

When I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p  = &(*(*daytab+1)+5);then it shows error?

Answer: That's becausea[i]is equivalent to*(a+i), not*a+i.


Question:
As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search.

is there any other option for this one? just want to know tho

Answer:
Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value.

And doing that is O(N).


Question:
As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search.

is there any other option for this one? just want to know tho

Answer:
Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value.

And doing that is O(N).


Question:
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?
Thanks in advance.

Answer: Open the project properties and do :


Question:
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?
Thanks in advance.

Answer: Open the project properties and do :


Question:
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?
Thanks in advance.

Answer: Open the project properties and do :


Question: I am usingrecv()to read data from a socket andfcntl()to set the socket blocking/non-blocking. My question is: If I calledrecv()(blocking) and I callfcntl()from another thread and set the socket non-blocking, will the currently runningrecv()return or the effect offcntl()will only take place after the blockingrecv()returns and I call it again?

Answer:
It won't affect the current receive operation.

Strange thing to do.


Question:
Is there a way to go from the below

```
int a; ///< This is a variable
int b = 3; ///< This is another variable
```

To the below?

```
int a;      ///< This is a variable
int b = 3;  ///< This is another variable
```

Answer: align_right_cmt_spanshould be the correct setting.


Question:
Is there a way to go from the below

```
int a; ///< This is a variable
int b = 3; ///< This is another variable
```

To the below?

```
int a;      ///< This is a variable
int b = 3;  ///< This is another variable
```

Answer: align_right_cmt_spanshould be the correct setting.


Question:
Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. we have to do this in sub-linear time. I.e. do not just go through each element searching for that element.
can we solve this using binary search???

Answer: you could perform a binary search on the array,it means the index the binary search resulted was not the first occurence.


Question:
The exposed API from c is:

```
bam_hdr_t *bam_hdr_init(void);
```

how do I write its wrapper in Julia?

ccall((:bam_hdr_init,"lib.so"), Ptr{bam_hdr_t})works in Julia v0.5, but not in v0.4.

Answer: ccall((:bam_hdr_init,"lib.so"), Ptr{bam_hdr_t},())works for both versions of Julia


Question:
Output is:10and it gives no error.

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

but it gives me an error:

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

I understand that pointer de-referencing is causing the error. But how is that happening?

Answer:
Because you are using an uninitialized pointer.
Your*i = &jshould bei = &j


Question:
I need to select one processor from my Comm to do some works ( I don`t want other processors do the work ).
Since I split my Comm to the groups, I cannot always pick one specific rank ( for example 0) as my master. I need to choose it from my current comm. Any suggestion?

Thank you.

Answer: The rank of a process is always relative to a communicator. After you split your processes, you can just take process 0 in the new communicator to perform the work you want.


Question:
FromSSL_CTX_load_verify_locations:

SSL_CTX_load_verify_locations - set default locations for trusted CA certificates

Does this means I can put certificates in location (or file), which passed as parameter toSSL_CTX_load_verify_locationsfunction. And are these certificates automatically will be trusted?

Answer: That is correct. This is how you specify the list of certificate authorities that are trusted.


Question:
Is using__MSDOS__enough with djgpp or should__DJGPP__be used instead?

By comparison, I know_WIN32isn’t defined by default on cygwin(based on the assumption djgpp and cygwin have the purpose to build an Unix layer to hide real OS details).

I no longer have a DOS machine to test it.

Answer:
To list the predefined macros and their values, use

```
djgpp -E -x c -dM /dev/null
```


Question:
Is there a way to read a HH:MM format from a file usingfscanf(), and treat it like an int? The file has this format :

```
3 14:50 20.10
```

Is it possible to do something likefscanf(fp, "%d ... %f, &a, &b, &c);andbwill have 1450?

Answer:
I'm afraid you can't do this in a line. However, you can:

```
fscanf(fp, "%d %d:%d %f", &a, &b1, &b2, &c);
b = b1 * 100 + ((b1 > 0) * 2 - 1) * b2; // in case b1, b2 are the different sign.
```


Question:
I have a pointer*pthat points to astruct S.Shas various fields.

Is it possible to assign structureSto the structure pointed to by*pusing only one assignment?OR,do I need to assign the fields, one by one?

Answer:
This example assigns a struct using a pointer and one statement.

```
int main(void) {

    struct Foo {
        char a;
        int b;
        double c;
    } *foo, *bar;

    foo->b = 10;
    bar = foo; /* now  bar->b=10 as well */
}
```


Question:
I need to determine x from the expression root(y).

"Y" has a range to its separated value with maximum 10^1000.
I solved it in the normal way and I saw the right result. But when Y is very large, the program outputs the wrong answer.

```
#include<stdio.h>
#include<math.h>
int main()
{
    long long int x,y;
    scanf("%lld",&y);
    x=sqrt(y);
    printf("%lld",x);
    return 0;
}
```

Answer: Use some bignum library, for exampleGMP


Question:
As show in the following code, what is the difference between 0 and CVMX_FAU_REG_64_ADDR(0) in the cvmx_fau_reg_64_t?

```
#define CVMX_FAU_REG_64_ADDR(x) ((x <<3) + CVMX_FAU_REG_64_START)
typedef enum
{
    CVMX_FAU_REG_64_START          = 0,
    CVMX_FAU_REG_64_END            = CVMX_FAU_REG_64_ADDR(0),
} cvmx_fau_reg_64_t;
```

Answer: In the code as written, both values == 0. There is no difference in the actual value.


Question: Is there in C/C++ standart constant that reflects how many bits are there in one byte (8)? Something like CHAR_BIT but for byte.

Answer:
According to the C standard, acharis one byte. ThereforeCHAR_BITis the number of bits in a byte.

The C standard says thatCHAR_BITis"number of bits for smallest object that is not a bit-field (byte)".


Question:
I have a text like this. And I want to show it in doxygen documentation as it is.
What type of command should I use.

Answer:
You can use verbatim, endverbatim.

http://www.doxygen.nl/manual/commands.html#cmdverbatim


Question:
If you useprintfsuch as:

```
printf("Time as a basic string = %s", ctime(&seconds));
```

The output would be:

```
Wed, 28 Oct 2009 11:35:37
```

How do I store this output thatctimegenerates so that:

```
char result[80] = ctime(&seconds);
```

Whatever I try just doesn't seem to work.

Answer:
You want to usectime_rinstead ofctime.

```
char result[80];
ctime_r(&seconds, result);
```


Question: In C, what is the best way to ignore the commas when usingscanfon a number like 1,000,000?

Answer:
I would say the best way is tonotusescanffor this. At least not using any number formats.

Instead read it as a string, then remove the commas, and finallyconvert to a number.


Question: I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be "#include"d? Should I send also specific flags to the gcc?

Answer: You can usepthread_createincluded in<pthread.h>, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.


Question: I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be "#include"d? Should I send also specific flags to the gcc?

Answer: You can usepthread_createincluded in<pthread.h>, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.


Question:
This command

```
gcc file.c -c
```

outputs me this

```
file.o
```

how to run above command so it outputs me object file with specified name for examplefile.dbg.o?

Answer:
That's it:

```
gcc -o file.dbg.o -c file.c
```


Question:
We need check whetherstat()call willaccess Hard diskduring its operation?

i coulnt find answer for above question.

can anyone help me on this?

Answer:
Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.

I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.


Question:
We need check whetherstat()call willaccess Hard diskduring its operation?

i coulnt find answer for above question.

can anyone help me on this?

Answer:
Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.

I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.


Question:
We need check whetherstat()call willaccess Hard diskduring its operation?

i coulnt find answer for above question.

can anyone help me on this?

Answer:
Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.

I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.


Question:
I want run a command write execlp function within c file in linux.
I want to run the following command :

ls -l

I can do ls command as follows :

execlp("/bin/ls" , "ls", NULL)

Answer:
Add the option to the parameter list:

```
execlp("/bin/ls", "ls", "-l", NULL);
```


Question:
This question already has answers here:Using pointers to iterate through argv[](6 answers)Closed7 years ago.

If I havechar **argshow can I loop through therowsof the array to determine how many there are?

For example, ifchar **args == {"one", "two", "three"}, how can I loop through each element, keeping count, and then return 3?

Answer:
Since yourargsis null-terminated, simply write

```
int i;
for (i = 0; args[i]; i++)
    // do something
```


Question: I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?

Answer:
Your question embodies a contradiction in terms.

'Abortively close' == RST.

Even if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.


Question: I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?

Answer:
Your question embodies a contradiction in terms.

'Abortively close' == RST.

Even if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.


Question: Im curious if they have an official name or just 'dot' and 'arrow'? I try search this in cpluscplus and in Deitel, but didn't find anything

Answer: The C standard calls themmember access operators, but only in the index. They aren't given a name anywhere else except the one place in the index. In the same place, the->operator is calledarrow operator,the.operator is calledstructure/union member operator.


Question:
I want to send duplicate string to my bison file.

In my flex file I use it like this

```
"<"     {return strdup(tOPEN);}

    ">"     {return strdup(tCLOSE);}
```

Is this right things to do?
Or should I use it like below the code.

```
"<"       { yyval. sval = strdup(yytext); return tOPEN;}
```

Answer:
```
"<"       { yyval. sval = strdup(yytext); return tOPEN;}
```

this is the right way of the using.


Question:
If I open a text file withopen("file.txt",O_RDONLY), do I need to close it withclose()?

Silly question, I know, but I am not entirely sure if the end of a process leaves open files open.

Answer:
The file will remain open until you close it or your process terminates. The process terminating will invalidate the file descriptors for that process, and so in essence "close" the files.

I would always close them explicitly, and as early as reasonable.


Question: I want to get a integer from to user. But I wonder what is the difference betweenfscanf(stdin, "%d", &x);andscanf("%d", &x);?

Answer:
What is the difference between stdin with fscanf and scanf?

Thescanffunction is equivalent tofscanfwith the argumentstdininterposed before the arguments toscanf.  C11 §7.21.6.4 2

So aside from a different amount of typing the code, they are the same.


Question:
I have an array

```
char msgID[16];
```

How do I increment this by 1? I read the high and low 8 bytes into 2 differentuint64_tintegers

```
uint64_t high, low;
memcpy(&low,  msgID, sizeof(uint64_t));
memcpy(&high, msgID + sizeof(uint64_t) , sizeof(uint64_t));
```

If I do

```
low += 1;
```

How do I account for overflow?

Thanks for any help provided.

Answer:
It's quite simple, actually:

```
if(++low == 0)
    ++high;
```


Question:
Since Lua 5.3, inegers are supported.

But how can I do :

```
if type( 123 ) == "integer" then
end
```

Or

```
switch( lua_type( L, -1 ) )
{
case LUA_TINTEGER:
    break;
}
```

Sincetype()is still going to return"number"for both integer and reals, andLUA_TINTEGERdoes not exist ?

Thanks.

Answer:
usemath.typefor Lua 5.3

Returns "integer" if x is an integer, "float" if it is a float, or nil
  if x is not a number.


Question:
I code in C and I am little weak in C++, in my research I came across many methods to read XML from URL for my win32 application.
I found cURL andXmlTextReaderbut it's in C++.
Is there any function or other ways, where I can download XML from the URL and parse that XML using only C language and not C++?

I can work with C++ as well, but I want to avoid it as it's not I am comfortable with.

Answer: Libcurlhas pure C API.Expatandlibxmlare written in pure C too.


Question:
I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried:

```
char test[256] = {'N'};
```

But this only initializes the first index to'N'and the rest to 0.

Answer:
Usememset:

```
#include <string.h>

char test[256];
memset(test, 'N', 256);
```


Question:
I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried:

```
char test[256] = {'N'};
```

But this only initializes the first index to'N'and the rest to 0.

Answer:
Usememset:

```
#include <string.h>

char test[256];
memset(test, 'N', 256);
```


Question:
In C, If I have:

```
char *reg = "[R5]";
```

and I want

char *reg_alt = "R5"(equal to the same thing, but without the brackets), how do I do this?

I tried

```
*char reg_alt = reg[1:2];
```

but this doesn't work.

Answer:
There is no built-in syntax for dealing with substrings like that, so you need to copy the content manually:

```
char res[3];
memcpy(res, &reg[1], 2);
res[2] = '\0';
```


Question:
Given the short notation to declare arrays, how do I specify the type of myArray to be arrays?

```
[] myArray = {   //here [] should be array type
            {"obj1, "obj2"},
            {"obj1, "obj2"}
}
```

Answer:
Assuming you want a two-dimensional array of character strings:

```
const char *myArray[][2] = {
        {"obj1", "obj2"},
        {"obj1", "obj2"}
        /* any other elements */
};
```


Question: Is it good practice to use the weak attribute in production code so that for test code one can override functions?

Answer:
I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code:

using macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.


Question: Is it good practice to use the weak attribute in production code so that for test code one can override functions?

Answer:
I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code:

using macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.


Question: I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...

Answer:
The following types resemble natural numbers set with 0 included in C++:

unsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11.

Each one differs with the other in the range of values it can represent.


Question: I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...

Answer:
The following types resemble natural numbers set with 0 included in C++:

unsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11.

Each one differs with the other in the range of values it can represent.


Question:
I was given a piece of code in C, and the question asked about it is whats wrong with it? I would be fine answering, but the asterisk in front of the malloc casting is confusing the heck out of me!

```
char f() { return *(char*)malloc(10); }
```

Answer: The function returns an indeterminate value and has a memory leak because the dynamically allocated memory is not freed.


Question: Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.

Answer:
Example of sending a raw Ethernet frame in Linux:

https://gist.github.com/austinmarton/1922600


Question: Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.

Answer:
Example of sending a raw Ethernet frame in Linux:

https://gist.github.com/austinmarton/1922600


Question:
I currently have a code that checks whether a file is a directory or not, it goes as follows;

```
file = readdir (dir);
          if(file->d_type & DT_DIR){
          \* some code*\
          }
```

I was wondering, what is the if statement for the exact opposite of this. Something along the line "if file is not directory".

Answer:
Any boolean expression can be negated with thenotoperator (!):

```
if (!(file->d_type & DT_DIR)) {
```


Question:
```
#include <stdio.h>
int main(void)
 {
  char c[] = "Gate2011";
  char *p = c;
  printf("%s", p+p[3]-p[1]);
  return 0;
}
```

Output:2011

Why does it give this output? I tried different combinations and it always gives junk.

Answer:
becausep[3] = 'e' = 101andp[1] = 'a' = 97

101 - 97 = 4

p + 4= address of "2001" in "Gate2001"

interpreted as string ... there you go.

I also do not understand the downvotes :(


Question:
Is it possible to change the options in Clion so that the variables are aligned like so:

This should be applied in structs and methods.

Answer:
Yes.

Settings -> Editor -> Code Style -> C/C++ -> Wrapping and Braces -> Variable groups -> Align in columns

You can of course also use a custom formatting tool that does it as well.


Question:
I want to assign ' to a character but it keeps giving me error
any help?

```
void main()
    {
        char c  = ''';
    }
```

Answer: Special characters like ' or \ must be escaped with a backslash in these situations. In this particular case you got an error because the compiler thinks you opened and closed a null character with the first two '' and then opened another character without closing it with the third one.


Question:
I have a makefile, called "Makefile", and some target in it like:

```
file.o: file.c Makefile
      gcc <some flags & options> file.c
```

What exactly doesfile.o: file.c Makefiledo?

Answer:
That line describes the dependencies forfile.o.

If any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.


Question:
I have a makefile, called "Makefile", and some target in it like:

```
file.o: file.c Makefile
      gcc <some flags & options> file.c
```

What exactly doesfile.o: file.c Makefiledo?

Answer:
That line describes the dependencies forfile.o.

If any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.


Question: Is it possible for a function in a linux kernel module calling a function in another module ?

Answer:
Yes. Of course, the other kernel module must be loaded.

For an example, look at the USB code, which is implemented as a mullti-layer driver, with each layer in its own module.Reference linkhere.


Question:
I've searched the standard but didn't notice the mentioned part.

Is it just "anything but 0" and 1 or it is compiler-dependent?

Answer:
The result of the logical negation operator!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint.

Appears in C89/C90, C99, and C11.


Question:
This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.

Say I declare a global arrayint arr[10];Should I free it somehow in the end?

Answer: You need not free it.You should usefree()only when you have usemalloc().


Question:
This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.

Say I declare a global arrayint arr[10];Should I free it somehow in the end?

Answer: You need not free it.You should usefree()only when you have usemalloc().


Question:
why this code is showing value of a = 1120403456 (may be garbage) in Dev-C++.

```
#include<stdio.h>
int main()
{
    int a=5;
    float * pf;
    pf=(float *)&a;
    *pf=100.0;
    printf("%d",a);
    return 0;
}
```

Answer: The floating point number 100.0 is represented as 0x42C80000 in memory, which in decimal is 1120403456.  You're printing out the 32-bit integer representation of 100.0.


Question:
How does the commandls -lcount the number of hard links of an inode?
Does it use the Linux API or is it code that requires deeper knowledge of the Linux kernel source code?

I am not, yet, able to understand the source code ofls, because I just started learning C.

Answer: It callsstatto get information about the file (in astruct stat). Then it looks at thest_nlinkfield of thestruct stat.


Question:
lets say I have two int arrays, array1 and array2.

Is this line:

```
array1[i++] = array2[j++];
```

equal to this:

```
array1[i] = array2[j];
i++;
j++;
```

?

Answer: Yes they are equivalent,unlessyou've written#DEFINE i jor#DEFINE j i, in which case the behaviour of the first snippet isundefined.


Question: There is an option '-fshort-double' in GCC, Clang does not understand it. Is there some analog of this option for Clang 3.7 ?

Answer:
in looking at the web page:https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html#Option-Summary,

there is no-fshort-doubleoption ingcc.

therefore, the option is not valid to begin with.

suggest removing that option when changing toclang


Question:
I am trying to obtain a number of bits from a byte in C. Currently I am doing so by shifting and then bit masking (0xFF), however the shifting operator is taking a long time. Is there another way to this using only bitwise operations? And if so how?

Thanks!

Answer:
If you want to move a particular (single) bit to the least-significant position, you can use a hack like this:

```
(x & mask) != 0
```

wheremaskselects the single bit.


Question:
I am trying to obtain a number of bits from a byte in C. Currently I am doing so by shifting and then bit masking (0xFF), however the shifting operator is taking a long time. Is there another way to this using only bitwise operations? And if so how?

Thanks!

Answer:
If you want to move a particular (single) bit to the least-significant position, you can use a hack like this:

```
(x & mask) != 0
```

wheremaskselects the single bit.


Question:
What is the asmjit equivalent ofmov eax,[ecx+0CC]?

This is close:c.mov_ptr(x86::eax, x86::ptr(x86::ecx, 0x0CC)); but the arguments are wrong.

Any ideas?

Answer:
The answer is:

a.mov(x86::eax, x86::ptr(x86::ecx, 0x0CC));


Question:
How do I return a double without gettingrounded:

```
int function() {
    double d = 5.894;
    printf("d=%f\n", d);
    return d;
}

int main() {
    double d = function();
    printf("d=%f\n", d);
    return 0;
}
```

This gives me

```
d=5.894000
d=5.000000
```

What am I missing here?

Answer:
Your function returns ٰintit must returndouble

Change

```
int function()
```

to

```
double function()
```


Question:
How do I return a double without gettingrounded:

```
int function() {
    double d = 5.894;
    printf("d=%f\n", d);
    return d;
}

int main() {
    double d = function();
    printf("d=%f\n", d);
    return 0;
}
```

This gives me

```
d=5.894000
d=5.000000
```

What am I missing here?

Answer:
Your function returns ٰintit must returndouble

Change

```
int function()
```

to

```
double function()
```


Question: I need to get the path of %APPDATA% in my c program, to save a file in%APPDATA%\myprogram\How can I do that ?

Answer:
You should be able to get that information throughgetenv, here is an example.

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

int main ()
{
    char * app_data;
    app_data= getenv ("APPDATA");

    if (app_data!=NULL)
        printf ("The appdata path is: %s",app_data);

    return 0;
}
```


Question: Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?

Answer:
In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code.

In C++, unless->or*isoverloaded, the equivalence is as above.


Question: Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?

Answer:
In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code.

In C++, unless->or*isoverloaded, the equivalence is as above.


Question: Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?

Answer:
In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code.

In C++, unless->or*isoverloaded, the equivalence is as above.


Question: I have a small Linux project written in C is it possible to analyze it with a SonarQube?

Answer: According tohttps://en.wikipedia.org/wiki/SonarQube, it support c/c++, and is cross-platform, so you can do it I think.


Question:
Is there a simple lexer/parser for C language or a subset of it which is based on Flex/Bison?

I have found some open source parsers for C (TCC, LCC, ...) but none of them are based on bison.

Answer:
There is aC11 grammarfor YACC (a predecessor of Bison), it should work with Bison (maybe some tweaks will be needed).

GCC used to be based on Bison a long ago. GCC 3.4 source code contains afilewith C grammar.


Question: I have a small Linux project written in C is it possible to analyze it with a SonarQube?

Answer: According tohttps://en.wikipedia.org/wiki/SonarQube, it support c/c++, and is cross-platform, so you can do it I think.


Question:
I am doing vectorization using AVX intrinsics, I want to fill constant floats like1.0into vector__m256. So that in one register I got a vector{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}Does anyone knows how to do it?

It is similar to this questionconstant float with SIMD

But I am using AVX not SSE

Answer:
The simplest method is to use_mm256_set1_ps:

```
__m256 v = _mm256_set1_ps(1.0f);
```


Question:
This question already has answers here:C comma operator(4 answers)Closed7 years ago.

```
int a=3,1;
int b=(5,4);
```

I am a beginner in c and I noticed in a book this type of initialization . what does thisinitialisationmean?

Answer:
int b = (5,4)will first evaluate 5 then 4. The last thing that is evaluated will be assigned to the variable. For example

```
int b = (5,4,3,2,1)
```

in this case the value of b will be 1.


Question:
This question already has answers here:C comma operator(4 answers)Closed7 years ago.

```
int a=3,1;
int b=(5,4);
```

I am a beginner in c and I noticed in a book this type of initialization . what does thisinitialisationmean?

Answer:
int b = (5,4)will first evaluate 5 then 4. The last thing that is evaluated will be assigned to the variable. For example

```
int b = (5,4,3,2,1)
```

in this case the value of b will be 1.


Question:
I was looking into a code snippet and saw below statement. How will below statement evaluated?

```
x= 5|(high == 1 ? y : high == 0 ? z:0);
```

Answer:
The expression

```
x= 5|(high == 1 ? y : high == 0 ? z:0);
```

is evaluated as

```
x= 5|( high == 1 ? y : (high == 0 ? z:0) );
```

It has similar effect as that of

```
if(high == 1)
    x = 5|y;
else if(high == 0)
    x = 5|z;
else
    x = 5|0;
```


Question: Hi I want to declare a 12 bit variable in C or any "unconventional" size variable (a variable that is not in the order of 2^n). how would I do that. I looked everywhere and I couldn't find anything. If that is not possible how would you go about saving certain data in its own variable.

Answer:
Use a bitfield:

```
struct {
   unsigned int twelve_bits: 12;
} wrapper;
```


Question:
Say if you have the following IP address:

```
192.168.0.255
```

How can I store that human readable IP address into astruct in_addr? I'm brand new to network programming in C at this low level, so any help would be greatly appreciated.

Answer:
You can do

```
struct in_addr p;
inet_aton("192.168.0.255", &p.s_addr);
```


Question:
I Would like to know how I can do exponent function in this code part (that means how I can change ^ to something that works in c language)?

```
K = (S * (P/100/12)) / (1 - (1 + (P/100/12))^(-Y*12) );
```

Answer:
It's thepow()function frommath.h

```
K = (S * (P / 100 / 12)) / (1 - pow((1 + (P / 100 / 12)), (-Y * 12)));
```


Question: I'm working on a C grammar analysis program. While running C preprocessor, there are some libraries which check the environment and use#errorto stop compiling. How can I disable them, since I only need the preprocess step to finish?

Answer: Why do you want to disable them?  They are outputting an error and stopping compilation for a reason.  The only way I know to disable them is to modify the source code and remove them.


Question: I'm working on a C grammar analysis program. While running C preprocessor, there are some libraries which check the environment and use#errorto stop compiling. How can I disable them, since I only need the preprocess step to finish?

Answer: Why do you want to disable them?  They are outputting an error and stopping compilation for a reason.  The only way I know to disable them is to modify the source code and remove them.


Question: I am using GDB(peda-gdb) to debug a program, can I write something in a heap address so when the program reach that address It can read it out? I know the address but I do not know how to write something in that address. Thanks.

Answer:
You can write to the heap using C syntax, with commands that evaluate an expression likeprintorset var.  For example, to write an integer value to a specific location:

```
(gdb) set var *(int *)0xYOURADDR = 23
```


Question:
```
main()
{
int a,b=0,c=1,d=1;
a=++b&&++c||++d;
printf("%d %d %d",b,c,d);  //1 2 1
b=0,c=1,d=1;
a=b&&++c||++d;
printf("%d %d %d",b,c,d);  //0 1 2
}
```

Why second printf gives answer 0 1 2 instead of 0 2 1 ?

Answer:
Why second printf gives answer 0 1 2 instead of 0 2 1 ?

&&isshort-circuiting.

In

```
a=b&&++c||++d;
```

++cwill not be evaluated ifbis0which is the case here. Hencecis1instead of2.


Question: The sizeof(char) in C gives 1 and sizeof("a") gives 2. Please help

Answer:
Achari.e. a character has size 1.

Thestring literal"a"isnota character. It is a "string" (and by string I meanchar[]). All "strings" in C are null-terminated, so your "string" is actually:

```
{'a','\0'}
```

And that's two characters. So size is 2.


Question: I found that a single-linelanguage: c.travis.yml file basically does all I need, with the exception that I don't wantmake testto happen. Is there a way I could make Travis just run./configure && make?

Answer:
Have you tried overriding the default test script as described in:https://docs.travis-ci.com/user/languages/c#Default-Test-Script?

Something like:

```
script:
  ./configure && make
```


Question:
I have a memory address integer like this 0x80480ac and i want to assign it a char * like this:

```
char *address="\x08\x04\x80\xac";
```

How can i do it?

Answer:
I believe you are looking for:

```
char * address = (char *)0x080480ac;
```


Question: I found that a single-linelanguage: c.travis.yml file basically does all I need, with the exception that I don't wantmake testto happen. Is there a way I could make Travis just run./configure && make?

Answer:
Have you tried overriding the default test script as described in:https://docs.travis-ci.com/user/languages/c#Default-Test-Script?

Something like:

```
script:
  ./configure && make
```


Question:
I have a memory address integer like this 0x80480ac and i want to assign it a char * like this:

```
char *address="\x08\x04\x80\xac";
```

How can i do it?

Answer:
I believe you are looking for:

```
char * address = (char *)0x080480ac;
```


Question:
Can someone explain mecmpfuncwhich is used in theqsortfunction? What areaandbin this function and what are they pointing to?

```
int cmpfunc(const void *a, const void *b)
{
    return(*(int*)a - *(int*)b);
}
```

Answer: aandbincmpfuncare pointers toconst voidtype.cmpfunccan accept pointer to elements of array of any data type.void *pointer can't be dereferenced, therefore a castint *is needed before dereferencing.


Question:
I want to display "string pointer affected" but I get an error. Here is my code:

```
#include<stdio.h>

main()
{
  char* *p;

  char * s="string pointer affected";

  *p=s;

  printf("%s",*p);
}
```

Answer:
pdoesn't point to any known location, so writing to*pis a bad idea.

You mean to say:

```
p = &s;
```


Question:
I want to display "string pointer affected" but I get an error. Here is my code:

```
#include<stdio.h>

main()
{
  char* *p;

  char * s="string pointer affected";

  *p=s;

  printf("%s",*p);
}
```

Answer:
pdoesn't point to any known location, so writing to*pis a bad idea.

You mean to say:

```
p = &s;
```


Question:
I've been trying to make a program to input two numbers from the user.The XCode application is showing error as

Data argument not used by format string

How am I supposed to get over this?
please help
thanks

Answer:
just type%dinside the("Here is my number %d",Num)

You can find more formats here:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html


Question:
I want initialize a function pointer so that it is null. Which of these two ways is preferred?

```
void (*Pointer)(void) = NULL;
```

Or

```
void (*Pointer)(void) = (void (*)(void))0;
```

Answer:
0is implicit convertible to any pointer type. Though how your compiler implementsNULLdepends.

In your code you can simply write

void (*Pointer)(void) = 0;but it won't be portable , so writevoid (*Pointer)(void) = NULL;


Question:
Within a function, we have the following:

```
__asm__("movl $0xe4ffffe4, -4(%ebp)");
```

Does this mean that we move the contents of the memory address 0xe4ffffe4 over to the ebp register?

Answer:
This:

```
movl $0xe4ffffe4, -4(%ebp)
```

Says "move the 4-byte value 0xe4ffffe4 into the slot 4 bytes before the address stored in register ebp."


Question:
I am working on small project using Arduino. I have this char array which used to store some values. the problem is How to set this char array to null after assign some  values in Arduino?

```
char packetBuffer[200]
```

Answer:
Usememsetfromstring.h:

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


Question:
How do i make the printf("%d, veck[i]); print out all 100 numbers of the array instead of only 1-10?

```
int vek[100];
    for(int a=0;a<10;a++){
        for(int i=0;i<10;i++){
                printf("%d ", vek[i]); //only shows numbers 1-10
        }
     printf("\n");
     }
```

Answer:
You should change the index of vek.

```
printf("%d ", vek[10* a + i]);
```


Question:
How can I open a file in an ext2 file system. For example, lets say I want to open the file:/a/b/c.txt

I'm looking at the functions here:http://www.nongnu.org/ext2-doc/ext2.html

Answer:
The same as any other filesystem: usefopen("/path/to/the/file", "r")or similar.

The documentation you found is only relevant to people implementing the filesystem.


Question:
In the following floor loop, how wouldsum += n --be evaluated? I'm very, very confused...

```
int sum;
for(sum=0;n>0;sum+=n--);
```

Answer:
Forsum += n--the following operations are performed

addntosumdecrementn

Withsum += --n

nis decrementedthe new value ofnis added tosum

n--is calledpostdecrement, and--nis calledpredecrement


Question:
The following code:

```
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    pid_t mypid = getpid();
    write(1, &mypid, sizeof(pid_t));
    return 0;
}
```

Prints gibberish instead of actual pid. Why?

Answer:
write(..will not print formatted text, but rather binary output directly to a file descriptor.

Just useprintforfprintf:

```
fprintf(stdout, "%d", (int) mypid);
```


Question:
How can I remove, in C, a part of a string? I am interested especially in a built-in function, or an efficient code to do it.
I have this line of code:

```
char namefile[256] = "/Users/student/Desktop/Silviu/g7.08e11.01024"
```

and I want to keep only "g7.08e11.01024" so I can use it somewhere else.

Answer:
Usestrrchr:

```
const char* shortName = strrchr(namefile, '/') + 1;
```

strrchrreturns the address of the last occurence of/in the string.


Question:
How can I remove, in C, a part of a string? I am interested especially in a built-in function, or an efficient code to do it.
I have this line of code:

```
char namefile[256] = "/Users/student/Desktop/Silviu/g7.08e11.01024"
```

and I want to keep only "g7.08e11.01024" so I can use it somewhere else.

Answer:
Usestrrchr:

```
const char* shortName = strrchr(namefile, '/') + 1;
```

strrchrreturns the address of the last occurence of/in the string.


Question:
here is my CMakeLists.txt:

```
cmake_minimum_required(VERSION 3.3)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(ex ex.c)
target_link_libraries(ex xdo)
```

the full code ishere

of course, the libxdo.so and xdo.h is exist

Answer:
the checked answer is wrong, the right solution is:

```
#define __USE_XOPEN
#include "unistd.h"
#include <xdo.h>
```


Question:
Header file math.h is for mathematical functions like cos,sin, tan..
But how to write the ln function and not log?

Answer:
The C functionlogis the natural logarithm, which mathematicians usually write as "ln".

The C functionlog10is the logarithm base 10, which is sometimes written "log".


Question:
here is my CMakeLists.txt:

```
cmake_minimum_required(VERSION 3.3)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(ex ex.c)
target_link_libraries(ex xdo)
```

the full code ishere

of course, the libxdo.so and xdo.h is exist

Answer:
the checked answer is wrong, the right solution is:

```
#define __USE_XOPEN
#include "unistd.h"
#include <xdo.h>
```


Question:
```
#include<string.h>
#include<stdio.h>
void main()
{
 char *a="12345";   //Add number of that string
}
```

How can i add number of that string

example :

```
sum=1+2+3+4+5

sum=15
```

How can i do that?

Answer:
```
int sum = 0;
char *a = "12345";

while (*a) {
   sum += *a - '0';
   a++;
}

printf("sum=%d\n", sum);
```


Question:
Discovering gateway devices process using miniupnp is as follows:

CallupnpDiscover(...)to find all available devices which support UPnP protocol.CallUPNP_GetValidIGD(...)to get first gateway from this list.

Is there any solution to getallgateways from list, obtained in step 1?

Answer: Made aforkof miniupnpc. Added routineGetValidConnectedIGDs, which returns list of all gateway devices found.


Question:
```
#include<string.h>
#include<stdio.h>
void main()
{
 char *a="12345";   //Add number of that string
}
```

How can i add number of that string

example :

```
sum=1+2+3+4+5

sum=15
```

How can i do that?

Answer:
```
int sum = 0;
char *a = "12345";

while (*a) {
   sum += *a - '0';
   a++;
}

printf("sum=%d\n", sum);
```


Question:
Discovering gateway devices process using miniupnp is as follows:

CallupnpDiscover(...)to find all available devices which support UPnP protocol.CallUPNP_GetValidIGD(...)to get first gateway from this list.

Is there any solution to getallgateways from list, obtained in step 1?

Answer: Made aforkof miniupnpc. Added routineGetValidConnectedIGDs, which returns list of all gateway devices found.


Question: I have four parameters, each an integer and I want to find the smallest. What is the quickest and/or simplest way to do it? I can probably do a bubble sort but it seems overkill.

Answer:
```
int min(int a, int b){
    return a<b?a:b;
}
```

call as:

```
min(min(a,b),min(c,d))
```


Question:
I want to generate a random float value between 0 and 1 excluding 1, I.e.[0, 1). I've searched a lot but I couldn't find an answer of this. I've tried the following trick however it generates a negative values

```
(double)rand()/(double)RAND_MAX-1;
```

Answer:
You need parentheses to force the right order:

```
(double)rand()/((double)RAND_MAX + 1);
```

Also note, that you need +1, not -1.


Question:
Can i create my own properties with:

```
XChangeProperty(display, w, property, type, format, mode, data, nelements)
```

or can i only use the properties shown in
standards.freedesktop.org?

Answer:
You can create any property you want.

Just doXInternAtomwith your unique atom name, and you have apropertyof your own. Same fortype.


Question:
Can i create my own properties with:

```
XChangeProperty(display, w, property, type, format, mode, data, nelements)
```

or can i only use the properties shown in
standards.freedesktop.org?

Answer:
You can create any property you want.

Just doXInternAtomwith your unique atom name, and you have apropertyof your own. Same fortype.


Question:
I would like to retrieve time passed since kernel's start (in kernel space). It should be the match the timeprintk();is using (For example:[    5.832000] message).

jiffiesprovide different time, so I am not sure it fits me.

How can I achieve this?

Answer: What about usingget_monotonic_boottime?jiffiesare initialized to 5 minutes before boot to ensure that there is an overflow soon after booting and detect bugs.


Question:
How do I convert from string to unsigned int?

I know thatstrtoul()converts from string tounsigned long int, but I want normalintand notlong int.

I haven't been able to find a function that does that.

Answer:
but I want normal [unsigned] int and not long [unsigned] int.

You want to usestrtoul(), assign it to along unsigned int, test the result for being in the range of[0..UINT_MAX]and if this is the case assign thelong unsigned intto anunsigned int.


Question:
For example

the text file contains a line :A B CSo the method will declare 3 variables:in A, B ,C;

Answer: No . This type of facility is available in scripting languages like python and ruby but not in c/c++. You can use hashing or a struct to store this type of information.


Question:
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question

How can i combine one increment and one decrement statements into one single statement in C language.

ex: a++ and b-- into one single statement.

Answer:
Writea++,b--;

Two expressions separated by a comma are evaluated left to right.


Question:
Here's my problem.. I have two arrays: one has the total marks of students and another is a character string. So, I want the computer to assign a letter grade to the character string when the array with the total marks is in within a range..

Here's what a came up with but it won't compile and I don't have anything else in mind:

Answer:
Try this:

```
sprintf(grade[i], "%s", "A+");
```


Question:
I didnt get the logic behind the answer. I tried to print the value of a after definition and it shows a=72. Please help.

```
#include<stdio.h>
    main()
    {
       int a=400*400/400;
       if(a==400)
       printf("Do good");
       else
       printf("Have good");
    }
```

output : Have Good

Answer:
I guess that on your platformintis 2 byte wide, 16 bit.

Then

```
400*400 = 28928
```

Due to overflow

```
28928/400 = 72
```


Question: What is the Win32 API for sending messages between computers? I mean, what used to be achieved by the "net send" command and is now using "msg". I imagine it is some API over NetBIOS?

Answer: Bothnet sendandmsguse theWTSSendMessage()function.


Question:
I have the following code, where we try to left shift certain bits of a value:

```
int main()
{
   unsigned long mvb = 1;

   mvb << 8;
   printf("The shift value is %u\n", mvb);

   mvb << 56;
   printf("The shift value is %u\n", mvb);
}
```

but the result for all those two operation are both1, what is the reason, and how use it correctly?

Answer:
You need to assign it back to mvb after shifting like:

```
mvb = mvb << 8;
```


Question:
What are the differences, if any, between

```
*a = b;
```

and

```
a = &b;
```

Are these two different ways to make a var point to another var?

Answer: No, they do not do the same thing.*a = b;does not changeabut it changes whatapoints to.a = &b;does changeabut it does not change whatapointed to.


Question:
Starting from

```
char tval[20] = "temp:26.62";
```

how can I add a space character untiltvalis filled? I need that in the end to obtain this:

```
char tval[20] = "temp:26.62          ";
```

Answer:
Like this, probably

```
size_t prevlen = strlen(tval);
memset(tval + prevlen, ' ', 19 - prevlen);
*(tval + 19) = '\0';
```


Question:
There are some#definestatements in my C language code, and now i find some bug.
But the codeblocks IDE can not step into the #define block.

so i want to get the  Pre-compiled source code, which will expand the#definemacro.

Answer: If you use the-Eoption of gcc, you can expand the macros to a C file, and then compile the C file.


Question:
Withfopen, by setting it towwill automatically clear the file for me. However now I'm trying to do the same thing withopen,

```
int file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
```

This won't guarantee that the file is empty and write at the beginning(?). How can I achieve that?

Answer: AddO_TRUNC- Initially clear all data from the file.


Question: First time publishing hereSimple situation: In PUTTY, i have to create a file named admin.pid where it stores a PID when the user starts the "app" i'm creating. How can i do this? Thanks

Answer: Get the PID usinggetpid().Open the file usingfopen().Write the PID to the file byfprintf().Close the file usingfclose().


Question:
There are some#definestatements in my C language code, and now i find some bug.
But the codeblocks IDE can not step into the #define block.

so i want to get the  Pre-compiled source code, which will expand the#definemacro.

Answer: If you use the-Eoption of gcc, you can expand the macros to a C file, and then compile the C file.


Question:
Withfopen, by setting it towwill automatically clear the file for me. However now I'm trying to do the same thing withopen,

```
int file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
```

This won't guarantee that the file is empty and write at the beginning(?). How can I achieve that?

Answer: AddO_TRUNC- Initially clear all data from the file.


Question:
When you have the statement:

*str++ = *end

Does the*strget assigned the value of*endor does it get incremented and then get assigned the value of*end?

Answer: As apost-increment operator, it first assigns*endthen points to new/incremented address ofstr.


Question:
I'm learning C, and I am running into some problems which make me write (seemingly) redundant code. I am finding myself writing code like

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

which (since it is in a loop) would output something like

```
a b c
```

Is there any way to combine these print statements?

Answer:
just write :printf("%c ", someChar);

note the space after%c


Question:
Which numbers can a double type contain? (in C language)
I was trying to find the numbers that double can contain in c.
I know that a float can contain numbers between -10^38

Answer: In C, adoubleisusuallyan IEEE double.  I don't know if this is required by the standard, but these days it would be unusual for it to be something else.  Here's some info on double precision formats, particularly IEEE:double-precision floating point formats


Question:
I have a simple C library that I compile to a.sofile on my linux machine. I'd like to do the same on my Mac, but after I compile and move the library to/usr/local/lib, but I'm not sure how to link it seeing asldconfigisn't a thing.

How would I go about doing this?

Answer:
While Linux has.sofiles, OSX has.dylibfiles. The process is similar, you just invoke compiler as in

```
clang -dynamiclib -o libname.dylib sources.c
```


Question:
I have the following source:

```
int main() { 000J; }
```

With gcc 4.8.4 it compiles without errors.
I know there are suffixes like L or U, but I didn't find anything about J.

So what does it do?

Answer:
I get a warning:

Imaginary constants are a GNU extension

TheJsuffix is a GNU extension, which causes the literal to be of a_Complextype.

More info here:https://gcc.gnu.org/onlinedocs/gcc/Complex.html


Question:
I have the following source:

```
int main() { 000J; }
```

With gcc 4.8.4 it compiles without errors.
I know there are suffixes like L or U, but I didn't find anything about J.

So what does it do?

Answer:
I get a warning:

Imaginary constants are a GNU extension

TheJsuffix is a GNU extension, which causes the literal to be of a_Complextype.

More info here:https://gcc.gnu.org/onlinedocs/gcc/Complex.html


Question:
I create 100000 of such structs, by malloc'ing pointers to them.

```
test_struct test {
    char value[100];
}
```

Does it mean that all char[100] variables (100 * 100000 ~ 10mb) will go to stack memory, exceeding it and causing my program to crash?

Answer:
No.

When you allocate a struct on the heap, all of its members go on the heap as well.


Question: Thesizeof(data_type)operator returns thenumber of bytesand notoctets, so the size of a byte may not be 8 bits. How can one identify the size of a byte in bits on any platform?

Answer: I think you can dosizeof(type) * CHAR_BITto determine the number of bits. Include limits.h for the definition of CHAR_BIT.


Question:
If I dosizeof('r'), the character 'r' requires 4 bytes in memory. Alternatively, if I first declare acharvariable and initialize it like so:

```
char val = 'r';
  printf("%d\n", sizeof(val));
```

The output indicates that 'r' only requires 1 byte in memory.

Why is this so?

Answer:
This is because the constant'c'is interpreted as anint.
If you run this:

```
printf("%d\n", sizeof( (char) 'c' ) );
```

it will print1.


Question: Thesizeof(data_type)operator returns thenumber of bytesand notoctets, so the size of a byte may not be 8 bits. How can one identify the size of a byte in bits on any platform?

Answer: I think you can dosizeof(type) * CHAR_BITto determine the number of bits. Include limits.h for the definition of CHAR_BIT.


Question:
If I dosizeof('r'), the character 'r' requires 4 bytes in memory. Alternatively, if I first declare acharvariable and initialize it like so:

```
char val = 'r';
  printf("%d\n", sizeof(val));
```

The output indicates that 'r' only requires 1 byte in memory.

Why is this so?

Answer:
This is because the constant'c'is interpreted as anint.
If you run this:

```
printf("%d\n", sizeof( (char) 'c' ) );
```

it will print1.


Question:
I want to create a function like this but with priority. For that, I need the pid, but I don't know how to get it. Any idea?

Mine is to usesetpriority (0, pid, value), but I need the pid.

```
void cmd_exec(char * tr[]) {
    if (execvp(tr[0], tr)== -1)
        perror("Error");
}
```

Answer:
To get the process-id of the calling process usegetpid().

Please find the

Linux man-page here.current(Issue 7) POSIX documentation here.


Question:
I want to create a function like this but with priority. For that, I need the pid, but I don't know how to get it. Any idea?

Mine is to usesetpriority (0, pid, value), but I need the pid.

```
void cmd_exec(char * tr[]) {
    if (execvp(tr[0], tr)== -1)
        perror("Error");
}
```

Answer:
To get the process-id of the calling process usegetpid().

Please find the

Linux man-page here.current(Issue 7) POSIX documentation here.


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

void foo();
int main()
{
    int b = 0;
    int a[6] = {1,2,3,4,5,6};
    foo();
    return 0;
}

void foo()
{
    //write some code to print a and b
}
```

My Question is:

How to get the local variable from outside without pass any parameter ?

Answer: That's not possible. You need to pass a pointer to it to access it from a function or make it global.


Question:
I want to know that how to print0as000and1as001in c and so on.

I tried usingprintf("%3d", var);but it doesn't seem to work

can anyone please suggest any method

Answer:
You can do this with

```
printf("%03d", var);
```

to provide a minimum field width of 3 padded with leading zeros. Don't forget the enclosing "quotes". If you had put them in your posted code:

```
printf("%3d", var);
```

it would have been padded with spaces.


Question:
```
printf("%d",pow(5,3))
```

it's printing 0, and works fine when number is different from 5 why?

Can anyone explain this ?

Answer:
The return type of the power function is double. using the double conversion specifier to prints the output of power function.

the conversion specifier for double is not "%d". It should be "%f".


Question:
I was debugging a C code and came across below expression. I want to know,
how below expression will be evaluated in c?

x += y*2 != z;

Answer:
To figure out expressions like that start with theprecedence table:

Multiplication has precedence of 3, so it will be evaluated first!=has precedence of 7, so it will be evaluated next+=has precedence of 14, so it will be evaluated last.

Therefore,xwill be incremented by1ify*2is not equal toz.


Question:
This question already has answers here:What does this ">>=" operator mean in C?(5 answers)Closed7 years ago.

I know>>is Binary Right Shift Operator but what does>>=mean, like if I want Log2 onxI needwhile(x >>= 1) result++;.

Answer:
It's the bitwise shift right assignment operator;x >>= 1is equivalent tox = x >> 1.

(It has the same precedence as assignment=).


Question:
This question already has answers here:What does this ">>=" operator mean in C?(5 answers)Closed7 years ago.

I know>>is Binary Right Shift Operator but what does>>=mean, like if I want Log2 onxI needwhile(x >>= 1) result++;.

Answer:
It's the bitwise shift right assignment operator;x >>= 1is equivalent tox = x >> 1.

(It has the same precedence as assignment=).


Question:
How can I view C11 header files content of gcc compiler in CodeLite on Linux? if not possible, How/Where can I view them?

Please ignore this location en.cppreference.com/w/c/header since it's just documentary with no actual header file content

Answer: All the system header files, including the standard C header files, are under/usr/include. You can open any of them with any editor, including the CodeLite editor.


Question:
I want to find straight lines marked in the image, the coordinates point A, point B is the beginning and end of the segment. Please help me!
img:enter image description heresource:enter image description here

Answer:
It is called the "Hough Transform"

You could experiment using something like Mathlab, and then implement it using opencv houghtransform.

https://github.com/Itseez/opencv/blob/master/samples/cpp/houghlines.cpp


Question:
Assume there is a structfakes:

```
struct fakes {
....
};
```

And there is a pointer:

```
struct fakes *fakes;
```

I'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same.

Answer:
I'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same.

Yes, they are guaranteed to be the same.


Question:
What is the difference between

```
float f = (float) 99.32 ;
```

and

```
float f = 99.32f ;
```

Both of them compiled and ran successfully.

Answer:
```
float f = 99.32f ;
```

That is afloatliteral, which means a float variable being assigned with afloatvalue directly.

```
float f = (float) 99.32 ;
```

That is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.


Question:
What is the difference between

```
float f = (float) 99.32 ;
```

and

```
float f = 99.32f ;
```

Both of them compiled and ran successfully.

Answer:
```
float f = 99.32f ;
```

That is afloatliteral, which means a float variable being assigned with afloatvalue directly.

```
float f = (float) 99.32 ;
```

That is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.


Question:
In one of my assignments I am seeing this line used:

```
int index = -1, k;
```

Im not sure what is happening when there are to entries for the one variable.
What exactly is the variable "index" holding when it has two entries?

Answer: This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.


Question:
In one of my assignments I am seeing this line used:

```
int index = -1, k;
```

Im not sure what is happening when there are to entries for the one variable.
What exactly is the variable "index" holding when it has two entries?

Answer: This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.


Question:
Code:

```
#include <stdio.h>
int main()
{
  long cn=1;
  char ch;
  while((ch=getchar())!=EOF)
  {
    printf("%ld\t%c\n",cn++,ch);
  }
}
```

When I input word "secret" and hit enter it shows count up to 7 and not 6,why?

Answer: Because the "enter" character is read as well. This is in fact a "newline", ASCII code 10 (or hex 0A).


Question:
I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample

now i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection.

is there any way to do it?

Answer:
Seems like curl support--interfaceoption

```
curl --interface eth0
```


Question:
I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample

now i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection.

is there any way to do it?

Answer:
Seems like curl support--interfaceoption

```
curl --interface eth0
```


Question:
As per title, is there an equivalent ofpthread_barrier_ttype in windows? I' ve foundSYNCHRONIZATION_BARRIERbut seems available only since Windows 8.

Is there something more portable?

Thanks

Answer: Do it the old fashioned way before barriers were invented: with a counting semaphore


Question: There is good documentation here (http://www.postgresql.org/docs/8.3/static/xfunc-c.html), but I didn't find a way to read/modify/delete data from existing table by tablename and columns name from C extension.

Answer:
I guess what you need isSPI.

P. S. Do you actually use 8.3? Use the latest (9.4) if you're not restricted somehow.


Question:
In a single nibble (0-F) I can store one number from 0 to 15. In one byte, I can store a single number from 0 to 255 (00 - FF).
Can I use a byte (00-FF) to store two different numbers each in the range 0-127 (00 - 7F)?

Answer: The answer to your question is NO. Youcansplit a single byte into two numbers, but the sum of the bits in the two numbers must be <= 8. Since, the range 0-127 requires 7 bits, the other number in the byte can only be 1 bit, i.e. 0-1.


Question:
```
int m,digit[100],i=0, n = 15;
while(n)
{
    m = n%2;
    digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m];
    n = n/2;
}
```

I did not understand what is digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m];

Answer: digit[i] ="0123456789abcdefghijklmnopqrstuvwxyz"[m];is themth letter of0123456789abcdefghijklmnopqrstuvwxyz.


Question: When I resize my window and aWM_SIZEmessage is sent, does theWM_SIZEmessage get sent to the message queue or does the window procedure called directly?

Answer: Resizing a window by mouse sendsWM_SIZEdirectly to the window procedure, it does not go through the message queue.


Question: There is good documentation here (http://www.postgresql.org/docs/8.3/static/xfunc-c.html), but I didn't find a way to read/modify/delete data from existing table by tablename and columns name from C extension.

Answer:
I guess what you need isSPI.

P. S. Do you actually use 8.3? Use the latest (9.4) if you're not restricted somehow.


Question:
In a single nibble (0-F) I can store one number from 0 to 15. In one byte, I can store a single number from 0 to 255 (00 - FF).
Can I use a byte (00-FF) to store two different numbers each in the range 0-127 (00 - 7F)?

Answer: The answer to your question is NO. Youcansplit a single byte into two numbers, but the sum of the bits in the two numbers must be <= 8. Since, the range 0-127 requires 7 bits, the other number in the byte can only be 1 bit, i.e. 0-1.


Question:
```
int m,digit[100],i=0, n = 15;
while(n)
{
    m = n%2;
    digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m];
    n = n/2;
}
```

I did not understand what is digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m];

Answer: digit[i] ="0123456789abcdefghijklmnopqrstuvwxyz"[m];is themth letter of0123456789abcdefghijklmnopqrstuvwxyz.


Question: When I resize my window and aWM_SIZEmessage is sent, does theWM_SIZEmessage get sent to the message queue or does the window procedure called directly?

Answer: Resizing a window by mouse sendsWM_SIZEdirectly to the window procedure, it does not go through the message queue.


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

int main(void)
{
    char *s = "Jordan";
    printf("hello, %s\n, s");
}
```

Does anyone know a way that I can get this native C source code to work? I'm having trouble getting it to compile and run.

Answer:
Your second quote is in the wrong place. Try:

```
printf("hello, %s\n", s);
```


Question: Does gethostbyaddr() function uses internet connection for converting ip address to hostname? Or it uses some cached data (like DNS cache)?

Answer: Yes. It does a DNS lookup, which may be satisfied by the local resolver's cache or may not.


Question:
```
void main()
{
    int a;
    a=10;
    do
    while(a++<10);
    while(a++<=11);
    printf("%d",a);
}
```

The above program gives an output of14.
Can you please explain why?

Answer:
This code will make you understand why , Whenever you type a++ its always incremented

```
void main()
{
    int a;
    a=10;
    do{
    while(a++<10);
    printf("%d",a);
}
    while(a++<=11);
    printf("%d",a);
}
```


Question:
```
#include <stdio.h>
void main()
{
    char *s= "hello";
    char *p = s;

    printf("%c\t%c", p[0], s[1]);
}
```

output of this program is : h   e

Can anyone please explain how this program is working? I'm relatively new to c..

Answer:
p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers.

Note- There is no array declared in your program.


Question:
```
#include <stdio.h>
void main()
{
    char *s= "hello";
    char *p = s;

    printf("%c\t%c", p[0], s[1]);
}
```

output of this program is : h   e

Can anyone please explain how this program is working? I'm relatively new to c..

Answer:
p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers.

Note- There is no array declared in your program.


Question:
```
#include <stdio.h>
void main()
{
    char *s= "hello";
    char *p = s;

    printf("%c\t%c", p[0], s[1]);
}
```

output of this program is : h   e

Can anyone please explain how this program is working? I'm relatively new to c..

Answer:
p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers.

Note- There is no array declared in your program.


Question:
I need to find the length of an array, how would I do this without using thesizeoffunction.

eg if

```
Array 1 = [0 1 2 3 4 5 6]
```

the size of this array would be7.

Answer:
If you can't usesizeof(tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array):

```
int arr[] = {0, 1, 2, 3, 4, 5, 6, -1};
int count = 0;

while (arr[count] != -1) count++;
```


Question:
I need to find the length of an array, how would I do this without using thesizeoffunction.

eg if

```
Array 1 = [0 1 2 3 4 5 6]
```

the size of this array would be7.

Answer:
If you can't usesizeof(tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array):

```
int arr[] = {0, 1, 2, 3, 4, 5, 6, -1};
int count = 0;

while (arr[count] != -1) count++;
```


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:
This question already has answers here:Type of #define variables(7 answers)Closed7 years ago.

When I define a numerical constant with#define(e.g.#define pi 3.141593) is it anint,float,doubleor what?

Answer: Neither. It is a lexicographical replacement, that is, it will replacepiwith3.141593wherever it shows up.