Question: I am writing software that needs to compare two _mm256 vectors for equality. However, I would like there to be a margin of error +/- 0.00001. Eg, 3.00001 should be considered equal to 3.00002. Is there a simple way to do this using SSE/AVX/AVX2 instructions?

Answer: Subtract values being compared, mask out sign with*_and_*or*_andnot_*, compare with*_cmpgt_*against your margin populated with*_set1_*


Question:
I found the following answer:Convert void* to double

However, I am getting segmetation fault. Why is that?

Code:

```
void * p = (void *) 1234;
double n = *(double *)p;
```

Answer: Pointerpis assigned to address 1234 that you chose atrandom?. You are then referencing arandomaddress. It does not correspond to a valid allocated chunk of memory.


Question:
```
FILE* file = fopen(some file)

pcap_t* pd = pcap_fopen_offline(file)

pcap_close(pd)

fclose(file)
```

This code occurs double free error.

Could you explain about this happening?

My Guess is that pd and file pointers are sharing some datas.

Answer: As the documentation says, thepcap_closefunction closes the files associated with thepcap_tstructure passed to it. Closing the file again withfcloseis an error.


Question: Many programs assumesizeof(int)==sizeof(unsigned int). IMO it is not and I cant find anything in the Standard which guarantees it. Am I right or wrong?

Answer: C11 6.2.5.6 (Types) says "For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements."


Question:
I have trouble understanding the difference between bitwise concatenate and or.
For example, I have to bianry values which is 1111 and 0000.
If I do 1111 | 0000, will I get 1111 or 11110000?
And if I get 11110000 as the result, when should I use | as or operation?

Answer: 1111 | 0000is1111. There is no bitwise concatenate operator.  You can use left shift<<to move bits to the left1111 << 4is11110000.


Question: I have a problem that need to resample 16 bits depth to 32 bit depth mp3 in c program. any suggestion where I can find some repo as reference or web site to start with?

Answer:
Decode the MP3 into WAV or AIFF format with PCM coding, up-sample, then re-encode.FFMPEGis good for that.

However word of advice: You don't gain audio quality doing this, You only have 16 bits of information per sample, you can't add more to it. That's how information theory work.


Question:
I am trying to rewrite the code from AVR to STM32. How to translate this code into STM32?

```
#define READ_IO     PIND & (1 << PD4)
volatile unsigned char data_in = 0;
data_in = (READ_IO) >> PD4;
```

I use STM32CubeIDE

Answer:
Assuming pin4 on port D.

```
data_in = !!(GPIOD -> IDR & (1 << 4));
```


Question:
I have the following piece of code:

```
#include <stdio.h>
int main() {
    printf("%c","ACEGIK"[3] - 1);
    return 0;
}
```

I know that the result is F.

What does the [3] -1 mean ?

Answer:
"AGECIK"is an array of chars

you're taking the third element (counting from 0)"ACEGIK"[3]that'sG

subtracting 1'G' - 1and getting characterF

[3]is applied to the array

while-1is applied to character/value got from the array


Question:
I have the following piece of code:

```
#include <stdio.h>
int main() {
    printf("%c","ACEGIK"[3] - 1);
    return 0;
}
```

I know that the result is F.

What does the [3] -1 mean ?

Answer:
"AGECIK"is an array of chars

you're taking the third element (counting from 0)"ACEGIK"[3]that'sG

subtracting 1'G' - 1and getting characterF

[3]is applied to the array

while-1is applied to character/value got from the array


Question:
Suppose that we have

```
int arr[3];
char str[20] = "{10,20,30}";
```

Is it possible to initialise arr with str?

Answer:
You can't do that specifically, statically, but you can kind of do the reverse.

You can create a "to string" macro like this:

```
#define __STR(x) #x
#define STR(x) __STR(x)
```

Then you can use it like this:

```
#define NUMS {10,20,30}
int arr[3] = NUMS;
char str[] = STR(NUMS);
```


Question:
I have CodeBlocks 13.12 and I want to compile a c99 code on it. Is there any way I can do this. If there is any other way to compile a c99 code, that is okay as well.
Thanks!

Answer: From the option of add new flag I added-std=c99in the tab for compiler flag and it works.


Question:
Is there any way to store a glut color in a variable, like instead of doing this:glColor3f(1.0, 1.0, 1.0);being able to do this:

```
glColor white = glColor(1.0, 1.0, 1.0);
glColor3f(white);
```

which in turn creates much more readable code

Answer:
I suggest to store the color in an array and set the color withglColor3fv:

```
float white[3] = {1.0f, 1.0f, 1.0f};
```

```
glColor3fv(white);
```


Question:
I want to create the following looking 2D array of "-"

I attempted something like this but it did not work (for 10 by 10)

```
char table[10][10];

for (int i = 0; i < 10; i ++){
    for (int j = 0; j < 10; j++)
    {
        strcpy(table[10][i], "-");
    }
}
```

Answer:
The whole 2D array?

If not strings, usememset(table, '-', sizeof table);to fill every byte with'-'. Noforloop needed.


Question: I would like a method of flushing the instruction cache similar to__builtin___clear_cachein GCC but for clearing the instruction cache independent of the compiler. Is there any POSIX + C Standard compliant way to do this?

Answer: There is no C Standard method of flushing the instruction cache.


Question:
Consider the following pointer declarations.

```
int *p[10];

int (*q)[10];
```

What is the difference between 1st and second. How to read them in plain English?

Example:

```
int *p; // it will be read as "p is a pointer to an int"

int **p;  // p is a pointer to an integer pointer.
```

Answer: int *p[10]is an array of10pointers toint.int (*q)[10]is1pointer to an array of 10ints.


Question: Once I have enabledO_NONBLOCK, and then call a non-blocking function, and after it returns some I/O error happens, how may I get to know that something bad has happened, and how to handle it?

Answer:
You get the errors when they are ready for you to see them and you are ready to receive them.

sooner or later you end up calling read() or close() or whatever and that will give you the error.


Question:
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed9 months ago.

```
printf("%d \% %d = %d", 4, 3, 1);
```

I was expecting this to print "4 % 3 = 1", but instead it prints "4 %d = 3". How can I make this print the expected result? Does "\" not disable the "%" following it?

Answer: %%is the pattern to escape a%, so writeprintf("%d %% %d = %d")


Question: I have been looking through the documentation offopenandifstream, and what I cannot find is whether I need to seek to the beginning of a file after opening it. IthinkI can assume I don't need to, and experiments I have done support this hypothesis, but I find it safer to check.

Answer:
https://en.cppreference.com/w/c/io/fopen

says that it depends on the mode you open your file with. For example, if it's "append" -- the pointer is set to EOF.


Question:
I'm trying to print non-printable characters in C files, but I can't print the given character because I don't know its meaning. I noticed this when I compared my program with cat.

cat -nt file.txt:

```
134  is 127 7f
```

cat -n file.txt:

```
134 ^? is 127 7f
```

Answer: In theCaret Notation(whichcatuses when-vor-tis specified)^?representsthe DEL character(Unicode U+007F, ASCII encoding 127 decimal, 0x7f in hex).


Question:
I need to write a recursive function with 2 parameters that calculate the result of their multiplication byonly using addition

exemple :
mult(2,5)=>10

I wrote the function but I think that I'm missing something in the return

```
int mult(unsigned int num1, int num2) {
    if (num1 == 0) return 0;
    return mult(num1 - 1, num2);
}
```

Answer:
You should return:

```
return num2 + mult(num1 - 1, num2);
```


Question:
What is a merit for the signed int return value of memcmp compared to say bool?

I don't think I've ever used the return value of memcmp other than to compare it against zero.

Answer:
What is a merit for the signed int return value of memcmp

Useful for sorting objects based on their binary representation.

Note:memcmp()returns a +,0,- based on the first mismatched byte as if bytes areunsigned char, notchar.


Question:
I use-Werror ... -Wno-unknown-pragmascompiler flags (cause I don't need unknown pragmas to cause an error).

However, this silences all unknown pragma warnings.

Is there a way to produce-Wunknown-pragmaswarnings while not turning them into errors, and to apply-Werrorto all other warnings.

Answer: -Werror -Wno-error=unknown-pragmasshould do the trick.


Question:
I'm using GCC version 10.2.1  in Linux Debian (x86-64).
i write this c code:

```
#include <stdio.h>

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

Now my question is how can compile and run this code forarmv7l?
Target system Is a evaluation board
thank you

Answer:
you can usearm-linux-gnueabihf-gcc hello.c -o hellocommand . and befor you should install arm-linux-gnueabihf-gcc in your linux system .

here is full sample that work for me


Question:
This question already has answers here:How can I print a quotation mark in C?(9 answers)Closed11 months ago.

How to print"inprintf("something equal "x(as char)" ")??

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

int main(void) {
    printf("something equal \"x(as char)\" ");
    return 0;
}
```

In C, the escape character is\.
So to print a literal", instead of using it to end a string, use\".


Question: In my code I have two char pointer, one to a string and the other as an error indicator forstrtoumax()andstrtod(). I am currently using the typesize_t(aka unsigned long) to calculate the difference between them. Is there any type designed to specifically match pointer type size on every machine? Or do I have to check it myself with macros?

Answer: For pointer difference useptrdiff_t. If you're just trying to store a pointer as an integer, useuintptr_t(orintptr_t).


Question:
I have an integer array:

```
int s3[] = {97, 115, 100, 102, 103, 49, 50, 51, 37, 36, 33};
```

and I need its string value like"asdfg123%$!"

something like this:

```
printf ("%s", s4);   // and output should be => asdfg123%$!
```

Answer: Copy the array item by item in a loop and store each value in achar. Then null terminate thatchararray so that it becomes a string. Or alternatively don't declares3asintto begin with.


Question: Now I'm developing some software in the embedded Linux platform, I have some physical push buttons which I can read their pressing event through the file/dev/input/event1, in some special cases, I have to clear all event data stored in/dev/input/event1, but I don't know how.

Answer: Open the file in non-blocking mode andread()until there is nothing more to read. Use a buffer of PAGESIZE or 4K for efficiency.


Question:
I have a code snippet to initialize a sockets in windows. How would I initialize the socket in Linux environment.

```
WSADATA wsa
    if(WAStartup(MkeWORD(2,2), $wsa) !=0 )
    {
    exit(0);
    }
```

Answer:
On Linux you don't initialize a network environment like WSA. Sockets can be used out of the box.
Seehttps://man7.org/linux/man-pages/man2/socket.2.htmlfor documentation.


Question:
I want to find all my c source files from parent directory, compile them and create a static library with them all at once. I tried thisar -rc libmylib.a < gcc -c < find ../ -type f -name '*.c'but it throws:
bash: gcc: No such file or directory.

Answer:
gccdoesn't print the object file name so you'll have to divide it up into two command lines. Example:

```
find .. -type f -name '*.c' -exec gcc -c {} \;
ar -rc libmylib.a *.o
```


Question:
In order to declare a struct in C, I have been using

```
typedef struct Foo Foo;
```

and then defining it at some point below.

Why do I have to specify the name of the struct (Foo) twice?

Answer:
The format is

```
typedef old_type new_type
```

so for

```
typedef struct Foo Foo;
```

struct Foois the old type andFoois the new type, so whenever you typeFooit is really an alias forstruct Foo.


Question:
How to compute the projection of a GNSS module at a heighthwithx, y, z, roll, pitch, yawdata on a flat ground?

I searched online and couldn't find anything about how to handle such question.

Answer: A place to start might be equation 1.78 in 'GPS for Geodesy' Edited by Kleugsberg and Teunissen which you can take a look at in pdfdrive.


Question:
The signature of the JNI_OnLoad function is this:

jint JNI_OnLoad(JavaVM *vm, void *reserved);

What is the void *reserved parameter?

Answer: Although the documentation doesn't explicitly say so, this parameter is reserved for future use and should be set toNULLin all cases.


Question:
I am studying C. How is this answer 110?

```
#include <stdio.h>
   void main()

    {
         char c1,c2,sum ;
         c1='5';
         c2='9';
         sum= c1+c2;
         printf("sum=%d",sum);

    }
```

Answer:
The character'5'has an ascii value of 53.The character'9'has an ascii value of 57.

53 + 57 == 110.


Question:
This question already has answers here:Getting a weird percent sign in printf output in terminal with C(3 answers)Closedlast year.

when I useprintffunction in Visual Studio Code
there is always%character at the end of the line in terminal.
why dose this happen??

Answer:
That is your terminal's shell prompt. You have not printed a newline character, so the prompt appears immediately after your program's output.

```
printf("hello\n");
```


Question:
I have two questions for you;

Is there any way to just build and run c code internal terminal when I press to button given figure below. Just there is build and debug options.

Is there any way to open debug in internal terminal not new pop-up window like figure below.

Here is my task and json files.

Answer: I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.


Question:
I have two questions for you;

Is there any way to just build and run c code internal terminal when I press to button given figure below. Just there is build and debug options.

Is there any way to open debug in internal terminal not new pop-up window like figure below.

Here is my task and json files.

Answer: I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.


Question:
I took a job interview and the following algorithm was asked and I didn’t manage to find out it’s purpose.

```
int func(int a, int b)
{
    int c = b;
    while (c <= a)
        c <<= 1;
    int d = a;
    while (d >= b)
    {
        c >>= 1;
        if (c<= d)
            d -= c;
    }
    return d;
}
```

Answer: This function returns the modulo (a%b).


Question:
When running a "make" command, fatal errors are returned due to missing linux headers.

Example:
fatal error:  file not found

Answer:
I resolved this issue by creating aUbuntuvirtual machine (VM) usingVirtualBox.

Installed required softwareMounted shared folder

The make commands ran successfully in the vm.


Question:
i have a sensor

The datasheet says you can divide the data from the sensor by 100 to get the data you want.
And for example, 0xff97 is -1.05km/h

How does 0xff97 become -1.05 km/h?

Answer:
0xFF97is-105in 16-bittwo's complement integer representation.

If you divide that number by100, then you get-1.05 km/h.


Question:
I'm attempting to use ptrace to manipulate registers on aarch64.  Looking at sys/user.h in my aarch64 toolchain (android-ndk-r10e), I see

```
#elif defined(__aarch64__)

// There are no user structures for 64 bit arm.

#else
```

Perhaps I'm missing something obvious but how do I get/set registers for an aarch64 program?

Answer: struct user_pt_regsis defined in asm/ptrace.h which is (eventually) included by sys/ptrace.h.


Question:
In openSSL I used functionSSL_CTX_set_verifywithverify_mode= SSL_VERIFY_PEERandverify_callback= NULL.

What does it mean? The client will verify the server certificates chain or not?

Answer: Reworded answer bySteffen Ullrich: The optional callback can be used to possibly override the built-in validation.


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

After compiling, its giving output "A". Can anyone explain how i'm getting this?

Answer:
%cwill only accept values up to 255 included, then it will start from 0 again !

577 % 256 = 65; // (char code for 'A')


Question:
Im trying to make a widgets application inCwithSDL2and I've been wondering if there is anyway of making an SDL2 window not show up on the menu/window bar?

To hide something like this

Thanks!

Answer:
Take a look toSDL_WindowFlags,SDL_WINDOW_SKIP_TASKBARis what you are looking for.

```
Uint32 flags = SDL_WINDOW_SKIP_TASKBAR;
SDL_Window * window = SDL_CreateWindow(
    /* ... */
    flags
);
```


Question:
Doestmp = malloc(sizeof(x));the same automatically astmp = malloc(sizeof(x)); *tmp = x;?

More specifically, is malloc instantly initialising my variable or is it just allocating memory and I have to initialise it myself?

Answer:
No.

The memory returned by malloc isn't initialized.

Quotingcppreference,

Allocates size bytes of uninitialized storage.


Question:
Doestmp = malloc(sizeof(x));the same automatically astmp = malloc(sizeof(x)); *tmp = x;?

More specifically, is malloc instantly initialising my variable or is it just allocating memory and I have to initialise it myself?

Answer:
No.

The memory returned by malloc isn't initialized.

Quotingcppreference,

Allocates size bytes of uninitialized storage.


Question:
How can I get the Windows Hostname (NetBIOS)  while coding a windows 10 kernel driver?

I know GetComputerNameExA works in User mode, but how do I do the same in kernel mode?

Answer:
You can get hostname through the following registry path:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName

Read the registry.


Question:
So I have this script and I want to replace printed "Dont" with "Lets". I don't want to use system() since the effect is different.

```
#include <stdio.h>

int main(){
    printf("Dont do this");
    /* Replace printed "Dont" with "Lets" */
    return 0;
}
```

Answer:
Try\r:

```
#include <stdio.h>

int main(){
    printf("Dont do this");
    printf("\rLets");
    printf("\n");
    return 0;
}
```


Question:
What are the different ways to find the number of elements in a int array pointer which is allocated with malloc?

int* a = malloc(...)

Answer: There are zero ways to do that outside of keeping track of it separately from the allocation.


Question: I am doing all my assignments in a single .c file by writing functions, but now it seems that it affects the run time. Does it mean that if I do not call a function but define it then the function is also compiled and hence it slows down the program?

Answer:
No.
The only thing it affects is compile and link time and to some degree startup/load time (becauese of larger binary)

Most compilers will strip (i.e. remove) unused code when optimizations are turned on.


Question:
Let's say I have this struct

```
typedef struct
{
    int AM;
    char* name, surname;
}Item;
```

and I want to define a constant NULLitem with AM = -1 and NULL name/surname. Is there a way to do it with #define?

Answer:
```
#define NULLitem (const Item){ .AM = -1, .name = NULL, .surname = NULL }
```

That's a C99compound literal.


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

For example:

temp->next = NULLis same as(*temp).next = NULLlist->next->next = tempis same as ??

Answer: It's the same as(*(*list).next).next = temp


Question:
I am facing problem to understand this line of code.

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

This printf statement is used to clear the terminal in c.
Can anybody explain this to me?

Thanks.

Answer:
Take a look at the list of ANSI escape sequences:https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797

ESC[2J: erases the entire screen

General information:https://en.wikipedia.org/wiki/ANSI_escape_code


Question: In the MDR32(similar with STM32) microcontroller, there is a 16-bit STAT register that describes the ethernet status, the documentation says that 7..5 bits indicate the number of received packets, how can I get this value and save it inuint16_tvariable?

Answer:
Depending on how you read your notation, to get bits 5, 6 and 7 from an integer you can simply do:

```
auto ethStatus = (stat >> 5) & 7;
```


Question:
This question already has answers here:How to read a line from the console in C?(14 answers)Closedlast year.

I have a string that I want to execute in C file and I'd like to get the string from standard input.

```
echo "Here is some random text.\n" | ./main.c
```

Answer:
Read fromstdinlike any otherFILEstream.

```
#include<stdio.h>

int main()
{
    char line[BUFSIZ];
    fgets(line, sizeof(line), stdin);
    printf("stdin: %s", line);
}
```


Question:
I'm using the C SQLite library.

I need to obtain the value of a blob from a row. The row is in a table that does not have any row id.

This causes sqlite3_blob_open to return an error - that rowid is not present in the table.

Software like DB Browser for SQLite is able to query the value of these blobs, so there must be a way to do it.

Answer: The answer is to use sqlite3_step() in conjunction with sqlite3_column_blob()


Question:
In the document, I found thatfgets_unlocked()is not thread-safe.
However, I am not sure that can I usefgets_unlocked()without using any lock in a multi-threaded code, but ensure that each thread will access a different file (no two threads will access the same file)?

Answer: If each thread usesfgetsof any kind to read from different files and write to different buffers, you're safe. There's nothing shared between threads in that case.


Question: Opening a semaphore withsem_openwill also initialize it to any given value, is there any way to open a semaphore that is used by another thread without changing its value?

Answer:
What you say isn't true. Usingsem_opento open an existing semaphore doesn't change its value.

So, to answer you question,

```
sem_t *sem = sem_open( name, O_RDWR );
if ( sem == SEM_FAILED ) {
   perror( NULL );
   exit( EXIT_FAILURE );
}
```


Question:
I would like to run ansi C unit tests in VS by mean of Test Explorer (not only with Console).

I saw that it's possible for C++ projects (https://learn.microsoft.com/it-it/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2022), but I can't find any help about writing pure C test in Visual Studio.

Is it feasable? And in case how? Thx.

Answer:
Yes, it is. See myexample.
(To avoid LNK2019 error you shall include *.c to your test project, not *.h).


Question: I'm readingComputer Systems: A Programmer's Perspective. In section 3.8.2 there is an example that says &E[i] - E equals i, assuming E is an array of 4-byte integers. Why isn't the answer 4i?

Answer:
This is just how pointer arithmetic works in C.

Subtracting pointers gives a result in units of elements, not in units of bytes.  It's symmetric with the fact that if you want to access element 2 of the arrayE, you useE[2]or*(E+2), notE[8]nor*(E+8).


Question:
please see attached image, where the stack and data area are nicely shown in the gdb as text:

originally found in herehttps://www.youtube.com/watch?v=KAr2cjLPufA&t=1390sat 24:30

the audio is not good so I didn't get the name for the extension.

does somebody know and would be so kind to indicate a source?

much appreciated.

cheers.

Answer: mammon . The guess ishttps://github.com/mammon/gdbinit, see the comments below the video.


Question:
```
#define BIT(n) ( 1<<(n) )
#define A BIT(0)

void main(void)
{
    if(A == 0)
    {
    }
}
```

I want to see the definition ofA, vs code will jump to#define BIT(n) ( 1<<(n) )I hope vs code jump to#define A BIT(0)there are any way to achive that?

Answer: This is aknown bugin the C/C++ extension, which (seems like) will be fixed in the upcoming release 1.10


Question: I know I should use memmove if there's overlapping but I can't imagine how sprintf (or memcpy for that matter) would be coded such that it would run into a problem.

Answer: The source and target are clearly overlapping. So, yes, this counts.


Question:
```
#include <stdio.h>
int main()
{
    printf("%d", "123456"[1]);
    return 0;
}
```

The expected output is 123456, but it actually outputs 50. Why is that?

Answer:
"123456"[1]gives the character'2'. That character's ascii value is50.

To print the full number do:printf ("%d", 123456);orprintf ("%s", "123456");


Question:
I am trying to remove a route in Contiki if attack is detected. I am usingstruct route_entry *e; route_remove(e);

But I am getting the following error:undefined reference to 'route_remove'.

Answer:
route_removeis a Rime network stack function. By default, Contiki is built with uIP (IPv6) network stack, which does not have this function.

To remove a route when the IPv6 network stack is used,call this function:

void uip_ds6_route_rm (uip_ds6_route_t *route).


Question: Basically the title. I've been reading the manual pages and can't seem to make it work. Help would be much appreciated.

Answer:
Usegetopt_long()for function names.

A detailed explanation is givenhere.

Thanks @Barmar for the suggestion!


Question: I'm often using C code to take some input and manipulate it; for example, I want to scan a full phrase like "hello world" but as it contains a space, I find myself forced to use "gets" to include the spaces or even tabs sometimes.

Answer: you cant usescanf()orfgets, just remember use thestdinas input stream


Question:
i only found K_ANY event in thedoc(Events and Callbacks -> Common -> K_ANY).

how do i handle keypress and keyrelease events separately?
is it possible in this library?

can anyone help?

Answer: Only on IupCanvas and derived controls using the KEYPRESS_CB callback. It has an extra parameter that indicates if the key is being pressed or released.


Question:
i only found K_ANY event in thedoc(Events and Callbacks -> Common -> K_ANY).

how do i handle keypress and keyrelease events separately?
is it possible in this library?

can anyone help?

Answer: Only on IupCanvas and derived controls using the KEYPRESS_CB callback. It has an extra parameter that indicates if the key is being pressed or released.


Question: I am writing a code for Dots and boxes game in C and I need a function that exit the game and close the window based on an input from the user for example when he presses the letter 'e' on keyboard the game should close  and I have no idea how to do that

Answer:
There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE

```
#include <stdlib.h>

...
    exit(0);
...
```

e.g.exit(EXIT_SUCCESS);


Question: I am writing a code for Dots and boxes game in C and I need a function that exit the game and close the window based on an input from the user for example when he presses the letter 'e' on keyboard the game should close  and I have no idea how to do that

Answer:
There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE

```
#include <stdlib.h>

...
    exit(0);
...
```

e.g.exit(EXIT_SUCCESS);


Question: Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?

Answer:
linux-headersshould be installed exlicitly in alpine linux.

```
apk add linux-headers
```


Question: Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?

Answer:
linux-headersshould be installed exlicitly in alpine linux.

```
apk add linux-headers
```


Question:
Trying to compile a c project then encountered error like below

```
undefined reference to `__llvm_profile_instrument_target'
undefined reference to `llvm_gcda_start_file'
undefined reference to `llvm_gcov_init'
```

Answer:
It works withllvmcompiler too, just add--coverage.

https://clang.llvm.org/docs/SourceBasedCodeCoverage.html


Question:
Trying to compile a c project then encountered error like below

```
undefined reference to `__llvm_profile_instrument_target'
undefined reference to `llvm_gcda_start_file'
undefined reference to `llvm_gcov_init'
```

Answer:
It works withllvmcompiler too, just add--coverage.

https://clang.llvm.org/docs/SourceBasedCodeCoverage.html


Question: How can I copy a file without using standard C library functions in Linux? In other words, I would like to copy a file directly with system calls. Is it possible?

Answer:
file directly with system calls. Is it possible?

In pseudocode, usingsendfile:

```
int in = open("input", ...);
fstatat(in, &stat);
int out = open("output", ...);
sendfile(in, out, NULL, stat.st_size);
```


Question:
Is there any built-in for this operation (in C) ?

```
lock or QWORD [...], ...
```

In fact, I'm searching forlock orin C.

If there isn't any built-in, how can I write it in C inline-asm ?

I'm using GCC (C version 11).

Answer:
The standard C11 way of doing this is with <stdatomic.h> andatomic_fetch_or.  You can do things like:

```
#include <stdatomic.h>

atomic_int  var;

int res = atomic_fetch_or(&var, 0x100);
```


Question:
What is the use of thestat.hheader incat.c?

Here you have thecat.c

https://github.com/mit-pdos/xv6-riscv/blob/riscv/user/cat.c

Here you have thestat.h

https://github.com/mit-pdos/xv6-riscv/blob/riscv/kernel/stat.h

I do not see any direct use of thestatstruct in thecat.cso I wonder if there is an indirect one.

Answer: It was added inthis commitprobably becauseuser.huses thestruct stat *datatype


Question: I've tried different types of string input(scanf, getchar, gets), but none of them can finish input with Enter. Do you guys have any ideas?

Answer: As Cheatah said, the function you looking for isfgets(). Always try to avoidgets()as it offers no protections against a buffer overflow vulnerability and can cause big problems in your program. You can read some of the answers to this question to clarify the utility of each functionScanf() vs gets() vs fgets()


Question: I've tried different types of string input(scanf, getchar, gets), but none of them can finish input with Enter. Do you guys have any ideas?

Answer: As Cheatah said, the function you looking for isfgets(). Always try to avoidgets()as it offers no protections against a buffer overflow vulnerability and can cause big problems in your program. You can read some of the answers to this question to clarify the utility of each functionScanf() vs gets() vs fgets()


Question:
I just want to know if a line break (i.e. '\n') can only be written to the stdout if 1 byte is used for such, I mean, does a line break have to be called like this?

```
write(1, "\n", 1);
```

or can it be called like this?

```
write(1, "\n", 0);
```

Answer: Bytes are bytes. There's nothing magical about\nthat makes it not count. It has to be the former.


Question:
"undefined reference to 'func~'" error..

I'm new to that program, so I can't figure out the reason for the error.

enter image description here

Answer: You need to add#include <stdlib.h>


Question: I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?

Answer:
You can check man-pages:

```
$ man splice
```

Itsays:

```
CONFORMING TO
       This system call is Linux-specific.
```

So it is not in POSIX.


Question: I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?

Answer:
You can check man-pages:

```
$ man splice
```

Itsays:

```
CONFORMING TO
       This system call is Linux-specific.
```

So it is not in POSIX.


Question:
write the post order of the above BST

I,m confusing it starts with 50 or 60

Answer:
"Post order" means that a parent is always visitedafter("post") its children are visited.. So if you would start with 50, you cannot visit 60 anymore, as that would violate that rule.

The post order thus starts like this: 60, 50, 80, ...

As this is an assignment, please figure out the rest yourself, just making sure you always abide to the above rule.


Question:
I usedffigento generate bindings from a C header file.
One of the methods in C isopen(const char *path), and ffigen generated a binding methodopen(ffi.Pointer<ffi.Int8> path).
If I want to have a dart methodopen(String path)that access this binding method how can I convert the String parameter to ffi.Pointer<ffi.Int8>?

Answer:
Try

```
"Your message".toNativeUtf8().cast<Int8>()
```

Also see erjo's comment inhttps://github.com/dart-lang/ffigen/issues/72


Question:
If I compile a C program on Windows 10, can that program run on Windows 7?

If I compile a C program on Windows 10 Home, can that program run on Windows 10 Pro?

Answer: yes , you can run your program in any windows.I think knowing aboutcompile processcan help you.


Question:
I know that c works in two's complement but still i can't undrstand how the program below gives me 2147483647 as output.

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

int a=-2147483648;
a-=1;
printf("%d",a);

}
```

Answer: Becuase anintcan't contains the value-2147483648 - 1, so it result in an integer overflow, which leads to undefined behaviour. Undefined behaviour can result in anything.


Question:
```
(gdb) print inputInfo
$8 = (SObjectRecInput *) 0x7fffffffced0
```

For example, when I want to check the value of inputInfo, it prints out:

```
0x7fffffffced0
```

And its type is 'SObjectRecInput'.

How to actually print out its value?

Answer:
inputInfoappears to have a pointer type, so dereference it:

```
(gdb) print *inputInfo
```


Question:
I have an array of int pointers

```
int * arr[3];
```

If I want to define a pointer toarr, I can do the following:

```
int * (*p)[] = &arr;
```

However, in my code, I need to first declare that pointer:

```
int *(*p)[];
```

My question is, how to assign&arrto it after it has been declared. I have tried(*p)[] = &arr;but that didn't work.

Answer:
You can simply dop = &arr.

Tryhere.


Question:
This question already has answers here:Can a const variable be used to declare the size of an array in C?(5 answers)Closed1 year ago.

```
#include <stdio.h>
const int TAILLE_MAX = 10;
int iTableau[TAILLE_MAX]={3,6,0,8,97,0,5,6,0,8};
```

Answer:
const int TAILLE_MAX = 10;is not a compile-time expression in C, so it cannot be used as a compile-time array size. Replace the expression with a macro:#define TAILLE_MAX 10

See alsothis StackOverflow question.


Question:
This question already has answers here:Can a const variable be used to declare the size of an array in C?(5 answers)Closed1 year ago.

```
#include <stdio.h>
const int TAILLE_MAX = 10;
int iTableau[TAILLE_MAX]={3,6,0,8,97,0,5,6,0,8};
```

Answer:
const int TAILLE_MAX = 10;is not a compile-time expression in C, so it cannot be used as a compile-time array size. Replace the expression with a macro:#define TAILLE_MAX 10

See alsothis StackOverflow question.


Question:
How do i get this snippet of code to break the while loop with both "a" and "A"?
I can't get the OR function right. Thanks in advance for the help.

while((product = getchar()) !='a')

Answer:
If you want to break the loop whenproductisaorA, you need to check ifproductis notaandnotAin your loop condition:

```
while((product = getchar()) !='a' && product != 'A')
```


Question:
When I compile the extension I've got, I'm getting

```
error: ‘work_mem’ undeclared (first use in this function)
   17 |   Tuplestorestate *tupstore = tuplestore_begin_heap(true, false, work_mem);
```

What header includeswork_mem?

Answer:
Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile.

```
#include "miscadmin.h"
```


Question:
When I compile the extension I've got, I'm getting

```
error: ‘work_mem’ undeclared (first use in this function)
   17 |   Tuplestorestate *tupstore = tuplestore_begin_heap(true, false, work_mem);
```

What header includeswork_mem?

Answer:
Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile.

```
#include "miscadmin.h"
```


Question:
Why this code doesn't printА?

```
int main() {
    char str[] = {0x0, 0x4, 0x1, 0x0};
    write(1, str, 4);
}
```

Instead ofAit just print nothing and exit. This is strange because hexadecimal value ofAisU+0410.

Answer:
Follow this answerhttps://stackoverflow.com/a/6240184/14926026, you will see that the cyrillic A is not{0x0, 0x4, 0x1, 0x0}, but actually{ 0xd0, 0x90 }

```
int main()
{
   char str[] = { 0xd0, 0x90 };
   write(1, str, 2);
}
```


Question:
enter image description here

how can I do this using scanf funtion ranging form -1000 to 1000 ?
just %d numbers

Answer:
Try dooing a loop with ascanfand aprintfinside, like this:

```
int num = 0;
for(int i = 0; i < 5; i++){
   scanf("%d", &num);
   printf("%d", num);
}
```

You just need to change the5to the number of iterations you need.


Question:
enter image description here

how can I do this using scanf funtion ranging form -1000 to 1000 ?
just %d numbers

Answer:
Try dooing a loop with ascanfand aprintfinside, like this:

```
int num = 0;
for(int i = 0; i < 5; i++){
   scanf("%d", &num);
   printf("%d", num);
}
```

You just need to change the5to the number of iterations you need.


Question:
Specifically "the uri parameter may be a comma- or whitespace-separated list of URIs containing only the schema, the host, and the port fields" what does this mean?

Working with openLDAP in c.

Answer:
It is simple list of URIs. The list can be separated by whitespace or comma:

Example:

http://myhost.com:4567,http://myhost1.com:45,http://myhost2.com:34545

or

http://myhost.com:4567 http://myhost1.com:45 http://myhost2.com:34545


Question:
This question already has answers here:Returning an array using C(8 answers)Closed1 year ago.

How do I return a char array with any length in C?

```
char string[](int, int);
```

doesn't work; is there a way to return a char array?

Answer:
You are unable to do that in C.
Instead, return a pointer.

```
char *string(int length, int unused) {
  char *s = calloc(x, sizeof(char));
  return s;
}
```


Question:
is it possible to buildpjsipwithopus-codecforwindowsas dll?
I built pjsua2.dll alone but seems no way to use opus with it.

Answer: I downloaded opus and pjsip , opened pjsip from visual studio solution, added opus projects to solution and made reference to them from libpjpproject, then build it using this linklink


Question:
```
printf("%f  %.3f  %.2f  %.1f", 4.5678, 4.5678, 4.5678, 4.5678);
```

I tried putting \n at the end of the series of floats to separate the line

```
printf("%f  %.3f  %.2f  %.1f", 4.5678, 4.5678, 4.5678, 4.5678)\n;
```

Answer:
That \n should be inside the strings of printf not after it

```
printf("%f  %.3f  %.2f  %.1f \n", 4.5678, 4.5678, 4.5678, 4.5678);
```


Question:
I am usingntdll.libfunctions in my code to set the system timer to a higher resolution.

But when I build my project I get this error:

```
...
.../bin/ld.exe: ... undefined reference to `__imp_NtSetTimerResolution'
collect2.exe: error: ld returned 1 exit status
...
```

How do I tell the linker to link withntdll.libin my CMake?

Answer:
This worked for me:

```
if (WIN32)
    target_link_libraries(executable ntdll)
endif()
```


Question:
There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56.

Here's the code that I tried:

Answer:
```
int sum;
sum=(int)num1+(int)num2;
printf("%d",sum);
```

or

```
printf("%d",(int)num1+(int)num2);
```

The datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!


Question:
There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56.

Here's the code that I tried:

Answer:
```
int sum;
sum=(int)num1+(int)num2;
printf("%d",sum);
```

or

```
printf("%d",(int)num1+(int)num2);
```

The datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!


Question:
when I run the command

```
pidof lh
```

for lh program, I get two values. what are they. I was looking of pid oflhrunning program so I can increase the number of open files limithttps://unix.stackexchange.com/a/422732/211761

Why i am getting two values, if one is pid then what is the other

OUTPUT

```
37354 7968
```

which one above is pid and what is the other number. please tell

Answer: Both. You have two lh processes running.


Question:
From thispostand thiscodebase, I know that there are pointers for

Youngest childYoungest siblingOldest sibling.

So withOldest child, how do I get?

I am thinking of access "children" pointer (current->children) and traverse to the end of that doubly linked list.

Answer:
Get the oldest sibling of the youngest child:

```
current->p_cptr->p_osptr
```


Question:
I have a code that uses std=c++20.

I want to use a C library that was build with old gcc version.

Should I recompile the C library using the same compiler ?

If no, how could you judge that the 2 ABIs are compatible?

Answer:
There should be no problem using the library as it is. Don't forget to addextern "C"around the function prototypes.

More info:Using C Libraries for C++ Programs


Question:
From thispostand thiscodebase, I know that there are pointers for

Youngest childYoungest siblingOldest sibling.

So withOldest child, how do I get?

I am thinking of access "children" pointer (current->children) and traverse to the end of that doubly linked list.

Answer:
Get the oldest sibling of the youngest child:

```
current->p_cptr->p_osptr
```


Question:
I have a code that uses std=c++20.

I want to use a C library that was build with old gcc version.

Should I recompile the C library using the same compiler ?

If no, how could you judge that the 2 ABIs are compatible?

Answer:
There should be no problem using the library as it is. Don't forget to addextern "C"around the function prototypes.

More info:Using C Libraries for C++ Programs


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

I want to know how can I see the functions and the contents of a library in C language?

Answer: isnm libconfig.a | c++filtwhat you are looking for?


Question:
I am programming a microcontroller (PSoC5), which doesn't have a system time.

What is the best way to generate a seed to initializesrand?

TIA

Answer: If the chip has ADCs, one option is to take advantage of noise picked up on the ADCs.  Basically, you can take a few reads of the ADCs, then bitwise AND to keep the least significant bit.  Then use the all of the least significant bits sampled to generate your seed.


Question:
I'm doing a shell from scratch. If I store all tokens in an arraychar**, what I supposed to put in a string of arraychar**when quote is empty?

Example:

```
input>echo "" "" "" | cat -e
output>(space)(space)(space)$
```

Answer:
If you're mimicking POSIX shells then each""would tokenize to an empty string. The pipeline as a whole should tokenize to:

```
char *tokens[] = {"echo", "", "", "", "|", "cat", "-e"};
```


Question:
This question already has answers here:Splitting string into two integers(4 answers)Closed2 years ago.

```
string input = 1999-12-05
int year=1999
int month=12
int day=05
```

I want to split input to new three variable.Thank you.

Answer:
You can usesscanf:

```
char* input = "1999-12-05";
int year;
int month;
int day;
sscanf(input, "%d-%d-%d", &year, &month, &day);
printf("year: %d, month: %d, day: %d\n", year, month, day);
```

demo


Question: I want to read the source code of winsock, but I only see header which is winsock.h. where is winsock.c located I need to read the source code implementation so bad.

Answer: As to my knowledge Microsoft never released source code for that library. The best you can do is use Ida pro or simillar software to decompileWs2_32.dllorWs2_32.lib. That is the closest you will get to the source code, but it will be in pseudo C.


Question:
```
union one
{
    int *ui;
    int u;

} yoo;

void main()
{
    printf("%d\m", sizeof(yoo))
}
```

Why is the sizeof union not 8 bytes but 4 bytes even if I am using pointer in my union?

I am using a 64 bit machine.

Answer: Its because you have compiled it as 32-bit executable.


Question:
I want to do something similar to the code below but usingptr[i]

```
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
```

Answer:
ptr->xis the same as(*ptr).x.

*(ptr + i)is the same asptr[i].

Thus, by the transitive property,(ptr + i)->xis the same as:

```
ptr[i].x
```


Question:
I want to do something similar to the code below but usingptr[i]

```
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
```

Answer:
ptr->xis the same as(*ptr).x.

*(ptr + i)is the same asptr[i].

Thus, by the transitive property,(ptr + i)->xis the same as:

```
ptr[i].x
```


Question:
I am wondering what happens for variables & their content after STM32 mcu enters low power mode or exit from it? for example in sleep mode or standby.
do their content remove or survived?

best!

Answer:
You can preserve or not - it is usually (depending on the mode) up to the programmer. Memory consumes power so very often it is more energy efficient to reinitialize RAM after wake up (I do it sometimes in my projects)

Example: STM32L476:


Question:
I'm working with a C-functionfoo(FILE* file)that outputs some text to a file.

Rather than write to a .txt file, I'd likefooto write to the console.

Is there a way to pass 'the console' as a FILE*? (And if so, how) ?

(foois part of a library and I can't edit the source code directly)

Answer:
There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything).

```
foo(stdout);
```


Question:
I'm working with a C-functionfoo(FILE* file)that outputs some text to a file.

Rather than write to a .txt file, I'd likefooto write to the console.

Is there a way to pass 'the console' as a FILE*? (And if so, how) ?

(foois part of a library and I can't edit the source code directly)

Answer:
There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything).

```
foo(stdout);
```


Question:
My Code:-

```
#include<stdio.h>
struct Demo{
    int value;
};
int main(){
    struct Demo *l;
    l->value=4;
}
```

Getting Segmentation fault (core dumped)

Answer:
because L object doesn't point something.
use this :

```
#include <iostream>
using namespace std;
struct Demo
{
    int val;
};
int main()
{
    Demo* a = new Demo();
    a->val = 10;
    cout<<a->val;
}
```


Question:
why my code is not printing all values of the array?

```
#include<stdio.h>
#include<conio.h>
int main()
{
   int arr[5]={1,2,3,4,5};
   int *a;
   a=&arr[0];
   int i=0;
   for(i=arr[i];i<5;i++){
   printf("%d",*a);
       a=a+1;
   }
}
```

Answer: I guess this is homework, correct? Check the index of your loop. What you want to do is that yourforloops five times, regardless of the content of your array.


Question:
Why 10.5 become 10.0 after swap ?

```
#define swap(a,b) {int aux; aux=a; a=b; b=aux;}
float x=10.5, y=3.75;

swap(x,y);

// x=3.75, y=10.0;
```

Answer: auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.


Question:
Why 10.5 become 10.0 after swap ?

```
#define swap(a,b) {int aux; aux=a; a=b; b=aux;}
float x=10.5, y=3.75;

swap(x,y);

// x=3.75, y=10.0;
```

Answer: auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.


Question:
Let's imagine I have

```
String x = "hello there";
```

So I can print it from index e.g. 1 as:

```
Serial.println(x.substring(1));
```

ello there

I wanna do the same with

```
char x[] = "hello there";
```

Any ideas?(Except using loops to print char by char)

Answer:
You can use the & operator to get the string after the desired index like this:

```
Serial.println(&x[1]);
```


Question: For debugging purposes, when there are many make file inclusions, it's useful to print the full path of the makefile where a particular variable in the current makefile was first defined. Is there a way to do that?

Answer: Just runmake -p.  Make will print its internal database including all targets and variables that were seen along with the filename and linenumber where they were set.


Question:
given that

```
int w = 1;
int x = 6;
int y = 5;
int z = 0;

z = !z || !x && !y;
printf("%d\n", z);

z = x-- == y + 1;
printf("%d\n", z);
```

Could someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6?

```
z = x-- == y + 1;
```

Answer:
The expressionx--evaluated to the value ofxbeforebeing decremented.

Sox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.


Question:
given that

```
int w = 1;
int x = 6;
int y = 5;
int z = 0;

z = !z || !x && !y;
printf("%d\n", z);

z = x-- == y + 1;
printf("%d\n", z);
```

Could someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6?

```
z = x-- == y + 1;
```

Answer:
The expressionx--evaluated to the value ofxbeforebeing decremented.

Sox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.


Question:
I am a bit rusty in programming, so I came here to ask what's the meaning of this line?

```
int (*f)(int, int)
```

Answer:
Usehttps://cdecl.org/to translate thigs like that.

int (*f)(int, int)=> declare f as pointer to function (int, int) returning int.


Question: If I put an inline function in a .h file, then include that in the bridging header, can I invoke it in Swift? (Answer: Yes) But will it still be inline when invoked in Swift?

Answer:
The compiler will do what it wants but generally the answer isyes. This is part of why the atomics libraries and math shims that go down to C use header only inlined modules. So at least in release builds it can be fully optimized.

Seethisfor example.


Question:
Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information.

How does one can make clang emit human readable llvm ir document with debug information ?

Answer: The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information


Question:
Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information.

How does one can make clang emit human readable llvm ir document with debug information ?

Answer: The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information


Question: Imagine I havefile1.c,file2.c. First I compile one file withgcc -c file1.c -o file1.o. Is it OK to compile them together withgcc file1.o file2.c -o prog? I tried it and no errors are shown, but should I compilefile2.ofirst? Is it correct to mix.cand.ofiles?

Answer:
Yes, you can dogcc file1.o file2.c -o prog. You can also dogcc file1.c file2.c -o prog.

GCC will handle compiling file2.c behind the scenes.


Question:
I'm getting the following error message from Clang 10:

```
error: expected value in expression
#if FOOBAR
          ^
1 error generated.
```

No further info. What could be the cause for this?

Answer:
What could be the cause for this?

When the macro is defined to nothing

```
#define FOOBAR
```

then

```
#if FOOBAR
```

expands to just:

```
#if
```

And compiler prints an error -ifneeds an expression#if something-here.


Question:
if I write data to the middle of the allocated address space, will the file size increase. just likefseekdoes ?

or it will write to the beginning of the file ?

Answer:
The answer is no. writeto mmap will not grow the file or create sparse file.
I have to allocate the file manually.


Question:
In my rooted Android device,

```
jint fd = open("/dev/ashmem",O_RDWR);
```

gives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail.

Any ideas? Thank you for your help.

Answer: Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class


Question:
In my rooted Android device,

```
jint fd = open("/dev/ashmem",O_RDWR);
```

gives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail.

Any ideas? Thank you for your help.

Answer: Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class


Question:
I have a problem when comparing wchar_t with hex value.

```
wchar_t c;
FILE *f = fopen("input1.txt", "r");
fwscanf(f, L"%lc", &c); // c is 'ệ'
printf("%d", c == L'\0x1ec7');
```

'ệ' is 0x1ec7 hex. But the result is 0. And how to compare wchar_t with hex value?

Answer:
The correct notation isL'\x1ec7', notL'\0x1ec7':

```
#include <stdio.h>

int main() {
  wchar_t const c = L'ệ';
  printf("%d", c == L'\x1ec7'); // prints 1
}
```


Question:
Like

```
pri
ntf("hi");
```

I can use \ in macro but I think that doesn't work here :'(

Answer:
You can use\

```
pri\
ntf("hi");
```

Demo

From draft N1570 of the C standard, section 5.1.1.2 Translation phases:

Each instance of a backslash character ( \ ) immediately followed by a new-line
character is deleted, splicing physical source lines to form logical source lines.


Question: I need to create a matrix with 2 columns and unknown number of rows. I know I have to use malloc but I can't find how to declare such matrix. it should hold integers in the first column and doubles in the second. How do I do that?

Answer:
```
struct item {

  int i;
  double d;
};

struct item matrix = malloc(sizeof(struct item) * number_of_rows)

matrix[0].i = 544343;
matrix[0].d = 0.3434343;
```

Is that the code you are looking for?


Question:
I need a macro that puts "**" before and after the string value, it should work someway like this:

```
#define M(x) <something>
puts(M("abc"))
```

Output:

```
**abc**
```

I've tried things like

```
#define M(x) "**x**"
```

but it doesn't work :/Thanks in advance! :)

Answer:
Try

```
#define M(x) "**" x "**"
```

It uses a feature that C compiler concatenates sequence of string literals.


Question:
if I have two header files

a.handb.h

can I include "a.h" in b.h

and also include "b.h" in "a.h" ?

Answer:
You can, but it's not a very good idea. If you really must, you can prevent recursion with the use of include guards (which are a good idea regardless).

Ina.h:

```
#ifndef A_H
#define A_H

#include "b.h"

#endif
```

andb.h

```
#ifndef B_H
#define B_H

#include "a.h"

#endif
```


Question:
How to call an executable C in script shell ?
I did echoname_of_executable_filebut it didnt works

Answer:
You call it like this:

```
/path/to/name_of_executable_file
```

Or if it's in the current directory, like this:

```
./name_of_executable_file
```


Question:
How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem

I can set the DTR pin with :

EscapeCommFunction(hSerial,SETRTS);

But cant find an answer online on how to check the RI pin STATUS

Answer: You have to useGetCommModemStatusfunction.


Question:
How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem

I can set the DTR pin with :

EscapeCommFunction(hSerial,SETRTS);

But cant find an answer online on how to check the RI pin STATUS

Answer: You have to useGetCommModemStatusfunction.


Question:
```
float lgt = light.read();
if(isnan(lgt)){
    printf("Failed to read light!");
}
 else{
    printf("%f\n",lgt);
}
```

Second printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.

Answer:
Why floating point formats in Mbed Studio don't work?

Because you are compiling your program with newlib nano version that does not support floating point format inprintffamily.


Question:
```
float lgt = light.read();
if(isnan(lgt)){
    printf("Failed to read light!");
}
 else{
    printf("%f\n",lgt);
}
```

Second printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.

Answer:
Why floating point formats in Mbed Studio don't work?

Because you are compiling your program with newlib nano version that does not support floating point format inprintffamily.


Question:
I use C language and I have problem with malloc

```
double** matrix = malloc(matrixSize * sizeof(double*));

  for (size_t i = 0; i < matrixSize; i++) {
    matrix[i] = malloc(matrixSize * sizeof(double));
  }

  return matrix;
}`
```

Answer:
malloc returns a void-pointer

void*malloc(size_t size);

so you will have to typecast this to double**

```
double** matrix = (double**)malloc(matrixSize * sizeof(double*));
```


Question:
As mentioned by the title, I would like to achieve something like this:

```
void my_exit(int status)
{
#ifdef _GCOV
   __gcov_flush();
#endif
   _exit(status);
}
```

But I do not know if there is a_GCOV（or something similar） defined when compiling with--coverage. Any idea will be appreciated!

Answer:
Doesn't seem to be:

```
$ true | gcc -E - -dM > no-coverage.h
$ true | gcc -E - -dM --coverage > coverage.h
$ diff no-coverage.h coverage.h
```


Question:
```
void Setup() {
    gameover = false;
    dir = STOP;

    x = width / 2;
    y = height / 2;

    fruitX = rand() % width; //display fruit in a random place
    fruitY = rand() % height; score = 0;
}
```

Answer: Please use#include <stdlib.h>at the top of c code.


Question:
We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related?

a[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?

Answer:
These arenotthe same.

The syntaxE1[E2]is exactly equivalent to*((E1) + (E2)).  So*(a + 2)is the same asa[2].  It should now be clear that this is not the same asa[1].


Question:
We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related?

a[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?

Answer:
These arenotthe same.

The syntaxE1[E2]is exactly equivalent to*((E1) + (E2)).  So*(a + 2)is the same asa[2].  It should now be clear that this is not the same asa[1].


Question:
I am using windows 10 and MinGW-x64 gcc 8.1.0. I was trying to take a long double as input using scanf. Here is the code:

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

int main(int argc, char const *argv[])
{
    long double a;
    scanf("%Lf",&a);
    printf("%Lf",a);

    return 0;
}
```

the output on the console is 0.000000.
Why is that so?
Is it a windows issue?

Answer: i guess in c mingw does not support long double datatype


Question: I need to save a user input into a 2D array in a way where the user inputs something like '123456789' and I save that input into an array so that array[0][0] == 1, array[1][2] == 6 etc. Is there something like getchar() that I could use, but for numbers?

Answer:
You can use getchar() itself, and convert it to integer using:

```
char c = getchar();
int arr[3][3];
arr[0][0] = c - '0';
```

Referthisstackoverflow answer.


Question: I know that a pointer points to a memory address, but is it possible to just use the&symbol instead of a pointer?

Answer:
&vwill get you the address of the variablev, but&vis an r-value, not an l-value.

In order to have an l-value containing the address of a variable you would have to use the*syntax, as inT *p = &v;.


Question:
I want to calculate a number to the powerp, gotSegmentation faultas a result.
This code is supposed to work:

```
#include <stdio.h>

int my_power(int nb, int p)
{
    if (nb != 0){
        return nb*my_power(nb, p-1);
    }
    return 1;
}

int main(int argc, char argv[]){

    printf("%d\n", my_power(5, 3));
    return 0;
}
```

Answer:
In your code, your recursion never ends.
Change the base case topb<=0and it will work.


Question:
I am trying to deep copy from one structure to another structure
However structure has many pointers,how do I copy it in single statement?
Do I have to manually copy each structure pointer member?

Answer: You have to manually copy everything if you want a deep copy.


Question:
Follow-up question forthisanswer.

Is there any hosted C implementations (__STDC_HOSTED__is 1) which haveCHAR_BIT > 8?

If so, then which ones?

UPD. Fix typo: before:__STDC_HOSTED__is0, after:__STDC_HOSTED__is1.

Answer: I don't know if there was ever a post-standardisation version, but various Cray 64-bit vector supercomputers had a C compiler in whichsizeof(long) == sizeof(double) == 1, a.k.a.everything is 64 bits wide.


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

int main() {
    if (~0 == 1)
        printf("yes\n");
    else
        printf("no\n");
}
```

why is theifstatement false? can anyone explain?

Answer:
~Binary One's Complement Operator is unary and has the effect of 'flipping' bits.

So when you do~0 == 1it will check for-1 == 1which is false


Question:
I'm trying to format a string like this:

```
printf("%d%c", buffer[i], i == num_ints-1? '': ',');
```

So that the numbers print like this:

```
123,929,345
```

Yet doing''is invalid. Is it possible to simulate a 'nothing-char' or just not do anything in the ternary?

Answer:
You can't have an empty char, but you can have empty strings. So use%s.

```
printf("%d%s", buffer[i], i == num_ints-1? "": ",");
```


Question:
I see that when I use that code:

```
char c,d;
scanf("%s",&c);
scanf("%s",&d);
printf("%c%c",c,d);
```

seems fix the problem of save ENTER character indvariable.

It's a good way or compiler add the string terminator in the memory address next tocvariable (equals fordvariable)?

Answer: No, because it will also want to null-terminate the string. In other words, write to*(d + 1)(at least!), and that's undefined behavior (namely, overflow).


Question:
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU.

I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9
Below is the Query and response.

query : 33 02 00 00 00 47 3C 2A
resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68

Answer: You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.


Question:
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU.

I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9
Below is the Query and response.

query : 33 02 00 00 00 47 3C 2A
resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68

Answer: You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.


Question:
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm?

```
for(i=0;i<n;i++){
 for(j=0;j<2;j++){
    x = arr[i][j]
  }
}
```

So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?

Answer:
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And

```
O(2n) = O(n)
```


Question:
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm?

```
for(i=0;i<n;i++){
 for(j=0;j<2;j++){
    x = arr[i][j]
  }
}
```

So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?

Answer:
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And

```
O(2n) = O(n)
```


Question:
Can we add two numbers using pointers but without using any variable like a,b?
I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?

Answer:
Simple answer :

```
int *a = (int *)malloc(sizeof(int));
*a = 10;
int *b = (int *)malloc(sizeof(int));
*b = 20;
printf("%ld + %ld = %ld\n", *a , *b , *a + *b);
```


Question:
Can we add two numbers using pointers but without using any variable like a,b?
I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?

Answer:
Simple answer :

```
int *a = (int *)malloc(sizeof(int));
*a = 10;
int *b = (int *)malloc(sizeof(int));
*b = 20;
printf("%ld + %ld = %ld\n", *a , *b , *a + *b);
```


Question: Instead of writingif(exp[i] =='*' || exp[i] =='/' || exp[i] =='+')can i write something like thisif(exp[i] == {'*','/','+'}).But writing this throws me an error, So is there any simple way of doing this ?

Answer:
You can use thestrchr()function together with acompound literal:

```
if( strchr( (char[]){'*','/','+','\0'}, exp[i] ) )
```

Or if you prefer, the far more readable string literal version:

```
if( strchr("*/+", exp[i]) )
```


Question:
When compiling withgccI usedtimeto get compile time.

```
time gcc main.c && ./a.out
```

when trying to do the similar thing inclangI can't get the result

```
clang -time main.c && ./a.out
```

gives me a waring:

clang: warning: argument unused during compilation: '-time'

probably my approach is false, so please help me find compile time using clang

Answer: Tryclang main.c -ftime-report


Question:
This question already has answers here:Algorithm to find nth root of a number(5 answers)Closed2 years ago.

C hassqrt()andcbrt(), but those are only the second and third roots. What if the root is an arbitrary number? What if I need the 57nth root?

Answer:
Use thepowfunction, taking advantage of the fact that getting the 57 root is the same as raising to the power of 1 / 57.

More generically, to get theyroot ofx:

```
double result = pow(x, 1.0 / y);
```


Question:
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes

```
fscanf(fp,"{%s %s %d}",name,username,username1);
```

Answer:
This should work:

```
fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1);
```


Question:
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes

```
fscanf(fp,"{%s %s %d}",name,username,username1);
```

Answer:
This should work:

```
fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1);
```


Question:
```
char str[] = "a";
char ch = 'a';
```

speaking of the difference between the two, we all knowstrpoint to a memory space which stored [a, \0], but I want to ask whether there is a difference betweenstr[0]andch?

Answer:
but I want to ask whether there is a difference betweenstr[0]andch?

No.

str[0]andch, both are of typechar, and hold the value'a'. From this aspect (type and value), there is no difference.


Question: I can add include paths in Visual Studio easily but I couldn't find a way to do it in GCC? Any helps please?

Answer:
Use the-Icommand-line argument:

```
gcc -Ipath
```


Question:
I would like to convert an int to a byte in C.

In Java, I'd write:

```
int num = 167;
byte b = num.toByte(); // -89
```

In C:

```
int num = 167;
???
```

Answer:
You can simply cast to a byte:

```
unsigned char b=(unsigned char)num;
```

Note that ifnumis more than 255 or less than 0 C won't crash and simply give the wrong result.


Question:
How do I convert this array with ASCII numbers to text, so every number get's a letter. So "72" gets H, 101 gets E and so on.

int a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};

Answer:
You can iterate over the array, and use the%cformating parameter  to print the ascii characters of the int value

```
for (int i = 0 ; i < 11; i ++){
   printf("%c", a[i]);
}
```


Question:
I'm trying to learn C programming right now but I'm a bit stumbled upon the concept of declaring an array of pointers to functions. The statement is right here:

```
int (*menu_option[10])(char *title);
```

What exactly is happening here?

Answer:
from thespiral rulehere

menu_optionis an array of 10function pointersthey takechar*as an argument and return anint

usehttps://cdecl.org/to parse C gibberish to English


Question:
I am new to C language but I useGitpodfor other languages. I would like to know how to run this simple "hello world" main.c program from the Gitpod interface step by step?

```
#include <studio.h>
void main(){
    printf("hello")
}
```

Many thanks !

Answer:
After fixing the errors you can compile the code withgcc main.cand run the binarya.out.
Errors as already mentioned:

studio.h->stdio.h...hello")->...hello");


Question:
I am new to C language but I useGitpodfor other languages. I would like to know how to run this simple "hello world" main.c program from the Gitpod interface step by step?

```
#include <studio.h>
void main(){
    printf("hello")
}
```

Many thanks !

Answer:
After fixing the errors you can compile the code withgcc main.cand run the binarya.out.
Errors as already mentioned:

studio.h->stdio.h...hello")->...hello");


Question: I have a small project in C language and I want to implement the program, the program cuts off the WiFi network

Answer:
You can for example disconnect through a terminal command.

e.g. in Windows OS

```
system("netsh wlan disconnect");
```

example.c

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

int main(void)
{
    system("netsh wlan disconnect");
    system("echo Wifi disconnected!");
    return 0;
}
```


Question:
Whenever I create a.hfile, Airline interprets it as acppfile (in the filetype section). How do I set it toc?

I couldn't find an answer online, and I don't know in where to change the source code of Airline to do what I want.

Answer:
Filetype is set by standard Vim ftplugin. To change the default

```
let g:c_syntax_for_h = 1
```

See:h c.vimfor more options.


Question:
I have a following line in C:

```
printf("size of sizeof is %d\n", sizeof(printf("lol!\n")));
```

Am I getting the size of a function pointer here?

Answer: Here,sizeofevaluates the return type ofprintf. (Here anint)


Question:
Actually my options are :"C_Cpp.clang_format_fallbackStyle": "{ BreakBeforeBraces: Linux, IndentWidth: 4, ColumnLimit: 80, UseTab: Never, SortIncludes: false, AlignAfterOpenBracket: DontAlign }"

I have:

```
for (int i = 0; i < 5; i++)
    ;
```

I want:

```
for (int i = 0; i < 5; i++);
```

Answer:
This is a known issue and it make a warning. The only way is to write this:

```
for (int i = 0; i < 5; i++) {}
```


Question:
Actually my options are :"C_Cpp.clang_format_fallbackStyle": "{ BreakBeforeBraces: Linux, IndentWidth: 4, ColumnLimit: 80, UseTab: Never, SortIncludes: false, AlignAfterOpenBracket: DontAlign }"

I have:

```
for (int i = 0; i < 5; i++)
    ;
```

I want:

```
for (int i = 0; i < 5; i++);
```

Answer:
This is a known issue and it make a warning. The only way is to write this:

```
for (int i = 0; i < 5; i++) {}
```


Question:
I want to initialize a value of all array members to their index.

```
int main()
{
    int i;
    int arr[10];

    for (i = 0; i <= 9; i++)
        arr[i] = i;
}
```

Should I consider the sequence point in this case?Isarr[i] = ilegal and portable?

Answer:
You need to consider sequence points if you modify something more than once in one place,orif you both read and modify something in one place.

You're not doing any of that, so your code is fine.


Question:
I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it.

How can I declare it in global scope and assign its size in themainfunction?

Answer:
```
#include <stdlib.h>   // for malloc

int *globalarray;

int main()
{
  ...
  globalarray = malloc(thesizeyouwant * sizeof(*globalarray));
  ...
  globalarray[0] = foo;
  ...
  free(globalarray);
}
```


Question:
I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it.

How can I declare it in global scope and assign its size in themainfunction?

Answer:
```
#include <stdlib.h>   // for malloc

int *globalarray;

int main()
{
  ...
  globalarray = malloc(thesizeyouwant * sizeof(*globalarray));
  ...
  globalarray[0] = foo;
  ...
  free(globalarray);
}
```


Question: I have a C++ project, and the main file with the main function is a.c, but when I include my.hthat is supposed to be C++, I think I am getting errors because it thinks it is C. How can I tell it that my header should be C++ and not C, like my main?

Answer: You cannot#includeC++ header in a C source file. A header is not compiled separately. All that#includedoes - it makes the compiler work as if the header was a part of the file.


Question: How could I write it in C language? I tried many things, but it seems that I cannot understand the exp and sin functions.

Answer:
A direct implementation could be:

```
double y = exp(pow(sin(x),3)) + pow(x,6) - 2*pow(x,4) - pow(x,3) - 1.0;
```


Question: I would like to convert a double into character string and I findgcvt()and_gcvt(). I just wondering what is the difference between them. Both return withchar*and both need value, number of digits and buffer as a given parameters

Answer:
As per thegoogle search result

The_gcvt()function is identical togcvt(). Use_gcvt()for ANSI/ISO naming conventions.


Question: Why doesthis functionin the Linux kernel take avoid *unusedparameter that serves no purpose in the body of the function?

Answer:
Because it is a callback.
The prototype of all callbacks used in this context must be equal, sometimes may have an unused parameter.

kthread_runresquires a function like this in the first parameter:

```
int cb(void *param);
```


Question:
The function was written to free a list i created earlier...

```
rekord *felszab(rekord *el)
{
    rekord *temp;
    for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp)
    {
        temp=mozgo->kov;
        free(mozgo);
    }
    return el;
}
```

Answer: You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types


Question:
The function was written to free a list i created earlier...

```
rekord *felszab(rekord *el)
{
    rekord *temp;
    for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp)
    {
        temp=mozgo->kov;
        free(mozgo);
    }
    return el;
}
```

Answer: You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types


Question:
```
printf("%i\n",2&2==2);
```

This should print out a 1 but I get a 0, why is this?

```
int ans=2&2;
printf("%i\n",ans==2);
```

This prints a 1, how come the first way does not work?
This is the case with if statements as well

Answer:
The order of operations is different than you think it is. A correct way to write it in a single line would be:

```
printf("%i\n", (2 & 2) == 2); // Prints 1
```


Question:
```
int main() {
    x=5;
    printf("%d",x+3);
}
```

xcould be either5or8after this example (I know that the output on the screen would be 8.)

Answer:
The value at the address ofxremains unchanged in this example. Inside theprintf, we first get the value at the address ofxand then add it to 3 and output it to the screen.
This is why we use statements likex=x+3to change the value.


Question: I've use cURL command-line tool with --libcurl and a url of mine(the url works in normal C), however I get the error "curl.h" does not exist, although it is in the same directory. I can't figure out how to include headers in emscripten. All of the supposed documentation on this usually ends up being about something else entirely.

Answer: I figured it out, I was being dumb


Question:
If I have the following lines of code, why is b-a = 2?

```
int a[] = {1,2,3,4,5};
int *b = &(a[2]);
```

Answer:
To elaborate slightly on Eugene's answer,ais a pointer to the beginning of the array, anda[2]is the same as*(a+2).

So you could say that the&"cancels" the*as you dereference the pointer and then look at the address of the element that it points to. So*b = &(a[2]) = &(*(a+2)) = a+2.
Thereforeb-a=2


Question:
I can use GCC to convert assembly code files into reallocatable files.

```
gcc -c source.S -o object.o -O2
```

Is the optimization option effective? Can I expect GCC to optimize my assembly code?

Answer:
No.

GCC passes your assembly source through the preprocessor and then to the assembler.  At no time are any optimisations performed.


Question:
My input is: 1 + 2

I found that the value stored inargv[2][1]andoparen't the same, I just want to see if they are both the "+" operand.opstores the ascii value of "+" whileargv[2][1]stores some random value. How would I compare them?

*I don't want to use "strcmp"

Answer:
Array indexes start at0, so you need to use[0]to compare the first character of the argument.

```
if (argv[2][0] != c) {
```


Question:
```
unsigned int file = open(argv[1], O_RDONLY);

printf("%u\n", file);
printf("%u\n", elf.offset);

lseek(file, elf.offset, SEEK_SET);

printf("%u", file);
```

OutPut:

```
3
52
3
```

Shouldn'tfilebe set to52?

Answer:
Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned.

try thisprintf("lseek_offset: %d\n", lseek(file, elf.offset, SEEK_SET));


Question:
```
unsigned int file = open(argv[1], O_RDONLY);

printf("%u\n", file);
printf("%u\n", elf.offset);

lseek(file, elf.offset, SEEK_SET);

printf("%u", file);
```

OutPut:

```
3
52
3
```

Shouldn'tfilebe set to52?

Answer:
Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned.

try thisprintf("lseek_offset: %d\n", lseek(file, elf.offset, SEEK_SET));


Question:
This question already has answers here:What is the meaning of a dot (.) after an integer in c?(2 answers)Closed2 years ago.

I read a code online and the next line caught my attention since I don't know why does it have a "." after the 0:

```
variable=0.;
```

I couldn't find the answer after looking for it. Could you please tell me what is the dot for?

Thanks!!

Answer: The dot makes it adouble. A clearer way to write it is0.0.


Question:
As far as I know, ~0x00 equals to:
First step, change 0's to 1 and 1's to zero, Second step, add 1
Step 1: 11111111111111111111111111111 (count =32)

Step 2: 11111111111111111111111111111+1=0

Where am I doing wrong?

Answer:
The~operator does not perform 2's complement negation.  You can do that with the unary-operator (assuming your machine uses 2's complement representation).

What~does is invert all bits.  That's all it does, no adding 1.


Question:
As far as I know, ~0x00 equals to:
First step, change 0's to 1 and 1's to zero, Second step, add 1
Step 1: 11111111111111111111111111111 (count =32)

Step 2: 11111111111111111111111111111+1=0

Where am I doing wrong?

Answer:
The~operator does not perform 2's complement negation.  You can do that with the unary-operator (assuming your machine uses 2's complement representation).

What~does is invert all bits.  That's all it does, no adding 1.


Question:
When I use the following code I tried to replicate the idea thatsqrt(x)of something equalsX^(1/2)

```
pow(x, (1/2);
```

It returned 1 no matter what value I entered. I already solved this issue with the sqrt function but wanted to know why this is happening for the future.

Answer:
In it's original form,1/2is integer division, producing a result of0.

Math 101: Anything raised 0, is 1.


Question:
Within C how can I name a function? Just the name.

typedef strlen StringLengthfails to compile with:strlen does not name a type.

Answer:
A function pointer is a solution

static Integer(*StringLength)(const Byte*) = strlen;


Question:
Why am I getting an error when using theatoi()function?

```
#include <stdio.h>
#include <string.h>
int main()
{
    char s1[10], s2[10];
    int x=5, y=6, z;
    sprintf(s1, "%d", x);
    sprintf(s2, "%d", y);
    strcat(s1, s2);
    z = atoi(s1);
    printf("%d, %s", z, s1);
    return 0;
}
```

Answer:
```
#include <stdlib.h>
```

Will fix it.


Question:
Here's my code:

```
#include <openssl/bio.h>
int main (void)
{
    BIO* bo = BIO_new(BIO_s_mem());
}
```

I'm compiling my code by doinggcc -lcrypto test.c.

Any idea what's wrong?

Answer:
You have the arguments in the wrong order, trygcc test.c -lcrypto

Seewhy order matters


Question: When I received packet withrecvat linux, is the kernel did de-fragmentation so I will get de-fragmentation data? Or should I take care of it on user-space?

Answer:
When receiving UDP data via a socket of typeSOCK_DGRAM, you'll only receive the complete datagram (assuming your input buffer is large enough to receive it).

Any IP fragmentation is handled transparently from userspace.

If you're using raw sockets, then you need to handle defragmentation yourself.


Question:
When analyzing core on different machine, that binary was built for I ran into:

```
warning: .dynamic section for "/lib64/libc.so.6" is not at the expected address (wrong library or version mismatch?)
```

Is there a way to change which libc gdb is looking for?

Answer:
Thanks to@Kevin Boone!

set sysroothelped I set it to./and put desired libc in./lib64and then loaded core usingcore-file


Question: I use theMin-GW GCC compileronWindows 10. Every time I compile, I need to make a.exeand then run it. Could there be any way to do the whole thing in one step?

Answer:
You can combine commands in windows like you do on linux or macos!

```
gcc compilefile && c:/executefile.exe
```

(you need to replace that stuff with min-gw and your exe path)

links:

How do I run two commands in one line in Windows CMD?How to run an executable in Windows Terminal?


Question:
When analyzing core on different machine, that binary was built for I ran into:

```
warning: .dynamic section for "/lib64/libc.so.6" is not at the expected address (wrong library or version mismatch?)
```

Is there a way to change which libc gdb is looking for?

Answer:
Thanks to@Kevin Boone!

set sysroothelped I set it to./and put desired libc in./lib64and then loaded core usingcore-file


Question: I use theMin-GW GCC compileronWindows 10. Every time I compile, I need to make a.exeand then run it. Could there be any way to do the whole thing in one step?

Answer:
You can combine commands in windows like you do on linux or macos!

```
gcc compilefile && c:/executefile.exe
```

(you need to replace that stuff with min-gw and your exe path)

links:

How do I run two commands in one line in Windows CMD?How to run an executable in Windows Terminal?


Question:
Let's say I have aforloop and an array of ints. In myforloop, I sayif (array[i] == 2)then I want to skip all the rest of theforloop and go to the next instance. now I can't use thebreakkeyword as that will exit out of the entire loop.

What can I use to exit out of only one instance?

Answer:
You have to use continue to go to the next iteration:

```
if (array[i] == 2) continue;
```


Question:
Let's say I have aforloop and an array of ints. In myforloop, I sayif (array[i] == 2)then I want to skip all the rest of theforloop and go to the next instance. now I can't use thebreakkeyword as that will exit out of the entire loop.

What can I use to exit out of only one instance?

Answer:
You have to use continue to go to the next iteration:

```
if (array[i] == 2) continue;
```


Question:
Imagine I have a struct for a linked list:

```
struct node{
     int data;
     struct node* next;
     struct node* prev;
};
```

I free the last node; does thenextpointer of the node before it becomeNULLautomatically?

Because I noticed I didn't do it in a program but everything runs fine..

Answer:
No.

As for why your program appeared to run OK even if you forgot to reset a pointer, it could be you just got lucky.


Question:
Can anyone explain how does this work the output is A3 but how come it print 3

```
#include <stdio.h>

int main() {
    int i;
    if(printf("A"))
        i=3;
    else
        i=5;
    printf("%d",i);
}
```

Answer:
printf()returns the number of characters upon success and negative values on failure.

Therefore, ifprintf("A")succeeds, it will return1.

In C, values other than0is treated as true, soi=3;is executed.


Question:
I want to print my string which is "Something"without the first N lettersinside theprintfstatement.

Example 1: I can do the "opposite" (printfjust N first letters):

```
#include <stdio.h>
int main() {
  char str[] = "Something";
  printf("%5s", str);
}
```

Output:Somet

Expected Output:hing

Answer:
Start the printing in the middle:

```
printf("%s", &str[5]);
```


Question:
I have problem with NVIC registers in Keil.
in my data sheet NVIC starts with NVIC_ISERx

But in keil starts with ICTR register

So I have problem with matching addresses

Answer:
the order of the properties is not the same as the order in the peripheral.

It is clearly visible here:


Question:
I would like to figure out the memory address of the following:

```
>>> ($rbp + $rdi*2 - 8)
```

And then once I have that value, inspect that memory address with:

```
>>> x/wx $address
```

How would I do this in gdb?

Answer:
You can type this in directly after thep(rint) command. For example:

```
>>> p/x ($rbp + $rdi*2 -8)
$2 = 0x7fffffffe43e

>>> x/hx $
0x7fffffffe43e: 0x001b # 27
```

The$symbol stores the last value.


Question:
I would like to figure out the memory address of the following:

```
>>> ($rbp + $rdi*2 - 8)
```

And then once I have that value, inspect that memory address with:

```
>>> x/wx $address
```

How would I do this in gdb?

Answer:
You can type this in directly after thep(rint) command. For example:

```
>>> p/x ($rbp + $rdi*2 -8)
$2 = 0x7fffffffe43e

>>> x/hx $
0x7fffffffe43e: 0x001b # 27
```

The$symbol stores the last value.


Question: Does C have a#include<bitset>similar to C++ ? I have been looking for the past week. I can't find a equivalent directive preprocessor!

Answer: No, it does not. There are, however, ways to implement what you are looking for (or at least some sort of approximation). Take look at:http://c-faq.com/misc/bitsets.html- I think it is going to be useful.


Question:
I want to scan a value, and print the value that was scanned

```
int main()
{
    int n;
    printf("enter value: ");
    n = scanf("%d",&n);
    printf("%d",n);
    return 0;
}
```

however, the printed result gave me 1 instead of 9 as shown below. Why is this so and how do i solve this?

Answer:
Becausenget override by the return value of scanf

Just usescanf("%d", &n);if you don't want the number of parsed items assigned ton.


Question:
I want to scan a value, and print the value that was scanned

```
int main()
{
    int n;
    printf("enter value: ");
    n = scanf("%d",&n);
    printf("%d",n);
    return 0;
}
```

however, the printed result gave me 1 instead of 9 as shown below. Why is this so and how do i solve this?

Answer:
Becausenget override by the return value of scanf

Just usescanf("%d", &n);if you don't want the number of parsed items assigned ton.


Question:
This question already has answers here:Why is the gets function so dangerous that it should not be used?(13 answers)Closed3 years ago.

Why is implicit declaration of gets() not allowed in C99?I had referred this question, which was how I came to know about it's deprecation.

Answer: Yes, you should usefgets()instead.


Question:
This question already has answers here:Why is the gets function so dangerous that it should not be used?(13 answers)Closed3 years ago.

Why is implicit declaration of gets() not allowed in C99?I had referred this question, which was how I came to know about it's deprecation.

Answer: Yes, you should usefgets()instead.


Question: I'm trying to make changes and compile open source 3d printers firmware in eclipse. Added all the project related to firmware but it showing symbol could not be resolved error. The cause of error is IDE cannot find the symbols. How can I solve this. It's compiling properly and also working on board.

Answer: Found the solution in indexer of the eclipse used active configuration settings and it solved all the Indexer error. Thanks for the help guys.


Question: I'm trying to make changes and compile open source 3d printers firmware in eclipse. Added all the project related to firmware but it showing symbol could not be resolved error. The cause of error is IDE cannot find the symbols. How can I solve this. It's compiling properly and also working on board.

Answer: Found the solution in indexer of the eclipse used active configuration settings and it solved all the Indexer error. Thanks for the help guys.


Question:
How would I simplify all of this into one line?

```
REG &= ~BITA;
    REG &= ~BITB;
    REG &= ~BITC;
    REG &= ~BITD;
    REG &= ~BITE;
```

Answer:
You can use|(bitwise or) operator.

```
REG &= ~(BITA | BITB | BITC | BITD | BITE);
```


Question: Because FILE struct is depended on implementation, is there any fail-proof way to resolve FILE "object" to the path of the file it was create with?

Answer: It seems it is either hard due toFILEstructure being implementation dependent, or a sign of improperly designed code. As it stands now,stdlibdoes not provide any way of checking this exact thing. There are ways to check file handles, but those are system dependent and are not practical.


Question:
How does one definecopyanddeepcopymethods for a Python type defined in a C extension?

Looking at thedocumentation, there doesn't appear to be atp_slot for these methods.

Answer: There's no slot. You just define the same methods you'd define in Python, but in C. (Typically, that means implementing__reduce__and getting the default__reduce__-basedcopy.copyandcopy.deepcopybehavior, but you can also implement__copy__and__deepcopy__if you want.)


Question:
i'm having process id from Task manager, i need to get the process name (complete with extension) from it.
is it possible?
i checked other questions, they are mostly command based.

Answer:
Do you mean 'get the .exe filename by process ID' from C code?

If so, you may have interesting inOpenProcess()and followingGetModuleFileNameEx().
Don't forget toCloseHandle()after you get the exe filename. :)


Question:
i'm having process id from Task manager, i need to get the process name (complete with extension) from it.
is it possible?
i checked other questions, they are mostly command based.

Answer:
Do you mean 'get the .exe filename by process ID' from C code?

If so, you may have interesting inOpenProcess()and followingGetModuleFileNameEx().
Don't forget toCloseHandle()after you get the exe filename. :)


Question:
I used a C / C++ code from the Internet, but my IDE gives me the following error on macos:

```
Use of undeclared identifier cfmakeraw
```

I now face the question, whether cfmakeraw is available on Macos / Unix ?

Thank you 🙏

Answer:
On your Mac, fire up Terminal and runman cfmakeraw.

```
SYNOPSIS
     #include &lttermios.h>

     void
     cfmakeraw(struct termios *termios_p);
```

So it is available, but you must include<termios.h>.


Question: I am looking for a way to set a background image in gtk + 3 with c language , I already search and all the answer are for other languages or don't work anymore . Does anyone know  a proper way to do it ?

Answer:
For all problem encounter with the style in gtk i realize that using css for gtk wase the best answer , here some link that can be good to know

Css + Gtk Overview

Gtk + Css Properties


Question:
I used a C / C++ code from the Internet, but my IDE gives me the following error on macos:

```
Use of undeclared identifier cfmakeraw
```

I now face the question, whether cfmakeraw is available on Macos / Unix ?

Thank you 🙏

Answer:
On your Mac, fire up Terminal and runman cfmakeraw.

```
SYNOPSIS
     #include &lttermios.h>

     void
     cfmakeraw(struct termios *termios_p);
```

So it is available, but you must include<termios.h>.


Question: I am looking for a way to set a background image in gtk + 3 with c language , I already search and all the answer are for other languages or don't work anymore . Does anyone know  a proper way to do it ?

Answer:
For all problem encounter with the style in gtk i realize that using css for gtk wase the best answer , here some link that can be good to know

Css + Gtk Overview

Gtk + Css Properties


Question:
I wrote this code in Sublime:

```
int main (int argc, char **argv)
{
    printf("Hello World");
    return 0;
}
```

Saved it atC:\cygwin64\home\userashelloworld.c.

Typed in this on Cygwin64 Terminal:$ gcc -o helloworld helloworld.c

But I'm not seeing any output.Please help.

Answer: The windows executable can be obtained by:$ ./helloworld


Question: I am trying to get the contents of my adc register for debugging but I don't know how to print it with gdb. If the address register offset is0x08would I usep/x *0x08? I am getting a result but it is 64 bits and I'm expecting 32. Thanks.

Answer: Turns out I was trying to find the wrong address and using a confusing hex to binary converter. Thanks to @Eugene Sh. for helping.


Question: I am trying to get the contents of my adc register for debugging but I don't know how to print it with gdb. If the address register offset is0x08would I usep/x *0x08? I am getting a result but it is 64 bits and I'm expecting 32. Thanks.

Answer: Turns out I was trying to find the wrong address and using a confusing hex to binary converter. Thanks to @Eugene Sh. for helping.


Question:
I have the following code snippet for a PIC controller:

```
void __interrupt() ISR(void
{
    // do some stuff
}
```

when I use PC-Lint I always get the error message:

Error 10: Expecting identifier or other declarator

What can I do to handle the interrupt in PC-Lint?

Answer: You can define a dummy preprocessor macro by using the option-d__interrupt()=


Question: I foundthis example; here the two threads threadDefault and threadCustomized are terminated by using pthread_exit followed by return. Why did the author write both instructions?

Answer: Mohith Reddy's answer is correct but misses the point. Of course the return statement is never executed sincepthread_exitdoesn't return, but it's there to suppress warnings from the compiler in case it's not aware thatpthread_exitdoesn't return.


Question:
I'd like to know where the function__cpuid_countis on osx. I'm assuming that it's inlibcbut running:

```
nm -g /usr/lib/libc.dylib
```

or

```
nm -g /usr/lib/libSystem.B.dylib
```

Does not list the function in the outputs. Is there a better way to locate where it is?

Answer: You can't find a__cpuid_countfunction because there isn't one. It's defined as a macro that expands to inline assembly incpuid.h.


Question:
What is the difference between this:

```
int num = 5;
int* num1 = #
printf("%p", num1);
```

and this:

```
int num = 5;
int* num1 = #
printf("%p", &num1);
```

Answer:
In the first case,printf("%p", num1);, you're printing the value ofnum1, which is the address ofnum.

In the second case,printf("%p", &num1);, you're printing the address ofnum1.


Question:
In C, a directory is created like this:

```
mkdir("hello");
```

but what if we don't know the name of this directory (or it's told by user)? How can we define it to a computer? (%s is not working)

Answer:
I would recommend you to usesnprintfso you can take any type of input.

```
#include <stdio.h>

int main() {
    char name[50];
    int i = 5;
    snprintf(name, 50, "dir.%i", 5);
    mkdir(name, 0700);
}
```


Question: I know thatPythonis platform independent, but I don't understand how that works forCPython. If the interpreter and some of the modules are written inC, aren't those going to be platform dependent?

Answer: C is platform independent in the sense that it can be compiled for any machine for which a compiler is made to target that machine. That's why the Python source code is platform independent, even if a Python binary can only work on one platform.


Question:
Why *pointer is an integer but not the string content "Hello from pointer" Thanks!

```
int main(void) {
  char *pointer;
  pointer = "Hello from pointer";

  printf("*pointer is %d\n", *pointer);
  printf("\n");
}
```

the output is *pointer is 72

Answer:
It's because the ASCII code for'H'(which is the first element of the array) is72. It is completely normal.

Here is the ASCII Code table


Question:
```
#define len(a) if (a == 8)   1       \
               else if (a == 3) 0    \
               else -1
```

this code is just an example how do we use nested if else.
I don't want to use ternary operator as in that case i can't use else if statement.

Answer:
Don't abuse the preprocessor. Use a real function:

```
constexpr auto len(int const a) {
    if (a == 8) return 1;
    if (a == 3) return 0;
    return -1;
}
```


Question: I had tried running a program which I solved in codeblocks and using math.h library in cs50 ide by Harvard University(which is Ubuntu based). Its giving me an error that library is not included. How to include to my cs50 ide..?

Answer:
Are you including it in the compiling?

Easiest way to do it is to compile with: make filename

If that doesn't work check you are adding it correctly: #include


Question: I am trying to write Python C extensions and I'm on a mac. I know how to install thePython.hheader file on Linux, but I don't know how to do it on a Mac. How can I install it?

Answer:
The Python header file is a framework on Mac. You have to include it like this:

```
#include <Python/Python.h>
```


Question:
Is there a function to stretch an image's points to coordinates on the screen based on it's four points?

If not, is there a way I could do that using math?

Answer:
I mean something like a generalized texture-mapped quad.

SDL_RenderGeometry()/SDL_RenderGeometryRaw()were added inSDL 2.0.18.


Question:
can someone please convert this line:

strcpy_s(this->name, SIZE_NAME, d.getName());

to a strcpy function instead of strcpy_s?

thank you

Answer:
```
strcpy(this->name, d.getName());
```

That was easy