question
stringlengths
24
425
answer
stringlengths
5
405
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?
Subtract values being compared, mask out sign with*_and_*or*_andnot_*, compare with*_cmpgt_*against your margin populated with*_set1_*
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; ```
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.
``` 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.
As the documentation says, thepcap_closefunction closes the files associated with thepcap_tstructure passed to it. Closing the file again withfcloseis an error.
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?
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."
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?
1111 | 0000is1111. There is no bitwise concatenate operator. You can use left shift<<to move bits to the left1111 << 4is11110000.
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?
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.
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
Assuming pin4 on port D. ``` data_in = !!(GPIOD -> IDR & (1 << 4)); ```
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 ?
"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
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 ?
"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
Suppose that we have ``` int arr[3]; char str[20] = "{10,20,30}"; ``` Is it possible to initialise arr with str?
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); ```
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!
From the option of add new flag I added-std=c99in the tab for compiler flag and it works.
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
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); ```
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], "-"); } } ```
The whole 2D array? If not strings, usememset(table, '-', sizeof table);to fill every byte with'-'. Noforloop needed.
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?
There is no C Standard method of flushing the instruction cache.
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. ```
int *p[10]is an array of10pointers toint.int (*q)[10]is1pointer to an array of 10ints.
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?
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.
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?
%%is the pattern to escape a%, so writeprintf("%d %% %d = %d")
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.
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.
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 ```
In theCaret Notation(whichcatuses when-vor-tis specified)^?representsthe DEL character(Unicode U+007F, ASCII encoding 127 decimal, 0x7f in hex).
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); } ```
You should return: ``` return num2 + mult(num1 - 1, num2); ```
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.
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.
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.
-Werror -Wno-error=unknown-pragmasshould do the trick.
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
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
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)" ")??
``` #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\".
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?
For pointer difference useptrdiff_t. If you're just trying to store a pointer as an integer, useuintptr_t(orintptr_t).
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%$! ```
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.
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.
Open the file in non-blocking mode andread()until there is nothing more to read. Use a buffer of PAGESIZE or 4K for efficiency.
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); } ```
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.
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.
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 ```
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?
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.
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.
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.
The signature of the JNI_OnLoad function is this: jint JNI_OnLoad(JavaVM *vm, void *reserved); What is the void *reserved parameter?
Although the documentation doesn't explicitly say so, this parameter is reserved for future use and should be set toNULLin all cases.
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); } ```
The character'5'has an ascii value of 53.The character'9'has an ascii value of 57. 53 + 57 == 110.
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??
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"); ```
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.
I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.
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.
I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.
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; } ```
This function returns the modulo (a%b).
When running a "make" command, fatal errors are returned due to missing linux headers. Example: fatal error: file not found
I resolved this issue by creating aUbuntuvirtual machine (VM) usingVirtualBox. Installed required softwareMounted shared folder The make commands ran successfully in the vm.
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?
0xFF97is-105in 16-bittwo's complement integer representation. If you divide that number by100, then you get-1.05 km/h.
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?
struct user_pt_regsis defined in asm/ptrace.h which is (eventually) included by sys/ptrace.h.
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?
Reworded answer bySteffen Ullrich: The optional callback can be used to possibly override the built-in validation.
``` #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?
%cwill only accept values up to 255 included, then it will start from 0 again ! 577 % 256 = 65; // (char code for 'A')
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!
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 ); ```
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?
No. The memory returned by malloc isn't initialized. Quotingcppreference, Allocates size bytes of uninitialized storage.
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?
No. The memory returned by malloc isn't initialized. Quotingcppreference, Allocates size bytes of uninitialized storage.
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?
You can get hostname through the following registry path: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName Read the registry.
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; } ```
Try\r: ``` #include <stdio.h> int main(){ printf("Dont do this"); printf("\rLets"); printf("\n"); return 0; } ```
What are the different ways to find the number of elements in a int array pointer which is allocated with malloc? int* a = malloc(...)
There are zero ways to do that outside of keeping track of it separately from the allocation.
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?
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.
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?
``` #define NULLitem (const Item){ .AM = -1, .name = NULL, .surname = NULL } ``` That's a C99compound literal.
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 ??
It's the same as(*(*list).next).next = temp
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.
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
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?
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; ```
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 ```
Read fromstdinlike any otherFILEstream. ``` #include<stdio.h> int main() { char line[BUFSIZ]; fgets(line, sizeof(line), stdin); printf("stdin: %s", line); } ```
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.
The answer is to use sqlite3_step() in conjunction with sqlite3_column_blob()
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)?
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.
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?
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 ); } ```
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.
Yes, it is. See myexample. (To avoid LNK2019 error you shall include *.c to your test project, not *.h).
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?
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).
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.
mammon . The guess ishttps://github.com/mammon/gdbinit, see the comments below the video.
``` #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?
This is aknown bugin the C/C++ extension, which (seems like) will be fixed in the upcoming release 1.10
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.
The source and target are clearly overlapping. So, yes, this counts.
``` #include <stdio.h> int main() { printf("%d", "123456"[1]); return 0; } ``` The expected output is 123456, but it actually outputs 50. Why is that?
"123456"[1]gives the character'2'. That character's ascii value is50. To print the full number do:printf ("%d", 123456);orprintf ("%s", "123456");
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'.
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).
Basically the title. I've been reading the manual pages and can't seem to make it work. Help would be much appreciated.
Usegetopt_long()for function names. A detailed explanation is givenhere. Thanks @Barmar for the suggestion!
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.
you cant usescanf()orfgets, just remember use thestdinas input stream
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?
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.
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?
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.
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
There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE ``` #include <stdlib.h> ... exit(0); ... ``` e.g.exit(EXIT_SUCCESS);
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
There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE ``` #include <stdlib.h> ... exit(0); ... ``` e.g.exit(EXIT_SUCCESS);
Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?
linux-headersshould be installed exlicitly in alpine linux. ``` apk add linux-headers ```
Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?
linux-headersshould be installed exlicitly in alpine linux. ``` apk add linux-headers ```
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' ```
It works withllvmcompiler too, just add--coverage. https://clang.llvm.org/docs/SourceBasedCodeCoverage.html
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' ```
It works withllvmcompiler too, just add--coverage. https://clang.llvm.org/docs/SourceBasedCodeCoverage.html
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?
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); ```
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).
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); ```
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.
It was added inthis commitprobably becauseuser.huses thestruct stat *datatype
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?
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()
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?
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()
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); ```
Bytes are bytes. There's nothing magical about\nthat makes it not count. It has to be the former.
"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
You need to add#include <stdlib.h>
I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?
You can check man-pages: ``` $ man splice ``` Itsays: ``` CONFORMING TO This system call is Linux-specific. ``` So it is not in POSIX.
I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?
You can check man-pages: ``` $ man splice ``` Itsays: ``` CONFORMING TO This system call is Linux-specific. ``` So it is not in POSIX.
write the post order of the above BST I,m confusing it starts with 50 or 60
"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.
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>?
Try ``` "Your message".toNativeUtf8().cast<Int8>() ``` Also see erjo's comment inhttps://github.com/dart-lang/ffigen/issues/72
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?
yes , you can run your program in any windows.I think knowing aboutcompile processcan help you.
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); } ```
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.
``` (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?
inputInfoappears to have a pointer type, so dereference it: ``` (gdb) print *inputInfo ```
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.
You can simply dop = &arr. Tryhere.
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}; ```
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.
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}; ```
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.
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')
If you want to break the loop whenproductisaorA, you need to check ifproductis notaandnotAin your loop condition: ``` while((product = getchar()) !='a' && product != 'A') ```
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?
Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile. ``` #include "miscadmin.h" ```
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?
Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile. ``` #include "miscadmin.h" ```
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.
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); } ```
enter image description here how can I do this using scanf funtion ranging form -1000 to 1000 ? just %d numbers
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.
enter image description here how can I do this using scanf funtion ranging form -1000 to 1000 ? just %d numbers
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.
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.
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
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?
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; } ```
is it possible to buildpjsipwithopus-codecforwindowsas dll? I built pjsua2.dll alone but seems no way to use opus with it.
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

PS: More data (40k) can be found here Mxode/StackOverflow-QA-C-Language-40k.


This is a collection of ~5000 QA's in C Language from StackOverflow. The data has been initially cleaned, and each response is with Accepted Answer. All data is <500 in length.

The questions and answers were organized into a one-line format. A sample format is shown below:

{
    "question": "```\nFILE* file = fopen(some file)\n\npcap_t* pd = pcap_fopen_offline(file)\n\npcap_close(pd)\n\nfclose(file)\n```\n\nThis code occurs double free error.\n\nCould you explain about this happening?\n\nMy Guess is that pd and file pointers are sharing some datas.\n",
    "answer": "As the documentation says, thepcap_closefunction closes the files associated with thepcap_tstructure passed to it. Closing the file again withfcloseis an error.\n"
}
Downloads last month
45
Edit dataset card