Question:
I found this structure in the slides of my professor:

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

What does p mean? So far I used only the classical struct like this:

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

Answer:
```
struct point{
      int x;
      int y;
} p;
```

defines a variablepof typestruct point

it is same as

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


Question:
If I have the follow code " *k != (Queue *)0 * ", there is a violation of the rule 11.9. But why ?

Qich can I rewrite thise code for make it compliant to MISRA 11.9?

Answer:
You have to use the Keyword "NULL" to make it compliant:

```
*k != NULL
```


Question:
Can anyone explain the meaning of the code and give an example how to use it?
I can understandfoo[100], but notbar.

```
typedef struct{
   int a,b;
} CELL, *PCELL;

CELL foo[100];
PCELL bar(int x, CELL y);
```

Answer:
```
PCELL bar(int x, CELL y);
```

is a function declaration. It means thatbarwill take in anintand aCELLas parameters, and it will return a pointer to aCELLas a return value. The actual body of the function will be defined later.


Question: I'm writing a header file in C and needstdlib.hfor it to work. But, when I check if_STDLIB_His defined, the pre-processor says it's not, even if I include the file. I have tried it on multiple compilers, where it works on most but not ontdm-gcc. How can I fix this?

Answer:
Looking atstdlib.hsource code, it seems like the macro to look for in tdm-gcc might be_TR1_STDLIB_H.So you can try something like:

```
#if defined _STDLIB_H || defined _TR1_STDLIB_H
```


Question: I'm writing a header file in C and needstdlib.hfor it to work. But, when I check if_STDLIB_His defined, the pre-processor says it's not, even if I include the file. I have tried it on multiple compilers, where it works on most but not ontdm-gcc. How can I fix this?

Answer:
Looking atstdlib.hsource code, it seems like the macro to look for in tdm-gcc might be_TR1_STDLIB_H.So you can try something like:

```
#if defined _STDLIB_H || defined _TR1_STDLIB_H
```


Question:
i know that -> is a pointer |= is OR.
what is the logical meaning of such line?

TIMER0->ROUTELOC0 |= TIMER_ROUTELOC0_CC0LOC_LOC15

Answer:
|= does not mean OR. | means OR.

|= is similar to +=, that is

A |= B is the equivalent of A = A | B

So to answer your question:
It looks likeTIMER0is a structure with a memberROUTELOC0. The above expression is setting theROUTELOC0as the result whenROUTELOC0is ORed withTIMER_ROUTELOC0_CC0LOC_LOC15


Question: Question 3 onCareer Ridesuggests that*(x+i)is the same as&x[i]. Can someone please explain whether this is correct?

Answer: That answer is incorrect. Given a pointer variablexand an integer variablei,*(x + i)is the same asx[i]andx + iis the same as&x[i]. It looks like they took half from each side of that for their answer, but they didn't provide any explanation, so we'll never know.


Question:
When I try to compile my code, I am getting a c statement with no effect warning:

I am trying to use the bitwise operation to shift a value to the left. This is the code I am trying to do:

```
*bits << 5
```

bits is a unsigned pointer.

Answer:
You are calculating a value, but not assigning it to anything.

You probably want to do this instead:

```
*bits <<= 5;
// or equivalent
*bits = *bits << 5;
```


Question: Question 3 onCareer Ridesuggests that*(x+i)is the same as&x[i]. Can someone please explain whether this is correct?

Answer: That answer is incorrect. Given a pointer variablexand an integer variablei,*(x + i)is the same asx[i]andx + iis the same as&x[i]. It looks like they took half from each side of that for their answer, but they didn't provide any explanation, so we'll never know.


Question:
When I try to compile my code, I am getting a c statement with no effect warning:

I am trying to use the bitwise operation to shift a value to the left. This is the code I am trying to do:

```
*bits << 5
```

bits is a unsigned pointer.

Answer:
You are calculating a value, but not assigning it to anything.

You probably want to do this instead:

```
*bits <<= 5;
// or equivalent
*bits = *bits << 5;
```


Question:
A void function does not return any value as output and can take input values. The function below seems a void function, but there is the operator *, why?

```
void *function(){
     printf("hello")
}
```

Answer: That is not avoidfunction. That is a function that returns avoid*(pointer). But it seems incomplete, because theprintf()has no semicolon;and the function does not actually return avoid*.


Question:
A void function does not return any value as output and can take input values. The function below seems a void function, but there is the operator *, why?

```
void *function(){
     printf("hello")
}
```

Answer: That is not avoidfunction. That is a function that returns avoid*(pointer). But it seems incomplete, because theprintf()has no semicolon;and the function does not actually return avoid*.


Question:
I am currently working on a simulation using OpenMP. Whenever I try to execute with --trace to get the trace of the execution I get the following error

```
src/trace_graphics.c:5:10: fatal error: fut.h: No such file or directory
5 | #include <fut.h>
```

I redownloaded easypap but the file doesn't seem to come with it.

Answer:
I friend of mine found the solution so I'm posting it

```
sudo apt-get install libfxt-dev
```

This will do the trick


Question:
what is the meaning of "D type qualifier is meaningless on cast type at this line of code"

```
(*((volatile RCC_t * const)0x400FE060)).USESYSDIV = 1;
```

and how to solve it?

Answer: volatile RCC_t * constsays the pointer (not the thing it points to) isconst. But this is for avalue, which is just a result used in an expression. Qualifiers likeconstare properties ofobjectsin memory. So it serves no purpose in this cast.


Question: I need to get the size of a C/C++ executable at runtime in code. Unfortunately I  cannot use /proc/self/exe as it's restricted on the target system.

Answer:
Actually, it's a lot simpler than my attempt in the comments. The executable is simply:

```
(const char *)getauxval(AT_EXECFN)
```

That said, you should always try to open/proc/self/exefirst since the executable may have been deleted/moved/replaced while running.


Question:
While readinguname.c(in order to recreate it) I found a variable calledHOST_OPERATING_SYSTEM(line 371). It's never mentioned in the same file (as Strg+f told me) and not in the dependencies ofuname.c, as far as I could see.

Where is the variable initialized and how to access it?

Answer: HOST_OPERATING_SYSTEMis defined at build time using autoconf modules defined ingnulib.


Question:
How can I determine the maximum file path length allowed in the system my program is running on?
Is it inlimits.h? because I didn't find it there.

Answer:
It should be NAME_MAX defined in<limits.h>

https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html


Question:
How can I determine the maximum file path length allowed in the system my program is running on?
Is it inlimits.h? because I didn't find it there.

Answer:
It should be NAME_MAX defined in<limits.h>

https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html


Question:
I know for sure there is a command for CUP that prints out the produced parse tree.
Is there a similar command for Bison?

Answer:
No, there isn't.

If you want an AST or parse tree, you are responsible for building it, and the AST node objects should be able to print themselves out, as it were.


Question:
I know for sure there is a command for CUP that prints out the produced parse tree.
Is there a similar command for Bison?

Answer:
No, there isn't.

If you want an AST or parse tree, you are responsible for building it, and the AST node objects should be able to print themselves out, as it were.


Question:
I'm running Debian on an x86_64 Intel processor.

gcc (Debian 8.3.0) compiles the following program

```
#include <stdio.h>
#include <stdalign.h>
#include <stddef.h>

int main(){
  printf("%zd\n",alignof(max_align_t));
}
```

and outputs

```
16
```

What datatype requires a 16 byte alignment?

Answer: On x86_64,_Alignof(long double)==16.


Question:
I am getting core dump by this little programm.

```
#include <dirent.h>
int main(void) {

        printf("process n%s",(long)getpid());
        exit(0);
}
```

can you explain me why?

Answer:
You need to know where your functions come from, what they're returning and how to print the return value.

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

int main(void) {
    printf("process n%ld", (long)getpid());
}
```


Question: I was wondering whether clang's new amazing custom size (things like 13-bit int, or 70-bit int, etc.) will get added to gcc.

Answer: Well. C23 has finally implemented them as_BigInt


Question: I was wondering whether clang's new amazing custom size (things like 13-bit int, or 70-bit int, etc.) will get added to gcc.

Answer: Well. C23 has finally implemented them as_BigInt


Question:
Is there any difference between

```
const int* ptr[5];
```

and

```
const int (*ptr)[5];
```

?

I am trying to point to a const 5*5 2D int array, but I am not sure of the best way to do it

Answer:
```
const int* ptr[5];
```

This is an array of five elements, each element is a pointer toconst int.

```
const int (*ptr)[5];
```

This is a pointer to an array of five elements, each element is aconst int.


Question:
```
struct sigaction act;
memset(&act,0,sizeof act);
sigaction(SIGALRM, &act, NULL);
alarm(any_seconds);
```

My alarm code in linux.

I met "Alarm clock" message. But I don't want met this message.

How can I do? please help.

Answer:
You can catch the signal

```
static void alarmHandler(int signo)
{
    (void)signo;
    printf("Another message\n"); // or skip this line
}

...
alarm(any_seconds);
signal(SIGALRM, alarmHandler);
```


Question:
I declare double variables t and tau, and assign them values 1 and 0.00001
This line of code produces 536870912 in the console. What can be the reason?

printf("%i\n",round(t/(tau*double(2))));

By the way, I write code in a C++ compiler, but practically it's C.

Answer:
roundreturns adouble. Printing it with%iis undefined behaviour.

Use%ffor printingdouble:

```
printf("%f\n",round(t/(tau*double(2))));
```


Question:
About Leap Year algorithm,

```
if( (year%4==0 && year%100!=0) || (year%400==0))
```

Why does it use "or" instead "and"year%400==0?

Answer: Are you sure about knowing the meaning of what leap year is?


Question:
About Leap Year algorithm,

```
if( (year%4==0 && year%100!=0) || (year%400==0))
```

Why does it use "or" instead "and"year%400==0?

Answer: Are you sure about knowing the meaning of what leap year is?


Question: In my c programming homework I am asked toinitialize an array using an initializer list delimited by braces.I've googled every thing and I can't find an example of an initializer list delimited by braces. By the way, the array I am initializing is 2-D so if you could format your answer so that it is representative of a 2-D array, that would be very helpful. Thanks

Answer:
Here's an example:

```
int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };
```


Question: In my c programming homework I am asked toinitialize an array using an initializer list delimited by braces.I've googled every thing and I can't find an example of an initializer list delimited by braces. By the way, the array I am initializing is 2-D so if you could format your answer so that it is representative of a 2-D array, that would be very helpful. Thanks

Answer:
Here's an example:

```
int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };
```


Question: I want to create a file on/dev/mmcblk0, if it doesn't exist already, and then write to it. My question is how to check if there is already such file on the sdcard and then access it, does it show up like/dev/mmcblk0/somefile?

Answer: /dev/mmcblk0points to a drive, so you will need to mount the drive first before you can see what files are available on it or create new files.


Question: If we have a 32bit pattern of 1111 1111 1000 0000 0000 0000 0000 0000, which is -2^23 in int, when we convert int to float will this be -INF?

Answer: Conversions in C operate onvalues, and the value -2^23 is representable infloat, so the result of the conversion is the value -2^23.


Question: I'm trying to use the raylib on Visual Studio 2019, I followedthis tutorialI can build without anywarning, but when I run my program a error windows saying that it can't find "raylib.dll" apear. What can I do to solve this ?

Answer: I solve my issue by placing the raylib.dll that's inthis raylib distributionin the folder where my executable is build


Question: I got an assignment in which I can use any method, as long as it is part of the ANSI - c standard. I want to usefreopen, except I don't know if its part of the standard. I have looked at "The C programming language" book's list of methods and it doesn't seem to be there, but it was in C89 so I doubt it isn't in ANSI.

Answer:
freopen()functionconforms to C89.

And C89 isANSI C.


Question: Hello I am a complete beginner in a university course for C programming. I am trying to compare 4 inputs for exact matches using strcmp. The code only take into account the first two though. Is it possible to compare two strcmp values to compare 4 inputs?

Answer:
You can concatenate the results via&&.

```
if (strcmp(str1, str2) == 0 && strcmp(str1, str3) == 0 && strcmp(str1, str4) == 0) {
    printf("They match!")
}
```


Question:
I have currently an issue with debugging with visual studio code . I want to attach GDB to a C (.so) shared library module that is called via a main python program that interfaces with the C shared library with F2PY.

How do I procede to create a launch configuration in vscode for gdb to debug that C shared library?

Answer: Cross-language debugging from Python to C is only available in Visual Studio, not in VS Code.


Question:
```
for (unsigned i = 0; i < 3; i++) {
    if (i == 2) i = -1;
}
```

I can't understand why this loop is infinite. I get that it wraps around wheni = -1but UINT_MAX is greater than 3.

Answer:
If I rewrite your code, then might more clear to see why

```
unsigned i = 0;
while (i < 3) {
    if (i == 2) i = -1;
    i++;
}
```

i++happens at the end of the loop soibecame0again.


Question:
I want to search and replace a pointer

```
char* test
```

however, when I type

```
:%s/char* test/something/g
```

I get

```
E486: Pattern not found: char* test
```

I assume this is due to vim trying to use regex in search.

How can i tackle this issue? Is it possible to replace such text?

Answer:
You need to escape star symbol. This should work:

```
:%s/char\* test/something/g
```


Question:
```
for (unsigned i = 0; i < 3; i++) {
    if (i == 2) i = -1;
}
```

I can't understand why this loop is infinite. I get that it wraps around wheni = -1but UINT_MAX is greater than 3.

Answer:
If I rewrite your code, then might more clear to see why

```
unsigned i = 0;
while (i < 3) {
    if (i == 2) i = -1;
    i++;
}
```

i++happens at the end of the loop soibecame0again.


Question:
I want to search and replace a pointer

```
char* test
```

however, when I type

```
:%s/char* test/something/g
```

I get

```
E486: Pattern not found: char* test
```

I assume this is due to vim trying to use regex in search.

How can i tackle this issue? Is it possible to replace such text?

Answer:
You need to escape star symbol. This should work:

```
:%s/char\* test/something/g
```


Question:
How can I write following C expression using left-shift bit-wise operator (<<) and plus sign (+)?

```
y = x * 6;
```

Answer: x << nmeans x * 2nby definiton (C18 §6.5.7/4). Knowing that x * 6 means x * 2 + x * 4, which is x * 21+ x * 22, we can rewritey = x * 6;asy = (x << 1) + (x << 2);.


Question:
I just wrote a basic c program to run but compiler prompts the error (see attached image). I have installed Dev-C++ before where I did C++ Programming. But when I wrote C code it prompts  error I have deleted it & reinstalled the Dev-C++ again but couldn't run please help.
IDE Version: 5.11

Answer:
You must choose the right Project configuration (C project):

Remarque : you must have a project path without space. Exemple :C:\Ali\untiled\untiled.c


Question:
I just wrote a basic c program to run but compiler prompts the error (see attached image). I have installed Dev-C++ before where I did C++ Programming. But when I wrote C code it prompts  error I have deleted it & reinstalled the Dev-C++ again but couldn't run please help.
IDE Version: 5.11

Answer:
You must choose the right Project configuration (C project):

Remarque : you must have a project path without space. Exemple :C:\Ali\untiled\untiled.c


Question:
There is no re-negotiation in TLS1.3, will SSL_write yield SSL_ERROR_WANT_READ?  And will SSL_read yield SSL_ERROR_WANT_WRITE?

Here are openssl docs in SSL_write and SSL_read

Answer:
I created an issue in github, and got the developer's answer.

https://github.com/openssl/openssl/issues/11211#event-3094172350

In TLS1.3, SSL_write can yield SSL_ERROR_WANT_READ, and SSL_read also can yield SSL_ERROR_WANT_WRITE


Question: What happens when you call read() (or recv()) on an open socket, and you specify a length that is more the number of bytes ready to be read in the buffer (TCP) or the length of the next datagram (UDP)?

Answer: In both cases, if the size of the buffer is larger than the amount of available data, what data is available is read and the number of bytes actually read are returned from the function.  That return value is what you should use when operating on the data.


Question:
how to explain this right

```
char*(*a)(int, int);
```

just explain what does this declaration means. I'm not sure how to explain it right.
Thank you very much!

Answer:
ais a pointer to a function with two parameters of typeintthat returns achar*.

The ``Clockwise/Spiral Rule''

cdecl: C gibberish ↔ English


Question:
This question already has answers here:How do I determine the size of my array in C?(25 answers)Closed3 years ago.

For example a code like:

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

Is there anyway to get the 5 in arr[5]?
I haven't learnt C++ before.

Answer:
You can get it by getting the array size and divide it by the size of a single element:

```
int arr[5] = {1, 2, 3, 4, 5};
size_t lengthOfArr = sizeof(arr)/sizeof(arr[0]) ;
```


Question:
With C igraph we can create a graph from an adjacency list withigraph_adjlist.
It there a way to create a graph from an incidence list ?

Answer: Unfortunately no such functionality is implemented. Feel free to open an issue athttps://github.org/igraph/igraphto suggest such a feature. Alternatively, if you want to discuss it, theigraphproject recently opened a new forum to facilitate discussions, seehttps://igraph.discourse.group.


Question:
With C igraph we can create a graph from an adjacency list withigraph_adjlist.
It there a way to create a graph from an incidence list ?

Answer: Unfortunately no such functionality is implemented. Feel free to open an issue athttps://github.org/igraph/igraphto suggest such a feature. Alternatively, if you want to discuss it, theigraphproject recently opened a new forum to facilitate discussions, seehttps://igraph.discourse.group.


Question:
Is there any way to get freetype man pages?

I can't find them and have to use the documentation on the web.
The problem is when I don't have internet access.

Answer:
Freetype doesn't provide man pages. Only html documentation.

You can download it fromhere(see the archives that have "-doc" in their name).


Question:
What is a difference between((int) a)and(int(a))?

Is the second expression valid in pure "С" (not "C" under "C++")?

Answer:
There's no difference between them in C++. However, C supports only the first cast operation.

See this example fromtutorial:

```
double x = 10.3;
int y;
y = (int) x;    // c-like cast notation
y = int (x);    // functional notation
```


Question:
This question already has answers here:Using true and false in C(15 answers)Closed3 years ago.

I thought that C interpretedtrueas1but now I'm having doubts.

Full code (compiled with GCC 5.1):

```
if(true && true) // Error: 'true' undeclared (first use in this function)
{
}
```

Why does this happen?

Answer:
trueis not a keyword in C like it is in C++.

To access it you'll have to#include <stdbool.h>.


Question:
```
int ch;
  scanf("%c", &ch); //Read a character (%c)
  printf("You entered char %c %d\n", ch, ch);
  return 0;
```

expected output:  You entered char A 65Actual output: You entered char A 32577

Answer: chis of type int andscanf("%c", &ch)copies abytein to address location pointed by&ch.MachineEndiannessdecides where thecharvalue from iostream stored. ifchon stack garbage values present in remaining bytes ofch


Question:
I'm trying to access the whole array from a struct in a function, to compare two elements for no duplication. However, I am receiving anexpected expression errorinqueue.id[].

```
int count = sizeof(queue.id[]) / sizeof(queue.id[0]);
```

Answer:
```
int count = sizeof(queue.id[]) / sizeof(queue.id[0]);
```

should be

```
int count = sizeof(queue.id) / sizeof(queue.id[0]);
```


Question: I have twouint64variablesvar_1andvar_2and I want to set the bits ofvar_1according to the low-order6bits ofvar_2. How can I do this in C language?

Answer:
Like so:

```
uint64_t mask = 0x3F;
var_1 &= (~mask);
var_1 |= (var_2 & mask);
```


Question:
FILE *fopen(const char *filename, const char *mode);

I saw that some people only put the name of the file inside the "filename" part, some others put the entire path

example

FILE *fopen("mytext.txt", r);FILE *fopen("/myfolder/mytext.txt", r);

which is the correct one?

Answer:
If the file is in current directory when you run the program - no.

If it's not - yes, you will need to specify the path (absolute or relative to current directory)


Question: I have twouint64variablesvar_1andvar_2and I want to set the bits ofvar_1according to the low-order6bits ofvar_2. How can I do this in C language?

Answer:
Like so:

```
uint64_t mask = 0x3F;
var_1 &= (~mask);
var_1 |= (var_2 & mask);
```


Question:
Is there any other way of passing user's parameters into a program other than through

./program argument1 argument2

whereargument1andargument2will be passed on tomain'sargv[]?

Answer: Your application could read the values from the standard input, a configuation file or even environnent variables.


Question:
I'm using theVIPS libraryfor manipulating images and adding text to them. I want to know how to add spacing to characters in text?

The following image is an example of what I'm talking about.

Answer:
You can usepango markup. For example:

```
vips text x.png '<span letter_spacing="10000">Hello!</span>' --dpi 300
```

To make:


Question:
Is there any other way of passing user's parameters into a program other than through

./program argument1 argument2

whereargument1andargument2will be passed on tomain'sargv[]?

Answer: Your application could read the values from the standard input, a configuation file or even environnent variables.


Question: I'm currently developing a piece of software on a Raspberry Pi. Because I have to control motors very precisely i developed a C script, that does that for me. My current problem is, that I didn't found any solid method to transfer a list of signed floats from a Python3 Script to a C script. It is really important, that the method is fast.

Answer: You could use a socket to send data from one script to the another.


Question: I'm currently developing a piece of software on a Raspberry Pi. Because I have to control motors very precisely i developed a C script, that does that for me. My current problem is, that I didn't found any solid method to transfer a list of signed floats from a Python3 Script to a C script. It is really important, that the method is fast.

Answer: You could use a socket to send data from one script to the another.


Question:
I would like to do something like setting a macro name that activates portions of my code....

g++ -DVERBOSE=1 main.cc

during the Bazel build command:

bazel build //myproj:main

Is it possible?

Answer:
bazel build //myproj:main --cxxopt=-DVERBOSE=1

Or, use thecoptsattribute incc_*targets.

https://docs.bazel.build/versions/master/user-manual.html#flag--cxxopt


Question:
Is the codeint const*const pointer1=&constantVariable;legal?

If it isn't, what is the correct way of specifying it?

Answer:
It's OK!
Inint const*const pointer1=&constantVariable, the firstconstindicates that you couldn't change the value by *pointer1; the secondconstindicates the value of pointer itself(an address) couldn't be changed too. Actually pointer1 can point to a constant integer, even a normal variable.But it can't be set twice.


Question: Self explanatory question. Can we get multiple UDP packets in one socket recv call when using Multicast?

Answer:
When usingrecvfromorrecvon a UDP socket, you will only ever receive one complete packet at a time.

This applies to both unicast and multicast packets.


Question: I triedlocate kmalloc_sizes.hbut didn't find the file. And I usedapt-fileto search but couldn't find the package. How can I get this header file?

Answer:
The file you're looking for is actually calledkmalloc_sizes.h.

You can get it by installing the Linux kernel headers:

```
sudo apt-get install linux-headers-$(uname -r)
```

Ref:https://askubuntu.com/questions/75709/how-do-i-install-kernel-header-files


Question:
Is there any piece of code I can write or any other way to check which version of the C language my compiler is compiling?

I was wondering if there was a way for me to see if the compiler in question is C89, C99, C11, C18 etc. Perhaps utilizing__STDC_VERSION__.

Answer:
You can look at the__STDC_VERSION__macro, which hast the format YYYYMM and from that deduce whether you run C89, C99, C11 or C18.

See alsoWhat is the __STDC_VERSION__ value for C11?


Question:
I want to code a matrix calculator, and for that I need to ask the user for it's size,but when I'm declaring a 2d array it won't let me put a variable as a size, so what can I do?

```
int main()
{
    int n;
    print_enter_matrix_size();
    scanf("%d", &n);
  int matrix[n][n];
    return 0;
}
```

Answer: You can use dynamics arrays. For that you can use malloc to declare the size you want, Try this:allocate matrix in C


Question:
I have a really simple question:

```
const char *y = "string_test";
x = &y;
```

What type is x ?

Thanks in advance for your answers !

Answer:
Assuming you had a typo in your question, and the code is:

```
const char *y = "string_test";
x = &y;
```

x shall be defined as:

```
const char** x; // x is a pointer(Address of) a pointer to a constant char/string
```


Question:
I have a really simple question:

```
const char *y = "string_test";
x = &y;
```

What type is x ?

Thanks in advance for your answers !

Answer:
Assuming you had a typo in your question, and the code is:

```
const char *y = "string_test";
x = &y;
```

x shall be defined as:

```
const char** x; // x is a pointer(Address of) a pointer to a constant char/string
```


Question:
I am new to C.
I just want to know why initializing the array of int with int is working and why initializing an array of char with char is not working. Oram I wrong thinking that "1" is a char?

```
#include <stdio.h>

int main()
{
     int incoming_message_test[2] = {1, 2}; // why does this work?
     char incoming_message[2] = {"1", "2"}; // why does this not work?

     return 0;
}
```

Answer: You must change"1", "2"with'1', '2'


Question:
I don't seem to understand what's happening here

```
#include <stdio.h>

int var = 5;

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

Why does this program print a garbage value when the value of var is assigned to be 5?

Answer:
the local var has priority on the global var.
So the compiler translate it as (local) var = (local) var


Question:
I don't seem to understand what's happening here

```
#include <stdio.h>

int var = 5;

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

Why does this program print a garbage value when the value of var is assigned to be 5?

Answer:
the local var has priority on the global var.
So the compiler translate it as (local) var = (local) var


Question:
I am trying to find "python.exe" in szExeFile after aProcess32NextWcall.

I tried doing a

```
if(strcmp(lppe->szExeFile,"python.exe") == 0){
    //do stuff
}
```

but the check always fails despite the process running.
I have also tried using strncmp but it does not change anything.

What am I doing wrong?

Answer: Process32NextW()seems to usePROCESSENTRY32Wstruct with wide character strings. Trywcscmp()instead ofstrcmp().


Question:
I am trying to find "python.exe" in szExeFile after aProcess32NextWcall.

I tried doing a

```
if(strcmp(lppe->szExeFile,"python.exe") == 0){
    //do stuff
}
```

but the check always fails despite the process running.
I have also tried using strncmp but it does not change anything.

What am I doing wrong?

Answer: Process32NextW()seems to usePROCESSENTRY32Wstruct with wide character strings. Trywcscmp()instead ofstrcmp().


Question:
I'm trying tocompare a llvm Type and a Type*. I'm using the LLVM C APIs. Is there any possible method to do this?

I haveType*because I did LLVMTypeOf api to get the type from an LLVM Value. So if I can get theType from a Value, it would also fix the issue.

Answer: Types are unique in LLVM world, so you could compare their addresses.


Question:
I'm trying tocompare a llvm Type and a Type*. I'm using the LLVM C APIs. Is there any possible method to do this?

I haveType*because I did LLVMTypeOf api to get the type from an LLVM Value. So if I can get theType from a Value, it would also fix the issue.

Answer: Types are unique in LLVM world, so you could compare their addresses.


Question:
Is there a way to calculate the maximum value representable byunsigned intwithout usinglimits.h(so noUINT_MAX) or without using

```
unsigned int z = 0;
z = z - 1;
```

Answer:
The simplest way to do this is to simply assign -1 to anunsigned int.  You could also assign~0uto it.

If that's not acceptable, while inefficient, you could do something like this:

```
unsigned int i = 0;
while (i+1 > 0)
  i++;
printf("i=%u\n", i);
```


Question:
I have a file where I have saved C float arrays as binary data.
Is it possible to load this binary data into a Python list now?

Answer:
It's possible to do that using Numpy.memmap. Something like this:

```
import numpy as np
arr = np.memmap("filename", dtype="int32", mode="r")
```

Replace "filename" with the path to your array file and "int32" with the type you used in your C array.


Question:
I have a file where I have saved C float arrays as binary data.
Is it possible to load this binary data into a Python list now?

Answer:
It's possible to do that using Numpy.memmap. Something like this:

```
import numpy as np
arr = np.memmap("filename", dtype="int32", mode="r")
```

Replace "filename" with the path to your array file and "int32" with the type you used in your C array.


Question:
```
int x = 0x76543210;
char *c = (char*) &x;

Big endian format:
------------------
Byte address  | 0x01 | 0x02 | 0x03 | 0x04 |
              +++++++++++++++++++++++++++++
Byte content  | 0x76 | 0x54 | 0x32 | 0x10 |
```

why does the byte address ox01 stores only 0x76 not 0x765?

Answer:
A byte is 8 bits, and in hex that goes from 0x00 --> 0xFF (0 -> 255).

0x765 - which is hex - cannot possibly fit in 8 bits.


Question:
Let's say x=29 and y=13. What does this line of code actually do:

```
x%=y-3;
```

I just don't really know what does this mean?

Answer:
Modulo operator gives you remainder from division.

a % bis the remainder of division a by b

x %= y - 3is equal tox = x % (y - 3)and gives you remainder from division x by (y - 3) expression.


Question:
I saw this code:

```
char *str;
// Some code
if (! str || ! *str)
    return str;
```

Why need to check! *str？ Isn'tif (! str)enough?

Answer:
It depend on what you want to check:

The!strcheck is str is NULL.The!*strchecks that the first char instris NUL byte ('\0')

Combined, they will return 's' if s is NULL, or s point to a NUL char


Question:
I saw this code:

```
char *str;
// Some code
if (! str || ! *str)
    return str;
```

Why need to check! *str？ Isn'tif (! str)enough?

Answer:
It depend on what you want to check:

The!strcheck is str is NULL.The!*strchecks that the first char instris NUL byte ('\0')

Combined, they will return 's' if s is NULL, or s point to a NUL char


Question:
I have 2 files:stack.handstack.c. Both of them have a undefined typeelem_type.

So my question is:Can I leave them undefined until I include the stack.h and then give it a definition depended on the need of the calling file ?

Answer:
You cannot leave undefined type in stack.c in C because when a compiler tries to compile stack.c it won't be able to determine the type.

In C++ this is feasible via template.


Question:
How do we add new line to output buffer using printf in C?

Like in c++ we use endl, what do we use in C?

```
cout<<endl;
```

Answer:
You can write like this  printf("whatever message you want \n")
"\n" added at the end output a new line in buffer.


Question:
Let's say I have the following piece of code:

```
void foo(){
    static int bar = 0;
    bar++;
}
```

Does two successive calls to this function reset the value of the variable?

Answer: Initialization occurs when an object is created. For static objects, their lifetimes start when program execution starts. They are not reinitialized or reassigned when execution reaches the statements that define them.


Question:
How should I read each of these definitions ?

const char *arguments[]char *const arguments[]

I saw examples ofexecl()code using the first form but could not make it work under Linux and had to use the second form ?

Answer:
const char *arguments[]

argumentsis an array of unknown size of pointers toconstqualifiedchar.

char *const arguments[]

argumentsis an array of unknown size ofconstqualified pointers tochar.


Question: they used to ship sources for the C runtime in previous versions of VS. Would someone perhaps know what would be the default location in VS2017? Do they still ship the code with it?

Answer:
Ah.. found it in Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\crt
I hope the refactored code is as beautiful as the path is long.


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

int main(){
    int a[1] = {1};
    int b = 6;
    printf("%d\n", a[-1]);
    printf("%d\n", b);
    //printf("%d\n", (a-1 == &b));
    return 0;
}
```

I wrote the above code and found out it didn't work properly when using gcc or mingw to compile it, but when I uncommented 8th line, everything is just fine. Could anyone explain the code for me?

Answer: Thea[-1]is undefined memory space.


Question:
This question already has answers here:Multiplication and division: weird output in c(3 answers)Closed4 years ago.

I am using c preprocessor directive. I want to know how does this program work?

```
#define PRODUCT(x) (x*x)
   main()
   {
   int i=3,j;
   j=PRODUCT(i+1);
   printf("\n%d",j);
   }
```

The output is

```
7
```

Answer:
Why do I get 7 withPRODUCT(i+1)?

because3+1*3+1==3+3+1

Try#define PRODUCT(x) ((x) * (x))


Question: I'm looking for an example of  eBPF to write a seccomp filter, but I can't find none. Could someone tell me if is possible to use eBPF to write seccomp filter?

Answer:
Seccomp does not work with eBPF at the moment (only cBPF).

There wasa discussionnot long ago on that topic on the Linux networking mailing list. The eBPF maintainer is against adding eBPF support to seccomp.


Question:
I'm looking to break up binary into blocks or 8 digits. Is there a way to do the following in C without doing a second print line?

```
printf("%d%c", number>>(i-1) & 1, (i%8==0) ? ' ' : '');
```

Or is it not possible to do the "empty char" and I should add a second line to check for that?

Answer:
There's no such thing as an empty char. You can use%swith strings.

```
printf("%d%s", number>>(i-1) & 1, (i%8==0) ? " " : "");
```


Question: Is it possible to execute C code in a C program? For instance when reading input from the user.

Answer:
There's nothing built in to do this.

This simplest thing to do is save the given code to a separate file, invoke GCC as a separate process to compile the code, then run the compiled code in a new process.


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

int main()
{
    int p=10,q=20,r;
    if(r = p = 5 || q > 20)
     printf("%d",r);
     else
      printf("No output");

    return 0;
}
```

The output is 1 but how?
Please explain

Answer:
Precedence. To be more clear:

```
if(r = p = 5 || q > 20)
```

is the same as

```
if(r = p = (5 || q > 20))
```

5 is truthy, so the boolean expression evaluates to 1, which is then assigned tor


Question:
I get 'Permission denied' whenever I try to compile and run a program in Visual Studio code, in my Mac. How do I solve this?

Note the 'permission denied' in this picture

Answer:
You need to say something like

```
gcc -o film film.c
```

and then

```
./film
```

film.cis your source file.  In the example I've shown, the-oflag asksgccto put its output -- the compiled program -- in filefilm(with no conventional suffix).That'sthe file you want to run.


Question: Does using fopen(fileName, "w") overwrite the blocks being used by a file, or does it set the blocks that were once being used as free and then start writing to new blocks?

Answer: The C standard doesn’t specify how it’s implemented. So, itmightoverwrite the blocks, but there’s no guarantee. On a Unix/Unix-like environment, for example, it’s most likely a wrapper aroundopen()with some internalFILE *manipulation that we need not worry about.


Question:
This question already has answers here:What is special about numbers starting with zero?(4 answers)Closed4 years ago.

I was trying the following code

```
printf("%d", 010 % 10);
```

I was expecting it output be 0, but it is 8.

Why? Is there any way to get the last digit of an integer which is taken as input.

Answer:
Any numeric literal in c or c++ starting with a zero will be interpreted asoctal

So your calculation is 8 modulo 10, which is 8


Question:
In GTK3, how do I get a DrawingArea to respond keyboard events?
Should I connect the DrawingArea with a signal or is it more compicated?
I'm using GTK3 with the C language.

Answer: I fianlly found the solutionhere. I only connected the signal, but the GTK_CAN_FOCUS also need to be set for the drawingrea.


Question:
Whenever I try to compile c/cpp files it gives this error:

```
gcc: fatal error: cannot execute ‘as’: execvp: No such file or directory
compilation terminated.
```

I have also tried to include full path of file while compiling but same error occured.
Just to be sure of version mismatch I looked for both gcc and g++ version but both are same,
gcc/g++ version: 9.1.0.

How can I fix this?

Answer: ascommand is frombinutils. Have you installed this package?


Question:
I want a C macro that will expand into a function with an extra parameter based on a condition.

Something like this:

```
#define EXTRA 7
#ifdef ADD_ONE_MORE_ARG
#define dothis(...) dothat(EXTRA,...)
#endif
```

Such thatdothis(5);is expanded intodothat(EXTRA, 5);but I can't remember the syntax. TheanswerI found here didn't help. Thanks.

Answer:
```
#define callx(...) call(EXTRA, __VA_ARGS__)
```


Question:
Can someone explain me please what is RTL in the context of driver development for Windows ?

Development Tool : Visual studio 2019
Driver Type: Kernel Mode (kmdf).
Programming Language : C.

Answer: Many kernel API functions start with theRtlprefix - that's an abbreviation of Run Time Library.


Question: For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?

Answer:
"If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?"

Yes. The client will get the data that was sent before the FIN packet that closes the socket.


Question:
Can someone explain me please what is RTL in the context of driver development for Windows ?

Development Tool : Visual studio 2019
Driver Type: Kernel Mode (kmdf).
Programming Language : C.

Answer: Many kernel API functions start with theRtlprefix - that's an abbreviation of Run Time Library.


Question: For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?

Answer:
"If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?"

Yes. The client will get the data that was sent before the FIN packet that closes the socket.


Question:
What does this statement mean in C language (assuming s1 and s2 are character arrays)?

```
(s1[i] = s2[i]) != '\0'
```

Answer:
Consideringstrings are\0terminated by the standard.

```
(s1[i] = s2[i]) != '\0'
```

it will assigns2[i]tos1[i]then it will compare whether assigned value is\0or not.

It is usually used to break the loop while copying contents from one string to another.


Question: I'm trying to implement ElGamal cryptosystem and I decided to use OpenSSL to generate big primes. I've seen several functions that generate big random numbers but I haven't found a function to generate prime numbers. What function should I use?

Answer: That's a function of the underlying Big Number (BN) implementation rather than a specific high level crypto function, so I guess you'd useBN_generate_prime_ex.


Question: I have a binary mask which at some point I'm updating. It's ok for 1s in my old mask to become 0s but the other way around is not allowed. How can I assert using some binary operations that none of the 0s in the mask have turned into 1s?

Answer:
```
if (~old & new)
```

If you also want to know which bits changed from 0 to 1, just read each bit inbits = ~old & new;. If you just want to know if any 0s became 1s, that first line of code will do.


Question: I have a binary mask which at some point I'm updating. It's ok for 1s in my old mask to become 0s but the other way around is not allowed. How can I assert using some binary operations that none of the 0s in the mask have turned into 1s?

Answer:
```
if (~old & new)
```

If you also want to know which bits changed from 0 to 1, just read each bit inbits = ~old & new;. If you just want to know if any 0s became 1s, that first line of code will do.


Question:
I'm running this code and getting some garbage value while printing *ptr. What could be the possible reason and how can I avoid getting that?

```
# include <stdio.h>
int main()
{
  int test = 1;
  int *ptr = &test;
  *ptr++ = 10;
  test++;
  printf("\nThe value is %d", *ptr);
}
```

Answer:
You movedptrwithptr++. Why?

Don't do that.


Question: I know the C11 standard definesrsize_tassize_tin the optional Annex K, but in what header file(s)? Where does the C standard say this type should be defined?

Answer:
K.3.3  Common definitions<stddef.h>

The header<stddef.h>defines a type.The type isrsize_twhich is
  the typesize_t.

Quoting thedraft.

Reading further, this is also defined in<string.h>,<stdlib.h>,<stdio.h>,<wchar.h>and<time.h>. There may be others.


Question: I know the C11 standard definesrsize_tassize_tin the optional Annex K, but in what header file(s)? Where does the C standard say this type should be defined?

Answer:
K.3.3  Common definitions<stddef.h>

The header<stddef.h>defines a type.The type isrsize_twhich is
  the typesize_t.

Quoting thedraft.

Reading further, this is also defined in<string.h>,<stdlib.h>,<stdio.h>,<wchar.h>and<time.h>. There may be others.


Question:
I'm looking atunsigned char(byte) arrays ingdb, i.e.

```
(gdb) p/x buf@4
$76 = {0xac, 0xa, 0xb0, 0xa}
```

Is there a way of forcing the preceding 0s? i.e output like:

```
$76 = {0xac, 0x0a, 0xb0, 0x0a}
```

Answer:
From the gdbdocumentation:

'z'Like 'x' formatting, the value is treated as an integer and printed as hexadecimal, but leading zeros are printed to pad the value to the size of the integer type.

So...

```
(gdb) p/z buf@4
```


Question:
I'm wondering if the fopen command is smart enough to stop reading a file if it's to large and then wait for some proceeding read command to continue reading.

For that matter, how large is _iobuf?

Answer:
fopen(...)doesn't do any size checks; it just returns a file pointer. Are you thinking offread(...), by any chance?

You can always find the size of the file that you are going to read by usingstat(...)system call.


Question:
I'm trying to get the most significant bit of an unsigned 8-bit type in C.

This is what I'm trying to do right now:

```
uint8_t *var = ...;
...
(*var >> 6) & 1
```

Is this right? If it's not, what would be?

Answer:
To get the most significant bit from a memory pointed to byuint8_tpointer, you need to shift by 7 bits.

```
(*var >> 7) & 1
```


Question: I would like to know how to define a char array, in C, of three elementsa,b,c, whereais located on one first octet,bin one second andcin one third.

Answer:
Well,
In C, the size ofcharit's 1.
I think we can't know if it's 1 octet or more (or less).

So,

```
char tab[3] = {'a','b','c'};
```

doesn't work ?


Question:
When I build a simple console app with clang, it works fine:

void main() { puts("HELLO"); }

But when I create a Windows app withWinMain, I can't see stdout.

There must be a flag that fixes it, like MinGW's-mconsole

Answer:
A quick stdout-enabler for otherwise GUI apps:

```
if (AllocConsole())
{
    FILE* fi = 0;
    freopen_s(&fi, "CONOUT$", "w", stdout);
}
```

and thenstd::coutandprintfwork.


Question:
always the first line of my file is empty

whst can i do ?

```
printf("donner n");
scanf("%d",&n);

 for(int i=0;i<n;i++)
 { gets(ch);
   fprintf(f,"%s\n",ch);} ```
```

Answer:
change

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

to

```
scanf("%d\n",&n);
```

Should be able to get the results you want

Because the first empty line is a newline character that is not read at scanf.


Question:
always the first line of my file is empty

whst can i do ?

```
printf("donner n");
scanf("%d",&n);

 for(int i=0;i<n;i++)
 { gets(ch);
   fprintf(f,"%s\n",ch);} ```
```

Answer:
change

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

to

```
scanf("%d\n",&n);
```

Should be able to get the results you want

Because the first empty line is a newline character that is not read at scanf.


Question:
I'm trying to read from a .csv file in C and it works for my character arrays, but not for my long.

```
char fname[24];
char lnem[48];
char email[36]
long phone;

fscanf(fp, "%[^,],%[^,],%[^,]%*s,%lf", fname, lname, email, phone);
```

Answer:
The line should be

```
fscanf(fp, "%[^,],%[^,],%[^,],%ld", fname, lname, email, &phone);
//           removed %*s ----^  ^---- format specifier   ^---- address-of operator
```


Question:
I am trying to setup my eclipse to run some C but there is this long tool in the toolbar which i am not even using and I do not know how to disable it.

Can someone help me please?

Answer:
This isWindow|perspective|customise|Tool Bar Visibility

Perhaps this is a clue (photon launch bar):

https://www.eclipse.org/forums/index.php/t/1095011/

They suggest it is on the launch bar preference page.


Question:
I want to put the value of anarrayinto a float integer.

```
main(){
    float a;
    char array[4]="12.1";
    a=atoi(array);
    printf("%f",a);
}
```

When I uses this program, it gives12.000000as output but I want12.100000as output. Thanks in advance.

Answer:
Use of this :

atof()— Convert Character String to Float :

```
#include <stdlib.h>
double atof(const char *string);
```

This linkexplains about that.


Question:
Was working with some SASL code today and noticed the==in the below snippet. I'm no C expert but the only way I've ever used that operator was to test equality. Bug?

```
if ( !conn ) {
        rc == LDAP_SUCCESS;
        goto done;
}
```

Answer:
That statement does nothing. It's a bug.

Now, you COULD assign (rc == LDAP_SUCCESS) to a variable, which would store the boolean result of that operation (1 if true, or 0 if false).


Question:
I use Windows Subsystems for Linux(WSL), Ubuntu. I try compile simple code.

I get errors in WSL.

But, it works well in Visual Studio.

Answer:
gets_s()is a "secure" alternative togets()defined in the Microsoft C Runtime Library.  It is not included in the GNU C library used in Linux.

For portability usefgets()on thestdininput stream instead.


Question:
I use Windows Subsystems for Linux(WSL), Ubuntu. I try compile simple code.

I get errors in WSL.

But, it works well in Visual Studio.

Answer:
gets_s()is a "secure" alternative togets()defined in the Microsoft C Runtime Library.  It is not included in the GNU C library used in Linux.

For portability usefgets()on thestdininput stream instead.


Question:
This question already has answers here:How are floating point numbers stored in memory?(7 answers)Closed4 years ago.

If we create one variable of data type float and assign any value to it then how this is stored in memory?

float var = 13.34;

Answer: Float is a 4-byte size type, which consist of sign, exponent and mantissa (described in IEEE 754). The last bit represents sign, 8 followed bits are exponent and rest are mantissa.


Question:
This question already has answers here:How are floating point numbers stored in memory?(7 answers)Closed4 years ago.

If we create one variable of data type float and assign any value to it then how this is stored in memory?

float var = 13.34;

Answer: Float is a 4-byte size type, which consist of sign, exponent and mantissa (described in IEEE 754). The last bit represents sign, 8 followed bits are exponent and rest are mantissa.


Question: So I havechar **sentencewithsentence[0] = string0, sentence[1] = string1, etc. Is there a way I can print the entire array in lldb? So that it shows up as{string0, string1, ...}

Answer:
This is answered in:

View array in LLDB: equivalent of GDB's '@' operator in Xcode 4.1

particularly, you can use theparraycommand in any recent lldb.

There isn't a way to do this in the Xcode Locals view, but you can do this in the Xcode Debugger Console.


Question: So I havechar **sentencewithsentence[0] = string0, sentence[1] = string1, etc. Is there a way I can print the entire array in lldb? So that it shows up as{string0, string1, ...}

Answer:
This is answered in:

View array in LLDB: equivalent of GDB's '@' operator in Xcode 4.1

particularly, you can use theparraycommand in any recent lldb.

There isn't a way to do this in the Xcode Locals view, but you can do this in the Xcode Debugger Console.


Question:
```
(gdb) set disassemble intel
Ambiguous set command "disassemble intel": disassemble-next-line, disassembler-options.
```

When i set the disassembly syntax to intel, it show this error.

Answer:
Please use:

```
set disassembly-flavor intel
```

seeGDB Manualfor more details


Question:
I have existing C program which i want to call from tibco bw6. Is there any direct approach, like bw allow to invoke java code.

One possible solution is to use java invoke and jni. Direct call will be more preferable if possible

Answer:
if you have the .exe file you can use External Command activity otherwise I do not see any other simple solutions than to use swig with jni.

Regards


Question: I was wondering if there is a way to run a random statement in C that I created, such as a function. I know how to run a random integer but not how to randomly pick from a list of statements that I created.

Answer:
you can do like this with yourrandomValuethat you got fromrand()function:

```
int statement = randomValue % nState;
```

in above code, I assume that your program havenSatestates and you can use this variable in yourswitch.


Question: In system programming class, we are told that all system calls are made in c. For example opening a file for reading/writing. Does java run c codes behind?

Answer:
Yes java runs C Code behind the scene. Using the native keyword.

For Instance: System.currentTimeMillis() is a Native Method

Here is a good explaination how to use Native code:https://www.baeldung.com/java-native


Question: In system programming class, we are told that all system calls are made in c. For example opening a file for reading/writing. Does java run c codes behind?

Answer:
Yes java runs C Code behind the scene. Using the native keyword.

For Instance: System.currentTimeMillis() is a Native Method

Here is a good explaination how to use Native code:https://www.baeldung.com/java-native


Question:
My code uses ZLIB, and it seems that there are problems in usingfmemopen()and ZLIB functions afterwards...

Is there an equivalent offmemopen()in ZLIB? Or how can I create it if no equivalent exists?

Answer: No there is not. Furthermore, there is no need for such a thing, since zlib provides in-memory functions for compression and decompression.


Question:
I'm reading the C Programming Language (chapter 5), and I'm confused by this example:

```
int n, array[SIZE], getint(int *);
```

Why is this function call in here like that? Is this just some tricky example and invalid code?

Answer:
It's not calling the function; it's declaring its prototype.
It's equivalent to:

```
int n;
int array[SIZE];
int getint(int*);
```


Question:
```
a[b]
```

Is equivalent to*(a + b), so...

```
a[b & c]
```

Where&has a lower operator precedence than+, would this result in*(a + b & c)or*(a + (b & c))?

Answer:
TheC Standard, § 6.5.2.1,Array Subscriptingsays:

The definition of the subscript operator[]is thatE1[E2]is identical to(*((E1)+(E2)))

Note the brackets surroundingE2. The latter expression (*(a + (b & c))) is the correct outcome.


Question:
I'm currently creating a little game, and I need to create a condition.

In pseudo-code, it would look like something like this :

```
if (a < x with x included in [b -10; b +10])
{
    then c = 2
}
```

Is there an easy way to do this ?

I know it may not be really clear, so ask me further details if you didn't understand.

Answer:
```
if(a < x && x >= b-10 && x <= b + 10){

}
```


Question:
I'm currently creating a little game, and I need to create a condition.

In pseudo-code, it would look like something like this :

```
if (a < x with x included in [b -10; b +10])
{
    then c = 2
}
```

Is there an easy way to do this ?

I know it may not be really clear, so ask me further details if you didn't understand.

Answer:
```
if(a < x && x >= b-10 && x <= b + 10){

}
```


Question:
Is it bad practice when I assign new pointer to pointer without free?

```
char **arr = malloc(sizeof(*arr)*9);

...
...

arr[5] = strdup("sys");
arr[6] = strdup("var");
arr[7] = strdup("home");
arr[8] = NULL;

arr[5] = arr[6];
arr[6] = arr[7];
arr[7] = NULL;
```

Answer: Yes.  Since that pointer you reassigned (e.g. arr[5]) is no longer accessible it's memory can't be free'd and it is a memory leak.


Question:
I just did this

```
printf( (n==0) ? " %d" : " %3d", n );
```

but is there a conditional format descriptor?

So, it would mean something like"if this is very short use such and such padding, but, if this is longer use such and such padding."

Can do?

Answer:
There's no conditional, but you can use * to specify the width in the arguments. e.g.:

```
printf(" %*d", (n==0)?1:3, n);
```


Question: In a Windows application, I have aGetFirmwareEnvironmentVariableAfunction to read a firmware environment variable. Is there any way to write something in this variable in uefi driver and read from it later in Windows?

Answer:
The function to set an NVRAM variable is called SetVariable() and is available to UEFI drivers via EFI_RUNTIME_SERVICES table.

To know more about it's interface and usage, read chapter 7.2 Variable Services of theUEFI 2.6 specification.


Question:
Are there any different between those both (ptrfun1andptrfun2)?

```
int fun(int num){
    num *= num;
    return num;
}

int main(){
    int (*ptrfun1)(int num) = fun;
    int (*ptrfun2)(int num) = &fun;
```

Does both point to the functionfun?

Answer:
There is no difference at all.

A functiondecaysto a function pointer.


Question:
Are there any different between those both (ptrfun1andptrfun2)?

```
int fun(int num){
    num *= num;
    return num;
}

int main(){
    int (*ptrfun1)(int num) = fun;
    int (*ptrfun2)(int num) = &fun;
```

Does both point to the functionfun?

Answer:
There is no difference at all.

A functiondecaysto a function pointer.


Question:
What is the specifier%[^s]used for?

sis a variable.

In which cases can I use this specifier?

Answer:
The%[format specifier toscanfwill match a sequence of characters matching those that are listed between[and].  If the first character is^, then it matches charactersexcludingthose characters.

In your case%[^s]means "match any character besides the characters's'.sisnota variable in this case.


Question:
I don't fully understand how the "-" operator affects the following code:

```
#define COMP(x) ((x) & -(x))

unsigned short a = 0xA55A;
unsigned short b = 0x0400;
```

Could someone explain what COMP(a) and COMP(b) are and how they are calculated?

Answer:
(x) & -(x)is equal to the lowest bit set inxwhen using 2's complement for representing binary numbers.

This meansCOMP(a) == 0x0002;andCOMP(b) == 0x0400;


Question: I'd like to look at the source code Apache uses to process .htaccess files. I've downloaded and grepped the Apache source files with no luck.

Answer: I'm suspicious of your ability to grep..  I just downloaded the httpd source and it mentionshtaccesseverywhere.  Why not start by looking at the functionap_parse_htaccessdefined inserver/config.c.


Question:
This question already has answers here:What does "%3d" mean in a printf statement?(8 answers)Closed4 years ago.

can someone explain what the 25 in front of d does in an printf command ?
I have searched the web but don't find a good answer.

e.g.:
    printf("%-30s %10lu %25d - %ud\n", "unsigned int", sizeof(unsigned int), 0, UINT_MAX);

Thanks in advance.

Answer: %d indicates decimal value.25 total field width.


Question:
This question already has answers here:What does "%3d" mean in a printf statement?(8 answers)Closed4 years ago.

can someone explain what the 25 in front of d does in an printf command ?
I have searched the web but don't find a good answer.

e.g.:
    printf("%-30s %10lu %25d - %ud\n", "unsigned int", sizeof(unsigned int), 0, UINT_MAX);

Thanks in advance.

Answer: %d indicates decimal value.25 total field width.


Question: I have a MIDI controller with several knobs. Is it possible to query state of all values, which these knobs have, when I connect to the device usingmidiInOpenfunction without physically moving each of them?

Answer:
There is no standard MIDI message to inquire about the current state of a controller; messages are sent only when something changes.

Unless your controller has a vendor-specific extension that does exactly what you want, this is not possible.


Question:
I want to print function names (imported, exported, normal/local functions) but not variable names and so on.

SymEnumSymbolsExenumerates all symbols, but I only want functions.
Also can not find how to distinguish functions and variables insidecallbackfunction.

Is there a way to enumerate only functions?

Answer: SYMBOL_INFOpassed to your callback hasFlags, and there isSYMFLAG_FUNCTIONfor functions


Question:
I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer.
The AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows

Answer: Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.


Question:
I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer.
The AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows

Answer: Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.


Question:
I am writing a C program that does many comparisons and I was wondering if this actually saves memory.

Any help appreciated

Answer: No, it does not. Using a tricky syntax to do something that there's a well-known syntax for is never the right answer. You should use x==a.


Question: "Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32."

Answer:
Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.

This is as opposed to an experimental compiler or an in-development compiler.


Question: "Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32."

Answer:
Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.

This is as opposed to an experimental compiler or an in-development compiler.


Question: "Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32."

Answer:
Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.

This is as opposed to an experimental compiler or an in-development compiler.


Question:
what does asterisk(*++argv) mean?

```
void main (int argc, char *argv[])
{
 while (--argc)
  {
    printf ("%s\n", *++argv);
  }

}
```

Answer:
hereargvis a pointer to a pointer ofchartype

*argvpoints to the first argument string in the argv array, which is same asargv[0], similarly*(argv + 1)andargv[1]point to second argument string and so on..

Pointers in C: when to use the ampersand and the asterisk?


Question:
What is_ALPHA_macro?
I found this macroin this code.
What do you use this　macro  for?
Please tell me this macro or its references.

Answer:
I believe it is a macro that is#defined if the file is being compiled forDEC Alpha architecture. With Windows, of course, one must note that Alpha support was there for

Windows NT (discontinued after NT 4.0; and pre-release Windows 2000 RC1)

it means that in practice it is never#defined.


Question:
What is_ALPHA_macro?
I found this macroin this code.
What do you use this　macro  for?
Please tell me this macro or its references.

Answer:
I believe it is a macro that is#defined if the file is being compiled forDEC Alpha architecture. With Windows, of course, one must note that Alpha support was there for

Windows NT (discontinued after NT 4.0; and pre-release Windows 2000 RC1)

it means that in practice it is never#defined.


Question:
Is there function in a C library that iterates through an array and checks if two characters are next to each other?

For example :array[30] = "example@.com"Is it possible to go through the array and check if '@' and '.' are next to each other?

Answer:
Usestrstr:

```
if (strstr(array, "@.") || strstr(array, ".@"))
    /* the characters are touching */
```


Question:
Is there function in a C library that iterates through an array and checks if two characters are next to each other?

For example :array[30] = "example@.com"Is it possible to go through the array and check if '@' and '.' are next to each other?

Answer:
Usestrstr:

```
if (strstr(array, "@.") || strstr(array, ".@"))
    /* the characters are touching */
```


Question:
The question concerns implicit multiplication by the-operator.
For example

```
float a = 10;
float b;
```

b = -a;Is this valid? doesb = -10?

Answer:
This isn't implicit multiplication, but use of the unary-operator.

The code is valid, since the operator works on all arithmetic types, including floating point.


Question:
I am attempting to use a variable to store a conditional statement's result:

```
int age = 40;
int validAge = age > 40;

if (validAge) { /* ... */ }
```

Is the above code example allowed in C? If so, what type should I set these conditional variables?

Answer:
This is valid.

The expressionage > 40evaluates to either 0 or 1, so you can use any integer type (char,short,int,long, either signed or unsigned) to store it.


Question:
I am attempting to use a variable to store a conditional statement's result:

```
int age = 40;
int validAge = age > 40;

if (validAge) { /* ... */ }
```

Is the above code example allowed in C? If so, what type should I set these conditional variables?

Answer:
This is valid.

The expressionage > 40evaluates to either 0 or 1, so you can use any integer type (char,short,int,long, either signed or unsigned) to store it.


Question: How can I show theprintfstatements inrpl-of0.cin the mote output window like the way we can see theprintfstatements inrpl-icmp6.c? I have triedDEBUG_PRINTandDEBUG_FULLbut to no avail.

Answer: replace#define DEBUG DEBUG_NONEwith#define DEBUG DEBUG_PRINT


Question:
Why does-fsanitize=undefinedthrow

runtime error: left shift of 1 by 31 places cannot be represented in type 'int'

on this code

```
uint32_t z;
z = 1 << 31;
```

?

Answer:
Make the 1 unsigned:

```
uint32_t z;
z = UINT32_C(1) << 31;
```


Question: So, I'm trying to compile my C code using the command "gcc -o file file.c", but I get "error: libnet.h: No such file or directory" I included libnet.h (#include ) and I also installed libnet. I'm running CentOS 7.

Answer:
yum install libnetonly installs the precompiled library.

You need to install the headers usingyum install libnet-develbefore you can use it in your own software.


Question:
It's a long time since I did any coding of any sort.

I'm trying to remember the name (in C) of an item you put at the beginning of your code that allows compilation to a constant for efficiency but can have its value adjusted before compilation if necessary.

What is it called? (specifically the name in C and optionally the name in general)

Thanks.

Answer: #definestatements allow you to define a constant at the beginning of your code.


Question: So, I'm trying to compile my C code using the command "gcc -o file file.c", but I get "error: libnet.h: No such file or directory" I included libnet.h (#include ) and I also installed libnet. I'm running CentOS 7.

Answer:
yum install libnetonly installs the precompiled library.

You need to install the headers usingyum install libnet-develbefore you can use it in your own software.


Question:
It's a long time since I did any coding of any sort.

I'm trying to remember the name (in C) of an item you put at the beginning of your code that allows compilation to a constant for efficiency but can have its value adjusted before compilation if necessary.

What is it called? (specifically the name in C and optionally the name in general)

Thanks.

Answer: #definestatements allow you to define a constant at the beginning of your code.


Question:
Is there a possibility to split large.afiles into multiple smaller ones?

I'm currently having an issue with a.afile being multiple GiB large and GCC raises an error even with the flag-mcmodel=medium.

Answer:
Use binutils tool "ar":

```
ar -x libbig.a
```

for extracting the objects from the archive and

```
ar -r libsmall.a obj1.o obj2.o obj3.o
```

for creating a new archive.


Question:
Is there a possibility to split large.afiles into multiple smaller ones?

I'm currently having an issue with a.afile being multiple GiB large and GCC raises an error even with the flag-mcmodel=medium.

Answer:
Use binutils tool "ar":

```
ar -x libbig.a
```

for extracting the objects from the archive and

```
ar -r libsmall.a obj1.o obj2.o obj3.o
```

for creating a new archive.


Question:
time_t t;

printf("%f\n",time(&t));

it throws "Can not print float number"

Answer:
You may try

#include <stdlib.h>
printf("%jd\n", (intmax_t) time(NULL));.


Question:
This is my code :

```
void render(char * world) {...}
int main() {
  char world[HEIGHT * WIDTH];
  render(&world);
  return 0;
 }
```

Tell me if I have given enough information!
Thanks in Advance!

Answer: You just need to passworld. Passing&worldis passing the address ofworld, which is already achar *, so you're passing achar **.


Question:
This is my code :

```
void render(char * world) {...}
int main() {
  char world[HEIGHT * WIDTH];
  render(&world);
  return 0;
 }
```

Tell me if I have given enough information!
Thanks in Advance!

Answer: You just need to passworld. Passing&worldis passing the address ofworld, which is already achar *, so you're passing achar **.


Question: manpages of theprintfand online documentations often showprintf(3)when explaining the functionality ofprintf. What does the "3" denote?

Answer:
3denotes the section whichprintfis a part of. Section3corresponds to: Library calls (functions within program libraries).

You could also issueman <section number> <keyword>, eg.man 3 printfto look up a keyword in a specific section.man 1 printfwill show you theprintfshell command.


Question:
I compiled a program and get

```
format_io.c:3:6: error: cannot combine with previous 'void' declaration specifier
void int int int
     ^
format_io.c:3:10: error: cannot combine with previous 'void' declaration specifier
void int int int
         ^
```

how readformat_io.c:3:6:,when check line 6, do no t find the void error.

Answer:
filename:line:column

Column 6 of line 3. And column 10 of line 3.


Question:
I'm not sure about how to get an inverse index , index%size it's ok to a straight ring index but what I need  it's if tou are in 0 index get the last index as the previous of 0.

```
[0][1][2][3] // the previous index of 0 should be 3
```

Answer:
In the languageCthe remainder operator can be used as follows to get a true (positive) modulo result:

```
(index+n-1)%n
```

wherenis the length of your array.


Question:
I mean this | | not this %.
Like let's say that I've got two integers x and y and and integer z.
Now

```
z = x - y
```

Is there a way to express |z| so that if z is positive it stays positive and if z is negative it's turnt into its opposite? I don't mean to express it with an if, just a mathematical equation, symbol or something like that.

Answer:
You want theabs()function, provided in themath.hheader.

Example:

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


Question:
I found this question:

What is the output ofprintf("%-x", 2048);?

I know that the"%x"is outputting the hexadecimal format of the number, but I can' quite understand what the minus sign does here, since the output is the same for bothprintf("%-x", 2048);andprintf("%x", 2048);.

Answer:
std::printf, std::fprintf, std::sprintf, std::snprintf:

-: the result of the conversion is left-justified within the field (by default it is right-justified)


Question:
I found this question:

What is the output ofprintf("%-x", 2048);?

I know that the"%x"is outputting the hexadecimal format of the number, but I can' quite understand what the minus sign does here, since the output is the same for bothprintf("%-x", 2048);andprintf("%x", 2048);.

Answer:
std::printf, std::fprintf, std::sprintf, std::snprintf:

-: the result of the conversion is left-justified within the field (by default it is right-justified)


Question:
I came up on this question:
I have the following instruction

```
float *f = (float*) malloc(5*sizeof(float));
```

and a consequence of this is that

```
&f is of type float**
```

I don't understand why it's like this.

Answer: The type offisfloat*, i.e., a pointer to float. So&fis the address off, so its type is address to pointer of float, aka pointer to pointer of float, meaningfloat**.


Question:
I'm trying to pass a string to a function:

```
void PassString(unsigned char * value)
{
    // ...
}

int main(void)
{
    while(1)
    {
        PassString("TEST");
    }
}
```

I'm getting warning: (359) illegal conversion between pointer types.

Answer:
The string literal being passed is of typechar []but the argument is given asunsigned char *.

So change the type of the argument tochar[].


Question:
Let's say I have:

file1.c

```
uint8_t array[] = {1, 2, 3};
```

main.c

```
extern uint8_t array[];
```

Does this create a copy of the variable array in main.c?

Answer: No, it tells the linker "there's a variable somewhere with this name, please fill in a reference to it whenever it's mentioned".


Question:
Is it possible to have a POSIX thread remain "alive" after executing the function given as an argument? As in reusing that thread for further work.

For example, given a queue of functions to execute, is it possible to have a pthread execute several of them? The alternative would be creating a pthread for every task.

Answer:
No.

What you describe reminds me of athread pool, where a set of threads is waiting for work (your functions in this case) to execute.


Question: I am creating a program that implements a tic-tac-toe game using a 2-D array with multiple functions. How would I create a function where it clears all 'x' and 'o' characters in each cell and have the cells reset it back to the underscore character '_'? An example along with your explanation would be much appreciated!

Answer:
You can usememsetto reset the array to_as below.

```
char array[10][10];
memset(array, '_',  sizeof(array));
```


Question:
Is there any way to let CLion update the declaration in the .h file if I change the function definition in the .c file ?

The copy and pasting is such a repetitive task..

Answer: It depends on changes I guess. I always useRefactor->Change Signatureto update function return type, name, arguments in both files (source and header).


Question:
I have no idea how to pass command like:

```
echo -e \"\E[1;3mHello!"
```

tosystem(), since I have to put it in quotation marks cause it'sconst char, any help?

Answer:
Double quotes need to be escaped in strings, as do backslashes:

```
system("bash -c 'echo -e \"\\E[1;3mHello!\"'");
```


Question: Does thegcc 166 compilerfor theSiemens C167micro controller exist in open source ?, or can I find it?

Answer: According to the sitelinkI found thatGCC 166it is a compiler available for sale byRigel corp


Question: Does thegcc 166 compilerfor theSiemens C167micro controller exist in open source ?, or can I find it?

Answer: According to the sitelinkI found thatGCC 166it is a compiler available for sale byRigel corp


Question:
This question already has answers here:struct declaration(2 answers)Closed4 years ago.

I read such a snippet code of in5.2.  The indirection:

```
struct contact
{
    int n1;
    float n2;
    char st[10];
} d1;
```

What's the meaning of using d1 here? is it a recommended practice to define such a struct?

Answer: That simply declare astruct contactvariable namedd1. That is not really readable and is not used generally.


Question: I was given the task of writing a program  that determines the maximum number of  processes a user can have, just like the bash's  "ulimit -u" built-in command  butusing system calls and C. Any hint as to how achieve this?

Answer:
Theulimitbuiltin is just an interface to thegetrlimitandsetrlimitfunctions.

See thegetrlimit, setrlimit man page.

In particular, you are interested in theRLIMIT_NPROCresource.


Question:
I see that theapr_pool_*interface exposes

void  apr_pool_tag (apr_pool_t *pool, const char *tag)

which lets me tag a pool.

That's all well and good, but how do I extract the tag from a pool at a later time? I can't find the "getter" for the above setter. How are these tags used?

Answer: Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.


Question:
I see that theapr_pool_*interface exposes

void  apr_pool_tag (apr_pool_t *pool, const char *tag)

which lets me tag a pool.

That's all well and good, but how do I extract the tag from a pool at a later time? I can't find the "getter" for the above setter. How are these tags used?

Answer: Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.


Question:
I see that theapr_pool_*interface exposes

void  apr_pool_tag (apr_pool_t *pool, const char *tag)

which lets me tag a pool.

That's all well and good, but how do I extract the tag from a pool at a later time? I can't find the "getter" for the above setter. How are these tags used?

Answer: Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.


Question:
I have a UnsafeMutablePointer pointing at a C string, I want to convert the bytes at this pointer to a Swift String, the data is a C string, so UTF8.

Is it possible to iterate byte by byte until NULL? Or some easier way?

Answer:
CChar is an alias for Int8, so you can useCChar-based methodshere.

```
let str = String(cString: pointer)
```


Question:
Let's say I have two variables.

```
int a = -10;
int b = 10;
```

How can I return 0 if they have different sign or 1 if they have same signs ?
Again without if statements

Answer:
Like this?

```
return ((a >= 0 && b >= 0) || (a < 0 && b < 0));
```


Question:
For example:

```
void *p1 = someStringPointer;
void *p2 = p1;
```

Although these are two unique pointers, given that they both point to the same value, are they still different memory objects?

Answer:
If you print the address ofp1andp2

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

They have different addresses, so yes they are different memory objects.


Question:
How can I create an array such that I could access the elementsa[1000000],a[1]anda[2]and not even using the size of 1000000?

If possible please provide the answer inC++.

Answer:
Usestd::unordered_map<>.

```
enum { N = 9 };
int arr[N] = { 0 };
std::unordered_map<int, int> m;
for (int i = 0; i < N; i++)
{
    ++m[arr[i]];
}
```


Question:
In this code the person has to enter y if wishes to continue, but why does it ask him the question two times when he enters y.

```
char c = 'y';
while(c!='n'){
    printf("Do you wish to continue: (y or n):");
    c = getchar();
}
```

Here is the console

Answer:
why does it ask him the question two times when he enters y

The enter key the user hits is taken as another character (a new-line:\n)  as well.


Question:
In this code the person has to enter y if wishes to continue, but why does it ask him the question two times when he enters y.

```
char c = 'y';
while(c!='n'){
    printf("Do you wish to continue: (y or n):");
    c = getchar();
}
```

Here is the console

Answer:
why does it ask him the question two times when he enters y

The enter key the user hits is taken as another character (a new-line:\n)  as well.


Question:
I am following instructions to write a program of characters counting:

```
#include <stdio.h>
main()
{
    double nc;

    for (nc=0; getchar() != EOF; ++nc);
    printf("%.0f\n", nc);
}
```

After it was compiled and run,

```
$ ./a.out
ff
fdg
fd

fdr
```

It did not print the counting.What's the problem with my code?

Answer:
I'm pretty sure you never enterEOF.

UseControl+Zon Windows orControl+Don UNIX/Linux/OSX to getEOF.


Question: I am struggling to understand if there is any overflow with the following equation using 8 bit signed integers.0b00000000 - 0b10000000

Answer: This question is taggedc, and in C, all arithmetic in types lower-rank thanintgets promoted toint, andinthas at least 16-bit range, so(signed char)0-((signed char)-128)is just 128.


Question:
I was getting wrong values fromlog(), so I wrote this program just for testing:

```
#include <math.h>
#include <stdio.h>
void main()
{
  printf ("%1f", log(10));
}
```

This should print "1", but I get "2.302585"

Why is this and how can I fix it?

Answer:
Thelogfunction is for thenaturallogarithm with basee.

It seems you wantlog10instead.


Question:
```
struct Node *prevX = NULL, *currX = *head_ref;
  while (currX && currX->data != x)
 {
   prevX = currX;
   currX = currX->next;
 }
```

Why was currX placed here? How can it affect the outcome?

Answer: while (currX)tests the truthiness ofcurrX. It's effectively short forwhile (0!=currX).


Question:
```
struct Node *prevX = NULL, *currX = *head_ref;
  while (currX && currX->data != x)
 {
   prevX = currX;
   currX = currX->next;
 }
```

Why was currX placed here? How can it affect the outcome?

Answer: while (currX)tests the truthiness ofcurrX. It's effectively short forwhile (0!=currX).


Question:
I have a rather odd situation where I will have multiple interfaces connected to the same network. When I receive a broadcast or multicast message, I would like to know what interface it came from. It there a way to do that in C or ideally Python?

Thanks!

Answer: The most obvious one would be to bind several sockets, each toone interface only- do not listen to0.0.0.0.


Question:
What is the intention to set handle to an object as pointer-to pointer but not pointer? Like following code:

```
FT_Library library;
FT_Error error = FT_Init_FreeType( &library );
```

where

```
typedef struct FT_LibraryRec_  *FT_Library
```

so&libraryis aFT_LIBraryRec_handle of typeFT_LIBraryRec_**

Answer: It's a way toemulatepass by reference in C, which otherwise only have pass by value.


Question:
What is the intention to set handle to an object as pointer-to pointer but not pointer? Like following code:

```
FT_Library library;
FT_Error error = FT_Init_FreeType( &library );
```

where

```
typedef struct FT_LibraryRec_  *FT_Library
```

so&libraryis aFT_LIBraryRec_handle of typeFT_LIBraryRec_**

Answer: It's a way toemulatepass by reference in C, which otherwise only have pass by value.


Question: If there is a broken VHD chain (for example the parent VHD was modified, that's why the child no longer mounts), there's a way to fix it by using Hyper-V "Reconnect" feature. How do I do the same programmatically?

Answer: I think you wantAttachVirtualDisk, but I'm not sure if that's what you are after with regards to VHD chains.


Question: If there is a broken VHD chain (for example the parent VHD was modified, that's why the child no longer mounts), there's a way to fix it by using Hyper-V "Reconnect" feature. How do I do the same programmatically?

Answer: I think you wantAttachVirtualDisk, but I'm not sure if that's what you are after with regards to VHD chains.


Question:
```
int pop(STA* stack)
{
    if (!isEmpty(stack))
        return stack->array[stack->top--] ;
    return '$';
}
```

What is the useage of the (return'$') in this function?
What kind of value will it return?

Answer:
It seems like it's just default return value in case stack is empty (which should not really happen, precondition of callingpop()should be for stack not to be empty. )

It will return 36 ( code of$)


Question:
I noticed thatprintf()has specifiers%Fand%f.

What are the differences?  The link above says%Fwill give "Decimal floating point, uppercase".

I fail to see what an uppercase floating point is.

Thanks!

Answer:
Per the C 2018 standard, clause 7.21.6.1, paragraph 8:

The F conversion specifier produces INF, INFINITY, or NAN instead of inf, infinity, or nan, respectively.


Question:
I have a portion of the code as:

```
__weak  void TimingDelay_Decrement(void) {

}
```

and it keeps throwing up the captioned error. I checked the web and couldn't find relevant content for the__weakcase. Any help is appreciated.

Answer:
Because it is ARM Cortex gcc toolchain so the__weakis a definition of__attribute__((weak)).

The easiest way to add is to amend thegcccommand line arguments:-D__weak=__attribute__((weak))


Question: If I have multiple if-statements nested inside each other which are all in a for-loop, will a break statement on the inner-most if-statement break out of the for-loop or just into the next if statement?

Answer: It will break the loop (the inner most loop that the if contains in) no matter how many if statments are nested inside. Abreakbreaks from a loop and not from if statement.


Question:
This program gives output as 4 3 2 1.
Why does it stop at 1 when no condition is given for i?
Do main(10) and main(i) differ?

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

Answer:
You actually have a condition:

if (--i)is equivalent toif(--i != 0)


Question:
I typed this program on code blocks but it is showing error on int main line
Here's the program

```
#include <stdio.h>

int main()
{
 printf("Hello");
 return 0;
 }
```

The message return is " multiple definition of main"

Answer: The sample code is correct. It might be an IDE configuration error. Usegccto compile your code on Linux and on Windows you can installMinGWand execute from a command window.


Question: I am a beginner to ffmpeg and libavcodec in c programming on a linux machine. I want to know the difference between these API's.

Answer: av_register_allregisters absolutely everything - i.e. muxers, demuxers and protocols + it calls toavcodec_register_all.avcodec_register_allonly registers codecs. Bare codecs are seldom useful as such.


Question:
```
main()
{
char a1='=';
char a2='=';
printf("%d",a1+a2);
}
```

Code is as above , it simply perform '='+'=' and printing the value 122.(why??)..

Answer:
Because ASCII value of'='is61

ASCII Values


Question:
the following short code snippet results in a invalid initializer error, and as a beginner in C, I do not understand why.

```
unsigned char MES[] = { 0x00, .... };
unsigned char *in[] = &MES;
```

Is this not the correct way to do it?

Answer:
&MESis a pointer to an array ofunsigned char.

inis an array of pointers tounsigned char.

Try instead :

```
unsigned char (*in)[] = &MES;
```

which makesinalso a pointer to an array ofunsigned char.


Question:
All I can find on this topic is mentions ofFSMoveObjectToTrashSyncfunction, which is nowdeprecated and no alternative is listed for it.

How to do it from C or Objective-C code?

Answer:
Use NSFileManager:

https://developer.apple.com/documentation/foundation/nsfilemanager

trashItemAtURL:resultingItemURL:error:
  Moves an item to the trash.


Question:
This question already has answers here:How to check the value of errno?(3 answers)Closed5 years ago.

I'm using syscallstat, it returns 0/-1. When -1 is returned it means, error occurred and errno is set as it should be (source:man 2 stat).

But I want to access errno and print it, how to do that?

Answer:
You can get it fromerrno.

Also you can print the error usingstrerror


Question:
i'm recording with VUG and receive this error when click a button to acces to another page.

here is my configuration:

If someone know how to solve it, thanks in advance.

Answer:
go under recording options and set a new connection.
Any server, all Ports (value 0) and go further with the settings (direct/proxy etc.). If you are not sure which settings you should use just try and edit them as long as the record is empy


Question:
i'm recording with VUG and receive this error when click a button to acces to another page.

here is my configuration:

If someone know how to solve it, thanks in advance.

Answer:
go under recording options and set a new connection.
Any server, all Ports (value 0) and go further with the settings (direct/proxy etc.). If you are not sure which settings you should use just try and edit them as long as the record is empy


Question:
What I'm trying to do would look like this in Python
(wherenis float/double):

```
def check_int(n):
    if not isinstance(n, numbers.Integral):
        raise TypeError()
```

Since C/C++ are typestrong, what kind of cast-and-compare magic would be the best for this purpose?

I'd preferably want to know how it's done in C.

Answer:
Usefloor

```
#include <cmath>

if (floor(n) == n)
    // n is an integer (mathematically speaking)
```


Question: Is it possible to create a window without it showing up on taskbar in X11 using c?

Answer:
That depends on GUI toolkit you are using. For example, GTK+ providesgdk_window_set_skip_taskbar_hintfunction.

If you don't use any GUI toolkit and directly interface X11, you need to add_NET_WM_STATE_SKIP_TASKBARatom to_NET_WM_STATEproperty.


Question: Is it possible to create a window without it showing up on taskbar in X11 using c?

Answer:
That depends on GUI toolkit you are using. For example, GTK+ providesgdk_window_set_skip_taskbar_hintfunction.

If you don't use any GUI toolkit and directly interface X11, you need to add_NET_WM_STATE_SKIP_TASKBARatom to_NET_WM_STATEproperty.


Question:
```
const int rxBytes = uart_read_bytes(UART_NUM_0, data, RX_BUF_SIZE, 10 / portTICK_RATE_MS);
```

Answer: To flush input data you can read from the uart repeatedly with a timeout of 0 until zero bytes are returned.


Question:
void TraverseList(const List *l , void (*Visit)(ListEntry)) { // }

I confused about the above function call within the argument of a function,how it is working?

Answer:
Visitis a function pointer parameter passed to theTraverseListfunction. It should point to a function with the format

```
void func (ListEntry);
```

Likely,TraverseListwill call the passed function for every item in the list.


Question:
void TraverseList(const List *l , void (*Visit)(ListEntry)) { // }

I confused about the above function call within the argument of a function,how it is working?

Answer:
Visitis a function pointer parameter passed to theTraverseListfunction. It should point to a function with the format

```
void func (ListEntry);
```

Likely,TraverseListwill call the passed function for every item in the list.


Question:
When we have :

```
struct node {
    char...
    int....
    struct node *....
}

typedef struct node Node;
```

and then we have a function like this:

```
int function(Node f){...}
```

What is thisf?

Answer: fis an input argument of the typeNode. The typeNodeis synonym of the typestruct node.


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

Why is the increment ofidone after the comparison in each test case?

Answer:
i <= 8succeeds for the last time wheni = 8.

In the last iteration,i++is executed, theni <= 8fails becausei = 9.

Note that the,is asequence point, soi++is absolutely guaranteed to be executed beforei <= 8.Not so for similar constructs.


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

Why is the increment ofidone after the comparison in each test case?

Answer:
i <= 8succeeds for the last time wheni = 8.

In the last iteration,i++is executed, theni <= 8fails becausei = 9.

Note that the,is asequence point, soi++is absolutely guaranteed to be executed beforei <= 8.Not so for similar constructs.


Question:
I have this code

```
if(orden[i]==1)
    for(i=0; i<ARRAY_SIZE; i++)
        if(v[i]<v[i+k])
            printf("print once ");
```

How can I make it so that it prints the line only once, if the condition inside the for loop is satisfied?

Answer:
Use thebreakcommand to exit theforloop.

```
if(orden[i]==1)
    for(i=0; i<ARRAY_SIZE; i++)
        if(v[i]<v[i+k])
        {
            printf("print once ");
            break;
        }
```


Question:
int main(int argc, char* argv[])

In this code argv[] is a string not array so how can i use as a array to perform sum operation?

Answer:
You can do it like this

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

int main(int argc, char const *argv[])
{
    int sum = 0;
    int i = 1;
    for(;i<argc;++i)
        sum += atoi(argv[i]);
    printf("%d\n",sum);
    return 0;
}
```

And the result:

```
$ gcc test.c && ./a.out 1 2 3 4
10
```


Question:
int main(int argc, char* argv[])

In this code argv[] is a string not array so how can i use as a array to perform sum operation?

Answer:
You can do it like this

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

int main(int argc, char const *argv[])
{
    int sum = 0;
    int i = 1;
    for(;i<argc;++i)
        sum += atoi(argv[i]);
    printf("%d\n",sum);
    return 0;
}
```

And the result:

```
$ gcc test.c && ./a.out 1 2 3 4
10
```


Question:
I wrote an ntrip client in C using sockets(http://read.pudn.com/downloads116/sourcecode/unix_linux/493018/NtripLinuxClient.c__.htm), Receiving the reqest works fine, but after some time the server stops sending correction data because I do not now how to send nmea updates to the server.

Does anyone know how that would work?

thanks in advance

Answer: You just need to send your_nmea + '\r\n' regularly and that should work.


Question:
I wrote an ntrip client in C using sockets(http://read.pudn.com/downloads116/sourcecode/unix_linux/493018/NtripLinuxClient.c__.htm), Receiving the reqest works fine, but after some time the server stops sending correction data because I do not now how to send nmea updates to the server.

Does anyone know how that would work?

thanks in advance

Answer: You just need to send your_nmea + '\r\n' regularly and that should work.


Question:
```
a|b=c
```

knowingaandc, how to calculateb

For example:

```
0011 | b = 0111
```

Knowinga = 0011andc = 0111, how to figure outbto be0101

Answer:
There will be more than one correct answer.

For simplicity consider the trivial example:1|0 = 1i.e. a=1, b=0 and c=1. In this case, b can also be 1.

So given that the bit inais 1, we won't be able to know for sure whether the bit inbis 0 or 1.


Question: I'm trying to do math calculations that they require more than 100 decimals of precision. C data types cannot go beyond 16 bytes (long double), so I cannot compute more than ~17 decimals. Is there a way to create a variable in C that can get more precision?

Answer: Realistically you need an arbitrary-precision arithmetic library, seeWikipediafor some options. I personally have foundGNU MPFRto be fairly reliable, though I have also heard good things aboutArb.


Question:
Given a preprocessor macro like

```
#define DECLARE(NAME) \
    int NAME;         \
    int NAME_2
```

Name_2denotes a new identifier. Is it possible to expandName, so that

```
DECLARE(x);
```

becomes

```
int x;
int x_2;
```

Answer:
You can use##glue:

```
#define DECLARE(NAME) \
   int NAME;         \
   int NAME##_2
```


Question:
Given a preprocessor macro like

```
#define DECLARE(NAME) \
    int NAME;         \
    int NAME_2
```

Name_2denotes a new identifier. Is it possible to expandName, so that

```
DECLARE(x);
```

becomes

```
int x;
int x_2;
```

Answer:
You can use##glue:

```
#define DECLARE(NAME) \
   int NAME;         \
   int NAME##_2
```


Question: I'm wondering if someone know effective approach to calculate bits in specified position along array?

Answer:
Assuming that OP wants to count active bits

```
size_t countbits(uint8_t *array, int pos, size_t size)
{
    uint8_t mask = 1 << pos;
    uint32_t result = 0;

    while(size--)
    {
        result += *array++ & mask;
    }
    return result >> pos;
}
```


Question: I'm wondering if someone know effective approach to calculate bits in specified position along array?

Answer:
Assuming that OP wants to count active bits

```
size_t countbits(uint8_t *array, int pos, size_t size)
{
    uint8_t mask = 1 << pos;
    uint32_t result = 0;

    while(size--)
    {
        result += *array++ & mask;
    }
    return result >> pos;
}
```


Question: I am making calculator for physics, but when I was coding the focal length equation I needed to find the reciprocal of the fraction found for the focal length.

Answer:
```
double eqn_reciprocal= pow(eqn,-1);
```

this would do the trick


Question:
PVS-Studio gave me a warning about this :

```
char c;
sscanf(line, "%d", &c);
```

I changed %d to %c but this created a bug because "c" now contains the ASCII value of the number and not the decimal one, so I went back to "%d".

So what's the correct specifier to ? is there another solution ?

Answer: cis achar. You asked to scan anint. PVS-Studio did right in warning you. Change the type ofctointand scan for a%d.


Question:
I am facing difficulty in converting a binary array to a decimal number:

```
bin[8] = {10,00,00,10};
```

I want the equivalent of this array element as a decimal number, i.e.130.

Answer:
A standard solution goes like this:

```
int f(char s[])
{
    int n = 0;
    int i;

    for (i = 0; i < 8; ++i) {
        n <<= 1;
        n += s[i] - '0';
    }

    return n;
}
```


Question:
I am facing difficulty in converting a binary array to a decimal number:

```
bin[8] = {10,00,00,10};
```

I want the equivalent of this array element as a decimal number, i.e.130.

Answer:
A standard solution goes like this:

```
int f(char s[])
{
    int n = 0;
    int i;

    for (i = 0; i < 8; ++i) {
        n <<= 1;
        n += s[i] - '0';
    }

    return n;
}
```


Question:
I'm new to C and wanted to know, what does a bitwise shift 1 << 9 in an enum definition do in this case below:

```
static enum {
    DEAD, LIVE
} state[1 << 9];
```

Answer:
The expression1<<9is the same as 29, which is 512.

So an array of 512 enums is declared.


Question:
Code to receive message like "hi i am man" and convert it to upper case "HI I AM MAN".

```
n = read(newsockfd, buffer, 255);
printf("Here is the message: %s\n", buffer);
```

Answer:
```
#include <stdio.h>
#include <ctype.h>

  n = read(newsockfd, buffer, 255);
  for(int i = 0; i < n; i++)
    buffer[i] = toupper(buffer[i]);
  printf("Here is the message: %s\n", buffer);
```


Question:
I am confused as to how to set the "editable" property to a specific child of a GtkTreeView, instead of the entire cell renderer.

```
|  Column  |
[+] Parent
 |__ Child
 |__ Child2 <-- Press to edit
```

I didn't seem to find a way to do that.

Answer:
You add another boolean column to your ListStore. Then set your Renderer editable property to that extra column.

Sorry, I don't know the C code for a short example.


Question:
The elements of an uninitialized char array in C all have the value 'Ì' (or -52 as an integer; 0xCC or 204 as char). Is this another type of null character? Or is it just a value that fills in the values of an uninitialized char array?

(In case it makes any difference, I am using visual studio)

Answer: Uninitialized variables have indeterminate values. They can make the behavior of your program undefined if the value is used to be a trap representation.


Question:
For example, I have two digit bits:

```
0b0111111
0b0000110
```

I want to shift a state variable by 7 digits and combine them together.

```
0b00001100111111
```

Can I accomplish by shifting?

Answer:
You do this by shifting the bottom number left 7 digits, then performing a bitwise OR of the result and the first number.

```
unsigned int a = 0x3f;
unsigned int b = 0x06;
unsigned int result = (b << 7) | a;
```