question
stringlengths
25
894
answer
stringlengths
4
863
I have a program in C for which I need to initialize arrays with initial values. This program has been done in two versions, one with statically allocated memory and the other with dynamically allocated memory viamalloc()(in each case both the size and the initial values are known a priori). In the first case the arr...
You can have a static array that contains the initial values, andmemcpyit to the allocated memory. ``` static float init_data[] = { 1.0, 2.0, 3.0 }; float *test_data = malloc(sizeof init_data); memcpy(test_data, init_data, sizeof init_data); ```
I need a way to get the time in a high precision (milliseconds or microseconds) for a PRNG algorithm I'm writing in C (C11), astime(0)is not precise enough. I tried using several other possible solutions, which I found on StackOverflow, but none of them worked for me. Anyways my problem is now fixed, with the help o...
You can use theGetSystemTimeAsFileTimefunction, which gives you the current time in 100ns intervals since 1/1/1601 UTC. ``` FILETIME ft; uint64_t ts; GetSystemTimeAsFileTime(&ft); ts = 0; ts |= ft.dwHighDateTime; ts <<= 32; ts |= ft.dwLowDateTime; ``` Note that the system clock is most likely not that precise, so d...
I usepthread_mutex_tin my program for thread synchronization control.Do I need to do some finishing works when thepthread_mutex_tis no longer in use?Or, can I do nothing? Thank you for your help
You mention that"the pthread_mutex_t is no longer in use".I assume you mean that you no longer need to use it, ever, in any of your threads. In this case: Thepthread_mutex_tmust be in theunlocked state.You should callpthread_mutex_destroy. The requirement for the mutex to be unlocked appears in the documentation fo...
Let us suppose the following piece of code: ``` #include <stdio.h> #include <math.h> int abs(int x){ return x*2; } int main(){ printf("%d\n",abs(-2)); return 0; } ``` When I compile and execute it, I noticed that the abs function of math.h is being used. Actually, this happens even if I remove the #inc...
absis not declared inmath.honlystdlib.h.GCC uses built-in abs and ignores your code.You need to use-fno-builtinflag and the program will behave your way. https://godbolt.org/z/v9xM3jbbj
If I have an ELF binary written in C and compiled using an Android NDK, is there an API for logging messages so that they show up in logcat?
Yes. This can be done by including ``` #include <android/log.h> ``` and calling ``` int __android_log_print( int prio, const char *tag, const char *fmt, ... ); ``` You can even set the default tag via ``` void __android_log_set_default_tag( const char *tag ); ``` This way, you can pullNULLas the tag i...
How should I read a specific number of lines in C? Any tips, since I can't seem to find a relevant thread. I would like to read N lines from a file and N would be argument given by the user. Up until this point I have been reading files this way: (line by line until NULL) ``` int main(void) { char line[50]; ...
IfNis given by the user, you could just make your loop count up toN: ``` for (int i = 0; i < N && fgets(line, sizeof line, file); ++i) { fputs(line, stdout); } ```
The output of the following program isT = 0.0000. ``` #include <stdio.h> #include <math.h> #define Fs 8000 int main() { float T = 1/Fs; printf("T = %f", T); return 0; } ``` However, when the macroFsis declared as a float variable inside main, I get the correct outputT = 0.000125. Can anyone explai...
Integer divided by integer = integer. Integer divided by float = float. Either: ``` #define Fs 8000.0 ``` and/or ``` float T = 1.0/Fs; ``` and/or ``` float T = 1/(float)(Fs); ```
I'm trying to change the x value in this code but I'm getting segmentation fault. ``` #include <stdio.h> #include <stdlib.h> typedef struct { int **x; } Type; int main() { int a = 1; Type *type = malloc(sizeof(Type)); type->x[0] = &a; return 0; } ```
if you want an array of pointers to ints ``` int main() { int a = 1; Type *type = malloc(sizeof(Type)); type->x = malloc(sizeof(int*) * 10)) ;// say we need 10 type->x[0] = &a; return 0; } ```
As you can see above I have 1 file in my programsecond file is added.When i try to execute one of my file i encounter with this problem Can you please help me with this error. Thank you. I mentioned problem above
You have twomainfunctions in your project, one in each file. A C program can have only onemainfunction. Remove one of themainfunctions or rename one of them to get the project to build. If you're writing lots of short C programs, you shouldn't use Xcode. With Xcode you have to create a new project for each program. ...
I cannot printfloatvariables when calling my functions.intvariables print but floats won't print their proper value when passed to my function. I tried to change thefloattointand that worked ``` int main() { int foo = 6; call(foo); } void call(int bar) { printf("%d", bar); } ``` This worked and it does...
you need a forward declaration of call ``` void call(float integerrrr); int main(){ float integerrrr=6; call(integerrrr); } void call(float integerrrr){ printf("%f", integerrrr); } ``` your compiler probably warned you about this
I want to convert 1byte of array element into 2 bytes E.g ``` arr[size] = {0x1F}; ``` So, I want 0x1F will be stored in 2nd array like, ``` arr_2[size] = {0x01, 0x0f} ``` I have tried like following way... ``` for(i=j=0; j<2; i++){ arr_2[j] =(0xF0 & arr[i]) >> 4; arr_2[j++]=(0x0F & arr[i]); } ``` Thanks is a...
In fact you are doing all correctly except the for loop statement ``` for(i=j=0; j<2; i++){ arr_2[j] =(0xF0 & arr[i]) >> 4; arr_2[j++]=(0x0F & arr[i]); } ``` in the body of which you are setting at least the same element of the arrayarr_2twice. It is redundant. You could just write ``` arr_2[0] =(0xF0 & arr[0...
I have a multidimensional array and I want to define each element of this array in a different section. Something like: ``` int array [2][200]; array[0] __attribute__((section (".section1"))); array[1] __attribute__((section (".section2"))); ``` I know this piece of code is not correct because__atribute__ ((section...
No. The array is a contigous chunk of memory and elements cannot be in different sections. C standard (6.2.5.20): An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. Do you have any suggestions on how I can do it? You need to have ...
I accidentally noticed that the following snipped of code compiles under GCC: ``` void myFunction(void) { int i, y = 0; for (i = 0; i < 10; i++) y++; while (y); } ``` I've never encountered such a piece of code before and wasn't able to find any information about such a construct after doing some...
There is no such thing as afor ... whileloop. What you see are two independent loops. First, there is aforloop. The only instruction in the body of that loop isy++;. Then you see anoter loop:while(y) ;. That is not related at all to theforloop. The body only consists of an empty instruction;. Asynever changes in th...
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); ```
Can someone please explain to me which part is what in this: ``` enum bb { cc } dd; ``` I understand thatenum bbis the name of the enumeration and that{ cc }is its enumerator, but I have no clue whatddis.
``` enum bb { cc } dd; ``` bb- enum tag.cc- enumerator constant. As it is first and it does not have an expicity defined value it will be zero (0);dd- variable of typeenum bb It can be written as: ``` enum bb { cc }; enum bb dd; ```
Somehow, my program is treating variables as big endian, even though my system is little endian. When I execute "lscpu | grep Endian", it returns ``` Byte Order: Little Endian ``` But when I run a debug gcc (x86_64 linux) executable with following code: ``` int x = 1235213421; printf("%x", x);...
You toldprintfto print an integer so it does so according to the endianess, making the code portable. If you wish to view how the data is stored in memory, you have to do it byte by byte, like this: ``` int x = 1235213421; unsigned char* ptr = (unsigned char*)&x; for(size_t i=0; i<sizeof(int); i++) { printf("%.2x",...
How to run a C file in Visual Studio without:having error message#include stdio.h cannot open source file; andnotdownload mingw for Visual Studio Code?
DownloadVisual Studio Code & make sure you installC/C++&C/C++ Extension Packin extensionsGo toRemote Explorer-> SelectConnect to WSL(https://i.stack.imgur.com/fLVNw.png)Go to File -> Open Folder -> enter C directory/mnt/cEnterCtrl + Shift + P-> Typeconfigurations-> Select(UI)-> Enter/usr/bin/gccinComplier PathLastly,B...
Getting anidentifier "QWORD" is undefinederror in this code According to thisdoc, a QWORD is defined as ``` typedef unsigned __int64 QWORD; ``` As a workaround, I've manually added the definition ``` typedef uint64_t QWORD; ``` It seems odd these common data types BYTE, WORD and DWORD are defined, but the QWORD...
I have foundQWORDinwinDNS.has shown by this code, which compiles in the older 2015 32-bit MSVC and in the 2022 64-bit MSVC. ``` #include <stdio.h> #include <windows.h> #include <winDNS.h> int main(void) { printf("%zu\n", sizeof(QWORD)); return 0; } ``` Program output: ``` 8 ``` The definition occurs in th...
I have : ``` #include <stdio.h> int main(void) { int s,i,t[] = { 0, 1, 2, 3, 4, 5 }; s = 1; for(i = 2; i < 6 ; i += i + 1) s += t[i]; printf("%d",s); return 0; } ``` Why is the result 8? What I'm thinking: ``` first loop: 2<6 True i+=i+1 is 5 s=1+t[5] =>1+5=6 second loop : 5<6 True i=5+5+2=11 s=6+t[11]??? ...
The loop increment expression (i += i + 1in your case) happensafterthe loop body, not before. So in the first iteration you do ``` s = 1 + t[2]; ``` More generally, anyforloop could be expressed as awhileloop: ``` for (a; b; c) { d; } ``` is equivalent to ``` { a; while (b) { { ...
I have the following code: ``` #define DEF1 "first" #define DEF2 "second" #define INIT_LIST { DEF1, DEF2 } ``` Is there any way to get number of entries in INIT_LIST at compile time?
You can pass a char-pointer array of unknown size and initialized using INIT_LIST as a compound literal tosizeof. Then divide bysizeofchar-pointer and you get the number of elements in INIT_LIST. Like ``` #define INIT_LIST_ELEMENTS (sizeof((char*[])INIT_LIST) / sizeof(char*)) ```
I am trying to pass a string to a function and tokenize the string, but it gives me an access violation error when it tries to execute strtok. ``` int main(void) { char String1[100]; // note: I read data into the string from a text file, but I'm not showing the code for it here tokenize(String1); return 0; } void t...
If your compiler is not giving you plenty of warnings about this code, pleaseenable more warnings. You need to#include <string.h>to get the prototype forstrtok().You either need a prototype fortokenize(), or more simply, just move its definition abovemain().(Where your actual bug is) The second parameter ofstrtok()sh...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 months ago.Improve this question I am using char arr...
if you must do it byte by byte then do this ``` u32 i; for (i=0;i<name_size;i++) { printf("\nin While"); pn->name[i]=temp_name[i]; } pn->name[i] = '\0'; ``` ie - add the trailing zero. simpler would be strcpy
Legal operators ! ~ & ^ | << >> I have tried this code: ``` int lhs = ((x << 31)>>31); int rhs = (x >> 31); return (~(lhs ^ rhs)); ``` But output was not always as expected
I don't know of any data type whose MSB is bit 30. However, 32- bitints have their MSB in bit 31, so you might try using that value instead.You should always useunsignedtypes when performing bit operations.#include <stdint.h> uint32_t lsb = ((uint32_t)(value & 1)); uint32_t msb = ((uint32_t)((value >> 31) & 1)); ret...
I'm using the Code Composer Studio from Texas Instruments for a microcontroller application. This is an eclipse based environment. Now there is a file, which has more than 5000 lines of code and it does not show the precompiler macros (the #if/#else case is can not be distinguished, because the background is white for...
This setting is "scalability": Window-> Preferences->C/C++-> Editor->Scalability. There are checkboxes for things to disable in large files (live parsing, syntax coloring etc) and how large a file must be to trigger these limitations. The default usually is 5000 lines.
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.
I was reading theGNU C Library Reference Manualand I found: int ENFILE“Too many open files in system.” There are too many distinct file openings in the entire system. Note that any number of linked channels count as just one file opening; see Section 13.5.1 [Linked Channels], page 354. This error never occurs on GNU/...
As requested. The kernel table that records open files grows dynamically. The system runs out of memory before it runs out of open file table entries.
What's my mistake? ``` #include <stdio.h> #include <math.h> #include <locale.h> #include <stdlib.h> int main() { int j, i, F, n=4; float**matr; float**mass; printf("Начальная матрица:\n*"); mass = (float**)malloc(n*sizeof(float)); matr = (float**)malloc(n*sizeof(float*)); for(i=0; i<n; i++) ...
useprintf("\t%2.2f",matr[i][j]);to print the value what you are assigned.
Just getting into c network programming, and have been looking at Beej's guide. In the section onsend()andrecv()I came across this code: ``` int send(int sockfd, const void *msg, int len, int flags); ``` followed by this sentence: "sockfd is the socket descriptor you want to send data to (whether it’s the one retur...
Yes,send()(orwrite(),writev()etc) can be used to copy data to a peer via the open socket. The peer can then userecv()(orread(),readv()etc) to obtain the data.
So, the output should come out with a incrementing triangle of looped numbers (1,2,3,...) combined with a decrementing triangle of stars. Like this: ``` 1******** 12******* 123****** 1234***** 12345**** 123456*** 1234567** 12345678* 123456789 ``` So far I have this but just can't figure out how to decrement the star...
You have: For k in 8 down to 0 (exclusive),Print*. This always prints 8 stars, but you want 9-i of them. For k in i+1 to 9 (inclusive),Print*.
I am trying to call an external C function in modelica with a function as an argument. So the C function needs to take a modelica "function" as input. Is it possible to do that in modelica ? For example : ``` function foo input Function fun; output Real bar ; external "C" bar = myCFunction(fun) annotations(...
No, I don't think that's possible. You can check theModelica Specificationabout allowed input types to external functions.
Let's say I have an array that looks like: ``` char arr[MAX_ARR_LENGTH][30] = {"Tom", "and", "Jerry" }; ``` Now, how do I append a new string that the end of the array? Let's say I want to add "Jack" as a new element so the array shoud look like: ``` char arr[MAX_ARR_LENGTH][30] = {"Tom", "and", "Jerry", "Jack" }; ...
The other answers are good and correct, but to be as simple as possible: ``` #define MAX_ARR_LENGTH 10 #define MAX_STR_LENGTH 30 char * arr[MAX_ARR_LENGTH][MAX_STR_LENGTH]; size_t arr_size = 0; // number of elements in use ``` To add an element: ``` if (arr_size < MAX_ARR_LENGTH) strcpy(arr[arr_size++], "Jill")...
Let's say I have an array that looks like: ``` char arr[MAX_ARR_LENGTH][30] = {"Tom", "and", "Jerry" }; ``` Now, how do I append a new string that the end of the array? Let's say I want to add "Jack" as a new element so the array shoud look like: ``` char arr[MAX_ARR_LENGTH][30] = {"Tom", "and", "Jerry", "Jack" }; ...
The other answers are good and correct, but to be as simple as possible: ``` #define MAX_ARR_LENGTH 10 #define MAX_STR_LENGTH 30 char * arr[MAX_ARR_LENGTH][MAX_STR_LENGTH]; size_t arr_size = 0; // number of elements in use ``` To add an element: ``` if (arr_size < MAX_ARR_LENGTH) strcpy(arr[arr_size++], "Jill")...
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 am following a course where we are writing an OS on a microcontroller. The OS is written in C and the instructor initializes stack spaces for each thread in the following way. int32_t TCB_STACK[NUM_OF_THREADS][STACK_SIZE]; How can the memory be allocatedif there isn't any OS already running to service this in the...
You don't have to "allocate" anything as such on a bare metal system, you have full access to all of the physical memory and there's no one else to share it with. On such a system those arrays end up in statically allocated RAM memory known as.bss. Where.bssis located and how large it is, is determined by the linker ...
What is the purpose of using MPI_Pack/MPI_Unpack? Is it better than working with mpi structure types or derived types?
Packing & unpacking is great as a serialization tool: if you can turn an object (in an informal sense) into a sequence of "1 int, 3 chars, 2 doubles, 5 chars, 2 shorts" (or whatever) you can pack this into a "self-documenting message". The receiving side can unpack this with very little knowledge of what is in your me...
This question already has answers here:Print bytes of a void pointer(6 answers)How to print values of void pointer if data types are unknown?(3 answers)Can you printf value from a void * in C(5 answers)Closed8 months ago. ``` static inline uint256_t sha256(const void *data, size_t len) { secp256k1_sha256_t cxt; ...
Use a loop. ``` const unsigned char *bytes = data; for (size_t i = 0; i < len; i++) { printf("%02X ", bytes[i]); } ```
i am usingnanodumpfor dumping lsass.exe. everything is ok, but when i get to mimikatz by following command,got error: mimikatz.exe "sekurlsa::minidump <path/to/dumpfile>" "sekurlsa::logonPasswords full" exit mimikatz error:ERROR kuhl_m_sekurlsa_acquireLSA ; Memory opening i use "x64 nanodump ssp dll", and AddSecuri...
this was for invalid file signature dumped by nano ssp module, this probled solved by this command: ``` [nano git source]/scripts/restore_signature.exe ```
I used list implementation to create a graph. However, I don't get why we need to perform a breath-first with queue or depth-first with stack to reach all nodes because when we use this implementation, we can reach all nodes. For example, in this photo, I can do that ``` struct Node* temp = A; while(temp != NULL) ...
You don't need a BFS or DFS search to visit all nodes of a graph. Those aretreetraversal algorithms. If your graph isn't (just) stored as a tree, you wouldn't use an algorithm to visit it like a tree. As an aside, your approach is a BFS and a DFS! A linked list is really just a unary tree, and the approach you desc...
uint8_t *out = mmap(NULL, OUT_SIZE, MAP_ANON, PROT_READ | PROT_WRITE, -1, 0); I am running this line on an ARM64 Macbook and I keep gettingBad file descriptor. I am not trying to map a file, so how do I fix this?
You appear to have reversed theprotargument with theflagsargument. It is plausible that as a result,mmap()thinks you are trying to map a real file, and therefore expects the given file descriptor to be valid. Of course, -1 is not a valid file descriptor. It looks like the call you wanted would be: ``` uint8_t *out...
(char *) NULLorchar * msg = NULLtriggersMISRA 10.5: The value of an expression should not be cast to an inappropriate essential type. So what is the correct way to cast NULL to some pointer? N.B.: I am using MISRA checks in CLion.
Assuming you didn't define a home-made version ofNULL(which would be another MISRA violation), thenchar* msg = NULL;is fine and MISRA compliant. Conversion from a null pointer constant to a pointer type without casting is explicitly listed as compliant at multiple places in the guidelines. (char *) NULLlooks like non...
i have the belowo loop in c that print the prime number ``` for(int i = 2; i<=arraySize; i++) { //If arraySize is not 0 then it is prime if (numbers[i]!=0) printf("%d,",numbers[i]); } ``` the out put after enter 50 for example is 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47, i want ...
Instead of printing a comma after each number, print itbefore. Then you can use a variable to tell if this is the first number being printed, and not print the comma. ``` first=true; for(int i = 2; i<=arraySize; i++) { //If numbers[i] is not 0 then it is prime if (numbers[i]!=0) { printf("%s%d", (fir...
Considering the followingcdeclexamples: ``` cdecl> explain void(*signal(int, void (*)(int)))(int) declare signal as function (int, pointer to function (int) returning void) returning pointer to function (int) returning void cdecl> explain void (*)(int) syntax error ``` I'm aware of the 'human' way to interpretvoid ...
The C standard defines how to interpret type names without an identifier in§6.7.7 Type names: ¶2 In several contexts, it is necessary to specify a type. This is accomplished using a type name, which is syntactically a declaration for a function or an object of that type that omits the identifier. There's also a set ...
I am trying to do an atomic increment on a 64bit variable on a 32 bit system. I am trying to useatomic_fetch_add_explicit(&system_tick_counter_us,1, memory_order_relaxed); But the compiler throws out an error -warning: large atomic operation may incur significant performance penalty; the access size (8 bytes) exceeds...
how I can achieve atomicity without using critical sections? On an object that is larger than the size of a single memory "word?" You probably can't. End of story. Use a mutex. Or, useatomic<...>and accept that the library will use a mutex on your behalf.
I am trying to do an atomic increment on a 64bit variable on a 32 bit system. I am trying to useatomic_fetch_add_explicit(&system_tick_counter_us,1, memory_order_relaxed); But the compiler throws out an error -warning: large atomic operation may incur significant performance penalty; the access size (8 bytes) exceeds...
how I can achieve atomicity without using critical sections? On an object that is larger than the size of a single memory "word?" You probably can't. End of story. Use a mutex. Or, useatomic<...>and accept that the library will use a mutex on your behalf.
This is what I expect my string array s to be after the program is run: {"#0", "#1", "2"}.This is what I am getting: {"#2", "#2", "2"}.How do I modify this code so that I can get {"#0", "#1", "#2"} in the main after the function is executed? What am I doing wrong? Please help. ``` #include <stdio.h> void func(char *...
First, you have every element in your array pointing to the same character array. Second, they are all pointing to alocalcharacter array. This leads to undefined behavior. Local variables in functions get allocated on the stack. When the function call is over, that memorymaybe overwritten with some other value.
We can return struct literal from a function by casting anonymous literal initializer to the return type: ``` struct foo f() { return (struct foo) { .bar = 42 }; } ``` Is it possible without mentioningstruct fooanywhere in the initializer? Separate declaration: ``` struct foo result = { .bar = 42 }; return ...
No. It is not possible. Both a declaration (6.7.6) and an initialization of compound literals requires a type specifier (6.5.2.5, 6.7.9).
``` int x; printf("enter number >"); scanf("%d",&x); for(int i=1;i<=x;i++) { i=i+1; printf("%d ",i); } ``` Doesn't it operate like this in C language? for x=5 ``` i=1 2=1+1 i=2 3=2+1 i=3 4=3+1 i=4 5=4+1 i=5 6=5+1 ``` output should be 2 3 4 5 6 then but the...
i++ increments the variable i to fix your code ``` int x; printf("enter number >"); scanf("%d",&x); for(int i=1;i<=x;) { i++; printf("%d ",i); } ```
My Main file The file where I store global variables The 2 files compile well but nothing is printed as I want.
The problem is your functionsum(int a, int b)has argument names that shadow the global variables you are trying to access. Also you need to call thesum()function, not just declare it. Try this instead: ``` #include <stdio.h> extern int a; extern int b; void sum() { printf("Sum is : %d", a + b); } int main() { ...
I have a context in which for testing and security reason I want to fork a process then revoke the parent's permissions on the child process. Is there a function to break this parent/child connection when or after forking a process? Some functions e.g.waitpidwork only for child processes I want these functions to no...
So you want to make the child-processesorphaned? Then usetwoforks: One to create an intermediate child process. Then the child process doesanotherfork for the actual child-process. The intermediate child-process (the direct child) then exits, making the new grand-child process orphaned (its new parent will become th...
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.
I'm trying to get an integer value for the number of windows running with a specific windows class/title. Is there a function that can do that? I've triedFindWindowbut it doesn't seem to go through ALL the windows. An example of what I am trying to do would be finding the number of Windows a user has open with the "V...
EnumWindows Enumerates alltop-levelwindows on the screen by passing the handle to each window, in turn, to an application-defined callback function. You can useGetClassName,GetWindowTextto retrieve the name of the class and the text of the specified window's title bar respectively. See theScreenCaptureforHWNDexample...
This question already has answers here:What is a designated initializer in C?(3 answers)Closed8 months ago. I've seen a piece of code that goes like this: ``` int charP[] = { ['A'] = 1, ['B'] = 2, ['C'] = 3, ['D'] = 4}; ``` My syntax highlighter for C++ does not recognize it, but the syntax highli...
In C it'sarray initializationusing a designated initializer. It's covered in section 6.7.9 of the C 2017 specification. In C++ it's invalid syntax (@Ranoiaetep, @CaptainObvlious).
If the bits ofepoll_event.eventsfield is zeroed, does it disables the event? ThekqueuehasEV_DISABLE, that EV_DISABLE Disable the event so kevent() will not return it.The filter itself is not disabled. ``` epoll_event ev; ev.data.fd = 0; /* stdin file descriptor */ ev.events = EPOLLIN; epoll_ctl(epollfd, EPOL...
No, a 0 events field doesn't disable checking the associated file descriptor for events.EPOLLHUPin particular will get returned even if it's not explicitly asked for. You have to remove the descriptor from the epoll interest list, and re-add it when you want to resume monitoring it.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 months ago.Improve this question What's the problem ...
Thestring"\n" is not the same as thecharacter'\n'. In the comparisonch != "\n"you are comparing ch (which should bedeclared an int) with a pointer (a pointer to a string of chars), which isn't what you intended.
``` #include<stdio.h> void main() { int g = 83; int h = (g++, ++g); printf(“%d”, h); } ``` **g++** will increment **g** after **;** My answer: h = 84 Correct answer: h = 85 I am a beginner that's why I am confused.
We first evaluate the left operandg++sogis now 84 but otherwise ignore the result. Then we evaluate the right operand++gsogis now85. Here is the relevant sections of the specification: The presence of a sequence point between the evaluation of expressions A and B implies that every value computation and side effect...
Consider the following code in C : ``` void main() { char *x = "abc"; char *y = "defgh"; unsigned int c=0; int len = ((strlen(x) - strlen(y)) > c) ? strlen(x) : strlen(y); printf("%d\n", len); } ``` I'm getting output as 3, but the condition in ternary operator((strlen(x) - strlen(y)) > c...
Thestrlenfunction has a return type ofsize_twhich is an unsigned integer type. This means thatstrlen(x) - strlen(y)also has this type. So instead of resulting in a value of -2 you get a result which is a very large positive value. This value is greater than 0, so the condition is true. If you cast the results of t...
I having problems extracting chx then ch only returns the first charecter ``` char* chini(long int a){ char* chx[12]; itoa (a,chx,10); return *chx; } ``` ``` char ch[12]; *ch=chini(init); puts(ch); ``` I want to have all of chx in ch but it only returns chx[0]
char* chx[12];is an array of pointers notcharsYou return a reference to the local variable which stops to exist when function returns. Both are undefined behaviours (UBs) You have three ways of doing it: ``` char *chini1(int a){ char *chx = malloc(12); itoa(a ,chx, 10); return chx; } ``` IMO the be...
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.
I have been playing around with what would be considered valid C syntax and what wouldn't,I tried1<2<1, and to my surprise, it is a valid C syntax. Does anyone know what that would do or represent ? I tried figuring it out by testing the value this kind of expressions take and changing the integer values but found n...
In C, when using a relational operator such as<, the result will always be1if the condition is true, or0if the condition is false. Due to therules on operator precedence and associativity, the expression ``` 1<2<1 ``` is equivalent to: ``` (1<2)<1 ``` The sub-expression(1<2)is true, so it will evaluate to1, so th...
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 "%" fol...
%%is the pattern to escape a%, so writeprintf("%d %% %d = %d")
I train myself in building a compiler. When I read the file I sometimes need to look a few characters ahead of my current position to know which token I have to generate. There are two options that come to my mind in that case: I read the entire file first and access the characters with an index variableI read one c...
Thanks for the comments. My decision is to just read the file entirely first and then later check if I run into any performance issues.
OK so the following command (see below) displays all variable names and their type information of the structure _KTHREAD inWindbg. But if I have the address of a specific _KTHREAD object how can I display thevalueof a particular variable located in this struct ? ``` lkd> dt _KTHREAD ``` I then tried the following co...
Just add the address dt _KTHREAD 0x12345 or if the address is in a register dt _KTHREAD @eax
I would like to know if it is possible to use a specific operator in a macro definition I have a macro where it works fine It is as follows: ``` #define TestMacroDefine(i, ...) \ Start->Client(i, __VA_ARGS__); ``` Example of use: ``` TestMacroDefine(pck->i, &pck->len); ``` As you can see I use the & operator, ...
Yes (leave out the last;of the macro though): ``` #define TestMacroDefine(i, ...) Start->Client(i, &__VA_ARGS__) int main() { TestMacroDefine(pck->i, pck->len); } ``` will expand to what you wanted: ``` $ cpp 1.c ... int main() { Start->Client(pck->i, &pck->len); } ```
I saw a question which had code snippet in C like this ``` #include <stdio.h> int main() { char s[] = "MANIPAL2022"; printf("%s", s+s[4]-s[3]); return 0; } ``` which returned: ``` 2022 ``` I am not able to understand what is being done here and how is the adding of characters showing these values. M...
``` s+s[4]-s[3] ="MANIPAL2022"+'P'-'I' ="MANIPAL2022"+80-73 ="MANIPAL2022"+7 ="2022" ``` Here the last step is how pointer works. Withs = "WESTHAM2022",s+s[5]-s[3]=s-19, pointing at an undefined area, thus it can return anything or crash
In mallinfo structure there are two fieldshblksandhblkhd. The man documentation says that they are responsible for the number of blocks allocated by mmap and the total number of bytes. But when I run next code ``` void * ptr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); *(int *) ptr ...
I did some experiments and they led me to the conclusion that this field is filled only whenmmapoccurred when callingmalloc. A normalmmapcall doesn't show up in this statistic, which is logical, because this is a system call, and the statistic is collected in user-space
When inputting strings which are separated by a comma the second string will print with space on the beginning. I need to scan and print comma separated string without whitespace in the beginning. This is my current code. ``` #include <stdio.h> int main() { char s[30]; char r[30]; scanf("%[^,],%[^\n]",...
Adding a whitespace before%[]will exclude it. ``` scanf("%[^,], %[^\n]",s,r); ```
My program (a text editor) enters raw mode of terminal like this: ``` tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) ``` so that it can read key strokes, draw using escape codes etc. But now I want to do this:echo hello | myprog, to read stdin from a pipe and then display it in the program UI. But now STDIN_FILENO points...
Usually,/dev/ttyis the current console, and if you don't need stdio interfaces, you can open it, receiving a fd, withint ttyfd = open("/dev/tty", O_RDWR). (It's usually a bad idea to mix Unix I/O and stdio I/O on the same device. But if you really want to, open withFILE* ftty = fopen("/dev/tty", "rw");and get the fd o...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 months ago.Improve this question If I have a probabi...
I think this would be an example of how to implement what you're trying to do: ``` int main() { double probability = 0.8; srand(time(0)); double randomNumber = (double) rand() / RAND_MAX; if (randomNumber < probability) { // execute code } return 0; } ```
I'm using an (static) external library (zmq.a) in our code, and during the compilation process of our program it says ../libzmq.a(src_libzmd when making a shared object; recompile with -fPIC However if I compile the library itself with -fPIC, our code now compiles but I received an error on launch: "undefined symbol...
Okay, so I was able to solve it. The way I changed theCFLAGSetc.overridedthe other flags, I needed to just add the '-fPIC' instead. One of the overrided flags was '-O2' therefore it couldn't find the stat symbol (as can be seen from the suggested answer before).
I've been trying to use regular expressions (<regex.h>) in a C project I am developing. According toregex101the regex it is well written and identifies what I'm trying to identify but it doesn't work when I try to run it in C. ``` #include <stdio.h> #include <regex.h> int main() { char pattern[] = "#include.*";...
lineandpatternare swapped. regcomptakes the pattern andregexectakes the string to check.
My code is supposed to make a pyramid as such, but just gives me a line, why? I've tried changing the conditions of the for and while loops and haven't found any solution. Any help would be appreciated!! ``` # ## ### #### ##### ###### ####### ######## ``` ``` #include <stdio.h> #include <cs50.h> int main(void) { ...
Declarejinside theforloop so it starts at 0 on each iteration. ``` for(int i = 0; i < n; i++) { int j = 0; while (j <= i) { printf("#"); j = j + 1; } printf("\n"); } ``` The inner loop could also be rewritten as aforloop. ``` for(int i = 0; i < n; i++) { for (int j = i; j >= 0; j...
I want to use the ternary operator and an empty char '' to spell correctly the word "neightbor" (with or without a "s"). I want to do the following : ``` printf("There is %d neightbor%c\n", nbNeighbors, (nbNeighbors>1)?'s':''); ``` obviously, I get an arrorerror: empty character constant How can I menage to use t...
Youcoulduse a non-printable character but they may end up looking like something else. You'd be better off using strings: ``` printf("There %s %d neighbor%s\n", nbNeighbors != 1 ? "are" : "is", nbNeighbors, nbNeighbors != 1 ? "s" : "" ); ```
I'm new to rust and I'm struggling to connect my rust code with a C library. The library expects a raw pointer*f32to the memory buffer of size 3*N. In rust code I have an arrayVec<[f32;3]>of size N. How can I get a raw pointer of type*mut f32from this array? ``` let coords: Vec<[f32;3]> = vec![[0.0,0.0,0.0]; N]; // C...
Because arrays are flat in memory, the layout of a pointer*mut f32toN * 3elements is the same as of*mut [f32; 3]ofNelements. Therefore, you can justcast(): ``` let ptr: *mut f32 = coords.as_mut_ptr().cast::<f32>(); ```
I'm using a Swedish keyboard layout and can't get access to many keys such as the bracket keys since I have to press AltGr to get access to them. I'm using theXkbKeycodeToKeysymto translate keycodes to keysyms but I only get 0 as a keysym when pressing AltGr. AltGr is Mod5Mask according to the X.h file. The state is ...
The function I needed wasXutf8LookupStringand using that. I followed thistutorialfor when configuring the input context.
Want to retrieve a date type from a postgres table using liqpq PQexecParams() in binary mode (please humor me).https://www.postgresql.org/docs/14/datatype-datetime.htmlsays that a date is 4 bytes (4713 BC to 5874897 AD). src/include/utils/date.h defines: ``` typedef int32 DateADT; ``` But obviously given the support...
Date is an integer day count from POSTGRES_EPOCH_JDATE (2000-01-01).
What is the difference between the 2?__INT_MAX__is defined without adding a library as far as I know andINT_MAXis defined inlimits.hbut when I include the libraryINT_MAXgets expanded to__INT_MAX__either way (or so does VSCode say). Why would I ever use thelimits.hone when it gets expanded to the other one?
You should always useINT_MAX, as that is the macro constant that is defined by the ISO C standard. The macro constant__INT_MAX__is not specified by ISO C, so it should not be used, if you want your code to beportable. That macro is simply an implementation detail of the compiler that you are using. Other compilers wi...
I have this code in C. The function needs to know the length of the string. Is there no way for me to pass just the string and then, inside the function, get the size? ``` char text2[] = "Hello!!"; write_coord_screen(2, 2, text2, sizeof(text2), FB_BLACK, FB_WHITE); ```
Take a look atstrlen. Notice however, thatstrlenis aO(n)operation, so if you know the length of the string (as you do in the above example) it may be preferable to pass that directly instead of computing it. Also, in the above example,sizeof(text2)will be 8, but the length of the string is 7.sizeofwill take into cons...
This question already has an answer here:"expression must have a constant value" error in VS code for C(1 answer)Closed9 months ago. I'm writing a program and I've faced an issue where I cannot set the array size to the user's liking. I know it's a pointer-related issue. ``` #include <stdio.h> int main() { int ...
VLAs are optional and MS compiler does not support them. You need to dynamically allocate the array: ``` int *array = malloc(length * sizeof(*array)); ``` after use you need tofreeit manually ``` free(array); ```
My pet project uses-nostdlibso I can't use any C libraries however I can include them for constants. Below is my code. If I compile usinggcc -Wfloat-equal -nostdlib -O2 -c a.con gcc or clang it'll give me the error below. I was curious if there's a way to check without triggering this warning. I suspect I can't unles...
You can usereturn d < INFINITY && (float) d >= INFINITY;. Another option isreturn isfinite(d) && isinf((float) d);if you want to classify negative values symmetrically. (These are macros defined inmath.h.)
I want to add a 4 at the end of the file and I have thought that I can do this in 2 different ways: First method: ``` int a = 4; FILE *f = fopen("file.txt","wb"); fseek(f,0,SEEK_END); fwrite(&a,sizeof(int),1,f); ``` Second method: ``` int a = 4; FILE *f = fopen("file.txt","ab"); fwrite(&a,sizeof(int),1,f); ``` I ...
These arenotthe same. The"wb"mode willtruncate the file to zero size, while the"ab"mode will open the file and simply place the file pointer at the end. So if you don't want to wipe out the contents of your file, use"ab".
As thedocumentationhighlighted, thelseek()function allows the file offset to be set beyond the end of the file. But what if I set it beyond the beginning of the file? Let the current offset be 5, What will actually happen when I trylseek(fd, 10, SEEK_END)? As mentioned, assume that I create a new file, and call the ...
Assuming that what you're asking if you can seek to before the beginning of the file (which your code example wouldn't do): Thespecification for lseek()says that it will return-1and seterrnotoEINVAL: The whence argument is not a proper value, or the resulting file offset would be negative for a regular file, block s...
given the following text-file ("file_text); ``` example text ``` I'm trying to read the content of this file in this way: ``` #include <stdio.h> #include <stdlib.h> int main(){ char* arr = malloc(64); FILE* f_fd = fopen("file_txt", "r"); fread(arr, 1, 64, f_fd); printf("|%s|\n", arr); return 0; } ``` bu...
The name of your file is "file_text", but you trying to open this file with: ``` fopen("file_txt", "r"); ``` try to open it with"file_text"file name.
If I want to create a vector ofsizecomponents and I want all components to be1, one way to do this is, of course, to use aforloop in this way ``` #include <stdio.h> int main() { int size=100; int array[size]; for(int j=0; j<size; j++) { array[j]=1; } } ``` But it doesn't look like the wa...
I'm afraid there are no alternatives to the loop in standard C. Ifgccis an option you can useDesignated initializersto initialize a range of elements to the same value: ``` int array[] = {[0 ... 99] = 1}; ```
This question already has answers here:How exactly does the ?: operator work in C?(5 answers)Closed9 months ago. ``` int max_of_four(int a,int b,int c,int d){ int max = a > b ? a : b; max = c > max ? c : max; max = d > max ? d : max; return max; } ``` so this is the code I found on net I was gonna wr...
Youre looking at "ternary" operators. They typically work of the form condition ? value_if_true : value_if_false So to translatec > max ? c : max;to a traditional if: if (c > max) { return c } else return max;
``` #include<stdio.h> #include <stdlib.h> int main() { char *a = malloc(sizeof(int) * 18); printf("%d",sizeof(a)); } ``` What is the size of a gonna be on a 32-bit system? I tried it on a 64-bit system and a was 8. Will it be the same on a 32-bit system?
"32 bit" refers to the maximum data size that the CPU can execute in a single instruction. This actually has no relation at all to the address bus of the same CPU, so a question asking "how large is an address on a 32 bit CPU" can't be answered. For example most 8 bit CPUs on the market have 16 bit address buses. And...
``` if(year%400==0 || (year%100!=0 && year%4==0)) ``` statement is in the form ofa or (b' and c) Does this reduce toa or (b or c')? ``` if(year%400==0 || (year%100==0 || year%4!=0)) ``` Is there a mistake in this reduction? (I thought it was correct but these two does not give the same results.)
Does this reduce toa or ( b or c' )? No. You can see this by building a truth table. Wecanchange theandto anor. ``` b' and c = ( b' and c )'' = ( b or c' )' ``` so ``` a or ( b' and c ) ``` becomes ``` a or ( b or c' )' ``` Not useful, except to show it's not equivalent toa or ( b or c' ). We can change t...
My c programm(for linux) needs users to have a specific programm lets say "foo" be installed to work. I am using cmake to generate build files. This program is to be distributed. How can I make sure that it is installed using cmake. I foundthisbut it's for checking at runtime. I want to check it before building the...
Iffooprovides a CMake package, usefind_packageto findfoo: ``` find_package(foo REQUIRED) # Use the foo::foo imported target or foo_EXECUTABLE cache variable ``` There aremany built-in packagesfor CMake includingPythonandFLEX. Iffoodoesnotprovide a CMake package and you only need the path to the executable, then ...
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.
ERROR: type should be string, got "\nhttps://en.cppreference.com/w/c/io/fopen\n\nsays that it depends on the mode you open your file with. For example, if it's \"append\" -- the pointer is set to EOF.\n"
I have code that uses multiple different strings in the code, like "my-app/123" and "my-app/#". Sometimes it's also used for further formatting (include other variables with%placeholders). Now I need to make this prefix more configurable by adding a#definestatement for the string prefix. It then looks like this: ``` ...
ChangeMQTT_TOPIC + "/#"toMQTT_TOPIC "/#". During compilation, adjacent string literals are concatenated.
I keep getting these warnings I want to calculate the image size in colors in (Mo) and in black and white in (Ko) so for this I'm using a parameters that are past in a terminal command which are (image length and width) Here is my code ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>...
To convert achar*to anintin C, you don't cast the pointer. Instead you useatoi.
``` #include <stdio.h> int main() { unsigned long long int the_num = 600851475143; printf("%llu", the_num); return 0; } ``` When I try to compile this, I get the following warnings: ``` 3.c: In function 'main': 3.c:10:12: warning: unknown conversion type character 'l' in format [-Wformat=] print...
I changed the language standard toc99by adding-std=c99flag while compiling and the warnings disappeared.
When trying to compile the following code based on the openSSL reference code (https://www.openssl.org/docs/man3.0/man3/RSA_generate_key.html) ``` #include <openssl/rsa.h> #include <openssl/evp.h> int main(){ EVP_PKEY*pkey=EVP_RSA_gen(1024); } ``` It throws the following error: ``` /usr/bin/ld: /tmp/ccLRNWp1.o...
Question solved followingundefined reference to `EVP_PKEY_CTX_new_id'first comment. Just be sure that you are linking to a correct directory since the directory name may change from lib to lib64
When trying to compile the following code based on the openSSL reference code (https://www.openssl.org/docs/man3.0/man3/RSA_generate_key.html) ``` #include <openssl/rsa.h> #include <openssl/evp.h> int main(){ EVP_PKEY*pkey=EVP_RSA_gen(1024); } ``` It throws the following error: ``` /usr/bin/ld: /tmp/ccLRNWp1.o...
Question solved followingundefined reference to `EVP_PKEY_CTX_new_id'first comment. Just be sure that you are linking to a correct directory since the directory name may change from lib to lib64
I'm new in programming and exited to learn new things! I wanted to create and run makefile in c, to see how it's working, but I'm having the same problem again and again. I will send the picture and the source (from geeksforgeeks) that I'm using.... Thanks a lot 🙏. https://www.geeksforgeeks.org/how-to-use-make-uti...
You need toinstall make, or if it's already installed, update you search path for commands to where it's installed.
I receive this error from the following c code. ``` if (system("clear") == -1) { fprintf(stderr, "system() failed"); } ```
Don't usesystem(). If caller of your program can manipulate the search path for command then any command named clear can be executed instead of the one you intended. Implement the feature in C instead: ``` #include <stdio.h> void clear() { // Move cursor to top-left corner and clear the erase entire screen f...
I have a c file that it's located in the folder /my_test as shown below. I can run the command below successfully if I'm located on the "my_test" directory. ``` ~/my_test$ strace -e write -f gcc -I/home/user/my_test/headers -fsyntax-only mymainfile.c ``` is it possible to run the same command from a different direct...
The-Imean adding extras headers path, the same thing for-Lbut for precompiled objects (libraries). So you need to remove-Iyou did, the command should be like this: ~/new_test$ strace -e write -f gcc -I/home/user/my_test/headers -fsyntax-only /home/user/my_test/mymainfile.c