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 arrays are initialized via an header that contain their definition such as. float test_data[FEATURES][N][SAMPLES_BATCH] = {-0.715339, -0.50792, -0.307726, ...,}; For the second case, on the other hand, I was wondering if there was a way to initialize the memory once allocated quickly otherwise the alternative would be to load them from files.
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 of the code @dbush provided
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 don't expect 100ns granularity. Another option isQueryPerformanceCounter, which will give you microsecond intervals from an undetermined starting point: ``` LARGE_INTEGER ticks; QueryPerformanceCounter(&ticks); uint64_t ts = ticks.QuadPart; ```
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 forpthread_mutex_destroy: It shall be safe to destroy an initialized mutex that is unlocked. Attempting to destroy a locked mutex results inundefined behavior. (emphasis is mine) This post contains some more info about the proper usage ofpthread_mutex_destroy:How to safely and correctly destroy a mutex in Linux using pthread_mutex_destroy?.
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 #include <math.h>. But I don't understand what is happening here.
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 in__android_log_print. You'll have to add-llogto your linker flags.
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]; FILE *file; file= fopen("filename.txt", "r"); printf("File includes:\n"); while (fgets(line, 50, file) != NULL) { printf("%s", line); } fclose(file); return(0); } ```
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 explain what is going on? Is it possible to get the correct output with the macro too? ``` #include <stdio.h> #include <math.h> int main() { float Fs = 8000; float T = 1/Fs; printf("T = %f", T); return 0; } ```
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. Use a text editor like Visual Studio Code, TextMate, or Sublime Text instead. Text editors like these have bundles you can install that let you build and run C programs from within the editor.
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 indeed print 6. But, doing the same but with floats only prints out 0.00000: ``` int main() { float foo = 6; call(foo); } void call(float bar) { printf("%f", bar); } ``` How do I correctly call and then print float variables?
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 advance..!!
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]) >> 4; arr_2[1] = 0x0F & 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 "section name"))should be used in the array definition. Do you have any suggestions on how I can do it? Thanks in advance
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 two separate arrays in different sections and array of two pointers referencing those arrays.
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 searching around. It leads me to wonder what the purpose of such a construct is and what it is meant to do?
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 the body, that will be an infinite loop.
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); ``` It returns 0x499FDC6D, while for little endian it should return 0x6DDC9F49
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", ptr[i]); } ```
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,BE VERY SUREto setIntelliSenseModetolinux-gcc-x64or anyx64compiler instead ofx86becausex64is for 32-bit compilers whilex84is for 64-bit compilers which gcc inUbuntuworkspace might not support. (https://i.stack.imgur.com/qT8zU.png)Voila! There should not be anysquiggle linesafterwards. PleaseVotethis answer if it helped you!
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 is not?
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 these (MSVC 2015) header files ``` Sspi.h WinDNS.h datacontainer.h wmcodecdsp.h wmnetsourcecreator.h wmscontext.h wmsdkidl.h wmsincomingcounters.h wmspacket.h ```
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) { { d; } c; } } ``` For your specific case it's: ``` { i = 2; while (i < 6) { { s += t[i]; } i += i + 1; } } ```
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 tokenize(char data[]) { strtok(data, ','); // gives me an access violation error } ``` When I used strtok in main, it works, but not when I pass it to the function.
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()should be achar *, not achar. So change','to",".
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[] insidea struct I used temporary array to get string from user and it works fine , when I try to copy this temporary array to the variable array inside the struct I get \command files at end of string ``` for (u32 i=0;i<name_size;i++) { printf("\nin While"); pn->name[i]=temp_name[i]; } ```
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)); return !(msb ^ lsb);
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 both). When I reduce the code to less than 5000 lines, it shows everything correctly. So, is there a setting somehwere, where I can choose the maximum number of lines before it compresses? (I had a question once when I open a large file about that, but now it never shows it again).
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/Hurd systems. This error never occurs on GNU/Hurd systems.- Why?
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++) { matr[i]=(float*)malloc(n*sizeof(float)); for(j=0; j<n; j++) matr[i][j]= 9+rand()%20; } for(i=0; i<n; i++){ for(j=0; j<n; j++) printf("\t%2.2f",matr[i]); printf("\n"); for (i=0; i<n; i++) free (matr[i]); free(matr); free(mass); } } ``` Problem is here: ``` for(j=0; j<n; j++) printf("\t%2.2f",matr[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 returned by socket() or the one you got with accept())." The way I understand it, if sockfd is a stream socket, it's in a connected state. By "sockfd is the socket descriptor you want to send data to", does this mean the data is actually sent (by way of sockfd) to therecv()'ing socket connected to sockfd?
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 stars. ``` #include <stdio.h> int main() { int i, j; for(i=1; i<=9; i++) { for (j=1; j<=i; j++) { printf ("%d",j); } int k; for(k=8; k>0; k--) { printf("*"); } printf("\n"); } } ``` And it prints out this: ``` 1******* 12******* 123******* 1234******* 12345******* 123456******* 1234567******* 12345678******* 123456789******* ```
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(...); end foo; function Function input Real u; output Real y; algorithm y := u*2; end Function; ``` When I use the "check" option, I get some error stating fun is undeclared which I don't if I do not use a function as input. I looked online and in the use manual of dymola but I haven't found an example stating it was possible, nor impossible.
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" }; ``` How do you achieve this in C? I tried using for loops but because it is a 2D array, I wasn't able to figure out the right technique.
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" }; ``` How do you achieve this in C? I tried using for loops but because it is a 2D array, I wasn't able to figure out the right technique.
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 first place?Am I missing something?
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 script. The linker script decides which parts of the memory to reserve for what. Stack,.bss,.dataand so on. Similarly the flash memory for the actual program may be divided in several parts.
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 message. The only caveat is that the receiving side may not know the size of the buffer that is incoming, so you may need to do a Probe first.
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; secp256k1_sha256_initialize(&cxt); secp256k1_sha256_write(&cxt, (uint8_t *)data, (int)len); uint256_t res; secp256k1_sha256_finalize(&cxt, (uint8_t *)&res); return res; } ``` I want to see what's insidedataand what's being returned by the above function, so printing seems like an easy way but how do i print contents of*datanot the pointer todatabecause*%p*gave me an address.
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 AddSecurityPackage winapi for attaching to lsass when i was testing all way's, detect that nanodump specified dump file size(default=>report.docx),is different from procmon.exe Full and Mini dump output. my test: procmon full = 71 MB procmon mini = 1.6 MB nanodump = 11 MB what can i do for dump by nanodump,compatible with mimikatz::logonpasswords?
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) { //do something temp = temp->next; } ```
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 describe performs both a DFS and BFS of it.
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 = mmap(NULL, OUT_SIZE, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0); ``` Note: it occurs to me that detecting this kind of error is a good reason for the convention (or requirement, in some implementations) that the file descriptor be specified as -1 for an anonymous mapping.
(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 nonsense, what's that supposed to achieve? Either way, rule 10.5 has nothing to do with any of this since that rule is about value conversions, not about pointer conversions. So it would seem that your MISRA checker is broken, like they tend to be.
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 to to not print the last comma how i can do it i tried this code but not working ``` printf("%d%s", numbers[i], (i !=arraySize-1) ? "," : ""); ```
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", (first ? "" : ","), numbers[i]); first = false; } } ```
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 (*)(int)by trying to add imaginary identifier to the proper location, but wonder how compiler systematically determines it, obviouslycdeclcan't.
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 of grammar productions that defines how this works.
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 the max lock-free size (4 bytes) [-Watomic-alignment] My question is how I can achieve atomicity without using critical sections.
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 the max lock-free size (4 bytes) [-Watomic-alignment] My question is how I can achieve atomicity without using critical sections.
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 **s){ for(int i=0; i<3; i++){ char buf[10]; snprintf(buf, 10, "#%d",i); s[i]=buf; } } int main() { char *s[3]; func(s); for(int i=0; i<3; i++){ printf("%s", s[i]); } return 0; } ```
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 result; ``` will not do, as it still explicitly mentions thestruct footype. Is it possible to get the return type of enclosing function withtypeof? I tried: return (typeof(#__func__())) { .bar = 42 };andreturn (__auto_type) { .bar = 42 };, but apparently C's type inference doesn't go outside of a single expression. I'm writing a preprocessor macro and would like to avoid the extra argument for the type. gccspecific solutions are welcome.
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 output is 2 4 6 why ?
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() { sum(); } ```
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 longer work on the child process.
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 theinitprocess, with id 1).
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 "Visual Studio" class.
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.For the others, as @IInspectable said, useEnumChildWindows. But as far as Visual Studio is concerned,EnumWindowsis enough.
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 highlighter for C does. It sort of behaves like a Python dictionary, socharP['A']would spit out1. Maybe I'm not looking hard enough, but can anyone point me in the right direction because every time I search "C++ dictionary" or "C dictionary", it always involves Maps and not this. What is it? What are its limitations?
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, EPOLL_CTL_ADD, evfd, &ev); ev.events = 0; epoll_ctl(epollfd, EPOLL_CTL_MOD, evfd, &ev); ``` So, does the above makes thestdoutevent not being reported toepoll_wait?
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 of this code. ``` do { ch = fgetc(file); printf("%c", ch); } while (ch != "\n"); fclose(file); ``` In file i just have "Hallo, world\n" and when i try to read info i have a infinity loop. If i change toch != EOFI have a correct answer.
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 associated with A is sequenced before every value computation and side effect associated with B. (5.1.2.3) The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value. (6.5.17)
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)is false, because this will be3-5 > 0which is false. Hence, the output should be 5. I couldn't understand what went wrong.
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 these functions toint, you'll get the expected result. ``` int len = (((int)strlen(x) - (int)strlen(y)) > c) ? strlen(x) : strlen(y); ```
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 best:: ``` char *chini2(char *chx, int a){ itoa(a,chx,10); return chx; } ``` The worst: ``` char *chini3(int a){ static char chx[12]; itoa(a,chx,10); return chx; } ```
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 no pattern.
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 the entire expression is equivalent to: ``` 1<1 ``` Since this expression is false, it will evaluate to0. Therefore, writing1<2<1is equivalent to writing0.
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 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 char at the time withgetc(file);and in case I have to go back to some previous character I usefseek(file, -1, SEEK_CUR); Which one of these options is more efficient? Which would you prefer?
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 command in Windbg with a known address of a_KTHREAD object. Is this command correct ? ``` lkd> dt _KTHREAD FFFFA80000050000 WaitPrcb ```
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, is there any way I can migrate this operator to the macro definition? do something like: ``` #define TestMacroDefine(i, ...) \ Start->Client(i, &__VA_ARGS__); ```
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. Moreover a string of the same length likeWESTHAM2022returned nothing I tried to understand the pattern for this and forchar s[] = "WESTHAM2022" printf("%s", s+s[5]-s[3]);The compiler returned some garbage value!)�U And for ``` char s[] = "WESTHAM2022"; printf("%s", s+s[2]-s[3]); ``` it returned9WESTHAM2022
``` 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 = 10; ``` Fieldshblksandhblkhdare also zero. While the total number of free bytes in the blocks decreases. Could you please explain why this behavior is observed? I also tried to allocate all free space and use mmap after it. But in this situation fields also equal to zero Compiler: gcc 9.4.0 OS: Ubuntu 20.04.1
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]",s,r); printf("%s\n",s); printf("%s",r); return 0; } ``` The output when hello world, o wor is the input is ``` hello world o wor ``` It should be ``` hello world o wor ```
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 to a pipe not to a terminal andtcsetattrfails withimproper ioctl. How do I getfdof an actual terminal when being a destination of a pipe?
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 out of theFILE*withfileno(ftty).)
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 probability between 0 and 1 where 1 executes every time and 0 never executes, how would I implement that into my code? For instance, I have a probability of 0.8, how would I program a section of code to run 80% of the time. I assume we used the rand() function but I don’t know how to implement that.
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 stat" Edit: I use the following commands in order to generate libzmq.a (on rdht 7 x86): autoreconf --install && mkdir build && cd build && ../configure && make CFLAGS='-fPIC' CXXFLAGS='-fPIC' && make install
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.*"; char line[] = "#include <stdio.h>"; regex_t string; int regex_return = -1; regex_return = regcomp(&string, line, 0); regex_return += regexec(&string, pattern, 0, NULL, 0); printf("%d", regex_return); return 0; } ``` This is a sample code I wrote to test the expression when I found out it didn't work. It prints 1, when I expected 0.It prints 0 if I change thelineto"#include", which is just strange to me, because it's ignoring the.*at the end.
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) { int n = get_int("Add the height of the pyramid: "); int j = 0; for(int i = 0; i < n ; i++) { while (j <= i) { printf("#"); j = j + 1; } printf("\n"); } ```
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--) printf("#"); printf("\n"); } ```
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 this trick to get the right spelling in oneprintf?
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]; // Call a wrapper of C function expecting a raw pointer *mut f32 wrapped_c_function(coords.????, 3*N); ``` I triedcoords.as_mut_ptr()but it doesn't work because of the type mismatch: ``` mismatched types expected raw pointer `*mut f32` found raw pointer `*mut [f32; 3]` ``` So I need to "flatten" the data to be treated as a pointer to flat f32 buffer. What is the correct way of doing this?
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 128 when pressing it. I've tried to pass different levels and groups toXkbKeycodeToKeysymwith no results.
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 supported date range it's not a normal int. Something like this: ``` int32_t haha = be32toh(*((uint32_t *) PQgetvalue(res, 0, 17))); ``` Gives haha=1466004328 for 2022-10-25. Which is clearly not a day count and since its not a ratio of 86,400 is also not seconds since an epoch. Number is also too small to be microseconds. How do I interpret the 4 bytes of postgresql 'date' data? Added Later: This question contains an error - PQgetvalue() references column 17 (a text value) instead of column 18 (a date value) - with that corrected haha=8332
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 will probably not define that macro, and will implementINT_MAXin some other way.
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 consideration the nul terminator, but usually when we talk about the length of a string we talk about the number of characters it has. On top of this,sizeofonly works in your case becausechar text2[]declares a character array. If instead you'd have writtenconst char *text2 = "Hello!!"you'd be forced to usestrlen.
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 length; scanf_s("%d", &length); int array[length]; //"expression must have a constant value" } ```
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 unless I call code I don't compile warning: comparing floating-point with ‘==’ or ‘!=’ is unsafe [-Wfloat-equal] ``` #include <math.h> int IsInfinity(double d) { return d != (double)INFINITY && (float)d == INFINITY; } ```
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 think they are exactly the same. Am I right?
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 functionwrite(fd, buf, 5). The current file offset would be 5. Then using lseek function above, I expect the result would either be 0 or some errors may occurred.
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 special file, or directory.
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; } ``` but it doesn't print the really content of the file. I see for example:|P?p|or|P^2|..And I don't understand why I get it. NOTES: 64 is the max size of this file.
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 way programmers would do it. How can I do this vectorially, that is, without changing one element at a time?
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 write the greatest number what does this code mean or '?' and ':' mean?
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 many 8/16 bitters even support 24 bit or larger address buses. Although as it happens, the vast majority of 32 bit CPUs on the market conveniently also have 32 bit address buses. But this is no guarantee unless you have a specific CPU in mind.
``` 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 theandto anorusing the same approach. ``` a or ( b' and c ) ``` becomes ``` ( a' and ( b or c' ) )' ``` Again, not useful. It can be simplified toyear % 4 == 0, as long as you only deal with the years 1901 to 2099.
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 program.
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 you can usefind_program: ``` find_program(Foo_EXECUTABLE foo REQUIRED) ``` From here you can use theFoo_EXECUTABLEvariable in yourexecute_processoradd_custom_commandcalls.
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 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: ``` #define MQTT_TOPIC "my-app" ``` But how can I use it without writing several lines of code and allocating memory for every usage? I've tried this but the compiler doesn't understand what I want: ``` esp_mqtt_client_subscribe(client, MQTT_TOPIC + "/#", 0) ``` Strings are so complicated in C. The compiler should be able to resolve all of this because it's a preprocessor symbol, not a runtime string.
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> int main(int argc, char *argv[]) { float resultKo, resultMo; resultKo = ((int)argv[1] * (int)argv[2]) / (1024); resultMo = (((int)argv[1] * (int)argv[2])/(1024 * 1024))*3; printf("la taille de l'image en niveau de gris : %.2fko\n",resultKo); printf("la taille de l'image en couleur : %.2fMo", resultMo); return 0; } ```
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=] printf("%llu", the_num); ^ 3.c:10:9: warning: too many arguments for format [-Wformat-extra-args] printf("%llu", the_num); ^~~~~~ ``` Maybe it's just a bug or something?.. GCC version: gcc version 6.3.0 (MinGW.org GCC-6.3.0-1) Compiled using the following command: gcc -Wall -Wextra -pedantic 3.c
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: in function `main': rsa2.c:(.text+0x28): undefined reference to `EVP_PKEY_Q_keygen' collect2: error: ld returned 1 exit status ``` I'm compiling with the next command. ``` gcc -I/usr/include/openssl/ rsa2.c -lcrypto -lssl ``` And my openssl version is ``` openssl version OpenSSL 3.0.7 1 Nov 2022 (Library: OpenSSL 3.0.7 1 Nov 2022) ``` What I might be missing?
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: in function `main': rsa2.c:(.text+0x28): undefined reference to `EVP_PKEY_Q_keygen' collect2: error: ld returned 1 exit status ``` I'm compiling with the next command. ``` gcc -I/usr/include/openssl/ rsa2.c -lcrypto -lssl ``` And my openssl version is ``` openssl version OpenSSL 3.0.7 1 Nov 2022 (Library: OpenSSL 3.0.7 1 Nov 2022) ``` What I might be missing?
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-utility-to-build-c-projects/ I tried to run makefile and then I wanted to use the commands in makefile to see how they r working.
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 fputs("\e[;1H\e[2J", stdout); } ```
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 directory? Let's say I'm in /home/user/new_test instead. ``` ~/new_test$ strace -e write -f gcc -I/home/user/my_test/headers -fsyntax-only -I/home/user/my_test/mymainfile.c ``` I believe the "-I" flag only works for header files only correct? is there an equivalent flag for the c file?
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