question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Im trying to take 4 digit number from user in c language.
1) I have tried usingscanf("%d%d%d%d",&a,&b,&c,&d);When I compile the code i write the numbers (1234) and enter the code does not execute after pressing enter.
2) I tried :
```
a=getche();
b=getche();
c=getche();
d=getche();
```
but when usinggetchea,b,c,d saving as char not integer. And the code didn't work properly again.
What should i do? How can i take 4 numbers from user and save every digit in different integer?
|
There is another way just enter the entire numbers and they will be separated:
```
int number, result;
printf("Please, enter four numbers: ");
scanf("%d", &number);
while (number > 0) {
result = number % 10;
number /= 10;
printf("%d\n", result);
}
printf("\n");
```
The result:
Please, enter four numbers: 12344321
|
I have got two functions. One function calls the print functions.Calling function (keyis a number between 0 and 42 symbolizing keys of a remote and thekeymapjust maps names to the keys):
```
void calling_function(int key){
print_info("[KEY]", ("%#4x %s", key, keymap[key - 1]));
...
}
```
And the printing function:
```
print_info(char *prefix, char *message){
print("%s %s\n", prefix, message);
}
```
But the output looks like this:[KEY] COLOR_RED
So the int is missing, why is it not inserting the integer? I would like to not work withsprintf()
|
The second parameter toprint_infoischar *message. You've passed it("%#4x %s", key, keymap[key - 1])which knowing the comma operator evaluates to just the last itemkeymap[key - 1]which seems to also be achar *lucky enough. You need to use some type ofprintffunction to fill in theprintfstyle format specifiers in"%4x %s"
|
POSIX read function is defined asssize_t read(int fd, void *buf, size_t count);, taking itsbufargument asvoid*.
Does it matter if the actual buffer passed in is an array ofchars orunsigned chars? If so, which one should I use? I googled and read the man, but even thetypeof the buffer isn't mentioned, let alone its signedness.
|
The reason for having the declared typevoid *is that you can read pretty much any type. You can read achar. You can read anunsigned char. You can read anint, if what you wrote to the file earlier was also anint. You can read astruct div_t, if that is what was written to the file.
Pick whatever type was written to the file, or if you're reading arbitrary bytes, whichever type works best for your later processing.
|
I have the following files and content
1.txt
```
fruit="mango"
```
C file
```
#include<stdio.h>
void main()
{
char *cmd=NULL;
system("sed -c -i /^[[:blank:]]*fruit[[:blank:]]*=/s/=.*/=\"apple\"/ 1.txt");
}
```
o/p has to be fruit="apple"
but it is displaying fruit=apple (double quotes are not coming)
when i try the command separately as Linux command it is showing with double quotes.
|
In a C string literal,\"is the escape sequence for the"character. It looks like you want to escape the"character with the\character in the shell as well. In order to do that, you should write it as\\\"in your C string literal. The\\in the string literal source produces a single\in the actual string object (array ofchar). The\"in the string literal source produces a"in the actual string object.
|
I want to start a subprocess viapopen. I'm having trouble transferring data to itsstdin.
Here's the Golang code that helps you understand what I'm trying to achieve in C.
```
subProcess := exec.Command("./command")
subProcess.Stdin = bytes.NewReader([]byte{1, 2, 3}) // create stream from bytes
subProcess.Run()
```
Taken fromhere
I'm looking for a cross platform solution._popenis available on Windows, but I can't useforkorclone. As a result, I don't know how to setstdinfor a subprocess.
My problem is, I can't find a way to do that withoutfork.
|
Is_popenandpopenok?
```
#ifdef __WIN32__
#define popen _popen
#endif
FILE *subprocess_stdin = popen("./command", "w");
fwrite(((char[]){1,2,3}), 1, 3, subprocess_stdin);
```
|
This question already has answers here:Given a starting and ending indices, how can I copy part of a string in C?(3 answers)Closed5 years ago.
I have a string
```
str = "hello"
```
I want to make a new string which is the first two digits ofstr"he".
How do I do this in C?
|
Usestrncpy(), like this:
```
#include <stdio.h>
#include <string.h>
int main(void) {
char src[] = "hello";
char dest[3]; // Two characters plus the null terminator
strncpy(dest, &src[0], 2); // Copy two chars, starting from first character
dest[2] = '\0';
printf("%s\n", dest);
return 0;
}
```
Output:
he
|
I have a 4096K binary in memory, in little-endian format. I want to read a couple of the 8 bit values as auint16_thow do I do it in the most performant manner?
```
void execute_cart (i6507_t* cpu, uint8_t* memory) {
// uint16_t start = memory[0xFFFC]; // this address contains a 16 bit value
}
```
Update: I am running on x86-64 arch, the binary is for an old 8 bit console.
|
You'll need to read two bytes separately and combine them into a singleuint16_tvariable:
```
unsigned offset = 0xfffc;
uint16_t start = memory[offset];
start |= (uint16_t)memory[offset+1] << 8;
```
Ifmemorystarts an an address that is well aligned andifthe offset is a multiple of 2, then you can do this in a single read:
```
uint16_t start = *(uint16_t *)&memory[0xfffc];
```
|
After researching, I read that the increment operator requires the operand to have a modifiable data object:https://en.wikipedia.org/wiki/Increment_and_decrement_operators.
From this I guess that it gives compilation error because(a+b)is a temporary integer and so is not modifiable.
Is this understanding correct? This was my first time trying to research a problem so if there was something I should have looked for please advise.
|
It's just a rule, that's all, and is possibly there to (1) make it easier to write C compilers and (2) nobody has convinced the C standards committee to relax it.
Informally speaking you can only write++fooiffoocan appear on the left hand side of an assignment expression likefoo = bar. Since you can't writea + b = bar, you can't write++(a + b)either.
There's no real reason whya + bcouldn't yield a temporary on which++can operate, and the result of that is the value of the expression++(a + b).
|
I want to open file namedex1, ex2, ex3 ...exnetc.
Now when i put the value ofnlike,n=1, ex1will be opened
for,n=2, ex2file will be opened and then I will read or write my c program output array from or into it.
can the name of the file be given as a string?
As I am new with programing please help me to solve this problem.
|
Normally when you open a file you use the functionfopen
```
fp = fopen ("file.txt", "w+");
if (fp == NULL)
{
exit(1); // Or you can raise some error code and return if this code is in a function.
}
// Process the file
```
Now in your case, you need to manipulate the filename. So you can take a C string for this.
```
char filename[10];
// N is set from code above
sprintf(filename,"ex%d",N);
fp = fopen (filename, "w+");
// Further behaviour is same
```
|
I tried this in a function, but I dont see anywhere the result in MPLAB X IDE. Why? Where I can find the printed result? I am using pic32 Curiosity development board and XC32.
```
int a = 5;
int b = 10;
printf("a = %d\nb = %d\n", a, b);
```
Any info? Thanks in advance!
|
printfalways uses the UART as STDOUT.
If you use the simulator you could enable UART IO under Project Properties. Know it's your choice if you like to see your printed data in a file or in an output window.
|
After researching, I read that the increment operator requires the operand to have a modifiable data object:https://en.wikipedia.org/wiki/Increment_and_decrement_operators.
From this I guess that it gives compilation error because(a+b)is a temporary integer and so is not modifiable.
Is this understanding correct? This was my first time trying to research a problem so if there was something I should have looked for please advise.
|
It's just a rule, that's all, and is possibly there to (1) make it easier to write C compilers and (2) nobody has convinced the C standards committee to relax it.
Informally speaking you can only write++fooiffoocan appear on the left hand side of an assignment expression likefoo = bar. Since you can't writea + b = bar, you can't write++(a + b)either.
There's no real reason whya + bcouldn't yield a temporary on which++can operate, and the result of that is the value of the expression++(a + b).
|
I have 2 different versions of strlen which should do the same thing, but I'm not sure which one would be faster, more readable or more energy efficient.
```
//version 1
size_t strlen(const char *str) {
size_t retval;
for(retval = 0; *str != '\0'; str++) retval++;
return retval;
}
//version2
size_t strlen(const char *str) {
const char *s;
for (s = str; *s; ++s);
return(s - str);
}
```
Or would they just translate to the same assembly code?
|
Both of your function's time complexity isO(n). So regarding performance on time theoretically both of them will take almost same time to compute. Though standardstrlenfunction's time complexity is alsoO(n)but it may have more efficiency.
Have a look atthis.
|
I'm cognizant of usingsnprintf()in lieu ofsprintf()for safety. However, I always domemset()on buffer used bysnprintf(). I saw some codes using the function withoutmemset(). And, it works as expected. I mean there is no overwriting on the buffer. Let me exemplify,
```
char str[100];
snprintf(str, sizeof(str), "stackoverflow %zu", sizeof(str));
fprintf(stderr, "%s\n", str);
snprintf(str, sizeof(str), "soner");
fprintf(stderr, "%s\n", str);
```
Until now, I thought that the code would printsoneroverflow 100that's why I usedmemset(). Nevertheless, it printssoner. How is it done underhood? By the way, same thing is applied forsprintf().
|
Fromsnprintf:
A terminating null character is automatically appended after the content written.
If you were to inspect the buffer, you would find
```
{ 's', 'o', 'n', 'e', 'r', '\0', 'v', 'e', 'r', /* ... */ }
```
|
What is the query to match a function pointer, e.g., in the following code:
```
int foo(struct A *a, int b)
{
return a->x->y(b);
}
```
yis the function pointer to match.
|
Finally, this is the answer for a call to a function pointer. The main difficulty was to detect the type of function pointers using the query. So I added theignoringParens(functionType())traversal matcher to solve the problem. A simple usage offunctionType()will not work.
```
match callExpr(hasDescendant(memberExpr(hasType(pointerType(pointee(ignoringParens(functionType()))))).bind("member")))
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question
Forming the smallest number from the input number for eg.:
```
Input: 991233612
Output: 12369
```
What is the proper algorithm to solve this without using an array? I was asked this question at an interview and still can't figure out the correct way of doing it.
|
As others have pointed out sorting and removing duplicates is possible. But how about this algorithm (in pseudocode, implementation is left to the reader)?
```
bool contains(int x, int digit); // returns true if x contains digit in base 10 notation
int res = 0;
for (int digit = 0; digit <= 9; ++i) {
if (contains(intput, digit)) res = 10 * res + digit;
}
return res;
```
|
I opened a project from a colleague in mplab X, it was in an archive(.zip) I added to the original path where are all my projects and I added the correct path to Harmony, but this is the error when I build. I configured it for the correct target board and compiller and on an clean&rebuild I get the same error. Any ideas how to fix that?
|
SOLUTION:
The project was in 1 extra folder with the same name, created when I extracted its content... I removed it, restarted the IDE, set it as main project, set the settings again for compiler and target board, run the harmony configurator, so it loaded some files and guess what... Worked like a charm... Can't believe the issue was 1 extra folder which was holding the project... Thank you for your help.
P.S: No, he was using the same OS.
|
I try to change the addr form an array but cant understand where my mistake is.
```
uint8 a[255] = {1, 2, 3, 4...., 66};
main(){
uint8 *testpointer;
testpointer = (&a + 32);
```
The Address form my a[] is 0x00000FC. And i want that the testpointer get the Address 0x00000FC + 32. But if i do it like in my code, it get a address of 0x000020DG.
|
The problem is&a. That gives you a pointer to thearrayand not the first element.
The type of&aisuint8 (*)[255], notuint8 *.
To solve your problem you need to use plainaas it will decay to a pointer to its first element (ais equal to&a[0]).
|
Here, I am trying to enter the first name and last name as "Firstname Lastname".
I want to get the output as "Lastname, FN." where FN is the first letter of first name.
Example: Input= "James Garcia" ; Output="Garcia, J."
Please find the error in my code.
```
#include <stdio.h>
int main () {
char fn[20],ln[20];
printf("Enter a first name and a last name:");
scanf("%c %s",&fn,&ln);
printf("%s, %c.",ln,fn);
return(0);
}
```
|
You want this:
```
printf("Enter a first name and a last name:");
scanf("%s %s", fn, ln); // you are reading two strings,
// not one char and one string
printf("%s, %c.", ln, fn[0]); // you print one string and one char
// not two chars
```
Disclaimer: this is oversimplified code that does not do any error checking for brevity.
|
Here is a simple demo. But Xcode shows me the error 'pasting formed '->client_port', an invalid preprocessing token
expanded from macro 'PARSE_COLUMN'
cfg->##column = value'
I just want to set value for my struct quickly, and what is the problem with 'cfg->##column = value'
```
#include <stdio.h>
#define PARSE_COLUMN( column, value ) \
printf("parse column:%s\n",#column);\
cfg->##column = value
typedef struct {
int client_port;
} server_config;
int main(void) {
server_config *cfg = new server_config;
PARSE_COLUMN(client_port,123);
return 0;
}
```
|
##is used to concatenate two macro arguments, for examplecolumn##valuewould be exchanged withclient_port123in the code above.
You don't need to use it here, you can just writecfg->column = value.
|
```
const int rxBytes = uart_read_bytes(UART_NUM_0, data, RX_BUF_SIZE, 10 / portTICK_RATE_MS);
```
|
To flush input data you can read from the uart repeatedly with a timeout of 0 until zero bytes are returned.
|
This question already has answers here:Pointer subtraction confusion(8 answers)Closed5 years ago.
Consider the following in C
```
int arr[]= {1,2,3,4,5};
```
My system uses 4 bytes to store int data.
Now&arr[0] => 0022FEB0and&arr[1]=>0022FEB4at a moment of run
Now
```
int diff=&arr[1]-&arr[0];
```
Value stored in diff is1and not4.
Why?
|
That's the way pointers work. You are not calculating the byte difference. You're calculating the difference in number of elements.
To get the element size, usesizeof(*arr)
To get the byte difference, use(&arr[1]-&arr[0]) * sizeof(*arr)
|
How could you define a function that does nothing?
If you write:
```
void function(void);
```
it would be taken as a prototype but not as a function. Would that other one be correct?
```
void function(void) {}
```
|
Yes this
void function(void){}
is possible and it's a correct function definition.
the function can't have arguments and it can return nothing ?But it can have it's own function body though it doesn't expect any argument & return nothing.
For e.g
void function(void){ printf(" welcome to SO\n"); }
|
my goal is to write a small OPC-UA-Client in Delphi and i want to use the originalOPC-UA-Stackwithout any 3rd-party-SDK.
I am already able to compile the Ansi-C-Stack but the output are .obj and .lib files.
Is there a way to compile the stack to a DLL? I already tried do use link.exe to create a DLL from the Obj-Files but I get a lot of "unresolved external symbol" error messages, some of them i was able to resolve, but not all.
I also tried to use the obj. files directly in delphi, but then i have a lot of manual translation work.
|
Yes, you can compile it as a DLL with Visual Studio. In the project Properties, change the Configuration Type to .dll and also add the define '_UA_STACK_BUILD_DLL'.
|
```
#include <stdio.h>
main()
{
int n;
n+=2;
printf("sum=%d", n);
return 0;
}
```
Here the'Sum'=2
Another program:-
```
#include <stdio.h>
main()
{
int n,a=2;
n+=a;
printf("sum=%d", n);
return 0;
}
```
here the output'sum' = 3WHY so?? What is the problem in the code??
|
This is Undefined Behavior. Using uninitialized variables (nin both snippets) can produce unexpected results, meaning that running the first code twice might produce different outputs. There is no "correct" output for either of the codes, but if you'll setnto a specific value in both codes, you'll start getting consistent results.
This is UB (Undefined Behavior):
```
main()
{
int n;
printf("sum=%d", n);
return 0;
}
```
This is not:
```
main()
{
int n = 0;
printf("sum=%d", n);
return 0;
}
```
|
In this function, I tried to return differentintvalues depending on different char* input. But I got the error "control may reach end of non-void function". How can I solve it?
```
// Converts a fraction formatted as X/Y to eighths
int duration(char* fraction)
{
if (strcmp(fraction, "1/8") == 0)
{
return 1;
}
else if (strcmp(fraction, "1/4") == 0)
{
return 2;
}
else if (strcmp(fraction, "3/8") == 0)
{
return 3;
}
else if (strcmp(fraction, "1/2") == 0)
{
return 4;
}
}
```
|
You must make a default returned value when no condition from those are right
, try to add return -1 in the end
```
..
else if (strcmp(fraction, "1/2") == 0)
{
return 4;
}else{
return -1;
}
}
```
|
I had an executable compiled to use old system GLIBC 2.15 (ld-linux.so.3 / ld-2.15.so), that is a bootstrap to a shared library with newer GLIBC 2.20 dependencies.
Who can load the library and instruct to change to the newer GLIBC linker (ld-linux.so.3 / ld-2.20.so)?
|
You could upgrade the system glibc, but that would usually put the system out of support, so it is rarely the appropriate approach.
You can compile glibc yourself, install it in a non-standard location (say/opt/gnu/glibc-2.27), and then link your application in such a way that it uses the this new glibc instead of the system glibc. The glibc wiki contains instructions with the required linker flags:
Compile against glibc in an installed location
If you cannot relink the main program, you will have to use theexplicit loader invocationinstead, perhaps using a small wrapper script such as thetestrun.shscript that glibc generates automatically.
|
How a string is a static array in C.
```
#include <stdio.h>
void array();
int main() {
printf("first turn");
array();
array();
return 0;
}
void array() {
char a[] = "hello";
printf("this is at first call%c", a[1]);
a[1] = 'z';
}
```
In both calls toarray()the output is the same, so how we can call a string as a static array?
|
The text you're quoting is talking about a string literal, such as the argument toprintf()here:
```
printf("hello");
```
or the string that's used to initialize a pointer variable:
```
char *p = "hello";
```
In your code, you're declaring a local array, and the string literal is being used to initialize it. Your code is roughly equivalent to:
```
char a[6];
strcpy(a, "hello");
```
The second argument tostrcpy()would be allocated statically, butais local to the function.
|
I want to create a iOS project using c static libraries. I have downaloaded these files
ohNetGenerated-iOs-arm64-Debug.tar.gz
ohNetGenerated-iOs-arm64-Release.tar.gz
ohNetGenerated-iOs-armv7-Debug.tar.gz
ohNetGenerated-iOs-armv7-Release.tar.gz
ohNetGenerated-iOs-x86-Debug.tar.gz
ohNetGenerated-iOs-x86-Release.tar.gz
When I extract them they all have: libohNetGeneratedDevices.a
How can I generate a fat library? Is it possible
Thank you
|
Uselipoto create a fat library:
```
lipo -create armv7/libmylib.a arm64/libmylib.a x86/libmylib.a -output libfat.a
```
You can combine the versions of the library that are for different architectures in a fat library, but you can't combine versions of the library that are for the same architecture, so you can't combine the Release and Debug versions of the same architecture.
|
How a string is a static array in C.
```
#include <stdio.h>
void array();
int main() {
printf("first turn");
array();
array();
return 0;
}
void array() {
char a[] = "hello";
printf("this is at first call%c", a[1]);
a[1] = 'z';
}
```
In both calls toarray()the output is the same, so how we can call a string as a static array?
|
The text you're quoting is talking about a string literal, such as the argument toprintf()here:
```
printf("hello");
```
or the string that's used to initialize a pointer variable:
```
char *p = "hello";
```
In your code, you're declaring a local array, and the string literal is being used to initialize it. Your code is roughly equivalent to:
```
char a[6];
strcpy(a, "hello");
```
The second argument tostrcpy()would be allocated statically, butais local to the function.
|
I want to create a iOS project using c static libraries. I have downaloaded these files
ohNetGenerated-iOs-arm64-Debug.tar.gz
ohNetGenerated-iOs-arm64-Release.tar.gz
ohNetGenerated-iOs-armv7-Debug.tar.gz
ohNetGenerated-iOs-armv7-Release.tar.gz
ohNetGenerated-iOs-x86-Debug.tar.gz
ohNetGenerated-iOs-x86-Release.tar.gz
When I extract them they all have: libohNetGeneratedDevices.a
How can I generate a fat library? Is it possible
Thank you
|
Uselipoto create a fat library:
```
lipo -create armv7/libmylib.a arm64/libmylib.a x86/libmylib.a -output libfat.a
```
You can combine the versions of the library that are for different architectures in a fat library, but you can't combine versions of the library that are for the same architecture, so you can't combine the Release and Debug versions of the same architecture.
|
Trying to compile a source code written in C.
Location of the code is:C:\Users\Chris\Documents\prog\c\learn\GOODBYE.C
In CMD I typed the code:gcc goodbye.c -o goodbye
Got this error:
```
gcc: error: goodbye.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
```
I wanted the output to be namedgoodbye.
How do I fix this?
|
Make sure that you are runninggcc goodbye.c -o goodbyewhile you are in theC:\Users\Chris\Documents\prog\c\learn\directory.
If the c file is named GOODBYE.c then you should rungcc GOODBYE.c -o goodbye
|
I have problem when compiling the code that calculate the total sum of positive integer. What puzzled me is I managed to compile and run the code successfully on Online C Compiler (https://www.onlinegdb.com/online_c_compiler) but get LNK2005 and LNK1169 error on VS2017. How to fix it?
```
//Calculate total sum of positive integer.
#include <stdio.h>
int sum(int n);
int main(void) {
int n;
printf("Enter positive value of integer: ");
scanf("%d", &n);
printf("\nTotal value for %d is = %d\n", n, sum(n));
return (0);
}
int sum(int n) {
if (n == 0) return 0;
else return (n*(n+1)/2);
}
```
By the way, kindly ignore the scanf warning on VS2017, I will change it back to scanf_s later.
|
This is a common error that occurs if you have more than one source file that contains main function.
|
Trying to compile a source code written in C.
Location of the code is:C:\Users\Chris\Documents\prog\c\learn\GOODBYE.C
In CMD I typed the code:gcc goodbye.c -o goodbye
Got this error:
```
gcc: error: goodbye.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
```
I wanted the output to be namedgoodbye.
How do I fix this?
|
Make sure that you are runninggcc goodbye.c -o goodbyewhile you are in theC:\Users\Chris\Documents\prog\c\learn\directory.
If the c file is named GOODBYE.c then you should rungcc GOODBYE.c -o goodbye
|
I have problem when compiling the code that calculate the total sum of positive integer. What puzzled me is I managed to compile and run the code successfully on Online C Compiler (https://www.onlinegdb.com/online_c_compiler) but get LNK2005 and LNK1169 error on VS2017. How to fix it?
```
//Calculate total sum of positive integer.
#include <stdio.h>
int sum(int n);
int main(void) {
int n;
printf("Enter positive value of integer: ");
scanf("%d", &n);
printf("\nTotal value for %d is = %d\n", n, sum(n));
return (0);
}
int sum(int n) {
if (n == 0) return 0;
else return (n*(n+1)/2);
}
```
By the way, kindly ignore the scanf warning on VS2017, I will change it back to scanf_s later.
|
This is a common error that occurs if you have more than one source file that contains main function.
|
I am trying todlopenmemory allocators at runtime.
I have no problem withlibc,tcmallocandtbbmalloc. But trying todlopenjemallocresults in the following error (caught viadlerror) :
/path/to/lib/libjemalloc.so: cannot allocate memory in static TLS block
Do you have any idea of the reason for this error and hence how I could tackle this ?
|
I was able to find a solution to this thanks tojemalloc's GitHub repositoryissue #1237.
This solution was to recompilejemallocusing the--disable-initial-exec-tlsaccording to theINSTALL.md, my bad.
|
I was browsing the Linux kernel code and in thefilehid.h, theHID_QUIRK_ALWAYS_POLLmacro is defined as:
```
#define HID_QUIRK_ALWAYS_POLL BIT(10)
```
What is the meaning ofBIT(10)? I am not really familiar withCbut from what I know (and researched) there is no such bit manipulation function.
|
looks like you can find the answer inside the first header file included, i.e.bitops.h!
```
#define BIT(nr) (1UL << (nr))
```
i.e.BITdefines a bit mask for the specified bit number from 0 (least significant, or rightmost bit) to whatever fits into an unsigned long.SoBIT(10)should evaluate to the numeric value of 1024 (which is1 << 10).
|
I am trying todlopenmemory allocators at runtime.
I have no problem withlibc,tcmallocandtbbmalloc. But trying todlopenjemallocresults in the following error (caught viadlerror) :
/path/to/lib/libjemalloc.so: cannot allocate memory in static TLS block
Do you have any idea of the reason for this error and hence how I could tackle this ?
|
I was able to find a solution to this thanks tojemalloc's GitHub repositoryissue #1237.
This solution was to recompilejemallocusing the--disable-initial-exec-tlsaccording to theINSTALL.md, my bad.
|
I was browsing the Linux kernel code and in thefilehid.h, theHID_QUIRK_ALWAYS_POLLmacro is defined as:
```
#define HID_QUIRK_ALWAYS_POLL BIT(10)
```
What is the meaning ofBIT(10)? I am not really familiar withCbut from what I know (and researched) there is no such bit manipulation function.
|
looks like you can find the answer inside the first header file included, i.e.bitops.h!
```
#define BIT(nr) (1UL << (nr))
```
i.e.BITdefines a bit mask for the specified bit number from 0 (least significant, or rightmost bit) to whatever fits into an unsigned long.SoBIT(10)should evaluate to the numeric value of 1024 (which is1 << 10).
|
please help meHere is a problem of Codechef. And this is my submission:
```
#include <stdio.h>
#define M 60
int main()
{
int i,arr[M],input;
int s=0;
puts("Input:");
for(i=0;;i++){
scanf("%d",&input);
if(input==42){
scanf("%d");
break;
}
else{
arr[i]=input;
s++;
}
}
puts("Output:");
for(i=0;i<s;i++){
printf("%d\n",arr[i]);
}
return 0;
}
```
When i create the code it successfully ran with GCC 4.9.2, but when i submit this Codechef said that it has a runtime error. I tried but could not found the error.
So
Please help me to find out the error ...
|
the variable in the second scanf is missing
|
```
#include<stdio.h>
int main(){
int n;
printf("%d\n",scanf("%d",&n));
return 0;
}
```
I wonder why the output of this program is always '1' ?!
What's actually happening here ?
|
I suspect you wanted to use
```
int n;
scanf("%d", &n);
printf("%d\n", n);
```
but what you wrote is equivalent to
```
int n;
int num = scanf("%d", &n); // num is the number of successful reads.
printf("%d\n", num);
```
|
What does a recursive function return if it does not have a return statement in a separate sentence.
```
#include <stdio.h>
int rec(int i)
{
if (i != 3)
return rec(++i);
}
int main()
{
rec(5);
return 0;
}
```
|
FromC documentation on return:
Reaching the end of any other value-returning function is undefined behavior, but only if the result of the function is used in an expression.
So the behavior is undefined if any function that is supposed to return a value but doesn't return a value and when we try to use that returned value. On most implementation it returns a garbage.
For your case you are not using the return value so it has no effect here. Also you will get an infinite recursion since first call has 5 and it is incremented in later calls.
|
void TraverseList(const List *l , void (*Visit)(ListEntry)) { // }
I confused about the above function call within the argument of a function,how it is working?
|
Visitis a function pointer parameter passed to theTraverseListfunction. It should point to a function with the format
```
void func (ListEntry);
```
Likely,TraverseListwill call the passed function for every item in the list.
|
My code uses epoll for multiplexing. After EPOLLIN is encountered it reads one byte from ready socket.
```
read(fd, &onebyte, 1);
```
Can the above line return EWOULDBLOCK?
|
yes,
Errors:...EAGAIN orEWOULDBLOCKThe file descriptor fd refers to a socket and has been marked
nonblocking (O_NONBLOCK), and the read would block. POSIX.1-2001
allows either error to be returned for this case, and does not require
these constants to have the same value, so a portable application
should check for both possibilities
reference:the read() man description
|
What does a recursive function return if it does not have a return statement in a separate sentence.
```
#include <stdio.h>
int rec(int i)
{
if (i != 3)
return rec(++i);
}
int main()
{
rec(5);
return 0;
}
```
|
FromC documentation on return:
Reaching the end of any other value-returning function is undefined behavior, but only if the result of the function is used in an expression.
So the behavior is undefined if any function that is supposed to return a value but doesn't return a value and when we try to use that returned value. On most implementation it returns a garbage.
For your case you are not using the return value so it has no effect here. Also you will get an infinite recursion since first call has 5 and it is incremented in later calls.
|
void TraverseList(const List *l , void (*Visit)(ListEntry)) { // }
I confused about the above function call within the argument of a function,how it is working?
|
Visitis a function pointer parameter passed to theTraverseListfunction. It should point to a function with the format
```
void func (ListEntry);
```
Likely,TraverseListwill call the passed function for every item in the list.
|
My code uses epoll for multiplexing. After EPOLLIN is encountered it reads one byte from ready socket.
```
read(fd, &onebyte, 1);
```
Can the above line return EWOULDBLOCK?
|
yes,
Errors:...EAGAIN orEWOULDBLOCKThe file descriptor fd refers to a socket and has been marked
nonblocking (O_NONBLOCK), and the read would block. POSIX.1-2001
allows either error to be returned for this case, and does not require
these constants to have the same value, so a portable application
should check for both possibilities
reference:the read() man description
|
I made a simple client-server program in c using sockets and now i want to test it ,by simulating many clients connecting to the server at the same time!I wrote a script to execute the client:./client20 times but it didn't work for me since it waited for each client to finish.
Also i wrote another program in c ,this time with threads so it could execute each client withsystem(./client)and then detach the thread ,but again i had the same problem!
So what is the correct way to implement this?
|
The easiest solution is to do your shell script, but put an & after the ./clientk call, which will put it in the background and run the next command immediately
|
In reference to SOquestionMy friend's code gets compiled on his Windows PC but it doesn't for my Linux PC.I'm usingEclipse Luna (4.4.2),System Workbenchfor STM32-OpenOCDVersion: 1.13.2.201703061529, arm-none-eabi-gcc version 4.9.3And he's usingEclipse v4.6.3, and SW-STM32v1.15.0.201708311556, arm-none-eabi-gcc v4.7.2.
Forget about versions, a C code is case sensitive to includes and his compiler just outright ignores that!
Anyone have any clue if a flag has been set along with his compiler? Shouldn't we remove this to be on par with the C standard?
|
The reason for this as stated by @Gerhardh is the difference in how the OS searches for files. Windows is not case sensitive whereas Linux is. Sticking to a coding standard is the best option.
Thank you Gerhardh
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed5 years ago.Improve this question
```
#include<stdio.h>
#define A 11
int main() {
int x=A
printf(x);
}
```
I could not run this code. I think there is a problem in this macro describing. If you help me i will be so content.
|
```
#include <stdio.h>
#define A 11
int main() {
int x(A);
// int x = A; in C
printf("%d\n", x);
}
```
|
ERROR: type should be string, got "\nhttps://www.gnu.org/software/m68hc11/examples/stdio_8h-source.html\n\nI wonder what does _exfun () mean above link in using C/C++ and what does it do? I have seen a code fragment. Here is:\n\n```\n#ifndef _EXFUN\n # define _EXFUN(N,P) N P\n#endif\n```\n\nWhat does this code do? If you explain that, i will be so happy. Thanks\n" |
I just tested it and it chains two statements.
```
_EXFUN(printf("Hello, ");, printf("World!\n");)
```
Apparently, this is a hack used so that the same statement will be preprocessed differently depending on how_EXFUNis implemented in the header file. It mainly has to do with declarations. But I can not give any example of when it is useful.
|
I was browsingWikipedia/Restrict, and found that
The compiler can e.g. rearrange the code, first loading all memory locations, then performing the operations before committing the results back to memory.
Later, I noticed that
```
void updatePtrs(long int *restrict ptrA, long int *ptrB, long int *val)
{
*ptrA += *val;
*ptrB += *val;
}
```
and
```
void updatePtrs(long int *restrict ptrA, long int *ptrB, long int *val)
{
*ptrB += *val;
*ptrA += *val;
}
```
don't yield the same assembly with-Ofast. This applies for both GCC and Clang.
You can experiment with themhereandhere
Why do they have different assemblies? Was this expected?
|
NeitherptrBnorvalarerestrict, soptrBandvalcould point to the samelong. When they do, the order of*ptrA += *val;and*ptrB += *val;matters.
Even if all pointers wererestrict, the compiler would only be allowed, not required, to rearrange the operations.
|
In reference to SOquestionMy friend's code gets compiled on his Windows PC but it doesn't for my Linux PC.I'm usingEclipse Luna (4.4.2),System Workbenchfor STM32-OpenOCDVersion: 1.13.2.201703061529, arm-none-eabi-gcc version 4.9.3And he's usingEclipse v4.6.3, and SW-STM32v1.15.0.201708311556, arm-none-eabi-gcc v4.7.2.
Forget about versions, a C code is case sensitive to includes and his compiler just outright ignores that!
Anyone have any clue if a flag has been set along with his compiler? Shouldn't we remove this to be on par with the C standard?
|
The reason for this as stated by @Gerhardh is the difference in how the OS searches for files. Windows is not case sensitive whereas Linux is. Sticking to a coding standard is the best option.
Thank you Gerhardh
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed5 years ago.Improve this question
```
#include<stdio.h>
#define A 11
int main() {
int x=A
printf(x);
}
```
I could not run this code. I think there is a problem in this macro describing. If you help me i will be so content.
|
```
#include <stdio.h>
#define A 11
int main() {
int x(A);
// int x = A; in C
printf("%d\n", x);
}
```
|
ERROR: type should be string, got "\nhttps://www.gnu.org/software/m68hc11/examples/stdio_8h-source.html\n\nI wonder what does _exfun () mean above link in using C/C++ and what does it do? I have seen a code fragment. Here is:\n\n```\n#ifndef _EXFUN\n # define _EXFUN(N,P) N P\n#endif\n```\n\nWhat does this code do? If you explain that, i will be so happy. Thanks\n" |
I just tested it and it chains two statements.
```
_EXFUN(printf("Hello, ");, printf("World!\n");)
```
Apparently, this is a hack used so that the same statement will be preprocessed differently depending on how_EXFUNis implemented in the header file. It mainly has to do with declarations. But I can not give any example of when it is useful.
|
I was browsingWikipedia/Restrict, and found that
The compiler can e.g. rearrange the code, first loading all memory locations, then performing the operations before committing the results back to memory.
Later, I noticed that
```
void updatePtrs(long int *restrict ptrA, long int *ptrB, long int *val)
{
*ptrA += *val;
*ptrB += *val;
}
```
and
```
void updatePtrs(long int *restrict ptrA, long int *ptrB, long int *val)
{
*ptrB += *val;
*ptrA += *val;
}
```
don't yield the same assembly with-Ofast. This applies for both GCC and Clang.
You can experiment with themhereandhere
Why do they have different assemblies? Was this expected?
|
NeitherptrBnorvalarerestrict, soptrBandvalcould point to the samelong. When they do, the order of*ptrA += *val;and*ptrB += *val;matters.
Even if all pointers wererestrict, the compiler would only be allowed, not required, to rearrange the operations.
|
```
#include <stdio.h>
void main(){
char c[] = "Hello";
char h = c[4];
printf("%s",h);
```
}
Why does h result in the position of the element,not the value ?The error is : warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
|
The statement
printf("%s",h);
causes warning as you mentioned
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2
has type ‘int’ [-Wformat=]
becausehis declared aschartype and to print character variable format specifier is%c. So use%cinstead of%sas%sexpects argument ofchar*type notchartype.
Why does h result in the position of the element,not the value ?No if you print likeprintf("%c\n",h);it prints the value whatc[4]holds.
|
When we have :
```
struct node {
char...
int....
struct node *....
}
typedef struct node Node;
```
and then we have a function like this:
```
int function(Node f){...}
```
What is thisf?
|
fis an input argument of the typeNode. The typeNodeis synonym of the typestruct node.
|
This question already has answers here:How to give to a client specific ip address in C(2 answers)Closed5 years ago.
My computer has 2 IP addresses for 2 Ethernet cards.192.168.0.1is a server, but how to set192.168.0.2as client inCwithwinsock2. By default client is always192.168.0.1.
|
You can callbindbeforeconnect, to give client a specific IP address or port.
```
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("192.168.0.2"); // bind to specific IP address
service.sin_port = 0; // not to specify port number
iResult = bind(ListenSocket, (SOCKADDR *) &service, sizeof (service));
// then call connect()...
```
|
I was working on a C project and i wrote the following line to check if the most significant bit of an int8_t is 1:
```
if (f & 0b10000000 == 0b10000000) {
```
and CLion threw up a warning, telling me 'Expression can be simplified to "f != 0"'
Would I be right in saying this is incorrect? I read over bitwise operations to be sure and I still feel like these are not equivalent operations, for instance f = 1 would return false with my expression, but this message is making me doubt myself.
Thanks for any help you can give!
|
The bitwise "and" operator&has lower precedence than==.
Therefore, your expressionif (f & 0b10000000 == 0b10000000)is equivalent toif (f & (0b10000000 == 0b10000000)).
If you just want to test bit 7, tryif (f & 0b10000000). Any non-zero value will be treated as "true".
Also, yes: CLion is wrong. Your original expression is equivalent toif (f & 1), which tests bit 0 (probably not what you intended).
|
I was working on a C project and i wrote the following line to check if the most significant bit of an int8_t is 1:
```
if (f & 0b10000000 == 0b10000000) {
```
and CLion threw up a warning, telling me 'Expression can be simplified to "f != 0"'
Would I be right in saying this is incorrect? I read over bitwise operations to be sure and I still feel like these are not equivalent operations, for instance f = 1 would return false with my expression, but this message is making me doubt myself.
Thanks for any help you can give!
|
The bitwise "and" operator&has lower precedence than==.
Therefore, your expressionif (f & 0b10000000 == 0b10000000)is equivalent toif (f & (0b10000000 == 0b10000000)).
If you just want to test bit 7, tryif (f & 0b10000000). Any non-zero value will be treated as "true".
Also, yes: CLion is wrong. Your original expression is equivalent toif (f & 1), which tests bit 0 (probably not what you intended).
|
This prints4. Why?
I'm aware how ternary operators work but this makes it complicated.
```
printf("%d", 0 ? 1 ? 2 : 3 : 4 );
```
Also this printsd.
???
```
int x=0, y=1 ;
printf( "d", x ? y ? x : y : x ) ;
```
|
For the first one, its a "Nested" terenary operator. I would put parentheses around it to make it more decodable. Consider0 ? 1 ? 2 : 3 : 4, Lets transform this to0 ? (1 ? 2 : 3) : (4)is0? the else part executes which is4
For the second you are missing the%d
|
When I was reading the bookUnix Network Programming, there are many socket apis/types having prefixes likesin_addrwithsin,inet_addrwithinet, andin_addr_twithin. What do those prefiexes actually mean, that is, what are the full names?
|
I believe in the very early days structure members had to be unique. Using the same name for a member in two different structures failed. This is still (and always was) true for assembly macros that help use C structs and preprocessor macros.
The structures and constants from the old days therefor use a prefix that is usually derived from the structure name or context. E.g. struct addressinfo uses a prefix of ai, struct sockaddr uses sa, struct sockaddr_in uses sin and so on.
Using unique names for each member allows using the same name for C and asm code, which made reading and writing code in both languages easier. No need to mentally switch tracks when switching language.
|
```
#include <stdio.h>
int a = 33;
int main()
{
int a = 40;
{
extern int a;
printf("%d\n",a);
}
}
```
Output : 33
Can anyone please let me know how Extern is working here ?
Why after declaring variable "a" with extern keyword, access to local variable "a" in main is lost ?
|
externused in this context refers to the variableat global scope.
So yourextern int arefers to the variable at global scope, andshadowsthe automaticadeclared inmain.
(The effect is similar to the::aof C++.)
|
I work on a u 18.04 and a third party tool (pymesh) that I use needs to includePython.h
I installed python-dev, python3-dev, libpython-dev and libpython3-dev.
Python.his found in the folders:/usr/include/Python/,/usr/include/Python3.6m/and/usr/include/Python3.6/.
Still when I try to compile a minimal C-program:
```
#include<Python.h>
int main(){}
```
I get the error:
```
$ gcc test.c
test.c:1:9: fatal error: Python.h: No such file or directory
#include<Python.h>
^~~~~~~~~~
compilation terminated.
```
I can fix this by making symbolic links to every header in one of those directories in, e.g.,/usr/local/include/or by specifying the path in the#includestatement, but is that the correct way of doing it?
|
You should use the-Ioption of gcc:
```
gcc -I /usr/local/include test.c
```
|
Is it possible to get a bdd for (x0 ∧ x1 ) ∨ (x0 ∧!x1 ) ∨ (!x0 ∧ x1 ) ∨ (!x 0 ∧!x 1 ) that still has nodes representing the variables x0 and x1, using CUDD? I know the above boolean formula simplifies to the constant function 1. But I still want a BDD that doesnt simplify the formula but represents it as a BDD 'containing' nodes corresponding to both x0 and x1. If not in CUDD, is it possible to do so using some other tool?
|
You might want to try the MEDDLY Library. (https://meddly.sourceforge.io/).
It is possible to use different types of reduction within this library. For example, quasi-reduction never skips a level (variable). That sounds like what you want.
Hope, that helps.
|
I have written a C application under Linux with GTK. A friend wanted to test it under Windows. So we compiled it using MinGW64.
The GUI and everything looks/works as it should. However, the fread() call does not work.
```
read = fread(workbuff, sizeof(char), rec_data_length, bin_file);
if (read != rec_data_length) {
/* Here is some error handling */
}
```
rec_data_length is 608. I ensured that the file is not corrupted and that these 608 bytes are available. The function returns 87.
Can someone explain this to me? Why does it work under Linux but not under Windows?
|
The problem with reading from this file was, that I opened a binary file with
```
fopen("foo", "r");
```
This worked fine under Linux. But on Windows I had to change it to
```
fopen("foo", "rb");
```
This solution works on both systems and behaves now as expected.
|
I am trying to typecast a value ofvoid *type touint32but getting error after compile:
error: cast from pointer to integer of different size
|
What the C standard says is this, C11 6.3.2.3/6:
Any pointer type may be converted to an integer type. Except as previously specified, the
result is implementation-defined. If the result cannot be represented in the integer type,
the behavior is undefined. The result need not be in the range of values of any integer
type.
This means that it is up to the compiler to specify what will happen on the given system. Apparently your particular compiler things that the result can't be represented and therefore throws a diagnostic message.
What you should do instead is to cast touintptr_t. This type is guaranteed to be large enough to contain an object pointer value.
|
I am going through a C dll and came across a structure
```
BufferData{int Len; int Ant; unsigned char Data[512]}
```
the structure is then initialized by creating an array
```
BufferData Data[16] = {0}
```
I am uncertain what this does given that Data is an array of Structures.
|
This is a quirk of C initializers. C has no "half initialized" variables; a variable is either uninitialized or fully initialized.
If an initializer specifies fewer values than the structure or array has members, all remaining elements are recursively implicitly initialized to zero.
Thus{0}is a universal initializer: It sets the first field (whatever that may be) to0and all remaining fields (if any) are automatically set to0, too.
In your case the first field is the first member of the first element ofData, i.e. we're explicitly settingData[0].Lenand relying on zero initialization for everything else.
|
This question already has answers here:Why does division result in zero instead of a decimal?(5 answers)Closed5 years ago.
I have the following statements:
```
const double s=1529340.57;
double f=1-1/1200;
for(j=1;j<=384;j++){
printf("Age %3d month %2d you have $%.2lf\n", (j+816) / 12, (j+816)%12, s*pow(f,j-1)-4000*((pow(f,j-1)-f)/(f-1)-1));
}
```
and I'm expecting to have the following results:
```
Age 68 month 1 you have $1526615.02
Age 68 month 2 you have $1523887.20
Age 68 month 3 you have $1521157.11
```
and so on.
But, I obtained the following output:
```
Age 68 month 1 you have $-1.#J
Age 68 month 2 you have $-1.#J
Age 68 month 3 you have $-1.#J
```
Do you know why?
Thanks!
|
Trydouble f=1-1/1200.0;. As Jean-François Fabre already mentioned 1-1/1200 is not intepreted as double in your version of code. The 1200.0 forces the compiler to handle your formular as decimal.
|
Client side works like this
```
clock_t s, f;
while(TRUE){
write
s_time = clock()
read
f_time = clock();
double client_time = (double)(f_time - s_time) / CLOCKS_PER_SEC;
fprintf(stderr, "ct = %lf\n", client_time);
}
```
Right after I send a message to the server, the timer starts and when the client reads a message from the server, the timer stops. In server it takes 5 to 10 seconds to answer back to clien. Here is my problem. the timer in client shows only a very short of time elapsed. around only 0.0000085. How do I keep the real elapsed time?
|
clockmeasures CPU time, that is how much time the CPU spent executing the code. Your code however is mostlynotutilizing CPU: it is blocked (in other words, doing nothing) whilereadwas waiting for data to arrive.
To measure the wall time elapsed, usegettimeofdayinstead ofclock.
|
```
#define MAX_LINES 20
#define MAX_LINE 20
int main(){
char *lines[MAX_LINES];
for(int i=0;i<MAX_LINES;i++){
char line[MAX_LINE];
lines[MAX_LINES+i]=line;
}
}
```
I'm so confused why my array of pointers "lines" doesn't have any of it's addresses changed when a "line" address is assigned to it. Why isn't that assignment working?
|
You're assigning to the wrong index in your array and the thing you're assigning won't exist when you need to use it, thatlinevariable falls out of scope. To fix that:
```
#define MAX_LINES 20
#define MAX_LINE 20
int main(){
char *lines[MAX_LINES];
for(int i=0;i<MAX_LINES;i++){
lines[i] = malloc(MAX_LINE);
}
return 0;
}
```
Though of course you should alwaysfreeanything you allocate as a matter of principle so writing a function to allocatelinesas well as free it is the best approach here.
|
This question already has answers here:Using GCC to produce readable assembly?(11 answers)Closed5 years ago.
I would like to see, after compiling some code (for example C), the resulting code in machine language or assembly. How can that be done?
|
Many compilers (includinggccandclang) have an-Soption that makes them output assembly instead of a binary file.
Alternatively you can view the assembly for an existing binary file using a disassembler. For exampleobjdumpfrom the GNU binutils can show you the assembly for a given binary using the-d(--disassemble) or-D(--disassemble-all) options.
|
```
#define MAX_LINES 20
#define MAX_LINE 20
int main(){
char *lines[MAX_LINES];
for(int i=0;i<MAX_LINES;i++){
char line[MAX_LINE];
lines[MAX_LINES+i]=line;
}
}
```
I'm so confused why my array of pointers "lines" doesn't have any of it's addresses changed when a "line" address is assigned to it. Why isn't that assignment working?
|
You're assigning to the wrong index in your array and the thing you're assigning won't exist when you need to use it, thatlinevariable falls out of scope. To fix that:
```
#define MAX_LINES 20
#define MAX_LINE 20
int main(){
char *lines[MAX_LINES];
for(int i=0;i<MAX_LINES;i++){
lines[i] = malloc(MAX_LINE);
}
return 0;
}
```
Though of course you should alwaysfreeanything you allocate as a matter of principle so writing a function to allocatelinesas well as free it is the best approach here.
|
This question already has answers here:Using GCC to produce readable assembly?(11 answers)Closed5 years ago.
I would like to see, after compiling some code (for example C), the resulting code in machine language or assembly. How can that be done?
|
Many compilers (includinggccandclang) have an-Soption that makes them output assembly instead of a binary file.
Alternatively you can view the assembly for an existing binary file using a disassembler. For exampleobjdumpfrom the GNU binutils can show you the assembly for a given binary using the-d(--disassemble) or-D(--disassemble-all) options.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question
I'm new to C programming, so I wonder if it's possible to read from a certain file using the system callread()until a space is found.
Example:
A file contains a number and a process PID (59 5542). I want to read first the number, saving it into a variable and then do the same thing with the PID.
Thanks in advance.
P.S: since this is an exercise for my Operating Systems class, I have to useread().
|
I recommend first reading the number and the PID with oneread()call into a sufficiently large buffer, then saving both into variables, e. g.:
```
char buf[20] = { 0 }, *end;
read(fd, buf, sizeof buf - 1);
int num, PID;
num = strtol(buf, &end, 0);
PID = strtol(end, NULL, 0);
```
|
I have written program to read from usb port (which is not connected to anything) .From java I am passing int filedescriptor and byte array and in jni I am converting byte array to char* and using read().
```
jbyte *bufferPtr2 = (*env)->GetByteArrayElements(env, buf, NULL);
unsigned char* d_data2 = (unsigned char*)bufferPtr2;
n = read(fd, d_data2, lengthOfArray);
```
After executing , n=1 but d_data2 is empty. Why is this? Does read() read null character as data?
|
Perthe POSIX documentation forread():
Theread()function shall attempt to readnbytebytes from the file associated with the open file descriptor,fildes, into the buffer pointed to bybuf.
The actual value of the bytes that are read does not matter.
So yes,read()will readNULbytes.
|
```
int i=0;
a[i] =3;
i++;
Vs
int i=0;
a[i++]=3;
```
Is it just a fancy way of writing code and saving lines or you really do improve the performance here?
|
Usinghttps://godbolt.org/, GCC with optimisations enabled generates the same code for both cases.
```
main:
sub rsp, 8
mov esi, 3
mov edi, OFFSET FLAT:std::cout
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
xor eax, eax
add rsp, 8
ret
_GLOBAL__sub_I_main:
sub rsp, 8
mov edi, OFFSET FLAT:std::__ioinit
call std::ios_base::Init::Init()
mov edx, OFFSET FLAT:__dso_handle
mov esi, OFFSET FLAT:std::__ioinit
mov edi, OFFSET FLAT:std::ios_base::Init::~Init()
add rsp, 8
jmp __cxa_atexit
```
Note: gcc has optimisedstd::cout << a[0]tostd::cout<<3
|
I have a global variable namedend_jumpwhich is either 3 or 7.Depending on what the value is, I want to end a for loop (optimized).My current code is:
```
int i;
for(i = 0; i < ((end_jump % 3) == 0) ? 4 : 10; i++){
/* do something with */ array[i];
}
```
I'm not getting any error message and the for loop goes on, but doesn't stop. Neither at 4, nor at 10.
Whats the problem?
|
SeeGCCcompiler warning :
```
warning: ?: using integer constants in boolean context, the expression will always evaluate to 'true' [-Wint-in-bool-context]
for(i = 0; i < ((end_jump % 3) == 0) ? 4 : 10; i++){
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
```
|
I am working with the xc8 compiler and want to tell him that my literal is only 8 bit wide.
123:no suffix, default int (16 bit in xc8)
123U:unsigned int also 16 bit wide
Any idea for a clean solution to describe a 8 bit literal?
|
Any idea for a clean solution to describe a 8 bit literal?
C only has 2literals:string literalsandcompound literals(C99). C identifies123and123uasinteger constants, notliterals.
To form a C 8 bit literal: make acompound literal
```
#define OneTwoThree ((uint8_t) { 123 })
printf("%zu %x\n", sizeof(OneTwoThree), OneTwoThree);
// expected output
1 123
```
IDK if xc8 supportscompound literals.
|
Is it possible that accept() return a value same as sockfd?
for example
```
int newfd = accept(sockfd, NULL, NULL);
```
Is it possiblenewfd == sockfd?
|
The short answer isNo.
Theaccept()man pageexplains:
Theaccept()system call is used with connection-based socket types (SOCK_STREAM,SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections for the listening socket,sockfd,creates a new connected socket, and returns a new file descriptor referring to that socket. The newly created socket is not in the listening state. The original socketsockfdis unaffected by this call.
It is thisnewsocket descriptor which is returned.
Thesockfdargument is a socket that has been created withsocket(), bound to a local address withbind(), and is listening for connections after a call tolisten().
The returned descriptor does not exist before the call toaccept().
|
I have a struct calledresultthat has the following definition:
```
struct result {
void** elements;
size_t n_elements;
};
```
But when I try to initialise it with the following properties{ NULL, 0 }I receive the following warning:
```
warning: excess elements in scalar initializer
struct result * result_elements = { NULL, 0 };
```
Is this an error because it's expecting a 2D array? If so, I thought NULL was permissible?
Cheers :)
|
This is a pointer
```
struct result * result_elements /**/;
```
You try to initialise it with
```
{ NULL, 0 }
```
You could initialise it e.g. with a scalar initialiser like
```
NULL
```
You could initialise a separate (non-pointer) variable with your non-scalar initialiser, e.g.
```
struct result avariable = { NULL, 0 };
```
And then you could initialise your pointer like
```
struct result * result_elements = &avariable;
```
|
just a fibonacci algorithm, how do i print every number of fibonacci sequence without repeat every step?
Does recursive functions is a good use in any way? I know it is more legible, but there is a visible delay in this simple algorithm if i put n = 40, whereas the iterative way of doing it is instantaneous.
```
int fib(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
return fib(n - 1) + fib(n - 2);
}
```
|
You can easily optimize the recursive solution by memoizing the already-computed values:
```
int fib(int n) {
static int cache[48] = {0}; // should be enough to hold all int fibs
if(n < 2) return n; // initial conditions
else if(cache[n]) return cache[n]; // a value already computed and memoized
else return cache[n] = fib(n - 1) + fib(n - 2); // the largest so far
}
```
Should speed up the computation by, uh, some factor.
|
I use QT Creator from MSYS2.
In QT creatorTools > Options > Build and Run > Kitscontrol which changes debugger is grey and I cannot change it, like in the screenshot below:
The problem is that in the kit for 32 bit software is set gdb for 64 bit software (which works incorrectly). I need to change 64 bit gdb in 32 bit kit to the gdb for 32 bit. How to do that?
Here is also screenshot from debuggers tab:
|
That kit was installed by the installer, which explicitly set that particular debugger. Those settings can not get changed via the UI! If there is something wrong there, then the Qt installer needs to be fixed.
Of course you can clone the kit and edit the cloned kit to your liking.
If you feel like wielding your text editor, then you can of course also change the settings that the installer wrote for Creator. They are stored in a file called profiles.xml somewhere in the "share" folder of your Qt Creator installation.
|
I have the following structs whereaccess2usesctx1indirectly throughaccess1. Suppose if I set the value ofval1throughaccess2, how can I make sure thataccess1also reflects the same changes as shown inmain()?
```
typedef struct __ctx1{
int val1;
int val2;
}ctx1;
typedef struct __access1{
int counts;
ctx1 cx1;
}access1;
typedef struct __access2{
int options;
access1 base1;
}access2;
int main(){
access2 *base2;
base2->base1.cx1.val1 = 5;
access1 *acc;
printf("val1 %d\n",acc->cx1.val1);
return 0;
}
```
|
Setaccto point to the address of that substructure:
```
access1 *acc = &(base2->base1);
```
You also never allocated space forbase2to point to, it should be:
```
access2 *base2 = malloc(sizeof access2);
```
|
```
#include <stdio.h>
int main()
{
int i=0;
while(i++,i<=8);
printf("%d\n",i);
return 0;
}
```
Why is the increment ofidone after the comparison in each test case?
|
i <= 8succeeds for the last time wheni = 8.
In the last iteration,i++is executed, theni <= 8fails becausei = 9.
Note that the,is asequence point, soi++is absolutely guaranteed to be executed beforei <= 8.Not so for similar constructs.
|
What is the correct macro to support code block and still be tolerant to type casting?
```
if (fooisneeded)
(void)foo();
```
#define foo() do {foo_subpart1(); foo_subpart2;} while(0): will not tolerate type cast
#define foo() 0; do {foo_subpart1(); foo_subpart2;} while(0): will break in bracelessif/<loop>
|
Using(void) foo()is just not possible with macros because that construct relies on a return type, which a macro, by its very nature, does not have. Neither does a macro have knowledge about C semantics or syntax, so computing a return type is impossible already.
What's the point anyway? Casting function expressions to(void)is intended to tell the compiler "you ain't gonna need it." A macro does not even return a value, it just does textual substitution. You ain't gonna need the "you ain't gonna need it."
Use aninlinefunction instead or just a function. If you need to do this sort of stuff, then macros are the wrong tool.
|
just a fibonacci algorithm, how do i print every number of fibonacci sequence without repeat every step?
Does recursive functions is a good use in any way? I know it is more legible, but there is a visible delay in this simple algorithm if i put n = 40, whereas the iterative way of doing it is instantaneous.
```
int fib(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
return fib(n - 1) + fib(n - 2);
}
```
|
You can easily optimize the recursive solution by memoizing the already-computed values:
```
int fib(int n) {
static int cache[48] = {0}; // should be enough to hold all int fibs
if(n < 2) return n; // initial conditions
else if(cache[n]) return cache[n]; // a value already computed and memoized
else return cache[n] = fib(n - 1) + fib(n - 2); // the largest so far
}
```
Should speed up the computation by, uh, some factor.
|
I use QT Creator from MSYS2.
In QT creatorTools > Options > Build and Run > Kitscontrol which changes debugger is grey and I cannot change it, like in the screenshot below:
The problem is that in the kit for 32 bit software is set gdb for 64 bit software (which works incorrectly). I need to change 64 bit gdb in 32 bit kit to the gdb for 32 bit. How to do that?
Here is also screenshot from debuggers tab:
|
That kit was installed by the installer, which explicitly set that particular debugger. Those settings can not get changed via the UI! If there is something wrong there, then the Qt installer needs to be fixed.
Of course you can clone the kit and edit the cloned kit to your liking.
If you feel like wielding your text editor, then you can of course also change the settings that the installer wrote for Creator. They are stored in a file called profiles.xml somewhere in the "share" folder of your Qt Creator installation.
|
I have the following structs whereaccess2usesctx1indirectly throughaccess1. Suppose if I set the value ofval1throughaccess2, how can I make sure thataccess1also reflects the same changes as shown inmain()?
```
typedef struct __ctx1{
int val1;
int val2;
}ctx1;
typedef struct __access1{
int counts;
ctx1 cx1;
}access1;
typedef struct __access2{
int options;
access1 base1;
}access2;
int main(){
access2 *base2;
base2->base1.cx1.val1 = 5;
access1 *acc;
printf("val1 %d\n",acc->cx1.val1);
return 0;
}
```
|
Setaccto point to the address of that substructure:
```
access1 *acc = &(base2->base1);
```
You also never allocated space forbase2to point to, it should be:
```
access2 *base2 = malloc(sizeof access2);
```
|
```
#include <stdio.h>
int main()
{
int i=0;
while(i++,i<=8);
printf("%d\n",i);
return 0;
}
```
Why is the increment ofidone after the comparison in each test case?
|
i <= 8succeeds for the last time wheni = 8.
In the last iteration,i++is executed, theni <= 8fails becausei = 9.
Note that the,is asequence point, soi++is absolutely guaranteed to be executed beforei <= 8.Not so for similar constructs.
|
What is the correct macro to support code block and still be tolerant to type casting?
```
if (fooisneeded)
(void)foo();
```
#define foo() do {foo_subpart1(); foo_subpart2;} while(0): will not tolerate type cast
#define foo() 0; do {foo_subpart1(); foo_subpart2;} while(0): will break in bracelessif/<loop>
|
Using(void) foo()is just not possible with macros because that construct relies on a return type, which a macro, by its very nature, does not have. Neither does a macro have knowledge about C semantics or syntax, so computing a return type is impossible already.
What's the point anyway? Casting function expressions to(void)is intended to tell the compiler "you ain't gonna need it." A macro does not even return a value, it just does textual substitution. You ain't gonna need the "you ain't gonna need it."
Use aninlinefunction instead or just a function. If you need to do this sort of stuff, then macros are the wrong tool.
|
I have a string with a ton of\n's, I'd like to turn each of them into\001\n\001CW1. What's the easiest way to do this, using glib? No regex, just plain replace.
|
This can easily be done withg_strsplitandg_strjoinv:
```
char **split = g_strsplit(text, "\n", -1);
g_free(text);
text = g_strjoinv("\001\n\001CW1 ", split);
g_strfreev(split);
```
While this is a very common construct in scripting languages, it's a bit weird to do in C/with glib, but I guess it is the right/only way.
|
When I define
```
void tfooo(){
int arr[SOME_LARGE_NUMBER];
// some code here
}
```
I am getting stack overflow, but when I add the static keyword
```
void tfooo(){
static int arr[SOME_LARGE_NUMBER];
// some code here
}
```
everything is fine.
What is the difference? Isn’t static arrays as opposed to dynamic arrays always defined on the stack?
|
It is often the case that an object declared automatic is allocated on the stack (which is relatively small), whereas an object declaredstaticis allocated elsewhere.
Notice, this depends on your machine and on your compiler.
|
This question already has answers here:Division result is always zero [duplicate](4 answers)Dividing 1/n always returns 0.0 [duplicate](3 answers)Closed5 years ago.
```
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,i;
double abc,sum=0;
printf("Enter a value for x:");
scanf("%d",&x);
for(i=0;i<=6;i++)
{
abc=pow(1/2,i)*pow((x-1)/x,i+1);
sum=sum+abc;
}
printf("Sum is %f\n",sum);
}
```
As what i have checked there is no overflow of values in data type either or is it something else?
|
The issue is in this line of code:
```
abc=pow(1/2, i) * pow((x-1) / x, i + 1);
```
1/2is always zero, and(x - 1)/xis also zero whenx> 0. You can use0.5or1.0 / 2.0if you'd like to use a decimal value. Also, be careful about dividing by zero.
The resulting code would look like this:
```
abc=pow(0.5, i) * pow((x - 1.0)/x, i + 1.0);
```
|
I have tried to write this function using Macros
```
unsigned int put_0_right(unsigned int value, int order)
{
int i;
for(i=0; i<order; i++)
value=clear_bit(value,i);
return value;
}
```
so I wrote this
```
#define unsigned int mettre_0_droite(value, order)(\
{\
int i=0;\
for(i=0; i<order; i++)\
{value=clear_bit(value,i);}\
return value;\
})
```
but I am getting this errorexpected declaration specifiers or '...' before '{' token
|
the task is probably to do something like this.
```
#define mettre_0_droite(value, order) ((value) & (~((1ul << ((order) + 1)) - 1)))
```
instead of loops
And if you do not understand the difference between the function and the macro you need a good C book.
|
I want to use the comparison of two strings as a condition of a cycle,
but the cycle goes into infinite loop and I do not know why.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void input(int a[], char *comando, char *aux) {
fgets(aux, 35, stdin);
sscanf(aux, "%s %d %d", comando, &a[0], &a[1]);
}
int table_size=10;
int ar_temp[2];
char comando[2];
char aux[35];
int main() {
while((strcmp (comando, "X"))!=0 || (strcmp (comando, "x")!=0)) {
input(ar_temp, comando, aux);
}
return 0;
}
```
Help me please
|
The condition is wrong, the while statement always evaluated to true.
```
while((strcmp (comando, "X"))!=0 || (strcmp (comando, "x")!=0))
```
It should be:
```
while((strcmp (comando, "X"))!=0 && (strcmp (comando, "x")!=0))
```
|
I'm quite new to C and I know that * is a pointer.
```
Person * father = (Person *) malloc(sizeof(Person));
Marriage * marriage = (Marriage *) malloc(sizeof(Marriage));
(* marriage).male = father;
```
My question here is why does the * sometimes come before and sometimes after? What is the reason for this?
|
Person *is a pointer to Person type(Person *)is a C type casting to the pointer to Person type (read up on type-casting if you're unfamiliar)(* marriage)is dereferencing the marriage pointer, which is basically accessing the variable stored in the memory location pointed to by the pointer. Also a tip, since marriage appears to be a pointer to a struct and you're accessing a member of that struct, you can avoid the(*marriage).malesyntax and use the->operator like thismarriage->male
|
I have this code:
```
const char *linesep = "\n";
char buffer[10];
buffer[0] = 'L';
```
How can I check linesep and buffer[0] are the same? Like using strcmp.
Thanks in Advance!
|
If you only want to compare acharto acharyou could simply do this:
```
#include <stdio.h>
int main(void)
{
const char *linesep = "\n";
char buffer[10];
buffer[0] = 'L';
printf("%s", linesep[0] == buffer[0] ? "same" : "not same");
return 0;
}
```
Demo:https://ideone.com/kUqkRC
|
I got this code:
```
const char *newLine = "\n";
printf('Content: %c\n', *newLine);
```
What happens now is a memory error.
Why is that happening?
|
The code crashes with a memory error (segmentation fault) becauseprintfexpects a null-terminated string as the first argument (i.e. a valid address pointing to some characters ending in a zero byte), but you are passing an (effectively random) integer to it which is not a valid address (unless you are very, very lucky :-).
As people commented, use double quotes to pass an actual string allocated by the compiler somewhere:
```
const char *newLine = "\n";
printf("Content: %c\n", *newLine);
```
|
```
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
struct name{
char array[8];
};
struct name na;
memset(&na.array,0,8);
}
```
It is the samememset(&na.array,0,8);thatmemset(na.array,0,8); ?
and it is the samena.arraythat&na.array[0]?
|
It is the same memset(&na.array,0,8); that memset(na.array,0,8); ?
Yes.
However, this only means that both variants behave equivalently.&na.arrayandna.arrayhave very different types.
na.arrayis of typechar[8], an array of eightchars.&na.arrayis of typechar(*)[8], apointerto an array of eightchars.
and it is the same na.array that &na.array[0] ?
Strictly speaking, no.na.arrayis actually of typechar[8]while&na.array[0]is of typechar *. However, there is an implicit conversion rule fromchar[8]tochar *, which is calleddecay. So,na.arraycandecayto achar *, which is precisely the type of&na.array[0].
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.