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) so I wanted to update my old code with this mechanism, but something similar does not seem to be available for strftime functions. Did I miss it ? Or why isn't it available ?
|
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 registered formatting specifiers.
|
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 suitable (at least on Debian). If you want to "modify it" every shutdown, I suggest you simply
```
rm /var/lock/strange_state
```
at termination.
|
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 the 6 possible the extra 1 space still has to be there.
Currently I am doing this:
```
printf("%6s %4s %4s %02hu:%02hu %02hu:%02hu\n", ...);
```
That results in this:
```
TP1944 LIS OPO 10:00 10:55
XV1 OPO LECO 12:00 13:35
```
So I know that it`s possible to format before the actual print output but what about after it? Is it even possible to do this with normal printing in C?
|
%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 transferred to the end
Code
Example
|
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);
return 0;
}
```
Output:eHllWorodl
Save the current character in a temporary variable, replace it with the next one.
|
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 cannot find out how to wrap it and get the typeMyFucntion.
typedef char* (*MyFunction)(char*);
|
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 have anything to do withctypes: for examplePointdefinition would be the same withouttypedef(struct Point { ... };).
|
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",
"Humid": "value"}
}
```
Like topic's name above, is it like a HTTP or MQTT protocol?
|
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 the methods described here to authenticate your request with a token.https://firebase.google.com/docs/database/rest/auth
|
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 cannot find out how to wrap it and get the typeMyFucntion.
typedef char* (*MyFunction)(char*);
|
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 have anything to do withctypes: for examplePointdefinition would be the same withouttypedef(struct Point { ... };).
|
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",
"Humid": "value"}
}
```
Like topic's name above, is it like a HTTP or MQTT protocol?
|
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 the methods described here to authenticate your request with a token.https://firebase.google.com/docs/database/rest/auth
|
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+1;i++)
{
cmd[i]=APPS[i].app;
}
```
But if I assign directly one by one to the array (without use loop to assign) it's ok like that:
```
struct command cmd [] = { APPS[0].app, APPS[1].app };
```
How should I modify my code?
|
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 to2here. Note that without the parentheses, the result would in most cases not be the same, as the comma operator has the lowest possible precedence (thanks to @dbush for helping me out here in the comments).
|
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 to do something like this:
```
int main(int argc, char *argv[]) {
return argv[1].f();
}
```
How can I achieve this and what else do I have to consider when compiling my code?
|
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 can then call elsewhere in your program.
|
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 to do something like this:
```
int main(int argc, char *argv[]) {
return argv[1].f();
}
```
How can I achieve this and what else do I have to consider when compiling my code?
|
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 can then call elsewhere in your program.
|
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 a conversion letter with no output ? I don't recall such a conversion letter. Or maybe playing with the flags...?
[Edit] I just noticed that scanf has something similar (but the reverse): an assignment suppression flag '*'. for instancesscanf("123 345 678", "%i %*i %i", &a, &b)will lead to a=123 b=678
|
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";
puts(a);
return 0;
}
```
|
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]);
}
return 0;
}
```
For which I get the following output
```
a 97
0
0
s 115
< 60
� -62
) 41
P 80
� -42
� -128
0 48
� -41
> 62
� -119
� -88
U 85
0
0
� -105
� -85
```
Afterstr[2]the chars are random for each execution, can someone please explain this behavior.
|
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;
unsigned short int newValue = 0xaa;
right= temp & 0xff; // split
left= (temp >> 8) // split
// temp needs to be 0xbcaa
// and I also need it the other way round, so 0xbc61 -> 0xaa61
```
|
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 = !AandA XOR 0 = A
Here is the demo:https://ideone.com/UIxPDV
|
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 bytes read from the file are:
```
buf[0] = 0x1B
buf[1] = 0x26
buf[2] = 0xB3
buf[3] = 0x54
buf[4] = 0xA1
buf[5] = 0xCF
```
And I'd like to have:uint64_t databe equal to0x1B26B354A1CF. That is, all the elements of the array "concatenated" in one single 64 bit integer.
|
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", 205); //205 = ASCII '═'
```
I expected the above code snippet to print ═ twice, instead it prints $c$c.
Do I really need to make a for i<20 printf loop?
Edit: trying to directlyprintf("═");will result inΓòÉbeing outputted. Again, because of the unicode-ascii conversion.
|
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 - 0, which gives3.
The only problem is that the result is of typeptrdiff_t, butprintf%ldexpects along int. If those types are different on your machine, it won't work. In aprintf()format string, the correct length modifier forptrdiff_tist— use"\n%td\n".
|
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 using functions. Can you give me some advice how to do this task plase
```
int exponent(double d)
{
int result;
frexp(d,&result);
return result;
}
```
|
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)
{
double_cast mydouble.f = d;
return ( mydouble.parts.sign )? mydouble.parts.exponent << 1: mydouble.parts.exponent;
}
```
|
```
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: ((4* (-(*p2)))/(*p1)+10 where *p1=12 ,*p2=4
expected output is 9 but why?
|
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 got these value?
Here's the code:
```
int main(void)
{
char i=240, j=250, sum;
sum = i+j;
printf("Result is: %d + %d = %d\n",i,j,sum);
return 0;
}
```
Here is the result: Result is: -16 + -6 = -22
|
BecauseChar is 8 bitsandit's capacity is 255
When you add i+j you put 490in 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 still 0 here.
}
```
When I was programming C, something like 1000 years ago, I would have had stern words for a dev on my team who tried using this trick.
|
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, stdin)
```
|
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's no newline in the buffer, usereallocto expand it and usefgetsagain, starting at the offset you left off at.
Alternately, if you're on a POSIX system like Linux you can just usegetlinewhich does all of this for you.
|
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:
```
static unsigned int array[10] = { [0] = 5, [1] = 5, [2] = 5, [3] = 5, [4] = 5, [5] = 5, [6] = 5, [7] = 5, [8] = 5, [9] = 5};
```
only less a burden to type and read.
Reference
|
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 writes to the fd directly. Otherwise, as long as nothingclosesthe fd, theFILE*should continue to work.
|
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 this library to creating parallel programs with threads which are recognized by kernel?
|
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/rx_trig_bytes file.
After opening port "rx_trig_bytes" file contents changes to "14", so I need write "1" to it after opening port to get good reply latency.
Is there any way to make this by API call or fix it after system boot / driver load ? Current realization looks ugly :(
|
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 in my C code
but I don't know how.
And I'd like to some help
(the function that sends the struct (the python code) already got the action and the params as string list )
|
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, stdin)
```
|
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's no newline in the buffer, usereallocto expand it and usefgetsagain, starting at the offset you left off at.
Alternately, if you're on a POSIX system like Linux you can just usegetlinewhich does all of this for you.
|
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:
```
static unsigned int array[10] = { [0] = 5, [1] = 5, [2] = 5, [3] = 5, [4] = 5, [5] = 5, [6] = 5, [7] = 5, [8] = 5, [9] = 5};
```
only less a burden to type and read.
Reference
|
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 writes to the fd directly. Otherwise, as long as nothingclosesthe fd, theFILE*should continue to work.
|
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 this library to creating parallel programs with threads which are recognized by kernel?
|
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 the error thatlibwinpthread-1.dllwas missing, but it clearly isn't. How can I get my computer to recognize it?
|
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 version 20.03
|
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
addr>(void *)0XFFFE00000000
How to solve this?
|
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 work. There doesn't seem to be aUINTPTR_C()macro, but perhaps it makes sense to useUINTMAX_C()?
Of course, if your unspecified "ARM" is 32-bit, then the address is way out of bounds and probably larger than the pointers will be ... quite confusing.
|
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 *fp;
char buffer[32];
// Open read-only
fp = fopen(binary, "rb");
// Read 128 bytes into buffer
fread (buffer, sizeof(char), 32, fp);
return 0;
}
```
|
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 bytes in your buffer and not 128 as your comment says.
|
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 to set the value.
e.g.
```
void foo() {
int c = 1234;
}
```
|
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 constant1234and the variablecwould be optimized away since they are not used.
|
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 answered with facts and citations.Closed4 years ago.Improve this question
I need to perform conversion of images from BGR to RGB image format and also backward conversion. I foundSimd Librarywhich contains functionSimdBgrToRgbwhich performs fast conversion from BGR to RGB.
But I didn't find any function for backward (RGB to BGR) conversion.
Maight any to know any C/C++ library which allows to perform this conversion?
|
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 same function twice in a function parameter list if that function has side-effects (as it does in your case), or if you pass the same parameter twice which allows something in the calling site to be modified (e.g. passing a pointer).
|
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 the error thatlibwinpthread-1.dllwas missing, but it clearly isn't. How can I get my computer to recognize it?
|
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 version 20.03
|
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
addr>(void *)0XFFFE00000000
How to solve this?
|
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 work. There doesn't seem to be aUINTPTR_C()macro, but perhaps it makes sense to useUINTMAX_C()?
Of course, if your unspecified "ARM" is 32-bit, then the address is way out of bounds and probably larger than the pointers will be ... quite confusing.
|
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 *fp;
char buffer[32];
// Open read-only
fp = fopen(binary, "rb");
// Read 128 bytes into buffer
fread (buffer, sizeof(char), 32, fp);
return 0;
}
```
|
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 bytes in your buffer and not 128 as your comment says.
|
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 to set the value.
e.g.
```
void foo() {
int c = 1234;
}
```
|
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 constant1234and the variablecwould be optimized away since they are not used.
|
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_T random_function()
{
return (rand(Fruits_T));
}
```
|
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 there are magical tricks to make Objective C and normal C work together but have no idea how to make the After Effects SDK and CoreML work together, if this is even feasible in the first place as I only see old simple tutorials on how to implement Objective-C in C++.
The reason why I want to make this work is due to Apple deprecating OpenCL in Mac OS, leaving me with only CoreML as a GPU-accelerated deep learning framework.
|
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.
```
unsigned int q = 90;
int w = -1;
printf("q+w=%u\n", q + w);
```
As the output to this program, which you can viewhere, the result is 89. I would expect theint wto be coerced to the typeunsigned intbefore arithmetic occurs, however, and produce the expected result.
|
-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 property enabled. (Windows 10)
Is there a solution for my problem using standard libraries only?
|
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 thetypedefsincestruct pointis definedafterthat?
|
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;
X *x;
} Y;
struct x {
int b;
Y *y;
};
```
|
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 due to a if / else branch somewhere in the ELF loading code (depending of the system state at a 't' time). If this bothers you you can restrict the instrumentation code to your own binary if you wish.
|
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 parameters
|
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 generated by the compiler to display the names of functions, parameters, and variables, but in general all that information is stripped out during compilation.
|
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;
};
typedef struct CAD CADEIA;
```
...
```
CADEIA** criar_cadeia(CADEIA **c)
{
CADEIA *novo;
char hash[TAM_HASH], caracteres[62];
c = (CADEIA**)malloc(sizeof(CADEIA*));
novo = (CADEIA*)malloc(sizeof(CADEIA));
```
...
```
strcpy(novo->hash_atual, hash);
strcpy(novo->prox->hash_anterior, novo->hash_atual); --->problem here
```
|
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 property enabled. (Windows 10)
Is there a solution for my problem using standard libraries only?
|
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 thetypedefsincestruct pointis definedafterthat?
|
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;
X *x;
} Y;
struct x {
int b;
Y *y;
};
```
|
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 due to a if / else branch somewhere in the ELF loading code (depending of the system state at a 't' time). If this bothers you you can restrict the instrumentation code to your own binary if you wish.
|
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(".rambss"))); \
struct ring_buffer var __attribute__((section(".rambss")))
```
device.h:91:29: error: section attribute not allowed for
'__iso_buf__buf'
RINGBUFFER_DECLARE_MEMB(__iso_buf, BUF_SIZE_ISOLATED);
|
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 afraid I still don't understand. Can someone help me understand the differences between the two, and which one is which?
Thanks!
|
__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 0;
}
```
the output is:buffer content: abc, notdefas it has just been written to the file. Could someone please explain?
|
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 good asmallocfollowed bystrcpy. Why should second case crash?
|
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 previouslymalloced memory once statementstrings[0]="AAA"has been executed.
To copy the contents into themalloced memory, writestrcpy(strings[0],"AAA"). Then thefreeshould be no problem any more.
|
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 0;
}
```
the output is:buffer content: abc, notdefas it has just been written to the file. Could someone please explain?
|
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 good asmallocfollowed bystrcpy. Why should second case crash?
|
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 previouslymalloced memory once statementstrings[0]="AAA"has been executed.
To copy the contents into themalloced memory, writestrcpy(strings[0],"AAA"). Then thefreeshould be no problem any more.
|
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:~/Desktop/Test/Tmps$ gcc 118.c -o 118
me@Device-xx:~/Desktop/Test/Tmps$ ./118
a
9710s
11510x
12010
```
|
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.
if (c == EOF || c == 0x0A) {
break;
}
printf("%d", c);
}
```
|
```
#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",*p);
return 0;
}
```
```
4056
4060 55
66
```
|
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 effectpis incremented.i = *++p;would effectively be the same as
```
i = *(p + 1);
p++;
```
Precedencedoes notcontrol order of evaluation - it only controls parsing (which operators are grouped with which operands).
|
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 all the help I've found is with ubuntu or Linux-based operating systems. So how do I get this to work? How do I get the folder?
|
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 didn't help. Thanks.
|
```
#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 of jump or return) and the first statement after the switch will be the same independently of which case was executed.
My question - is there anything in c/c++ specifications that would validate my assumptions or am I over reaching and should reset my timer inside each case explicitly?
|
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 some timing profiling on your code.
|
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 get the pid for it and search it on FTP inside theprocfolder, it doesn't contain anything, its empty.
What does this mean ? How should I check if the process is running by name ?
Here is a screenshot -15179is the process.
|
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.exe
Arg 1 is arg1
Arg 2 is stuff
Arg 3 is ?
```
|
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-in?
|
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 what does if(!head) means while checking the condition
to have
if(!head)
is like to have
```
if(head == NULL)
```
|
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 trouble understanding output of line of code -
then this line outputs the value of thei-thelement of the integral arrayaand exits the corresponding function.
|
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 opposite, assuming the question is correct.)
|
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 date apparently represent the actual expiry date
|
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 = getCurrentDate();
if(expiryDate >= currentDate)
{
// expired object!
}
```
|
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 error:
```
gcc: fatal error: cannot specify -o with -c, -S or -E with multiple files
```
I've tried to search on Google, but I've not found anything about it.
Maybe I used wrong keywords...
Anyone can help?
|
.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 * asdfasdfasdfasdf;
int abcdefghijklmn = aaaaaaaaaaaa
/ bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf;
```
Do I need to put backslash in the end ?
|
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 error:
```
gcc: fatal error: cannot specify -o with -c, -S or -E with multiple files
```
I've tried to search on Google, but I've not found anything about it.
Maybe I used wrong keywords...
Anyone can help?
|
.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 * asdfasdfasdfasdf;
int abcdefghijklmn = aaaaaaaaaaaa
/ bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf;
```
Do I need to put backslash in the end ?
|
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 like theisdigit()function?
|
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, the POSIX variants are locale dependent — the POSIX specifications forisspace()andisblank()are less emphatic about which characters are matched, but disclaim conflict with the C standard, so in the C locale, the behaviour is as required by the C standard.
|
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 * asdfasdfasdfasdf;
int abcdefghijklmn = aaaaaaaaaaaa
/ bbbaaaaaaaa * ccccaaaaaaaa - aaaaaaaaaaaa * asdfasdfasdfasdf;
```
Do I need to put backslash in the end ?
|
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 like theisdigit()function?
|
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, the POSIX variants are locale dependent — the POSIX specifications forisspace()andisblank()are less emphatic about which characters are matched, but disclaim conflict with the C standard, so in the C locale, the behaviour is as required by the C standard.
|
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 do I need to place this.
|
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, String1);
if ( String2[index]) {
printf ( "character \'%c\' not found in %s\n", String2[index], String1);
}
return 0;
}
```
|
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+");
while(1) {
char filename[500];
char logline[512];
char channel[512];
//Do stuff
sprintf(filename, "%s.log.txt", channel);
freopen(filename, "a+", logfile);
log_to_file(logline, logfile);
}
```
|
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 <stdlib.h>
int main(){
int a,b,c,d;
a =1;
b = c = 10;
d = a|| --b&&--c;
printf("%d\n",c);
printf("%d\n",a);
printf("%d\n",d);
return 0;
}
```
|
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 evaluated first as there is a sequence point after it and ifexp1is non-zero thenexp2is not evaluated.
|
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 <stdlib.h>
int main(){
int a,b,c,d;
a =1;
b = c = 10;
d = a|| --b&&--c;
printf("%d\n",c);
printf("%d\n",a);
printf("%d\n",d);
return 0;
}
```
|
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 evaluated first as there is a sequence point after it and ifexp1is non-zero thenexp2is not evaluated.
|
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 <stdlib.h>
int main(){
int a,b,c,d;
a =1;
b = c = 10;
d = a|| --b&&--c;
printf("%d\n",c);
printf("%d\n",a);
printf("%d\n",d);
return 0;
}
```
|
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 evaluated first as there is a sequence point after it and ifexp1is non-zero thenexp2is not evaluated.
|
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);
return 0;
}
OUTPUT
o
```
|
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 fine.
|
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. Can anyone refer me to any material I can read to understand what these are?
|
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);
return 0;
}
OUTPUT
o
```
|
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 fine.
|
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. Can anyone refer me to any material I can read to understand what these are?
|
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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.