question
stringlengths
25
894
answer
stringlengths
4
863
Long ago I wrote a variant ofstrftimewith added conversion specifications (https://www.gdargaud.net/Hack/SourceCode.html#StrfTime). Some time ago I discovered that you can add your own conversion specifiers toprintfwithregister_printf_function(https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html...
Theregister_printf_functionis a GNU extension that allows for registering customprintfformat specifiers. Currently the glibcstrftimefunctionimplementationandimplementationdoesn't allow registering custom format specifiers. The function justignores bad format specificationwhereasprintf checksthe array with custom regis...
I have a C script, I need to make it work as a lever, ie each time transfer my Linux from one state to another. I need something like this: ``` if (even_execution) {state = 0;} else {state = 1;} ``` Perhaps I should writeeven_executionvariable to a file or add an environment variable?
Since you're scripting, I suggest you use a scripting language for it. Such as: ``` #!/bin/bash STATE=$(cat .state) STATE=${STATE:-1} if ((STATE)); then echo ohyeah else echo ohno fi echo -n $((1-STATE)) > .state ``` Edit:regarding where to put the file, perhaps/var/lock/,/var/tmp/or/var/local/might be suit...
How can I achieve the following print format: ``` A B C D C E F TP1944 LIS OPO 10:00 10:55 XV1 OPO LECO 12:00 13:35 ``` Where: A string can go from 2-6 charsB and C strings can go from 3-4 chars Which means the print must take in count that even if for example the A string only uses 5 chars from t...
%sdefaults to right justification. Use"%-6s %-4s %-4s ..."to make it left justify.@Mark Tolonen
I've one string arraychar version[][8] = {"new", "old", "latest", "oldest", "ancient"}; and I've one macro ``` #define FS(file, attr) \ filesys(file, file_ ##attr## _ops) \ ``` How could I pass members ofversionof string array into the FS macro ?
You cannot. Macros are compile time and the compiler will no be able to splice the strings the way you want. Instead, try usingstrcat(), just don't forget that you need to keep track of how large your string arrays are.
It is necessary that in the array 4 elements were selected, in these elements the indices changed 0-2, 1-3, then the next 4 elements were taken and so until the array ends I tried to use built-in loops, but it didn't quite work out. Either the test was displayed shifted 2 indexes forward, or the first 2 indexes were ...
Without code we can't really help you fix it... but here is a solution: ``` #include <stdio.h> #include <string.h> int main() { char str[11] = "HelloWorld"; for(int i = 0; i < strlen(str); i += 2) { char tmp = str[i]; str[i] = str[i+1]; str[i+1] = tmp; } printf("%s", str...
I am trying to wrap a C library in Python using ctypes library. I wrap structs this way file.c ``` typedef struct { int x; int y; } Point; ``` file.py ``` import ctypes class Point(ctypes.Structure): _fields_ = [("x": ctypes.c_int), ("y", ctypes.c_int)] ``` But I have a statement like this and cann...
Check[Python 3.Docs]: ctypes - A foreign function library for Python. That's a function pointer. You can wrap it like this: ``` FuncPtr = ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_char), ctypes.POINTER(ctypes.c_char)) ``` But it very much depends on how are you going to make use of it. As a side note,typedefdoesn't...
i'm doing a small IOT project i have 1 master and 2 end node (using rf24l01). Master will receive 2 packages and store in JSON. For the database i'm gonna using Firebase and show it in Node-red. My data like this ``` { "1":{ "Temp":"value", "Humid": "value"} "2":{ "Temp":"value", "Hum...
I believe the question you are asking is, wether you can access Firebase real time databse through an API? If so, yes, Firebase offers a REST API for its realtime database. You can look up the specification here:https://firebase.google.com/docs/database/rest/save-data. If you want to secure your database, you can use...
I am trying to wrap a C library in Python using ctypes library. I wrap structs this way file.c ``` typedef struct { int x; int y; } Point; ``` file.py ``` import ctypes class Point(ctypes.Structure): _fields_ = [("x": ctypes.c_int), ("y", ctypes.c_int)] ``` But I have a statement like this and cann...
Check[Python 3.Docs]: ctypes - A foreign function library for Python. That's a function pointer. You can wrap it like this: ``` FuncPtr = ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_char), ctypes.POINTER(ctypes.c_char)) ``` But it very much depends on how are you going to make use of it. As a side note,typedefdoesn't...
i'm doing a small IOT project i have 1 master and 2 end node (using rf24l01). Master will receive 2 packages and store in JSON. For the database i'm gonna using Firebase and show it in Node-red. My data like this ``` { "1":{ "Temp":"value", "Humid": "value"} "2":{ "Temp":"value", "Hum...
I believe the question you are asking is, wether you can access Firebase real time databse through an API? If so, yes, Firebase offers a REST API for its realtime database. You can look up the specification here:https://firebase.google.com/docs/database/rest/save-data. If you want to secure your database, you can use...
I get an error in my C code: ``` error: incompatible types when assigning to type ‘struct command’ from type ‘char **’. ``` I don't know why can't I assign char *var[] to char **. ``` typedef struct Appstruct{ char *app[10]; } APP; struct command { char **argv; }; struct command cmd[10]; for(i=0;i<pipecount+...
You can’t assign to thestructobject, you need to assign to its member: ``` cmd[i].argv = APPS[i].app; ```
I am a student who is new to the world of Linux and C. I am doing a bit of kernel programming, but I don't know how to import sys.c, since it's not in the include directory. Specifically, I need it to use thegetrusagefunction within my code. Is it possible/ok to include it, and if so how?
You have to include include/linux/resource.h file where the declaration of the function resides. In this case should not include the .c file where you have the definition of the function.Read about #including .c file here
This question already has answers here:How does the Comma Operator work(9 answers)Closed4 years ago. I was readingthis questionabout sequence points and I saw this line: i = (i, ++i, 1) + 1; // well defined (AFAIK) I was wondering how is the following syntax called and what are its effects? i = (a1, a2, ...,an);
This is the comma operator forintoperands, together with grouping through parentheses, which is always allowed. First, ``` (i, ++i, 1) ``` evaluatesi, then++i, then1and returns the result of the last expression (which is1). Then ``` (i, ++i, 1) + 1 ``` is the same as ``` 1 + 1; ``` which results in2, soiis set t...
I have to write a c program, that gets a .so file (shared-object) as an argument in the main method and call a function f on it. It expects a function f to exist on this library. My program has to work for any .so file, so I can't include them directly. so by calling ``` ./myprogram myLibrary.so ``` myprogram has t...
What you're trying to do is called "dynamic loading" of libraries. On Unix-like operating systems, the call you're looking for isdlopen(). It takes a filename and some flags, and opens the specified shared library. You can then use thedlsym()routine to look up individual symbols (like your function f()), which you ...
I have to write a c program, that gets a .so file (shared-object) as an argument in the main method and call a function f on it. It expects a function f to exist on this library. My program has to work for any .so file, so I can't include them directly. so by calling ``` ./myprogram myLibrary.so ``` myprogram has t...
What you're trying to do is called "dynamic loading" of libraries. On Unix-like operating systems, the call you're looking for isdlopen(). It takes a filename and some flags, and opens the specified shared library. You can then use thedlsym()routine to look up individual symbols (like your function f()), which you ...
Say I have a printf with many parameters: ``` printf("%d %d %d %d", A, B, C, D); ``` For some reason I would like one parameter to no longer be printed, but still be listed in the parameter list (for instance for visual reason, or maybe it's a function call with a necessary side effect, etc). Can I replace %d with ...
If you for some reason must change these on the fly, then keep things simple: ``` printf("%d ", A); printf("%d ", B); if(c) printf("%d ", C); printf("%d ", D); ```
I want to know if have in the ISO specification that a concatenation of a constant array is implementation dependent or not? If it is depends on implementation, could you tell me which compiler does not concatenate? ``` #include <stdio.h> int main(void) { char *a = "concatenate" "this array"; ...
It is a standard feature, but it has nothing to do with constant arrays. It only works for string literals. The C standard defines a number of "translation phases". Phase 6 is: Adjacent string literal tokens are concatenated. See e.g.5.1.1.2 Translation phasesinthis draft standard.
This question already has answers here:How dangerous is it to access an array out of bounds?(12 answers)Closed4 years ago. I am pretty new to C and I have tried the following code ``` #include <stdio.h> int main () { char str[] = "a"; for(int x = 0; x < 20; x++) { printf("%c\t%d\n", str[x],str[x]); } ...
These random characters are just garbage from the memory. You read from a place in the memory you have not written intentionally. Note that one should not do it. If you try to read from/write to memory you are not suppose to read from/write to, OS might kill your application.
I need help with finding the correct bit mask. 0xbc61 has to be 0xbcaa, but I am not sure how to create the bit mask to affect only the part I have to change. I also tried splitting the value but wasn't sure how to "glue" them with the new one... ``` unsigned short int left, right; unsigned short int temp = 0xbc61; u...
You can use theXORhere: 0x61is0b01100001 0xaais0b10101010 To convert one value into another just useXORwith0xCB(0b11001011): ``` unsigned short mask = 0xbc61; .... // convert to new mask 0xbcaa mask ^= 0xCB; // mask now is 0xbcaa ... // convert back to 0xbc61 mask ^= 0xCB; // mask now is 0xbc61 ``` NOTE:A XOR 1 =...
I'm reading the values from a SD card in an ARM micro: ``` Res = f_read(&fil, (void*)buf, 6, &NumBytesRead); ``` wherefilis a pointer,bufis a buffer where the data is stored. And that's the problem: it's an array but I'd like to have the contents of that array in a single variable. To give an actual example: the 6...
Without type punning you can do as below. ``` uint64_t data = 0; for (int i=0; i<6; i++) { data <<= 8; data |= (uint64_t) buf[i]; } ```
I need to print a certain ASCII character, DOUBLE_HORIZONTAL_LINE(205) "═" 20 times. The file is encoded in unicode however, so I need to do something likeprintf("%c", 205), which is fine, except I can't figure out how to repeat the char. I tried using%1$c, but that just printed "$c" literally. ``` printf("%1$c%1$c\n...
You can do this: ``` char bar[21]; memset(bar, 205, 20); bar[20] = '\0'; puts(bar); ``` As a bonus, this is more efficient than printf(), because the entire string is written to stdout at once.
I'm new to C and in an exercise, I have to write the output of the following portion of code, which is3. But I couldn't understand why it is that. ``` int main() { char st[100]="efgh"; printf ("\n%ld\n",&st[3]-st); return 0; } ```
When you use an array in an expression, unless it is the argument of&orsizeof, it evaluates to the address of its first element. Thus&st[3] - stevaluates as&st[3] - &st[0], which is just pointer arithmetic: The difference between the addresses of two array elements is just the difference between their indices, i.e.3 ...
Hi I have a problem with one of exercise from codewars site. My job is to extract exponent from double value as a unsigned number. But I am not allowed to use any arithmetic and binary operation and include any extra files. So then i cant use charcters: +-*/%&|^~<>#?. I think that only way to solve this problem is usi...
Note: I have not tested the following, so it may need some 'tweaking' ``` #include <math.h> #include <stdint.h> typedef union { double f; struct { uint64_t mantisa : 52; uint64_t exponent : 11; uint64_t sign : 1; } parts; } double_cast; uint64_t normalizedExponent(double d)...
``` unsigned short int temp, temp2; temp = 0xbc61; // 1011110001100001 // temp2 has to be 0x61 (01100001) but I don't know how to shift, mask or whatever temp2 = (temp << 8); // this doesnt work, because I get 0x6100 (110000100000000) ```
To select the 8 lowest bits of1011110001100001, you need to perform a bitwise AND operation with11111111: ``` 1011110001100001 & 0000000011111111 ------------------ 0000000001100001 ``` That is, ``` temp2 = temp & 0xff; // or 255 ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question I want to solve pointer problems. The code was taken from book & I want to know how it was compiled Ex: (...
If you substitute the values, the expression converts to (4*(-(4)))/(12)+10 which is (Using BODMAS) (-16/12) + 10 16/12 division is an integer division so you get -1+10 = 9
This question already has answers here:Is char signed or unsigned by default?(6 answers)What happens when a char is assigned a value too large to fit in a byte?(1 answer)Closed4 years ago. Can someone explain the result of this? Please explain step by step clearly. Thanks a lot. Why it's -16, -6, - 22? How compiler ...
BecauseChar is 8 bitsandit's capacity is 255 When you add i+j you put ‭490‬in sum Then sum variableoverflowand it generate negative number Useintinstead ofcharfor sum variableit will solve your problem Readhttps://www.cquestions.com/2011/02/char-overflow-in-c.htmlfor more information
This is a C program in which the code from "int k" and "for" loop are enclosed in the curly brackets. What is the purpose of those curly brackets? ``` int main(){ int k; { int k; for (k=0;k<10;k++); } } ```
There are no "unwanted braces" in this code. There is an anonymous block, which is not an error. In fact, it is allowed by the spec. Your variablekis defined in the main scope, but then shadowed in the anonymous block. ``` int main() { int k = 0; { int k = 1; // do more stuff with k } // k is s...
In C, I want to take an input from the user but I don't know how long is it. I think I should usemalloc()to set the length of the text array: ``` char *text = NULL; text = malloc(sizeof(input)) ``` But, how can I do it at the same time that I'm storing the input to the array withfgets()? ``` fgets(text, sizeof text...
The string stored as a result of callingfgetswill contain a newline if it can fit in the buffer. If the read string ends in a newline you know you have a full line. If not, you know you need to read more. So start by usingmallocto allocate a buffer of a certain size. Then usefgetsto populate the buffer. If there'...
Consider the following example which initialize an array with a default value: ``` static unsigned int array[10] = { [ 0 ... 9 ] = 5 }; ``` What exactly this operator does? It is related to variadic macro__VA_ARGS__?
In standard C, since C99, designated initializers allow to initialize individual elements of an array in the form: ``` int array[4] = {[1] = 42}; ``` The syntax you stumbled upon is a range initializer, it is a GNU extension to initialize all elements between0and9to the given value, thus strictly equivalent to: ```...
I have generally worked only with file descriptors. I am not sure if a FILE * will continue to work correctly if the fd linked to it is used for someother purpose. Do FILE * and fd linked to it exist independently?
On POSIX systems, yes, the fd backs theFILE*. Closing theFILE*closes the fd. Interleaving use the fd andFILE*risks mucking up your data (theFILE*does user mode buffering that the fd bypasses); you'd have to either disable buffering (withsetvbufor the like) or make sure theFILE*is reliably flushed before anything write...
Do POSIX threads (managing by pthread library) works parallelly? My lecturer has told us that this library creates only user threads, that are not managed by Linux kernel. I wrote some code that fill large matrix and compared times of execution for threads and whole program and it seems to works parallelly. Can I use ...
Posix threads are kernel threads with glibc/musl (+possibly other pthread implementations) on Linux.
I'm writing software to communicate with badly designed hardware. This hardware can communicate with linux pc (kernel 4.15) by RS485 line (9600 8N1) and it has very short timings: pc should reply in 2ms after receiving request from device. I was able to solve this task using LOW_LATENCY flag and /sys/class/tty/ttySx/...
Funny you find this way ugly, considering everything is a file in Unix, it should be the smart way. I guess you are entitled to your own aesthetic sense. If you want to make another buffer size the default you can always change it in the driver and recompile the kernel as suggestedhere.
I created a C program and choose to use python as my GUI creator I wrote the python GUI and decided to create a struct ``` typedef struct GUIcommunicator { char action[MAX_SIZE]; char params[MAX_PARAMS][MAX_SIZE]; }GUIcommunicator; ``` I usingthis answerI will return the struct from the python receive him i...
If you are developing a linux based application, you can performInter-Process CommunicationusingFIFOfiles For windows based applications, you could useNamed-pipes
In C, I want to take an input from the user but I don't know how long is it. I think I should usemalloc()to set the length of the text array: ``` char *text = NULL; text = malloc(sizeof(input)) ``` But, how can I do it at the same time that I'm storing the input to the array withfgets()? ``` fgets(text, sizeof text...
The string stored as a result of callingfgetswill contain a newline if it can fit in the buffer. If the read string ends in a newline you know you have a full line. If not, you know you need to read more. So start by usingmallocto allocate a buffer of a certain size. Then usefgetsto populate the buffer. If there'...
Consider the following example which initialize an array with a default value: ``` static unsigned int array[10] = { [ 0 ... 9 ] = 5 }; ``` What exactly this operator does? It is related to variadic macro__VA_ARGS__?
In standard C, since C99, designated initializers allow to initialize individual elements of an array in the form: ``` int array[4] = {[1] = 42}; ``` The syntax you stumbled upon is a range initializer, it is a GNU extension to initialize all elements between0and9to the given value, thus strictly equivalent to: ```...
I have generally worked only with file descriptors. I am not sure if a FILE * will continue to work correctly if the fd linked to it is used for someother purpose. Do FILE * and fd linked to it exist independently?
On POSIX systems, yes, the fd backs theFILE*. Closing theFILE*closes the fd. Interleaving use the fd andFILE*risks mucking up your data (theFILE*does user mode buffering that the fd bypasses); you'd have to either disable buffering (withsetvbufor the like) or make sure theFILE*is reliably flushed before anything write...
Do POSIX threads (managing by pthread library) works parallelly? My lecturer has told us that this library creates only user threads, that are not managed by Linux kernel. I wrote some code that fill large matrix and compared times of execution for threads and whole program and it seems to works parallelly. Can I use ...
Posix threads are kernel threads with glibc/musl (+possibly other pthread implementations) on Linux.
I attempted the solution foundherewhich said to add MingW to the system path, but this did not work. I installed MingW alongside Codeblocks, and compiling works just fine. However, I have had issues with the themakecommand, which has led me to trying to see if there is issues with my compiler. Runninggcc.exeinCMDgave ...
I solved the same problem on my codeblocks going tosettings → compiler, choosing "Searching directories" and then choosing "linker" tab below and adding the following path: ``` C:\Program Files\CodeBlocks\MinGW\x86_64-w64-mingw32\lib ``` …(or your MingW installation). All libraries are linked statically. CodeBlocks...
I am getting the below error in linux arm architecture when trying to compare void pointer addr>(void *)0XFFFE00000000 .Here addr is of type void pointer error: ordered comparison of pointer with null pointer [-Werror=extra] This is happening only in Linux arm architecture,in other architecture it is working fine a...
Probably the integer literal is overflowing into 32 bits, which becomes 0 orNULL. But you shouldn't go around comparing random (void) pointers for being greater than some random integer, anyway. Cast the pointer touintptr_t, and make sure the literal is of a suitable type too, then it starts becoming more likely to w...
I'm trying to read a binary file of 32 bytes in C, however I'm keep getting "segmentation fault (code dumped)" when I run my program, it would be great if somebody can help me out by pointing where did I go wrong?. my code is here below: ``` int main() { char *binary = "/path/to/myfiles/program1.ijvm"; FILE ...
It's because of the path. Make sure that"/path/to/myfiles/program1.ijvm"points to an existing file. You should always check the return value offopen. ``` \\Open read-only fp = fopen(binary, "rb"); if(fp==NULL){ perror("problem opening the file"); exit(EXIT_FAILURE); } ``` Notice also that you are reading 32 ...
WhenInitializing variables in CI was wondering does the compiler make it so that when the code is loaded at run time the value is already set OR does it have to make an explicit assembly call to set it to an initial value? The first one would be slightly more efficient because you're not making a second CPU call just...
A compiler is notrequiredto do either of them. As long as the behavior of the program stays the same it can pretty much do whatever it wants. Especially when using optimization, crazy stuff can happen. Looking at the assembly code after heavy optimization can be confusing to say the least. In your example, both the ...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
For 24bpp images, it's the same shuffle: reverse 3-byte chunks. For 16bpp 5:6:5 image formats, it's again the same shuffle with symmetry around the middle field. Use any of the existing BGR to RGB functions you found.
I am learning C so I tried the below code and am getting an output of7,6instead of6,7. Why? ``` #include <stdio.h> int f1(int); void main() { int b = 5; printf("%d,%d", f1(b), f1(b)); } int f1(int b) { static int n = 5; n++; return n; } ```
The order of the evaluation of the function arguments isunspecifiedin C. (Note there's no undefined behaviour here; the arguments are not allowed to be evaluated concurrently for example.) Typically the evaluation of the arguments is either from right to left, or from left to right. As a rule of thumb don't call the...
I attempted the solution foundherewhich said to add MingW to the system path, but this did not work. I installed MingW alongside Codeblocks, and compiling works just fine. However, I have had issues with the themakecommand, which has led me to trying to see if there is issues with my compiler. Runninggcc.exeinCMDgave ...
I solved the same problem on my codeblocks going tosettings → compiler, choosing "Searching directories" and then choosing "linker" tab below and adding the following path: ``` C:\Program Files\CodeBlocks\MinGW\x86_64-w64-mingw32\lib ``` …(or your MingW installation). All libraries are linked statically. CodeBlocks...
I am getting the below error in linux arm architecture when trying to compare void pointer addr>(void *)0XFFFE00000000 .Here addr is of type void pointer error: ordered comparison of pointer with null pointer [-Werror=extra] This is happening only in Linux arm architecture,in other architecture it is working fine a...
Probably the integer literal is overflowing into 32 bits, which becomes 0 orNULL. But you shouldn't go around comparing random (void) pointers for being greater than some random integer, anyway. Cast the pointer touintptr_t, and make sure the literal is of a suitable type too, then it starts becoming more likely to w...
I'm trying to read a binary file of 32 bytes in C, however I'm keep getting "segmentation fault (code dumped)" when I run my program, it would be great if somebody can help me out by pointing where did I go wrong?. my code is here below: ``` int main() { char *binary = "/path/to/myfiles/program1.ijvm"; FILE ...
It's because of the path. Make sure that"/path/to/myfiles/program1.ijvm"points to an existing file. You should always check the return value offopen. ``` \\Open read-only fp = fopen(binary, "rb"); if(fp==NULL){ perror("problem opening the file"); exit(EXIT_FAILURE); } ``` Notice also that you are reading 32 ...
WhenInitializing variables in CI was wondering does the compiler make it so that when the code is loaded at run time the value is already set OR does it have to make an explicit assembly call to set it to an initial value? The first one would be slightly more efficient because you're not making a second CPU call just...
A compiler is notrequiredto do either of them. As long as the behavior of the program stays the same it can pretty much do whatever it wants. Especially when using optimization, crazy stuff can happen. Looking at the assembly code after heavy optimization can be confusing to say the least. In your example, both the ...
I have an enum with a specific set of values. I need a function to throw random output from the enum set of values every time the function is called. Can someone help? The function should be in C. ``` typedef enum fruits { Apple = 0x00, Orange = 0x04, Mango = 0x07, Pineapple = 0x08 }Fruits_T; Fruits_...
Callsrandonce somewhere in the beginning of your program.Store all possible values of the enum in an array with sizen.Callrand(n)and use the result as array index, to return the value stored there.
So I'd like to implement CoreML inside an Adobe After Effects plugin I'm developing. Thing is that the After Effects SDK is in C++ (it is C compatible), and the CoreML API is in only Objective C and Swift. All I want is the .plugin (the compiled After Effects plugin) to still work in After Effects with CoreML, I know...
To answer my own question, nGraph (also Tensorflow) with the PlaidML backend or the TVM compiler stack have both Metal acceleration support!
I am trying to cause an implicit type conversion between anintandunsigned intin some code that I wrote. The compiler gives an unexpected result. According to the rules for implicit conversion between signed and unsigned integers (of equal rank), the code should produce a large positive number as its output. ``` unsi...
-1gets converted toUINT_MAX(the formal rule for converting to unsigneds is that yourepeatedly add or subtract the maximum+1 until the result fits (6.3.1.3p2)).UINT_MAX+90 == 89.
I am saving some data into.txtfile like this: ``` void save_file() { char *file_name = "my_file.txt"; FILE *f = fopen(file_name, "w"); if (f == NULL) return; // some fprintf instructions fclose(f); } ``` Everything works perfectly. However, I would like this file to have read-only prop...
No. There is no way to set file permissions in pure C, without resorting to OS-specific methods. I assume, by 'standard libraries' you mean facilities described in C standard.
I was reading the bookmodern Cand was suprised to find that the following code works ``` typedef struct point point; struct point { int x; int y; }; int main() { point p = { .x = 1, .y = 2 }; } ``` However, the book does not go in detail about that. How does that work? Why doespointinmain()refer to thety...
The linetypedef struct point point;does two things: It creates aforward declarationofstruct pointIt creates a type alias forstruct pointcalledpoint. Forward declarations are useful if you need to know a struct exits before it is fully defined, for example: ``` typedef struct x X; typedef struct y { int a; ...
I've been counting the instructions executed by an empty C program using Intel's Pin. Most of the time I get a total instruction count of 118724, but now and then the count goes up to 118770. What can be the reason for this change? Code run:int main() {}
I feel like @Neitsa answered my question in their comment to the original post. I'll quote it here. But be wary that PIN starts very early in the process life, so it starts instrumenting everything the system loader is doing (basically in the libc). The fact that you have two different instruction count is probably d...
in python there's inspect.argspec which will give you data about a function including the parameter names, but in C I have no idea how I would get this information from a function. I essentially want to write a function that takes a function pointer and returns an array of strings representing the names of the paramet...
I essentially want to write a function that takes a function pointer and returns an array of strings representing the names of the parameters Function parameters in C don't have names outside the definition of the function, and the names disappear entirely once the code is compiled. Debuggers can use symbol files gen...
I have to allocate memory dinamically, every other list i see, the struct is coded like that.. don't know what's wrong. The struct is declared like: ``` struct CAD { char hash_atual[TAM_HASH]; char hash_anterior[TAM_HASH]; char timestamp[TAM_TEMP]; ALUNOS registros[REG_MAX]; struct CAD *prox; ...
The problem is thatnovo->proxis a pointer tostruct CADwhich is not initialized, hence it may contain garbage value. Before accessingnovo->proxyou should either set it to point to a valid memory address.
I am saving some data into.txtfile like this: ``` void save_file() { char *file_name = "my_file.txt"; FILE *f = fopen(file_name, "w"); if (f == NULL) return; // some fprintf instructions fclose(f); } ``` Everything works perfectly. However, I would like this file to have read-only prop...
No. There is no way to set file permissions in pure C, without resorting to OS-specific methods. I assume, by 'standard libraries' you mean facilities described in C standard.
I was reading the bookmodern Cand was suprised to find that the following code works ``` typedef struct point point; struct point { int x; int y; }; int main() { point p = { .x = 1, .y = 2 }; } ``` However, the book does not go in detail about that. How does that work? Why doespointinmain()refer to thety...
The linetypedef struct point point;does two things: It creates aforward declarationofstruct pointIt creates a type alias forstruct pointcalledpoint. Forward declarations are useful if you need to know a struct exits before it is fully defined, for example: ``` typedef struct x X; typedef struct y { int a; ...
I've been counting the instructions executed by an empty C program using Intel's Pin. Most of the time I get a total instruction count of 118724, but now and then the count goes up to 118770. What can be the reason for this change? Code run:int main() {}
I feel like @Neitsa answered my question in their comment to the original post. I'll quote it here. But be wary that PIN starts very early in the process life, so it starts instrumenting everything the system loader is doing (basically in the libc). The fact that you have two different instruction count is probably d...
I'm trying to move every declaration of the following macro into another memory segment. It works fine without the section attribute. Any ideas on why I can't use it here, and how I could make it work? ``` #define RINGBUFFER_DECLARE_MEMB(var, sz) \ uint8_t var ## __buf[sz] __attribute__((section("...
Stupid me, the problem was that the macro was used in a structure defenition: ``` struct a { RINGBUFFER_DECLARE_MEMB(umama, 3); }; ``` Which is ofcourse not allowed
I am beginning to get into the reverse engineering and am using IDA Pro and am working on deassembling a binary. I am trying to find the memory address for themainfunction of the C program I am working with. However, I see that there is a function in IDA for:mainand for__libc_start_main I have readthis postbut I am...
__libc_start_mainis called first, and it invokesmain. The former is part of the platform and does some initialization that most people don't even realize is happening, such preparing the threading system. The latter is the entry point of the user program and contains the "regular" code.
I have the following simple code: ``` #include <stdio.h> int main(){ char buffer[20] = "abc"; FILE *pFile; pFile = fopen("myfile1.txt", "r+"); fputs("def", pFile); fgets(buffer, 20, pFile); printf("buffer content: %s\n", buffer); fclose(pFile); return...
If you want to read randomly, you first have to tell the file reading routines, where you want to start. Usefseekto do this. e.g.:fseek(pFile, 0, SEEK_SET)before you try to get something withfgets.
What is the difference between: Case1: ``` char* strings[100]; strings[0]=malloc(100); char str[100]="AAA"; strings[0]=strdup(str); free(strings[0]); ``` Case2: ``` char* strings[100]; strings[0]=malloc(100); strings[0]="AAA"; free(strings[0]); ``` Case2 results in a crash.strdupis as ...
strings[0]="AAA";does not copy the contentsAAAinto the memory to whichstring[0]points, it rather letsstrings[0]point to string literal"AAAA"; and freeing a string literal is undefined behaviour, since you are freeing memory which has not been allocated throughmallocbefore. Note that you lost any access to your previou...
I have the following simple code: ``` #include <stdio.h> int main(){ char buffer[20] = "abc"; FILE *pFile; pFile = fopen("myfile1.txt", "r+"); fputs("def", pFile); fgets(buffer, 20, pFile); printf("buffer content: %s\n", buffer); fclose(pFile); return...
If you want to read randomly, you first have to tell the file reading routines, where you want to start. Usefseekto do this. e.g.:fseek(pFile, 0, SEEK_SET)before you try to get something withfgets.
What is the difference between: Case1: ``` char* strings[100]; strings[0]=malloc(100); char str[100]="AAA"; strings[0]=strdup(str); free(strings[0]); ``` Case2: ``` char* strings[100]; strings[0]=malloc(100); strings[0]="AAA"; free(strings[0]); ``` Case2 results in a crash.strdupis as ...
strings[0]="AAA";does not copy the contentsAAAinto the memory to whichstring[0]points, it rather letsstrings[0]point to string literal"AAAA"; and freeing a string literal is undefined behaviour, since you are freeing memory which has not been allocated throughmallocbefore. Note that you lost any access to your previou...
In the program,printf("%d", getchar())is printing an extra 10. when i give input like a, it prints 9710 instead of 97, same for others ``` #include <stdio.h> int main() { int c; while((c=getchar()) != EOF) { printf("%d", c); } printf("\n\tENDED\n\n"); return 0; } ``` ``` me@Device-xx:...
You didn't passato STDIN. Because you pressedaand Enter, you passedaand a Line Feed. Assuming an ASCII-based encoding (such as UTF-8), The letterais encoded as 0x61 = 97A Line Feed is encoded as 0x0A = 10 Maybe you want ``` while (1) { int c = getchar(); // Stop when a Line Feed or EOF is encountered. i...
``` #include<stdio.h> int main() { int i = 11; int *p = &i; foo(&p); printf("%d ", *p); } void foo(int *const *p) { int j = 10; *p = &j; printf("%d ", **p); } ``` //it showed compile time error. Can anyone please explain
int *const *p pis a pointer to aconstantpointer toint. You can changepitself;You cannot change*p;You can change**p. ``` void foo(int *const *p) { int j = 10; *p = &j; // nope printf("%d ", **p); } ```
Why does*p++first assign the value toiand then increment theppointer, even though++post-increment has a higher precedence, and associativity is from Right-to-Left? ``` int main() { int a[]={55,66,25,35,45}; int i; int *p=&a; printf("%u \n",p); i=*p++; printf(" %u %d",p,i); printf("\n %d",...
The semantics of the postfix++operator are that the expressionp++evaluates to thecurrentvalue ofp, and as aside effectpis incremented. Effectively,i = *p++;is the same as ``` i = *p; p++; ``` The semantics of theprefix++operator are that the expression evaluates to the current value ofpplus one, and as a side effec...
I am a C++ newb. I have the Eclipse Luna IDE for Windows 10 and downloaded the Eclipse C/C++ IDE CDT 9.4 plugin. I have some code which has ``` #include <stdio.h> ``` which is giving me "unresolved inclusion". Based on my research it means I do not have some include folder. I cannot find it on my Windows machine and...
Go to project properties, C/C++ General -> Paths and Symbols and for Language GNU C you should see the compiler default include folders. If not, you might have a path problem. And i thinkThishelps you!
I want a C macro that will expand into a function with an extra parameter based on a condition. Something like this: ``` #define EXTRA 7 #ifdef ADD_ONE_MORE_ARG #define dothis(...) dothat(EXTRA,...) #endif ``` Such thatdothis(5);is expanded intodothat(EXTRA, 5);but I can't remember the syntax. TheanswerI found here...
``` #define callx(...) call(EXTRA, __VA_ARGS__) ```
I'm configuring various GPIO pins on a microcontroller (which initiates a process that I need to time) inside a switch statement and then resetting a timer counter immediately after the end of the switch statement on the assumption that the period between the last instruction of each switch case (presumably some kind ...
the assumption that the period between the last instruction of each switch case (presumably some kind of jump or return) and the first statement after the switch will be the same This is implementation dependent behavior. Best way to find out what's happening is to look at the assembly code generated and perform som...
So I am running onQNXand I want to check if a process is up and running.I saw many examples on how to do this - basically iterate over theprocdirectory, and over and processes inside (which are some numbers - pid) and inside this there should be acmdfilefile. But on my controller if I list the processes usingpidinand...
Since you are using FileZilla as I can see from the screenshot. You need to login as root user to access /proc location. I'd recommend to SSH to the server and check the processes which are running using the ps, top or pgrep command. Using the command line provides much more options.
When I using Java, i need to type command likejava -?If user type-?at the end, why the application know this to reply output? Please tell me c code to identify the-?
They are passed as the parameters to main(): ``` #include <stdio.h> int main(int argc, const char* argv[]) { for (int i = 0; i < argc; i++) { printf("Arg %i is %s\n", i, argv[i]); } } ``` When compiled and then executed as ``` myProgram.exe arg1 stuff ? ``` It would output ``` Arg 0 is myProgram....
I am using Keras (with Tensorflow) to train my RNN model. Does anyone has an idea how can I use it in my C application? Does anyone tried something similar? I found a similar question here how to use Tensorflow Keras model in C++ hereConvert Keras model to C++but i want to convert it to a C environment.
I never tried, but this can be a way to do it. Firstly, convert the Keras model to Tensorflow, with tools likethisone or following thistutorial. After this step, you can use your model with thetf C API.
Let's say I'm debugging code like this ``` outer(fn1(), fn2()); ``` If I use thescommand, LLDB will first step intofn1, then I typefinto step-out,sagain steps intofn2,fin... and only now I'm able to step-intoouterwhich is what I wanted since the beginning. Is there a way to tell LLDB on which function call to step-...
lldb comes with an alias for exactly this:sif. In the given example, you can run: ``` (lldb) sif outer ``` You can remember it asstepintofunction It works with partial matches, it doesn't have to be called with the full function name. In this case, you could also runsif outfor example.
If head is a struct type pointer, pointing to the first node in link list then what does while(head) means? Does While loop runs till the head is not equal to NULL? Also what does if(!head) means while checking the condition
If head is a struct type pointer, pointing to the first node in link list then what does while(head) means? to have while(head) is like to have ``` while(head != NULL) ``` Does While loop runs till the head is not equal to NULL? yes (supposing there is nothing allowing to go out of the loop in its body) Also wh...
I don't understand the use ofreturn 0*statement?? Tried looking for answers on Google ``` return 0*printf("%d",a[i]); ``` I don't understand the outcome.
As for me then this ``` return 0*printf("%d",a[i]); ``` just a bad programming style. At least it would be better to write instead ``` return ( printf("%d",a[i]), 0 ); ``` not saying about ``` printf("%d",a[i]); return 0; ``` Maybe this statement is found in a recursive function. As for your question Having t...
What the difference between: ``` 1) !ret 2) ret != 0 ``` ? ``` if (ret != 0 || stack[fd] == NULL || stack[fd][0] == '\0') { if (!ret && *line) *line = NULL; return (ret); } ```
In a boolean context in C, a value of zero is considered "false" and a non-zero value is considered "true". Henceif (ret)(ifretis true) is equivalent toif (ret != 0)(ifretis not false), and similarlyif (!ret)(ifretis not true) is equivalent toif (ret == 0)(ifretis false). (i.e., the meanings of!retandret != 0are oppo...
I have these strings: ``` yy = "19"; mm = "05"; dd = "31"; ``` These represent the creation date of a certain object in my project. This object expires after one month. How do I check if the object has expired already? (I came across thissolutionbut thought there might be another way to do it.) UPDATE: the string ...
I ended up using the date format "yymmdd" so I can convert it to typelongand do a simple number comparison. ``` sprintf(buffer, "%s%s%s", yy, mm, dd); expiryDate = atol(buffer); // get current date of format "yymmdd" as well // getCurrentDate() is my function that gets the date from my SDK currentDate = getCurrentDa...
This question already has an answer here:cannot specify -o when generating multiple output files [C error](1 answer)Closed4 years ago. I've a question about GCC and objects file.. In few words when I try to do this command: ``` gcc -Wall -o obj/config.o -c global.h config/config.c ``` It's simply returns thisfatal...
.hheader files don't get directly compiled, only.csource files. Get rid ofglobal.h. ``` gcc -Wall -o obj/config.o -c config/config.c ```
Can someone explain me please what is RTL in the context of driver development for Windows ? Development Tool : Visual studio 2019 Driver Type: Kernel Mode (kmdf). Programming Language : C.
Many kernel API functions start with theRtlprefix - that's an abbreviation of Run Time Library.
For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?
"If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?" Yes. The client will get the data that was sent before the FIN packet that closes the socket.
For example ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf; ``` where to break? Is there any guidance to do that? Or is it safe to break anywhere? ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfa...
I always put operators in the beginning if I have to break the line ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf; ```
This question already has an answer here:cannot specify -o when generating multiple output files [C error](1 answer)Closed4 years ago. I've a question about GCC and objects file.. In few words when I try to do this command: ``` gcc -Wall -o obj/config.o -c global.h config/config.c ``` It's simply returns thisfatal...
.hheader files don't get directly compiled, only.csource files. Get rid ofglobal.h. ``` gcc -Wall -o obj/config.o -c config/config.c ```
Can someone explain me please what is RTL in the context of driver development for Windows ? Development Tool : Visual studio 2019 Driver Type: Kernel Mode (kmdf). Programming Language : C.
Many kernel API functions start with theRtlprefix - that's an abbreviation of Run Time Library.
For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?
"If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?" Yes. The client will get the data that was sent before the FIN packet that closes the socket.
For example ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf; ``` where to break? Is there any guidance to do that? Or is it safe to break anywhere? ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfa...
I always put operators in the beginning if I have to break the line ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf; ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question Wanted to know if there is any inbuilt function in C to check for special characters like space, tab just l...
Look up and learn the functions defined by the C11 standard in the§7.4 Character handling<ctype.h>functions. Theisspace()function looks for a fairly general set of white space characters: ``` ' ', '\t', '\r', '\f', '\n', '\v' ``` Theisblank()function looks for the set you want: ``` ' ', '\t' ``` To some extent, t...
For example ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf; ``` where to break? Is there any guidance to do that? Or is it safe to break anywhere? ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfa...
I always put operators in the beginning if I have to break the line ``` int abcdefghijklmn = aaaaaaaaaaaa / bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf; ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question Wanted to know if there is any inbuilt function in C to check for special characters like space, tab just l...
Look up and learn the functions defined by the C11 standard in the§7.4 Character handling<ctype.h>functions. Theisspace()function looks for a fairly general set of white space characters: ``` ' ', '\t', '\r', '\f', '\n', '\v' ``` Theisblank()function looks for the set you want: ``` ' ', '\t' ``` To some extent, t...
I am working on a C shared library that would contain one function that receives a filename, and returns a pointer to the C-array representation of the image. I readVIPS_INITneeds to be set in the beginning of the program, withargv[0]as its argument. However, since this is a shared library, I'm not sure where exactly...
libvips usesargv[0]to help discover message catalogues if its been relocated. If you don't need a relocatable package, you can just pass""and it'll be fine. Other notes: be careful not to init from more than one thread at the same time, and make sure init finishes before you try any processing.
``` char String1 = "1234567890+-"; char String2 = "1+a"; ``` String2 is an input and I want to check if it contains any character that is not in String1. I have tried usingstrpbrk(String2,String1)but this returns true as long as any character inString1exists inString2. Is there a better way to do it?
strspnwill return the index of the first character in String2 that is not in String1. If all the characters match, the index will be to the terminating zero. ``` #include <stdio.h> #include <string.h> int main ( void) { char *String1 = "1234567890+-"; char *String2 = "1+a"; int index = strspn ( String2, ...
This question already has an answer here:Should "freopen'ed" stdout be closed?(1 answer)Closed7 months ago. I'm writing a code which takes one file and saves it into another with a different name - however, I am not sure whether or not I need to fclose both files or not? ``` FILE *logfile = fopen("log.txt", "a+"); w...
From theman page Thefreopen()function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it.The original stream (if it exists) is closed.[...] So, you don't need to close the previous stream explicitly, once done usage, just close the recent stream.
In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance. ``` #include <stdio.h> #include ...
Precedence and order of evaluation are two different things. FromLogical ORdocumentation (emphasis mine): There is asequence pointafter the evaluation of lhs. If the result of lhs compares unequal to zero, then rhs is not evaluated at all (so-called short-circuit evaluation). In case ofexp1 || exp2,exp1is always eva...
In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance. ``` #include <stdio.h> #include ...
Precedence and order of evaluation are two different things. FromLogical ORdocumentation (emphasis mine): There is asequence pointafter the evaluation of lhs. If the result of lhs compares unequal to zero, then rhs is not evaluated at all (so-called short-circuit evaluation). In case ofexp1 || exp2,exp1is always eva...
In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance. ``` #include <stdio.h> #include ...
Precedence and order of evaluation are two different things. FromLogical ORdocumentation (emphasis mine): There is asequence pointafter the evaluation of lhs. If the result of lhs compares unequal to zero, then rhs is not evaluated at all (so-called short-circuit evaluation). In case ofexp1 || exp2,exp1is always eva...
Please read the comments in the program below : ``` #include<stdio.h> void test(char c[]) { c=c+2; //why does this work ? c--; printf("%c",*c); } int main() { char ch[5]={'p','o','u','r'}; //ch = ch+2; //this is definitely not allowed on array names as they are not pointers test(ch); ret...
You should keep in mind that the name of the array "decays" to a pointer to its first element. This means thattest(ch);is equivalent totest(&ch[0]);. Also,void test(char c[])is nothing butvoid test(char* c), a pointer to a character. Pointerscanbe incremented or decremented which is whyc = c + 2andc--compiles just fi...
I can not use sprintf, or any other function that puts everything together in a string n, I can not really use any libc function, it's part of a challenge I'm trying to solve Given: ``` int x=5; int y=2; ``` Expected Output: ``` res = 52; ```
This is one posible solution: ``` #include <stdio.h> int main() { int x= 342; int y= 224; int aux = y; while( aux ) { aux /= 10; x*= 10; } x+= y; printf("x= %d\r\n", x); // prints 342224 } ```
I'm reading the source code for a text editor application (Torvalds/uemacs on GitHub.com). There is a certain file (termio.c) that#includesthe contents of files such as: stsdef.h, ssdef.h, descript.h, iodef.h, ttdef.h and tt2def.h. I have absolutely no clue what these header files contain or what they are used for. Ca...
These headers are specific for the VMS operating system. They're guarded byboth#ifndef POSIXand#ifdef VMS. They contain theterminal bps settings and alikeforthis operating system. The files do not exist in Unixen or Windows, and are not needed there to compile uemacs.
Please read the comments in the program below : ``` #include<stdio.h> void test(char c[]) { c=c+2; //why does this work ? c--; printf("%c",*c); } int main() { char ch[5]={'p','o','u','r'}; //ch = ch+2; //this is definitely not allowed on array names as they are not pointers test(ch); ret...
You should keep in mind that the name of the array "decays" to a pointer to its first element. This means thattest(ch);is equivalent totest(&ch[0]);. Also,void test(char c[])is nothing butvoid test(char* c), a pointer to a character. Pointerscanbe incremented or decremented which is whyc = c + 2andc--compiles just fi...
I can not use sprintf, or any other function that puts everything together in a string n, I can not really use any libc function, it's part of a challenge I'm trying to solve Given: ``` int x=5; int y=2; ``` Expected Output: ``` res = 52; ```
This is one posible solution: ``` #include <stdio.h> int main() { int x= 342; int y= 224; int aux = y; while( aux ) { aux /= 10; x*= 10; } x+= y; printf("x= %d\r\n", x); // prints 342224 } ```
I'm reading the source code for a text editor application (Torvalds/uemacs on GitHub.com). There is a certain file (termio.c) that#includesthe contents of files such as: stsdef.h, ssdef.h, descript.h, iodef.h, ttdef.h and tt2def.h. I have absolutely no clue what these header files contain or what they are used for. Ca...
These headers are specific for the VMS operating system. They're guarded byboth#ifndef POSIXand#ifdef VMS. They contain theterminal bps settings and alikeforthis operating system. The files do not exist in Unixen or Windows, and are not needed there to compile uemacs.