Question:
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work?

The error I receive is: cannot open source file "pthread.h"

Answer:
In Visual Studio 2017

Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]


Question:
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work?

The error I receive is: cannot open source file "pthread.h"

Answer:
In Visual Studio 2017

Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]


Question:
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work?

The error I receive is: cannot open source file "pthread.h"

Answer:
In Visual Studio 2017

Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]


Question:
What is the meaning of the following operation in C

```
USIC2_CH0->PSR &= ~((uint32_t)USIC_CH_PSR_ASCMode_TFF_Msk);
```

I know that ifA|=BmeantA=A|Bthen what is meant by

A&=~B;? Does that meantA=~(A&B)??

Answer:
A &= ~BmeansA = A & (~B), notA=~(A&B).

You can see those two are different if you take A=b010 and B=b110, for example.

In context it's disabling the bits in that PSR bitfield that are set in the constant whose name ends in "TFF_Msk" above.


Question:
How can I use assembly instructions that contain quotation marks insideasm()?
like:

```
asm(
".section .rdata,"dr"\n"
);
```

The code above gives me this error:

```
expected ')' before 'dr'
```

Answer:
Any string literal, not just the ones required by anasmdeclaration, can contain double quotes if they are escaped. You escape them with a\. So when applied to your example:

```
asm(
".section .rdata,\"dr\"\n"
);
```


Question:
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks.

e.g in the Image below: does he count like the first row?

Answer:
It's an array of characters yes it counts the spaces,
it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0..

p.s: null is a character also, that gets on the end of the array


Question:
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks.

e.g in the Image below: does he count like the first row?

Answer:
It's an array of characters yes it counts the spaces,
it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0..

p.s: null is a character also, that gets on the end of the array


Question:
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks.

e.g in the Image below: does he count like the first row?

Answer:
It's an array of characters yes it counts the spaces,
it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0..

p.s: null is a character also, that gets on the end of the array


Question:
How can I define the type of an enum to beuint8instead ofint?

```
typedef enum
{
  R_DIRECTION_LEFT = 1,
  R_DIRECTION_RIGHT = 2,
  R_DIRECTION_TOP = 4,
  R_DIRECTION_BOTTOM = 8
} R_Direction;
```

Answer:
No you can't.

From standard §6.4.4.3C11 standard N1570

An identifier declared as an enumeration constant has type int.


Question:
I have a program that uses dynamic allocation for a uint8_t array; can I safely
assume that its length will always be one byte?

Answer: Ifuint8_texists, thensizeof(uint8_t)must be 1.uint8_tisrequiredto have width exactly 8 and no padding bits, andCHAR_BITis required to be at least 8. Ifuint8_texists, it can't have more than one char's worth of bits without violating these requirements.


Question:
How can I define the type of an enum to beuint8instead ofint?

```
typedef enum
{
  R_DIRECTION_LEFT = 1,
  R_DIRECTION_RIGHT = 2,
  R_DIRECTION_TOP = 4,
  R_DIRECTION_BOTTOM = 8
} R_Direction;
```

Answer:
No you can't.

From standard §6.4.4.3C11 standard N1570

An identifier declared as an enumeration constant has type int.


Question: I'm writing a user define function for Vertica and don't know how to initialize a Vstring of Vertica from a C string (char *) . Thanks for any suggestion?

Answer:
Following to Vertica documentation:

You cannot create instances ofVStringorVNumericyourself. You can manipulate the values of existing objects of these classes that HP Vertica passes to your UDx, and extract values from them. However, only HP Vertica can instantiate these classes.


Question:
For example, if I allocate more memory space then needed on a C string is there a way to return back the unused memory? Or is this automatically done?

```
char *x = malloc(256);
strcpy(x, "Hello World");
// return back unused x memory allocation
```

Answer:
You can callreallocto change the size of an allocation; this can be used to make it bigger or smaller.

The computer would have no basis for automatically making your allocation smaller.


Question: Not C# or C++, but C. Is there any C support in Visual Studio?

Answer:
Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community).

UnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler.

Answer:by default it appears not, but you can install the Clang component and it appears you will be able to.


Question: Not C# or C++, but C. Is there any C support in Visual Studio?

Answer:
Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community).

UnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler.

Answer:by default it appears not, but you can install the Clang component and it appears you will be able to.


Question:
```
FILE * fp = fopen ("excel.csv" , " w+ ");
fprintf (fp, "%s", "hello,world");
```

I want to printhello,worldwith comma in a single cell.
How can I print the same without printing in two different cells?

Answer:
Put quotes around the cell:

```
fprintf(fp, "%s", "\"hello,world\"");
```

IIRC Wikipedia hasa pretty good article on CSV.


Question: When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?

Answer:
You can view the symbols of a compiled program or object file withnm(1):

```
nm a.out
```

Displays all symbols ina.out.


Question: When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?

Answer:
You can view the symbols of a compiled program or object file withnm(1):

```
nm a.out
```

Displays all symbols ina.out.


Question:
I would like to realize in GTK3 a text window where to redirect the stdout using the c language.
Could you help me with suggestions about how to start.
Thank you.

Answer: I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.


Question:
I would like to realize in GTK3 a text window where to redirect the stdout using the c language.
Could you help me with suggestions about how to start.
Thank you.

Answer: I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.


Question:
I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives:

Use of undeclared identifier 'byte'

in the next line:

```
buf[2] = (byte)(addr & 0xff);
```

Answer:
In the .c file i have declaredbytewith the next code:

```
typedef uint8_t byte
```

uint8_t is similar to byte, so it compiled


Question:
I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives:

Use of undeclared identifier 'byte'

in the next line:

```
buf[2] = (byte)(addr & 0xff);
```

Answer:
In the .c file i have declaredbytewith the next code:

```
typedef uint8_t byte
```

uint8_t is similar to byte, so it compiled


Question:
What does this line mean?

```
if (strcmp(argv[0],"./lower")==0)
```

Before converting to lower or upper case why this condition is checked?
What does it results to?

Answer:
Comparingargv[0]is checking the name of the executable.

I assume you look at code similar tobusyboxin which you check the executable that the user used so you know which action to perform.


Question:
What is the difference between the two Instruction pointers (eip)? What is the goal of each one?

Frame info image:

There are two different eip?

Answer:
saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL).

eipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).


Question:
What is the difference between the two Instruction pointers (eip)? What is the goal of each one?

Frame info image:

There are two different eip?

Answer:
saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL).

eipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).


Question:
Is there a way to send a signal to all the processes of a process ID group except for the one that is sending it?

Withkill(0, SIGUSR1)we can send it to all the processes of a group including the one calling it, but what if we wanted to send it to all except for the one calling it?

Answer:
```
#include <signal.h>
#include <unistd.h>
...
signal(SIGUSR1, SIG_IGN); /* Ignore own signal */

killpg(getpgrp(), SIGUSR1); /* Send SIGUSR1 to pgrp */
```


Question:
Why "strrev()" and some other inbuilt string functions in c doesn't work in terminal?

```
#include<stdio.h>
main()
{
char c[50];
scanf("%s",c);
strrev(c);
printf("%s",c)
}
```

Answer:
strrevis not standard, but can be easily implemented

```
void strrev(char *s) {
    int i,n = strlen(s);
    for(i=n/2 ; i>=0 ; i--) {
        char c = s[i];
        s[i] = s[n-i-1];
        s[n-i-1] = c;
    }
}
```


Question:
I need to add quotes in begging and ending of a char.

```
char *Mychar = "hello";
printf("%c\n",Mychar[0]);
```

My result ishand my desired result is'h'.

Answer:
Just add them in the format string. For single quotes, you can just put them in there:

```
printf("'%c'\n",Mychar[0]);
```

For double quotes, you'll have to escape them:

```
printf("\"%c\"\n",Mychar[0]);
```


Question:
This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago.

The result of the values of A and B is as follows.

Answer: In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.


Question:
This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago.

The result of the values of A and B is as follows.

Answer: In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.


Question: Is it possible (using the CPLEX C APIs) to retrieve the variables type (CPX_CONTINUOUS, CPX_BINARY, CPX_INTEGER, ...)  of a model not handled by me but directly built from an .mps file?

Answer:
Yes, you can use theCPXgetctypefunction. Here's the example given in the documentation link:

```
status = CPXgetctype (env, lp, ctype, 0, cur_numcols-1);
```

To get the number of columns useCPXgetnumcols.


Question:
I have a code where am gettingPC Lint info 825, even though I'm using/* fallthrough */comment. Tell me if any of my usage is wrong.

Example code:

```
case 1:

case 2:

case 3:
{
    statement;
}

/* fallthrough */

case 4:
{
statement 1;
statement 2;
break;
}

default:
break;
```

Answer:
That's the wrong comment content. Try:

```
//lint -fallthrough
```

Seethe huge text filefor details.


Question:
I want to get a samesemIdusing same key.
Although, I calledsemgetmethod using same key, and returned differentsemId.

Please answer me the reason why this problem happened.

Sample source :

```
int id1, id2;
int semflg = IPC_CREAT | 0666;
id1 = semget(0, 1, semflg);
id2 = semget(0, 1, semflg);
```

Result : id1 != id2

Answer: Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.


Question:
I want to get a samesemIdusing same key.
Although, I calledsemgetmethod using same key, and returned differentsemId.

Please answer me the reason why this problem happened.

Sample source :

```
int id1, id2;
int semflg = IPC_CREAT | 0666;
id1 = semget(0, 1, semflg);
id2 = semget(0, 1, semflg);
```

Result : id1 != id2

Answer: Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.


Question: In Code::Blocks when i run and debug my code it says in the "Build messages section" (error: Cannot find id) I reinstalled both the coding platform (code::blocks) and the compiler individually and nothing has changed.

Answer:
Try simple program first to see if installation is correct:

```
#include <stdio.h>

int main()
{
    printf("Hello World");

    return 0;
}
```


Question:
Can I safely usememmem()if I want it to also run on Mac?

I know it requires:

```
#define _GNU_SOURCE
#include <string.h>
```

Answer:
Yes,memmemis available on MacOS.  Seethe man pagefor details.

You don't however need to#define _GNU_SOURCE.  That is specific to Linux.


Question:
I'm trying to make a game program in C.
How to get a char or input without displaying and pausing the screen?

Answer:
You mentioned you want to make a game in C.

Create your own window.
Capture and Process events.

This sounds a bit much for a beginner but actually it is not.
Use a library like SDL2 to help you with that.

Here is atutorial seriesthat walks you through some of the basics of game making.


Question:
Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable.
Can we get that information afterwards?

Answer: Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.


Question:
Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable.
Can we get that information afterwards?

Answer: Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.


Question: I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?

Answer: Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.


Question: I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?

Answer: Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.


Question:
I have a file and I want to make a backup file, with the same name as file but with "aux" at the end. How do I do this? I tried:

```
char *nameFile, *nameAux;
char *aux = aux;
nameAux = nameFile + aux;
```

Which didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile

Answer:
You can't just "add" C strings. effectively you've summed pointers.
SeeHow do I concatenate const/literal strings in C?


Question:
I have a file and I want to make a backup file, with the same name as file but with "aux" at the end. How do I do this? I tried:

```
char *nameFile, *nameAux;
char *aux = aux;
nameAux = nameFile + aux;
```

Which didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile

Answer:
You can't just "add" C strings. effectively you've summed pointers.
SeeHow do I concatenate const/literal strings in C?


Question:
I am working on an implementation of named pipes client/server for school. I have asked my teacher what happens if i use unlink while either of the pipes end is still opened. He had no answer for me.

Anyone know?

Answer:
Nothing in particular happens, except the name is removed from the file system so no future processes can open the same named pipe.

The processes that has the pipe open will continue as normal.


Question: how to get bluetooth address of same device either through command line or program

Answer:
Two problems: First is that you never check for errors from any of the system calls.

The second is that the child process shouldterminatewhich yours doesn't. Instead your child process continues in the loop and callaccepton the listening socket and so on, fighting with the parent process about connections. When the child process is done it should callexitto terminate.


Question: I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?

Answer:
The prototype is:

```
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
```

So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.


Question: I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?

Answer:
The prototype is:

```
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
```

So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.


Question: I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?

Answer:
The prototype is:

```
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
```

So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.


Question: I want to know whether threads created usingpthread.hlibrary are using one core, or they are running in multiple cores.

Answer:
A newly created thread has no affinity, and will be shuffled around the process as deemed best by the system.

If you need to pin it to a specific core,this answer provides detailsfor setting affinity to a specific pthread.


Question: I've found out where caused SEGSEV, but only happens when that function be called hundreds of thousands times to trigger some rare case, is it possible to set breakpoint there when something is true? either on the gdb command line or c source file

Answer:
Try like this:

```
(gdb) break file.c:15 if some_variable == some_value
```


Question:
Let's say here is a char with unknown digit number in C:

```
char char_id[1000] = {'1', '2', '3', ..., '8', '9', '\0'};
```

If I want the last two digit to form an integer i.e. '89'.

What is the easiest way?

Answer:
may be this

```
char char_id[1000] = {'1', '2', '3', /*..., */ '8', '9', '\0'};
int what_i_want    = atoi( char_id + ( strlen(char_id) - 2 ) );
```

by the way those dots are a bit of rubbish,  comment them


Question:
For example, if I had amakefilethat contains this:

```
dynArray.o: dynArray.c dynArray.h type.h
    gcc -Wall -ansi -c dynArray.c
```

How would I translate that into aCMakeLists.txtfile?

Answer:
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would.

```
add_library(<name> OBJECT <src>...)
```


Question:
For example, if I had amakefilethat contains this:

```
dynArray.o: dynArray.c dynArray.h type.h
    gcc -Wall -ansi -c dynArray.c
```

How would I translate that into aCMakeLists.txtfile?

Answer:
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would.

```
add_library(<name> OBJECT <src>...)
```


Question:
For example, if I had amakefilethat contains this:

```
dynArray.o: dynArray.c dynArray.h type.h
    gcc -Wall -ansi -c dynArray.c
```

How would I translate that into aCMakeLists.txtfile?

Answer:
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would.

```
add_library(<name> OBJECT <src>...)
```


Question:
I have the following code:

```
struct coord {
    float x;
    float y;
};

struct coord vertices[4];
```

But when I do the following, an error occurs:

```
void setVertices(float x, float y) {
    vertices[0] = (struct coord) { x, y };
}
```

Why isn't this allowed in C? Is there another way to do this? Thank you.

Answer: I can initialize structs that way, actually. The IDE just lagged on its error-checking for several minutes, for some reason.


Question:
When we create temporary files using tmpfile, in most cases we cannot easily predict the name. Coverity scan also complains about its vulnerability.
So is there any function to create a temporary file which cannot be guessed easily?

Answer:
If you using Linux, thenmkstemp

Or usetmpnam


Question:
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed5 years ago.

I was going through the logger code and came across a function

```
bool  LogMessage(const char *szFor, ...)
```

What does...indicates here?

Answer:
This is called anellipsis notation. This means, the function is avariadic function.

It canlegallyaccept any number and type of incoming arguments.


Question:
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed5 years ago.

I was going through the logger code and came across a function

```
bool  LogMessage(const char *szFor, ...)
```

What does...indicates here?

Answer:
This is called anellipsis notation. This means, the function is avariadic function.

It canlegallyaccept any number and type of incoming arguments.


Question: I'm trying to input data from filesample.txtinto my c program on netbeans.  How can I do that from command line?  I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?

Answer: If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"


Question: I'm trying to input data from filesample.txtinto my c program on netbeans.  How can I do that from command line?  I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?

Answer: If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"


Question: I'm trying to input data from filesample.txtinto my c program on netbeans.  How can I do that from command line?  I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?

Answer: If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"


Question:
This question already has answers here:What should main() return in C and C++?(19 answers)Closed5 years ago.

What will happen if we don't use it? will the compiler automatically add it like it does in C++?

Answer:
It will return0automatically in C99-compliant compilers (and later). In pre-C99 compilers the return value is undefined in such cases.

In other words, inmodernC you don't need an explicitreturn 0at the end ofmain.


Question: Given achar *str = "something %s something2 %d", how can I format it and produce a new string without printing out? I know of "printf" which prints out  a result, but I don't need a result to be printed out.

Answer: The answer issprintf: it's exactlyprintfto a buffer.


Question:
I'm trying to learn RDMA.

My question is, when doingibv_post_send, I should get a completion event on a completion queue. But how does theibv_post_sendknow to which completion queue? From what I see here, I could have createdmany.

Answer: Turns outwhen initiating a QP, it can be assigned to a send CQ and recv CQ in its init attributes.


Question:
A runtime I'ld like to to know if an stack defined struct sockaddr_storage was assigned to any IP address (IPv4 or IPv6)

Any idea?

Answer: Check thess_familyfield.  It will beAF_INETfor an IPv4 address, orAF_INET6for an IPv6 address.  You can then type-cast thesockaddr_storageaccordingly to eithersockaddr_inorsockaddr_in6in order to access thesockaddr_in::sin_addrorsockaddr_in6::sin6_addrfield, respectively, to make sure it is not set to zeros.


Question:
I want to open terminal and cat a file (show its content) using c;
i got error from code below:

```
char * com = "xterm cat /home/user/Desktop/file.c";
system(com);
```

or even:

```
char * com = "/usr/bin/xterm /bin/cat /home/user/Desktop/file.c";
system(com);
```

thanks for any help;

Answer:
You could change your command to:

```
xterm -e less file.c
```


Question:
I want to open terminal and cat a file (show its content) using c;
i got error from code below:

```
char * com = "xterm cat /home/user/Desktop/file.c";
system(com);
```

or even:

```
char * com = "/usr/bin/xterm /bin/cat /home/user/Desktop/file.c";
system(com);
```

thanks for any help;

Answer:
You could change your command to:

```
xterm -e less file.c
```


Question:
i have array of strings.

```
char strings[][30]={"word1","word2",......,""};
```

Iterated over them but at the end i got messageSegmentation fault (core dumped)

Tried with following code :

```
for(int i=0;strings[i] != "";i++){printing items...}
```

I think the problem is with!= ""but why isn't it working?

Answer: Usestrcmpto compare strings in C.==or!=doesn't work for strings in C.


Question:
Is this possible? I need to make a 2d array and each element is supposed to have an int array of size 2.

So if I make a 10x10 array I need each index to have a [x, y] where x and y are ints.

Answer:
```
int array[10][10][2];
```

Here you have a 3D array. Where the 2D array : array[..][..] has 2 elements inside it.

Or you can use structure.

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

then :

```
struct number array[10][10];
```


Question:
Does anyone know how to enable the use of OpenMP in Xcode 9.0?

In Xcode 8, I procide as described inthis tutorialbut it doesn't work anymore in Xcode 9.0 ...

The error is :clang-5.0: error: cannot specify -o when generating multiple output files

Thanks in advance for help

Answer:
I think the problem is in flag -index-store-path
In build settings > build options set Enable Index-While-Building Functionality to No


Question: I'm new embedded electronics and am learning via online tutorials.  I built and downloaded a code (with the uVision IDE) which made the blue and orange LEDs flash.  I want these LEDs to stop flashing, and I want the MCU to go back to the state it was at before I downloaded the code.  How would I do that?

Answer:
How to return:

Write FLASH mass erase functionCopy mass flash erase function to the RAM.Jump to itDo the software reset


Question:
I installed the MJPG-Streamer and i want to run this from a C program.
I start the MJPG-Streamer entering the following code in the pi terminal:

```
LD_LIBRARY_PATH=/usr/local/lib mjpg_streamer -i "input_file.so -f /tmp/stream -n pic.jpg" -o "output_http.so -w /usr/local/www"
```

I want to run mjpg streamer from a C program, how do I do this?

Thanks!

Answer: You can usesystem()function inside stdlib header.


Question:
This question already has answers here:What happens when I use the wrong format specifier?(2 answers)Closed5 years ago.

i have used the code.

```
char *y;
y="hello world";
printf("%c",y);
```

it just shows something useless.
What mistake i am making.

Answer:
Change :

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

to :

```
printf("%s",y);
```

as%cspecifier indicates achar. To identify a string, you need the specifier%s.


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

int a = printf("cs136/n");

int main(){
  printf("%d\n", a);
}
```

Error: (initializer element is not a compile-time constant)

Answer:
You can't use printf outside of an function. Move the line "int a = printf..." inside main.

You variable "a" is an global variable. You can only initialize "a" with an constant. For example:

```
int a = 42;

int main()
{
   a = printf(...
```


Question:
I saw the following line of codeherein C.

```
int mask = ~0;
```

I have printed the value ofmaskin C and C++. It always prints-1.

So I do have some questions:

Why assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?

Answer: It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.


Question:
I saw the following line of codeherein C.

```
int mask = ~0;
```

I have printed the value ofmaskin C and C++. It always prints-1.

So I do have some questions:

Why assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?

Answer: It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.


Question: Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?

Answer:
Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address.

llvm::Function Documentation


Question:
I need to print.5as0.5using theprintfstatement in C language.
It can be done easily using  the following code.

```
printf("%03f", myfloatvalue);
```

But the situation ismyfloatvalueis dynamic. So i am not sure whether it is a 3 character number, it could be.5or.56or.567. In the above cases i need to print as0.5,0.56, and0.567.

Answer:
%gdoes print the shortest possible representation of a float.

```
printf("%g",myfloatvalue);
```


Question: Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?

Answer:
Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address.

llvm::Function Documentation


Question:
Is this statement correct in C-language?

```
a && b && c
```

I want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?

Answer: Yes, the usage is correct. You can AND as many expressions as you want.


Question:
Is this statement correct in C-language?

```
a && b && c
```

I want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?

Answer: Yes, the usage is correct. You can AND as many expressions as you want.


Question:
In my driver module data is coming in callback function.
I want to add data to read callback but not able to find read callback in tty structure

Answer: There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3


Question: I'm new to Linux and C and when trying to run a basic "Hello World" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code

Answer:
You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents.

Either navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.


Question:
In my driver module data is coming in callback function.
I want to add data to read callback but not able to find read callback in tty structure

Answer: There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3


Question: I'm new to Linux and C and when trying to run a basic "Hello World" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code

Answer:
You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents.

Either navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.


Question:
This question already has answers here:hello world in C without semicolons and without IF/WHILE/FOR statements [closed](7 answers)Closed6 years ago.

I want to display hello world message in c without using semicolon. how can I do that?
Is it possible?

Answer:
Yes, It is possible.

```
#include<stdio.h>
int main(){
   if(printf("hello world")){}
}
```


Question: I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?

Answer:
There is a checkbox in Menue

"Settings""Editor..."General SettingsEditor SettingsEnd of Line options"show end of line chars"


Question: I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?

Answer:
There is a checkbox in Menue

"Settings""Editor..."General SettingsEditor SettingsEnd of Line options"show end of line chars"


Question:
I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C.

```
set_title(uint16_t *title)
```

Any idea how can I do this ?

Answer:
You need some form of interprocess communication to be able to do that.

There are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.


Question: What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?

Answer: No, there is not. You will have to use pointers.


Question:
I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C.

```
set_title(uint16_t *title)
```

Any idea how can I do this ?

Answer:
You need some form of interprocess communication to be able to do that.

There are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.


Question: What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?

Answer: No, there is not. You will have to use pointers.


Question: If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?

Answer:
Use this:

#define DOSTUFF(X) dostuff_##X()

The preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x().

On the other hand, consider renaming your methods to something meaningful.


Question:
How would you simplify the following if-else-if ladder such that the function call is made only once?

```
if (Condition A){
    A();
}
else {
    if (Condition B) {
        A();
    }
}
```

Answer:
Change it to:

```
if ((Condition A) || (Condition B)) {
    A();
}
```

As you want the functionA()to run ifCondition Aistrueor ifCondition Bistrue, you can use the||(OR) operator. This returnstrueif either conditions aretrue.


Question: If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?

Answer:
Use this:

#define DOSTUFF(X) dostuff_##X()

The preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x().

On the other hand, consider renaming your methods to something meaningful.


Question: I have only a compiled binary code (.hex) of pic microcontroller,how can i convert it to code line in mikroc in order to see the instruction of program?

Answer: When it's compiled, it ismachine codeand there's no (automatic) way of translating machine code to C. Youcanget a readable version of the code,assembly, using adisassemblerfor your target CPU. This of course requires you learning your CPU's assembly language.


Question: I have a string"2017-07-30_00:00:00"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be helpful.

Answer: strptime()is suported by bionic (i.e. available in NDK).


Question: I have a string"2017-07-30_00:00:00"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be helpful.

Answer: strptime()is suported by bionic (i.e. available in NDK).


Question:
I want my program to convert characters into integers, but not into their ASCII equivalents.
For example,'A'should equal 0, not 65, while'B'should equal 1.
Then I want to add that number to an ASCII character and convert that value back to achar.

Answer:
```
char test = 'C';
int num = test - 'A';
// result: 2 with ASCII and any other encoding
// having the uppercase letters in sequence
```


Question:
what is the true path to prevent codeblocks error.

I know question very short but when I selected any path I am getting error

Answer:
1-Create New console C project

2-Right Click your project and click properties in the context menu

3-go to the libraries page

4-click 'Avaliable in pkg-config' in the known libraries layout

5-and make it like the following picture


Question:
I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it?

I tried to look for information on the Internet, but unfortunately I did not succeed.

:)

Answer: So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?


Question: I am creating an apache module using eclipse c/c++ on eclipse but I am getting this errorType 'apr_pool_t' could not be resolved Eclipse C/C++I included/usr/include/apacheand/usr/libwhere is the structureapr_pool_t?

Answer: I solved by myself. It is as simple as include /usr/include/apr-1.0 in right click on my project properties->C/C++General->Paths & Symbols.


Question:
I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it?

I tried to look for information on the Internet, but unfortunately I did not succeed.

:)

Answer: So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?


Question:
I'm trying to compile android-kernel-goldfish-2-6-29 but when i use make -j2 to compile it, i get this error:

include/linux/compiler-gcc.h:86:30: fatal error: linux/compiler-gcc6.h: No
 such file or directory
 #include gcc_header(__GNUC__)

my ubuntu is 17.04 and i downgrade my gcc to

gcc version 4.7.4 (Ubuntu/Linaro 4.7.4-3ubuntu12)

can any body fix the problem?

Answer: I changed the goldfish version from 2.6.29 to 3.18 and now everything is okay.


Question:
I'm unable to understand below this line , could somebody tell me what it does ?

```
fscanf(file_pointer, "%*[^\n]");
```

Answer:
From thedocsone might see, that:

*- assignment-suppressing character which is used not to assign the value being read to any receiveing argument offscanf.

[^\n]- conversion specifier which matches any symbol except (^) new line (\n).

As a result, thisfscanfreads all symbols until new line is met.


Question:
i'm a new devopler in CUDA 8 and compiling my codes with nvcc
how can i install conio.h into my compiler
by the way i'm running my code on server at a company
thanks

Answer:
The short answer: you can't.
CUDA is based on C, but is a different language and a different compiler. And conio.h is not even part of C standard.
You ca however use printf from a Cuda kernel


Question:
I have the text file with 2000 lines and each line contains up to 256 characters.

I need to detect EOF as I'm reading the file.

Should the code process a line as it is read or should it read the lines into an array and then process the array one element at a time?

Answer:
If the data don't change in your file, you should stock the data in an array.

In the other case, you have to read your file each time you need to check a line.


Question:
Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state.

Is this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.

Answer: Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.


Question:
Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state.

Is this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.

Answer: Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.


Question:
```
char* p = init();
p = foo(p);        /* this one */
```

the functionfooprototype:

```
char* foo(char* p);
```

Is it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?

Answer: Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.


Question:
```
char* p = init();
p = foo(p);        /* this one */
```

the functionfooprototype:

```
char* foo(char* p);
```

Is it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?

Answer: Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.


Question:
How to detect if cable is unplugged on W5100 Ethernet controller?.

IndatasheetI can't find register for cable detection. But chip provides LAN status LED.

Answer:
W5100does not support reading register to get status if cable is plugged or not (network available or not). You can only check by doingfake connectionand wait for either any response or timeout.

Instead, you should useW5200which has this feature.


Question:
I am getting the following compilation error:

prog.c:13:5: error: called object is not a function or function pointer
    a=250(n-1)+192;

```
#include <stdio.h>

int main(){
    long long n,a;
    int t;

    scanf("%d",&t);
    while(t--){
        scanf("%lld",&n);
        a=250(n-1)+192;
        printf("%lld\n",a);
    }
}
```

Answer:
In C, you always have to write a*character for multiplication, as this:

```
a=250*(n-1)+192;
```


Question:
I am getting the following compilation error:

prog.c:13:5: error: called object is not a function or function pointer
    a=250(n-1)+192;

```
#include <stdio.h>

int main(){
    long long n,a;
    int t;

    scanf("%d",&t);
    while(t--){
        scanf("%lld",&n);
        a=250(n-1)+192;
        printf("%lld\n",a);
    }
}
```

Answer:
In C, you always have to write a*character for multiplication, as this:

```
a=250*(n-1)+192;
```


Question:
In Allegro, I can set the Window to be resizeable by running

```
al_set_new_display_flags(ALLEGRO_RESIZABLE);
```

before

```
display = al_create_display(800, 600);
```

however, if I resize the window, how will I know how big the window is that I resize?

Answer:
useal_get_window_constraints(ALLEGRO_DISPLAY *display,
   int *min_w, int *min_h, int *max_w, int *max_h).

Source


Question:
I have a message encoded with Nanopb implementation of Google Protocol Buffers.

I have to decode it to display the decoded result on a php page.

Is it possible to do it with PHP ?
If not, what is the best solution to do it in order to get an exploitable result in php ?

Thanks for your help.

Answer:
Use php implementation of google protocol buffers like for instance:

google/protobuf/php

protobuf-php


Question:
I have a message encoded with Nanopb implementation of Google Protocol Buffers.

I have to decode it to display the decoded result on a php page.

Is it possible to do it with PHP ?
If not, what is the best solution to do it in order to get an exploitable result in php ?

Thanks for your help.

Answer:
Use php implementation of google protocol buffers like for instance:

google/protobuf/php

protobuf-php


Question: I am running my C program and I want to see the memory used by this. I am using the profilergprof. Is it possible withgprof? Or maybe I have to study theValgrindprofile?

Answer:
If you want to go down the Valgrind route, Massif is the tool to use:

valgrind --tool=massif your_app -your_options


Question:
This the short code, that produces adouble free or corruptionerror.

```
SDL_Surface *surface;
SDL_Surface *surface2;
surface = NULL;
surface2 = SDL_LoadBMP("someImg.bmp");
surface = surface2;
SDL_FreeSurface(surface);
SDL_FreeSurface(surface2);
```

I don't understand, why I can't free second surface before I free first.

Answer: Both variablessurfaceandsurface2point to the same object. You are effectively freeing twice the same object.


Question:
I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line.

```
#include <stdio.h>

    int main(){

    printf("Hello World");

    return 0;
```

}

Answer:
Use a newline character, represented as'\n'. The slash is an escape character for a few special characters, such as tab'\t', and carriage return'\r'.

printf("Hello World\n");


Question:
I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line.

```
#include <stdio.h>

    int main(){

    printf("Hello World");

    return 0;
```

}

Answer:
Use a newline character, represented as'\n'. The slash is an escape character for a few special characters, such as tab'\t', and carriage return'\r'.

printf("Hello World\n");


Question:
This question already has answers here:What is the full "for" loop syntax in C?(7 answers)Closed6 years ago.

My question is simple,thus I will not go in deep

can we usefor()loop without condition like this

```
for(;;space+=1)
{
printf("  ");
break;
}
```

Answer:
Of course you can. An empty condition is taken to evaluate to1.

for (;;){/*ToDo - your code here*/}is idiomatic C.


Question:
If I use uninitialized global variable in C program, What happens? Is it undefined behavior?

```
#include <stdio.h>

int i;

int main()
{
    while(i < 5)
    {
        i++;
    }
    printf("%d\n", i);
    return 0;
}
```

Answer:
Is it undefined behavior?

No.

What happens?

ihas static storage duration (file scope). It will initialize to zero by default.


Question:
This is what I'm trying to do:-

```
double x = 4.0
    double y = 4.0
    x+y = 8.0
```

The input has to be of double type only (given condition of the problem).

Answer:
```
printf("%.1lf", yournumber);
```

will do the trick. This will print value to1decimal place. In case number is1.123, printed number will be rounded, in this case to1.1.


Question: Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?

Answer: If you're not planning on doing math on a "number", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.


Question: Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?

Answer: If you're not planning on doing math on a "number", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.


Question: What isSuper Loopin Embedded C programming language?

Answer:
This refers to the eternal loop usually located inmain()of a "bare metal" system (no OS), since such systems can never return from main. A typical bare metal embedded system looks like this:

```
void main (void)
{
  // various initializations

  for(;;) // "super loop" or "main loop"
  {
    // do stuff
  }
}
```


Question:
I am using struct module for serializing the data to send the data over socket. I observed thatstruct.pack(frmt, value1, ...)returns a string of the value 1 intwo byteshexadecimal format. Why does it returnonly in two bytes format? There should be some reason. Maybe I am missing something while understanding struct class.

Thanks in advance.

Answer:
Read the documentation of thepython struct module

If you concern about the size of the packed result readthis


Question:
In GCC the following C code compiles correctly-

```
int i = 7;
i = 5i;
printf("%d", i);
```

And prints-0.

The statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?

Answer:
This is aGCC extension for representing the imaginary component of complex numbers.

The compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.


Question:
In GCC the following C code compiles correctly-

```
int i = 7;
i = 5i;
printf("%d", i);
```

And prints-0.

The statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?

Answer:
This is aGCC extension for representing the imaginary component of complex numbers.

The compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.


Question:
I want to know number of tokens in the statement given below

```
a+++b---c
```

Please tell me number of tokens
I told my viva teacher that there are 7 tokens but he said it is wrong.

Answer:
You are correct. There are seven tokens: (in C)

```
a
++
+
b
--
-
c
```


Question: Is there some tutorial available for Bullseye code coverage tool. Is it automated? How do we find line coverage using this tool?

Answer:
Function coverage and decision coverage are supported in Bullseye coverage tool.I dont think line coverage/statement coverage is supported. Please see this link.

http://www.bullseye.com/measurementTechnique.html


Question:
Confused, Why does this work when I compile, when hold is an integer?

```
char value = 'p';
int hold = value;
printf("%c", hold);
```

Answer:
First, in

```
int hold = value;
```

is performed implicit conversion fromchartoint.

Second, in

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

the%cspecifier means something asconvert it tocharand print it as symbol.


Question:
Confused, Why does this work when I compile, when hold is an integer?

```
char value = 'p';
int hold = value;
printf("%c", hold);
```

Answer:
First, in

```
int hold = value;
```

is performed implicit conversion fromchartoint.

Second, in

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

the%cspecifier means something asconvert it tocharand print it as symbol.


Question:
Confused, Why does this work when I compile, when hold is an integer?

```
char value = 'p';
int hold = value;
printf("%c", hold);
```

Answer:
First, in

```
int hold = value;
```

is performed implicit conversion fromchartoint.

Second, in

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

the%cspecifier means something asconvert it tocharand print it as symbol.


Question:
I want to detect the last element of an array of integer in C code.
Otherwise i need to stop handling array data when the array element is empty.
really my array have a maximum size fixed  and it was filled from an external file so i dont know when it stop filling the array.

Answer:
Last element is in position

```
sizeof(array)/sizeof(array[0]) - 1
```


Question:
I want to write in Makefile like this

```
foo: foo.c
        $(CC) -o foo -Wall foo.c
```

but I'm not sure if allccimplementations support-Wall.

Answer:
No, there is no standard regarding the command-line interface of C compilers.

The Microsoft compiler (in Windows) for instance does not accept options starting with-at all, since that's not the syntax typically used with Windows programs.


Question: I know how to use the two functions, but I do not know what the suffix "at" means. Does it represent the abbreviation of "another"?

Answer: At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.


Question: I know how to use the two functions, but I do not know what the suffix "at" means. Does it represent the abbreviation of "another"?

Answer: At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.


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

int main(void) {

    int i;
    i = 10;
    i*= 10+2;
    printf("%d",i);
    return 0;
}
```

why is the output of the following code 120 and not 102?

Answer:
Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=.

C reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence


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

int main(void) {

    int i;
    i = 10;
    i*= 10+2;
    printf("%d",i);
    return 0;
}
```

why is the output of the following code 120 and not 102?

Answer:
Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=.

C reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence


Question:
If you're going to define these at all, why not define them as

```
#define SIZEOF_INT sizeof(int)
```

etc. so they are correct even if someone tries to use them to compile against a different architecture?

Answer:
I found the answer a minute after asking the question. These macros are sometimes used in the predicates of #if etc. where sizeof calls cannot be evaluated.

For example

```
#if SIZEOF_LONG_LONG_INT == 8
stuff
#endif
```


Question: Is there any way in MPI to get the total number of bytes transferred by my entire MPI program in C?

Answer: The best way is to use a MPI profiling tool such as the simplempiP. There are more sophisticated / heavyweight tools that can also do that, such as Score-P. You should check if there is something available if you are running your code on an HPC site.


Question:
What is the optimal code for the following block:

```
if (a != b)
    a = b
```

Answer:
You can just do

```
a = b;
```

because this way only one assignment will be run every time instead of the possibility of a condition check and an assignment.


Question:
If i create a pointer like:

```
int *pointer;
```

is also a variable (called pointer) created in the C Language? Why/why not?

Answer:
Let's get the terminology straight:

int *pointerdeclares a variableVariables have a name and a typeThe name of the variable ispointerThe type of the variable is "pointer toint"


Question: i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?

Answer: Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.


Question: i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?

Answer: Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.


Question:
This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago.

I got this message when I compiled a C program

"fatal error: dos.h: No such file or directory
compilation terminated."

I am currently using Ubuntu 16.04

Answer: I believe you can't do that, because from the sound of it, "dos.h" is specific to MS-DOS.


Question:
This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago.

I got this message when I compiled a C program

"fatal error: dos.h: No such file or directory
compilation terminated."

I am currently using Ubuntu 16.04

Answer: I believe you can't do that, because from the sound of it, "dos.h" is specific to MS-DOS.


Question:
I'm looking at a program that was written in C and I need to write it in C#.

What is the C# equivalent of this whole line?:

```
printf("%s", " ");
```

Answer:
If you can use C# 6, you could use string interpolation, and go like this.

```
Console.WriteLine($"{variableName} text");
```


Question:
This question already has answers here:Escape character in C(6 answers)Closed6 years ago.

I need to check into a loop if the user inserts '\' for exiting from the menu.

```
while(choise != '\'){
 // do stuff
}
```

But I get this error:

error: missing terminating ' character

Answer:
Backslashes are special characters and need to be escaped with another backslash:

```
while (choice != '\\') {
```


Question:
I'd like to store the variable(two spaces) in C.

It looks like there are no string data types in C, so how can I store such a value without having to create astring s = get_stringfunction?

Answer:
Strings in C programming are built as arrays of chars.

In your case:char c[] = "  ";


Question:
When we are writingprintf()in C, are we declaring it or defining?
If it is a definition then where is the declaration and vice versa?

Answer:
When we are writingprintf()in C, we are making a call toprintf,
which has adeclarationin the<stdio.h>header like thisint printf(const char *format, ...);, and we should include that header in the C program.

Thedefinitionofprintfis in the standard library implementation that
gets linked with the application code.


Question:
When we are writingprintf()in C, are we declaring it or defining?
If it is a definition then where is the declaration and vice versa?

Answer:
When we are writingprintf()in C, we are making a call toprintf,
which has adeclarationin the<stdio.h>header like thisint printf(const char *format, ...);, and we should include that header in the C program.

Thedefinitionofprintfis in the standard library implementation that
gets linked with the application code.


Question: I am getting stuck because of this error and can't test my application.

Answer:
You only can specific value indimentag. So, please give them aspordpvalue instead of name.

Hope this helped.


Question:
Will this work?
I expect

```
foo(myArraypointer + 10);
```

be the same as

```
foo( &(myArraypointer[10]));
```

will this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?

Answer: For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.


Question:
Will this work?
I expect

```
foo(myArraypointer + 10);
```

be the same as

```
foo( &(myArraypointer[10]));
```

will this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?

Answer: For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.


Question:
I have a function which splits a string into tokens and stores it in an array. How to determine the size of an array of strings of typechar**?

```
ie: char **input;
```

Answer: Keep a variable globally and increment that variable value in the function which is splitting the string into tokens & storing into array.


Question: How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?

Answer:
I solved the problem by adding following linker flag in project'sCMakeList.txt

```
MATH(EXPR stack_size "16 * 1024 * 1024") # 16 Mb
set(CMAKE_EXE_LINKER_FLAGS "-Wl,--stack,${stack_size}")
```


Question: How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?

Answer:
I solved the problem by adding following linker flag in project'sCMakeList.txt

```
MATH(EXPR stack_size "16 * 1024 * 1024") # 16 Mb
set(CMAKE_EXE_LINKER_FLAGS "-Wl,--stack,${stack_size}")
```


Question:
When duplicating a file descriptor fd calling dup, and closing the original file descriptors.

Do all the duplicated file descriptors get closed also?

Answer: No the duplicates won't be closed. Otherwise the main use-case (duplicating intoSTDOUT_FILENOandSTDIN_FILENO) would be pretty useless.


Question: If I use goto instruction inside a recursive function (wanting to exit the function before it finishes naturally) is the stack freed automatically or not?

Answer:
no, and so far as I know most compilers will not goto to exit the current function.

if you must escape directly from deep recursionthrowanexception(c++) or uselongjmp(c)  these actions will restore the stack.


Question: I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.

Answer: You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.


Question: Suppose I'm writing a program for an environment that has 32 bits for virtual spaces addresses (4294967296 addresses), what happens if create more than 4294967296 variables, effectively exceeding the number of possible addresses? Or all programs in an environment collectively use over 4294967296 addresses?

Answer: It depends precisely how you try to do it. It may crash, it may return an error, it may throw an exception.


Question:
I have a string char * a = '343'. I want to convert it into integer value.

Example.
char *a = "44221"
I want to store that value into into int a;

Answer:
This is is part of most C runtimes:

```
#include <stdlib>

char *a = "1234";
int i = atoi(a);
```

That's theatoifunction. Do read through the various methods available. C's library is pretty lean so it won't take long.


Question:
I'm  writing some kind of protocol to transmit with the NRF24 module so, the procotol is declared like this:

```
unsigned char protocol[16];
```

that protocol have 16bits or 16bytes size?

Answer: 16 bytes. 1 char is generally 1 byte on most systems.


Question: I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.

Answer: You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.


Question:
I have a cordova project and I added windows platform but when I run the project I have this error:

```
MSBuild v4.0 is not supported, aborting.
Error: AppPackages doesn't exists
```

Answer:
Try to set OS environment variable
VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\
which points to your Visual Studio folder with MSBuild directory.


Question:
I have a cordova project and I added windows platform but when I run the project I have this error:

```
MSBuild v4.0 is not supported, aborting.
Error: AppPackages doesn't exists
```

Answer:
Try to set OS environment variable
VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\
which points to your Visual Studio folder with MSBuild directory.


Question:
I have a cordova project and I added windows platform but when I run the project I have this error:

```
MSBuild v4.0 is not supported, aborting.
Error: AppPackages doesn't exists
```

Answer:
Try to set OS environment variable
VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\
which points to your Visual Studio folder with MSBuild directory.


Question:
I have define below array in int data types with hexa decimal data.

```
volatile int Send_Data[3] = {0x0H11, 0xAAAC, 0x0DD0};
```

How can I initialize hex array with int data type in c language?

Answer:
Hex array does not exist. Hex is only representation for numbers in computer language (used for programmers).

```
volatile int Send_Data[3] = {1, 2, 3};
```


Question:
I'm having issues with a c program that I want to debug.
I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it.
Thanks :)

Answer:
For GCC specify-gwhen compiling.

More here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html


Question:
I'm having issues with a c program that I want to debug.
I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it.
Thanks :)

Answer:
For GCC specify-gwhen compiling.

More here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html


Question:
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago.

like 52.7-->53, 5.5-->6, 3.2->3

Answer:
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:

```
((int)(num + ((num > 0)? +0.5 : -0.5)))
```


Question:
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago.

like 52.7-->53, 5.5-->6, 3.2->3

Answer:
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:

```
((int)(num + ((num > 0)? +0.5 : -0.5)))
```


Question:
I know thatint  *(*func)()means a function pointer which takes no arguments and returns an integer pointer but what does the following syntax means in C:

```
int *(*func())[]
```

Any explanations on how do we read such syntax in C would be very helpful.

Answer:
funcis a function and returning a pointer to an array of pointers to int.

reference link :http://gateoverflow.in/35193/regarding-pointers


Question:
I have a dynamic array of c-strings

char **my_strings = (char**)malloc(50 * sizeof(char*));

and I want to find it's actual length (how many strings it actually contains). How can I do this?

Answer:
You can't tell: it's your job to keep track of the size, or to use a magic value (NULL, say) to mark the final element.

Note that the c runtime probably keeps track of the amount of memory allocated, but this is not exposed to you in any portable way.


Question:
When attempting to compile

```
#include<stdio.h>

int main(){

printf("Hello World");

return 0;

}
```

I get the following errors with Solaris11 gcc:

hello.c:4:23: error: expected expression before ';' tokenhello.c:6:1: error: expected ';' before '}' token

Visual C++ can compile this code.

Answer: the '；' in line four (thereturnstatement) is not a standard ';'.


Question:
My function isvoid x(int *y);

I want to call it likex(&6);orx({6});,  I do not want to define an integer and assign 6 to it, I want single line.

Answer:
What you need iscompound literals

```
#include <stdio.h>

void x(const int *y)
{
    printf("%d\n", *y);
}

int main(void)
{
    x(&(int){6});

    return 0;
}
```


Question: I'm trying to read 4 user inputs that can either be one digit, two digits, or a letter. I've tried using %c, but that can't contain any two digit numbers. I've  also tried %d, but that reads all letters as 0. Is there anything that can cover all the bases?

Answer: In C there %c is usually for character inputs and %d is for integer. Usually you use these when scanning. Try %s this scans a string.


Question:
```
'#include <stdio.h>
int main()
{
    short arr[3][2]={3, 6, 9, 12, 15, 18};
    printf("%d  %d", *(arr + 1)[1], **(arr + 2));
}'
```

The output of the program is 15,15?

Answer: As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]


Question:
```
'#include <stdio.h>
int main()
{
    short arr[3][2]={3, 6, 9, 12, 15, 18};
    printf("%d  %d", *(arr + 1)[1], **(arr + 2));
}'
```

The output of the program is 15,15?

Answer: As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]


Question: How to do stop scrolling uitableview if new rows are not there in tableview in objective c?

Answer:
For disabling bounces for the tableView you can use:

```
self.tableView.bounces = NO;
```

this will disable it when it gets to the last row


Question:
Im new to programming with C and I'm having a hard time coming up with the proper formula to where it ignores, spaces, tabs, and new lines when I enter a string

My Current Code

Answer: Replaceelse specialCharacter++;withelse if(!isspace(str[x])) specialCharacter++;.


Question: For a class project I am writing, my teacher's style guide for functions says that "input parameters must appear before out parameters." I am not too sure what they mean by this?

Answer:
If I have a function

```
void foo(int a, int b, int* c)
{
    *c = a+b;
}
```

In the above case a and b are inputs while c is an output.

Generally you use "outputs" in this way if you are returning an array.


Question:
I did not understand why this works:

```
if(1)
{
    int i;
}
```

and this not:

```
if(1)
    int i;
```

error: expected expression before int

If you could supply some standard reference.

Answer: In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).


Question:
I did not understand why this works:

```
if(1)
{
    int i;
}
```

and this not:

```
if(1)
    int i;
```

error: expected expression before int

If you could supply some standard reference.

Answer: In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).


Question:
Got this

```
char array1[10][10];
```

Is it possible to get address of array1 ? In which type could I stock it ?
Already tried the following:

```
char *hold[10][10];
hold = &array1;
```

But doesnt work, ideas?

Answer:
What you have now is a 2D array ofchar *.  You need some parenthesis in this type.

```
char (*hold)[10][10];
```

This is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.


Question: Can someone please explain to me the difference between saya=1and*a=1in C.  I'm having difficulty conceptualizing how pointers are used.

Answer:
a = 1assigns1toa.

*a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)


Question:
Got this

```
char array1[10][10];
```

Is it possible to get address of array1 ? In which type could I stock it ?
Already tried the following:

```
char *hold[10][10];
hold = &array1;
```

But doesnt work, ideas?

Answer:
What you have now is a 2D array ofchar *.  You need some parenthesis in this type.

```
char (*hold)[10][10];
```

This is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.


Question: Can someone please explain to me the difference between saya=1and*a=1in C.  I'm having difficulty conceptualizing how pointers are used.

Answer:
a = 1assigns1toa.

*a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)


Question:
Can anyone explain what $(%SYMBOLIC) means in the make file target below?

```
R_all:  $(%SYMBOLIC)
    $(CD_MAKE) $(BASE_ROOT)    R_all
```

Answer: That's just a variable called%SYMBOLIC.  Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve


Question:
Can anyone explain what $(%SYMBOLIC) means in the make file target below?

```
R_all:  $(%SYMBOLIC)
    $(CD_MAKE) $(BASE_ROOT)    R_all
```

Answer: That's just a variable called%SYMBOLIC.  Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve


Question:
This question already has answers here:Two semicolons inside a for-loop parentheses(4 answers)Closed6 years ago.

I'm analyzing a C program and i find this loop that i can't understand. There is no counter or limit or variable.

```
/* ioloop */
  for (;;)
  {
// statements

  }
```

is this an infinite loop ?

Answer:
It's an idiomatic way of writing a potentially infinite loop in C.

Alternatives such aswhile(1)often issued a compiler warning.


Question: What's the exact difference betweenprintkandpr_infofunctions ? And under what conditions, should I choose one over the another ?

Answer:
Thekernel's printk.hhas:

```
#define pr_info(fmt,arg...) \
    printk(KERN_INFO fmt,##arg)
```

Just like the name,pr_info()isprintk()with theKERN_INFOpriority.


Question: I am working on a project in the X11 API, and I have a Window based custom control consistently rendering. But for some reason, when I re-size the window, the control does not redraw unless I interact with the control directly, or move the entire main window.

Answer:
I found the solution to my problem. I just needed to add the Structure Notify Mask to my custom window input.

```
XSelectInput(display, CustomWindow, StructureNotifyMask);
```


Question:
Regarding c variables, I want to know what the x does in:

```
int var[x]
```

Answer:
This is a declaration of aVariable Length Array(VLA).

The value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.


Question: Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?

Answer:
Yes it exactly the same. According to theposixstandard

The dup() function provides an alternative interface to the service
  provided by fcntl() using the F_DUPFD command. The call dup(fildes)
  shall be equivalent to:fcntl(fildes, F_DUPFD, 0);

dup()is shorter and easier to read, I would use that.


Question:
Regarding c variables, I want to know what the x does in:

```
int var[x]
```

Answer:
This is a declaration of aVariable Length Array(VLA).

The value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.


Question: Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?

Answer:
Yes it exactly the same. According to theposixstandard

The dup() function provides an alternative interface to the service
  provided by fcntl() using the F_DUPFD command. The call dup(fildes)
  shall be equivalent to:fcntl(fildes, F_DUPFD, 0);

dup()is shorter and easier to read, I would use that.


Question: I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?

Answer: Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.


Question: I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?

Answer: Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.


Question:
I have recently started to learn ANSI C. I have come across this:

```
int a[7];
*(a+2);
```

I don't understand how it's possible to add 2 toa. Does it add 2 to every element ina?

Also, what is the function of the*? Does it create a pointer?

Answer:
a+2causesato be interpreted as a pointer toa's first element. This is calledarray decaying.

It then offsets that pointer by2anddereferences(*) the resulting pointer. So it's the same asa[2].


Question: Are there any static code metrics tools that measure total size of static local variables in c functions. The tools that I explored report the stack size but not the size of the static local variables. Is there another option apart from using linux objdump and parsing the output?

Answer: The POSIXsizecommand can be used for this purpose. The size of the data section is the size of all data in static storage (except data declared const on some targets).


Question:
Everytime I compile and run c file, I have to type:

gcc filename.c

a.out

I don't want to do this in two lines, How to compile and run in one line on linux terminal?

Answer:
Try

```
gcc filename.c && a.out
```

It only runs the second command if the first was successful.  Seehttps://askubuntu.com/questions/334994/which-one-is-better-using-or-to-execute-multiple-commands-in-one-line


Question:
The .txt file will have the matrix we need to input into our program, it may have more than one matrices.

I am using VIM editor on Linux.

Is there any specific escape sequence to copy the .txt file while compiling?

Answer:
To redirect standard output to a file, the>character is used like this:

ls > file_list.txt

And To take input from the file , the<character is used like this:

./a.out < input.txt


Question:
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage :

What I was trying to print was the statement :

```
With the formatting character %p and '&'
```

Answer:
Using double percentage i.e.%%will print single%for you:

```
printf("With the formatting character %%p and '&'\n");
```


Question:
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage :

What I was trying to print was the statement :

```
With the formatting character %p and '&'
```

Answer:
Using double percentage i.e.%%will print single%for you:

```
printf("With the formatting character %%p and '&'\n");
```


Question:
I want the program to print the wordhelloto the text file by means of strings.

```
#include <stdio.h>

void main ()
{
    char word[10] = {"hello"};
    FILE*fp;
    fp = fopen("C:\\temp\\Dictionary.txt", "w+");

    fprintf(fp, word[0]);
}
```

Answer: You're printing first char instead of the string. And it might not be a valid format either. Correct call will befprintf(fp, "%s", word). And don't forget to close file too.


Question:
Is it possible to multiply usingi**in C?
For example, I can incrementiusingi++. Why doesn'ti**work in C?

```
#include <stdio.h>
int main(void)
{
    int result;
    for (int i = 2; i < 100; i**){
        result = i + 1;
        printf("%i\n", result);
    }

    return 0;
}
```

Answer: No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.


Question:
Is it possible to multiply usingi**in C?
For example, I can incrementiusingi++. Why doesn'ti**work in C?

```
#include <stdio.h>
int main(void)
{
    int result;
    for (int i = 2; i < 100; i**){
        result = i + 1;
        printf("%i\n", result);
    }

    return 0;
}
```

Answer: No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.


Question:
Let's say we have the following C code:

```
#include<stdio.h>
int main(){
  char *a = "askakasd";
  return 0;
}
```

I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:

Answer: It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.


Question:
Probably really trivial question, but:

Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).

What are the options to do this in C?
Should i spawn a new thread?

Answer with an example would much appreciated!

Answer: Ended up spawning a new thread and doing stuff that way.


Question:
Let's say we have the following C code:

```
#include<stdio.h>
int main(){
  char *a = "askakasd";
  return 0;
}
```

I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:

Answer: It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.


Question:
Probably really trivial question, but:

Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).

What are the options to do this in C?
Should i spawn a new thread?

Answer with an example would much appreciated!

Answer: Ended up spawning a new thread and doing stuff that way.


Question:
Probably really trivial question, but:

Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).

What are the options to do this in C?
Should i spawn a new thread?

Answer with an example would much appreciated!

Answer: Ended up spawning a new thread and doing stuff that way.


Question: !I had written this simple program on a different Ubuntu PC using Gedit]1

Answer:
You do not have execute permissions for your executable.

Use

```
chmod +x ./secondo
```

first to correct this.

Thisquestion gives more detail.


Question: !I had written this simple program on a different Ubuntu PC using Gedit]1

Answer:
You do not have execute permissions for your executable.

Use

```
chmod +x ./secondo
```

first to correct this.

Thisquestion gives more detail.


Question:
How to decide if two ip are on the same subnet or not?
The only input is the ip address and the subnet mask!
What is the optimal way, usingC/C++, to compute if two ip have the same subnet?

Answer:
```
bool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) {
   return (ipA & subnetMask) == (ipB & subnetMask);
}
```


Question: I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.

Answer:
If you are on Windows

system("cls");

If you are on Linux/unix

system("clear");


Question:
How to decide if two ip are on the same subnet or not?
The only input is the ip address and the subnet mask!
What is the optimal way, usingC/C++, to compute if two ip have the same subnet?

Answer:
```
bool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) {
   return (ipA & subnetMask) == (ipB & subnetMask);
}
```


Question: I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.

Answer:
If you are on Windows

system("cls");

If you are on Linux/unix

system("clear");


Question:
How to cast "ptr" to assign directly a zend_long into it without writing two lines?

```
zend_long *val = *ptr;
*val = *(ISC_LONG*)var->sqldata;
```

Answer:
Assuming that your original code is correct, the corresponding assignment looks like this:

```
*((zend_long*)*ptr) = *(ISC_LONG*)var->sqldata;
```


Question: I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?

Answer: Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.


Question:
How would I go to cast/convert literalchar '0'toint 0?

i.e.:

```
char string[] = "0101";
char ch = string[0];
x = magic(ch);
if (x)
    printf("int zero")
```

Answer:
```
ch = 0;
```

Now, if you want to convertanydigit-character to its numeric equivalent, you'd need something like:

```
ch = ch - '0';
```


Question: I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?

Answer: Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.


Question:
How would I go to cast/convert literalchar '0'toint 0?

i.e.:

```
char string[] = "0101";
char ch = string[0];
x = magic(ch);
if (x)
    printf("int zero")
```

Answer:
```
ch = 0;
```

Now, if you want to convertanydigit-character to its numeric equivalent, you'd need something like:

```
ch = ch - '0';
```


Question:
It is undefined behavior to do this?

```
char *a = "hello";
char b[] = "abcd";
a = b;
```

My compiler throws no warning, with the maximum warning level.

Answer:
There is no UB here. You are simply re-assigning a pointer to point at the address of the start of the array instead.

Note that you are not actually modifying the value thatais pointing at, onlyaitself, andais a normalchar *.


Question:
How to convert rgb to hexadecimal using GTK?

I can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.

Answer:
You can do this manually:

```
sprintf(spec, "#%02X%02X%02X", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255));
```

Be sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.


Question:
How to convert rgb to hexadecimal using GTK?

I can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.

Answer:
You can do this manually:

```
sprintf(spec, "#%02X%02X%02X", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255));
```

Be sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.


Question:
This question already has answers here:Maximum size of a bit field in C or C++? [duplicate](2 answers)struct bitfield max size (C99, C++)(4 answers)Closed6 years ago.

Is the following code legal?

```
struct BigInt {
     uint64_t a : 128;
};
```

Answer:
A bitfield must fit within a singleint, so you're out of luck unlessintis 128 bits on your platform.

(You were also missing a;at the end of thestructprior to the edit.)


Question:
I have one program that uses shared library. In shared library, error case they have written exit(0). So if that function is called then exit(0) will be executed of shared library.

Will it exit my program too ?

Answer: Yes it  terminates the calling process immediately.SIGCHLD signal will be  send to process which  inherited by process 1 or init.


Question:
I got a warning:

```
assignment makes integer from pointer without a cast.
```

The line that triggers the warning is:

```
nev[i][0]="";
```

Thenevvariable is a 2 dimension char block(please don't ask why, I don't know).

Thanks in advance guys!

Answer:
Ifnevis a 2-dimensional array ofchar, thennev[i][0]is achar. But""is an array ofchar, not achar.
                    – Barmar

nev[i][0]="";-->nev[i][0]=0;– BLUEPIXY


Question:
As the title suggests, I would like to create connection between a JavaScript (usingWebSocket) client and a C/C++ (usingWinsock) server.

A simple code example would be much appreciated.

Answer: You can't use Websocket at java side and a Winsock only implementation on C++ side, you have to implement Websocket over winsock or using some thing like Qt Platform which has an implementation Websocket under C++. sample codes are available onQt Docs.


Question:
In my program I have got a NxN table stored in one-dimensional table.
So, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly

So, what if my board becomes N1xN2 and N1 is different than N2?
How should I set the #define instruction then?

thank you in advance

Answer: It shouldn't work perfectly.  You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1


Question:
In my program I have got a NxN table stored in one-dimensional table.
So, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly

So, what if my board becomes N1xN2 and N1 is different than N2?
How should I set the #define instruction then?

thank you in advance

Answer: It shouldn't work perfectly.  You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1


Question:
I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36).
Thanks a lot!

Answer:
sample code

```
#include <stdio.h>

int main(void){
    char x = '\xD6';
    char asc[3];
    sprintf(asc, "%02X", (unsigned char)x);
    printf("%s\n", asc);//D6
}
```


Question:
I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36).
Thanks a lot!

Answer:
sample code

```
#include <stdio.h>

int main(void){
    char x = '\xD6';
    char asc[3];
    sprintf(asc, "%02X", (unsigned char)x);
    printf("%s\n", asc);//D6
}
```


Question:
I'm searching for a method to convert a two Byte UNICODEora variable (1-3 Byte) UTF-8 string to Chinese Simplified (GB2312). I found a lot of methods for php, Java, C# and Windows but nothing for standard "C".

Right now, my best solution is to translate this JavaScript example:https://gist.github.com/19317362/a1d8e40bfb6587463d4d

Thanks in advance!

Answer: As Remy Lebeau mentioned, I used the C-compatible library iconv.


Question:
I know the difference betweenself.xxxand_xxxBut I don't understand the difference betweenself->_xxx = yyyand_xxx = yyy

Is it only a matter of writing in ObjC and C?

Answer:
When accessing an ivar there is no difference betweenself->_ivarand_ivarin terms of resulting compiled code.

Only use case I can think of where it matters is if you have another local or global variable with the same name in the same scope, and you want to use the ivar.


Question: Normally when a foo() have memory problem the whole program will simply core dump, crash. But does C have any protection ways to guarantee a program will not crash, just goto a state or simply return, when core dump happens inside foo()?

Answer:
Can not say for try and catch statement in c but yes you can write signal handler to catch segfault.
Here is a link.How to catch segmentation fault in Linux?


Question:
The code i'm looking for is the following :

We have a source number100, a destination number,50and we have10steps.
100 ----> 50 in 10 steps.

How can i find the value X, corresponding tothe number i have to subto 100, 10  times to have 50. I found :dest*steps/srcbut didn't work...

Regards.

Answer:
It's as simple as this

```
X = (src-dest)/NumOfSteps
```


Question:
I was trying some C codes in Dev C++ and Visual C++.

For Example:

```
int t =6;
printf("\nt = %d ",&t);
```

The output is :

```
t = 2358848
```

why is it so ? How can I get the value of t?

Answer:
&tgives you theaddress oft, not its value.

To print the value do:

```
printf("\nt = %d ", t);
```


Question: If I have a .jar file with a compiled scala method, is there any way to call it from a C/C++ dll ? How can I do this? I have only been able to find infos on the opposite.

Answer: A Scala program (once compiled) is a Java class. So follow this suggestion:How to access the Java method in a C++ application


Question:
When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024.

system("ulimit -d 1024");
system("ulimit -d");

Answer:
If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA.

system()will fork and the ulimit command only affects the child process, not the calling process.


Question:
When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024.

system("ulimit -d 1024");
system("ulimit -d");

Answer:
If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA.

system()will fork and the ulimit command only affects the child process, not the calling process.


Question:
So I compiled a simple cpp program using clang++ with termux on android, but I can't run the program, I get the following error:

```
$ ./execname
-bash: . /execname: Permission denied
```

Answer:
Are you running on shared storage (under/sdcard)? The file system there does not support executable permissions.

Try compiling and running the file directly in the$HOMEdir!


Question: I wrote my c program add.c, then preprocessed with cpp, then compiled with CC to obtain an add.s file. Now I would like to open it to see the assembly code. Can't find a way to do it.

Answer:
The.sfiles are basically assemblersourcefiles, so you can pretty much open them in whatever tool you used to create the.cfiles in the first place.

In other words, mere mortals will opt forNotepad++orEmacs, but the true intelligentsia will useVim:-)


Question:
This question already has answers here:How to generate a random int in C?(32 answers)Closed6 years ago.

Here is my code:

```
alpha = ((rand() % 12) + 1) * 2 + 1;
```

I want to generate randomoddnumbers between 0-25. But except integer13. How can I fix this? Thank you.

Answer:
Generates number from 0 to 23. If it's a 13, then store 25 in your variable :

```
alpha = ((rand() % 11) + 1) * 2 + 1;
if (alpha == 13) alpha = 25;
```


Question: I have achar*to where I want to set the byte, from malloc. How do I set it to 1 or 0, for example?

Answer:
Assign to your dereferenced pointer:

```
//This will (obviously) set it to 1
*your_pointer = 1;

//This will set it to 0
*your_pointer = 0;
```


Question:
```
char msg[100] = {’C’,’P’,’R’,‘E’,‘\0’,‘2’,‘8’, ‘8’,‘\0’};
int my_length = 0xFFFFFFFF;
my_length = strlen(msg);
```

I thought it is nine, however, the answer is 4. anyone can explain? thanks

Answer:
strlenwill stop counting as soon as it hits a null terminator (as C uses null terminated strings and expects to only find them at the end of a string).

You have four characters before your first null terminator, therefore the length is 4.


Question:
I am trying to compile a C program and am required to use these flags. I was hoping you could tell me why I am getting these errors.

Command:

```
gcc -ansi –Wall –pedantic stack.c
```

Output:

gcc: –Wall: No such file or directorygcc: –pedantic: No such file or directory

Answer:
It's

```
gcc -ansi -Wall -pedantic
```

You're using one of those dashes:Dash(specifically, you are using en-dash U+2013). You need to use minus sign-instead


Question: I am working on compiler design for 8051. I want to declare a memory of say 30 locations, each location is of 8bits. How do I declare that in C?

Answer:
to declare 30 x 8 bits memory:

```
char memory[30];
```

to declare n x n memory:

```
char memory[30][30];
```

it declares 30 x 30 x 8bits memory.


Question:
What is the exact equivalent of the following function for Ubuntu?

http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html

Answer:
What you need is:

```
#include <endian.h>

result_in_host_endianness = be16toh(my_big_endian_number)
```

Seehttp://man7.org/linux/man-pages/man3/endian.3.html


Question:
What is the exact equivalent of the following function for Ubuntu?

http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html

Answer:
What you need is:

```
#include <endian.h>

result_in_host_endianness = be16toh(my_big_endian_number)
```

Seehttp://man7.org/linux/man-pages/man3/endian.3.html


Question: I have several header and source files that I needed to create, in which there are functions that generate random numbers. If I wanted to initialize my rng,  where do I have to put my "srand(time(NULL))" line, in my code? Is it ok to put it in my main.c file? Does it affect the other source files?

Answer: Yes, you can put it in the main file. Once you callsrandit is applicable for the entire program, even if it has multiple files.