question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I'm making a school project and I'm having some trouble.
I have this yacc grammer
```
FILE : '{' GEOMETRY '}'
;
GEOMETRY : key_type ':' value_point ',' key_coordinates ':' PONTO
;
PONTO : VETOR_MIN2 { printf("%s", $<str>1); }
;
VETOR_MIN2 : '[' numero ',' numero ']'
;
```
When I make that printf in the non terminal PONTO I only get this:[
but I should get something like this:[20, 10]What it's missing here? Please help.
Thanks for your time.
|
The semantic value of a rule is the value that resides in$$after that rule's actions have been run. If a rule does not have any actions (as is the case forVECTOR_MIN2), the default action is$$ = $1;(unless there is no$1or the types don't match, in which case there is no default action).
If you wantVECTOR_MIN2to produce a different value, you'll need to add an action and assign a different value to$$.
|
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.
|
I'm making a school project and I'm having some trouble.
I have this yacc grammer
```
FILE : '{' GEOMETRY '}'
;
GEOMETRY : key_type ':' value_point ',' key_coordinates ':' PONTO
;
PONTO : VETOR_MIN2 { printf("%s", $<str>1); }
;
VETOR_MIN2 : '[' numero ',' numero ']'
;
```
When I make that printf in the non terminal PONTO I only get this:[
but I should get something like this:[20, 10]What it's missing here? Please help.
Thanks for your time.
|
The semantic value of a rule is the value that resides in$$after that rule's actions have been run. If a rule does not have any actions (as is the case forVECTOR_MIN2), the default action is$$ = $1;(unless there is no$1or the types don't match, in which case there is no default action).
If you wantVECTOR_MIN2to produce a different value, you'll need to add an action and assign a different value to$$.
|
This question already has answers here:C function syntax, parameter types declared after parameter list(7 answers)Closed4 years ago.
My friend asked me could I add "frozen top line" feature to the standardless*NIX program. I started to view the source and was very surprised in function definition thefilename.c:
```
public char *
last_component(name)
char *name;
{
....
}
```
I wrote some code at the C and usually I met:
return_type function_name arguments_list;if it is function prototypereturn_type function_name arguments_list code-blockif it is function definition.
But here I found something new:return_type function_name arguments listsomething_mysterious;code block.
What does this syntax means?
|
This is old C syntax (also known as K&R style), where a function definition could be written as where the argument are declared on the subsequent line:
```
int func(a,b)
int a;
char b;
{
```
|
This question already has answers here:C: Which character should be used for ptrdiff_t in printf?(3 answers)Closed4 years ago.
I am trying to subtract 2 pointers such that they such give the number of elements.I could compile the program and run it .But after compilation it is throwing error as
pointerarithmetic.c: In function ‘main’:
pointerarithmetic.c:9:8: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
printf("%d",(q-p));
The code:
```
#include<stdio.h>
int main(){
int a[5]={0,10,20,30,40};
int *p,*q;
p=&a[0];
q=&a[2];
printf("%d",*p);
printf("%d",*q);
printf("%d",(q-p));
return 0;
}
```
The expected output should be number of elements.
|
Subtraction of pointers return a typeptrdiff_t(defined instddef.h), not an int.
Use%tdto print the result.
|
What does the functiontoascii()do?
Is there any practical use for it?
Note: This is not about the Windows functionToAscii.
|
Assuming you are talking about the POSIXtoascii, it says what it does right in themanpage.
toascii() converts c to a 7-bit unsigned char value that fits into the ASCII character set, by clearing the high-order bits.
If you need to ensure a value only uses the lowest seven bits, then you have a use for it, but you're probably more likely to bitwise-AND the value with0x7F.
|
Recently I saw in one project where they typedef int as BOOL and used it in place of bool. Does doing so provides any advantages?
```
typedef int BOOL;
```
|
One might do so if they were interfacing a lot with C code. Since C does not have abooltype - at least not untill C11 (I think it was, or maybe C99) introduced the_Booltype - which I can't honestly remember if is compatible with C++bool- they should have just adopted theboolkeyword (IMHO), but I digress.
Also, it is common in old C++ code bases that pre-date the C++98 standard where C++ gainedbool.
SolegacyandC compatibilityis the answer.
|
I know title sounds weird but I didn't know how to write it. I have simple structure:
```
struct student_t
{
char name[20];
char surname[40];
int index;
};
```
I also have function that have only one argument and it's pointer to this structure. I want to check single chars from string in structure but I don't know how to get to them.
I tried few things
```
p->name
```
Prints whole string.
```
*p->name
```
Prints first letter of string.
I thought that by adding numbers to pointer , I can move through string.
But when I try to use
```
*(p+n)->name
```
it prints 0.
I'm new in C, feel free to hate.
|
As EugeneSh commented:*(p->name + n)
|
What does the functiontoascii()do?
Is there any practical use for it?
Note: This is not about the Windows functionToAscii.
|
Assuming you are talking about the POSIXtoascii, it says what it does right in themanpage.
toascii() converts c to a 7-bit unsigned char value that fits into the ASCII character set, by clearing the high-order bits.
If you need to ensure a value only uses the lowest seven bits, then you have a use for it, but you're probably more likely to bitwise-AND the value with0x7F.
|
Recently I saw in one project where they typedef int as BOOL and used it in place of bool. Does doing so provides any advantages?
```
typedef int BOOL;
```
|
One might do so if they were interfacing a lot with C code. Since C does not have abooltype - at least not untill C11 (I think it was, or maybe C99) introduced the_Booltype - which I can't honestly remember if is compatible with C++bool- they should have just adopted theboolkeyword (IMHO), but I digress.
Also, it is common in old C++ code bases that pre-date the C++98 standard where C++ gainedbool.
SolegacyandC compatibilityis the answer.
|
I am doing some blob analysis on an embedded STM32H7 platform using C.
What do you think would be best way to accomplish this? Would it be possible to port openCV to STM32 and use those functions maybe? Let say I just want to use adaptive thresholding, would it be better to just write my own code for that or use some library that is already there?
Just to point out that I am obligated to use C. I know about some Python libraries for STM32 but I must use C for this project.
Thank you!
|
Writing your own functions is trivial. I have done minor on the subject and we had about 8 weeks to do it.
Porting OpenCV is not a good idea. It uses dynamic memory allocation everywhere which makes conservative use impossible and is written in C++.
Adaptive tresholding would take max a week of effort.
|
Official JNI API does specify if the copy is made while creating ajstringfromconst char *. Here is the quote:
```
NewStringUTF
jstring NewStringUTF(JNIEnv *env, const char *bytes);
```
Constructs a newjava.lang.Stringobject from an array of characters
in modified UTF-8 encoding.
Does it mean the copy ofconst char *is made or I have tostrdupit by myself?
|
NewStringUTFcreates a new String object in Java Heap. The string is backed by abyte[]orchar[]array in Java Heap, and it does not share any off-heap data you pass in.
So, you don't needstrdup, the contents will be copied (and possibly converted) to Java Heap anyway.
|
Why am I getting
duplicate ‘const’ declaration specifier [-Wduplicate-decl-specifier]
for this declaration?
```
extern uint8_t CalculateChecksum(const communicationBlock_t const *messageBlock);
```
WherecommunicationBlock_tis a struct.
I don't the function to be able to change the structure pointed to by the parameter, nor do I want it to be able to point that parameter elsewhere.
What am I doing wrongly?
|
Both of theconstkeywords you wrote apply tocommunicationBlock_t. You probably wanted this:
```
extern uint8_t CalculateChecksum(const communicationBlock_t * const messageBlock);
```
The rule is:constapplies to the left, unless it's the leftmost specifier, then it applies to the right.
|
As some function like MD5 can take input of variable length string/byte-array, and output a fixed length value byte-array(i.e. In hex). I want some standard function that can input variable length string/byte-array and output a user defined length byte-array/string.
Is there any way to do so?
|
You can use extendable-output function(XOF) like SHAKE-128/SHAKE-256 defined inNIST.FIPS-202.
Incyou can implememntSHAKE-128and can call in main() as:
```
shake128(0,shake_key,&shake_context); //set key for shake
shake128(output_len, output_var, &shake_context) //hash function
```
Instead of creating a fixed-length digest (e.g. like MD5/SHA-2/256), it can produce outputs of any desidered length.
|
Why am I getting
duplicate ‘const’ declaration specifier [-Wduplicate-decl-specifier]
for this declaration?
```
extern uint8_t CalculateChecksum(const communicationBlock_t const *messageBlock);
```
WherecommunicationBlock_tis a struct.
I don't the function to be able to change the structure pointed to by the parameter, nor do I want it to be able to point that parameter elsewhere.
What am I doing wrongly?
|
Both of theconstkeywords you wrote apply tocommunicationBlock_t. You probably wanted this:
```
extern uint8_t CalculateChecksum(const communicationBlock_t * const messageBlock);
```
The rule is:constapplies to the left, unless it's the leftmost specifier, then it applies to the right.
|
As some function like MD5 can take input of variable length string/byte-array, and output a fixed length value byte-array(i.e. In hex). I want some standard function that can input variable length string/byte-array and output a user defined length byte-array/string.
Is there any way to do so?
|
You can use extendable-output function(XOF) like SHAKE-128/SHAKE-256 defined inNIST.FIPS-202.
Incyou can implememntSHAKE-128and can call in main() as:
```
shake128(0,shake_key,&shake_context); //set key for shake
shake128(output_len, output_var, &shake_context) //hash function
```
Instead of creating a fixed-length digest (e.g. like MD5/SHA-2/256), it can produce outputs of any desidered length.
|
I have this code:
```
#include <stdio.h>
int func(unsigned int *a) {
printf("(func) Value: %d\n", *a);
}
int main() {
unsigned char a = 255;
printf("Value: %d\n", a);
printf("Bytes: %d %d %d %d\n\n", *&a, *(&a + 1), *(&a + 2), *(&a + 3));
func((unsigned int *) &a);
return 0;
}
```
I have the output of this program:
```
Value: 255
Bytes: 255 0 22 234
(func) Value: -367656705
```
Why i have negative func value, though the type is unsigned int?
|
Why i have negative func value, though the type is unsigned int?
```
int func(unsigned int *a) {
printf("(func) Value: %d\n", *a);
// ^^
}
```
Because%ddoes not match type of*a
|
I've tried changing it to double quotes, but this is wrong. I also tried figuring out what it means, but the compiler keeps giving me the same error.
[Error] empty character constant
Code
```
#include <stdio.h>
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for(i = 0; i < 10; i++)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if(c >= '0' && c <= '9')
++ndigit[c - '0'];
else if (c == '' || c == '\n' || c == '\n')
++nwhite;
else
++nother;
printf("digits = ");
for(i = 0; i < 10; i++)
printf ("%d", ndigit[i]);
printf(", white space = %d, other = %d \n", nwhite, nother);
}
```
|
The empty character constant error is because of the following comparison in theelse ifclause.
```
c == '' // '' is empty
```
Replace''with' '.
|
There is an 1-D array with elements {5,30,99,60,5,10}.
From this array, 1 sub-sequence is 5, 99 and 10 which sums up to a value of 114. Other sub-sequences sum are lesser than 114.
Two elements should not be contiguous in the sub-sequence ie {5, 30 and 60} is not a valid sub-sequence (for this problem). It can be either {5, 99, 5} or {30, 60, 10} etc. The array doesn't contain negative numbers.
What approach will be the right way to calculate this maximum sum? I am trying to implement it in C.
|
Recursion is your friend here
Sum is the maximum of
5 + maxSum of {99, 60, 5, 10}
or discard 5 in favor of 30 and
30 + maxSum of {60, 5, 10}
Assuming you do not have any negative numbers, you should use either5or30and then the remaining sequence. Discarding both of them does not make sense.
|
There is an 1-D array with elements {5,30,99,60,5,10}.
From this array, 1 sub-sequence is 5, 99 and 10 which sums up to a value of 114. Other sub-sequences sum are lesser than 114.
Two elements should not be contiguous in the sub-sequence ie {5, 30 and 60} is not a valid sub-sequence (for this problem). It can be either {5, 99, 5} or {30, 60, 10} etc. The array doesn't contain negative numbers.
What approach will be the right way to calculate this maximum sum? I am trying to implement it in C.
|
Recursion is your friend here
Sum is the maximum of
5 + maxSum of {99, 60, 5, 10}
or discard 5 in favor of 30 and
30 + maxSum of {60, 5, 10}
Assuming you do not have any negative numbers, you should use either5or30and then the remaining sequence. Discarding both of them does not make sense.
|
I don't know what datatypes can be used with enum in c programming
|
An enumeration is a set of named integer constant values (C 2018 6.2.5 16).
An enumeration constant has typeint(C 2018 6.4.4.3 2).
An enumerated type is compatible withcharor a signed or unsigned integer type (C 2018 6.7.2.2 4). The choice is implementation-defined, which means it is up to your C compiler.
Thus, the size of an enumeration type depends on your C compiler.
For example, inenum color { red, green, blue };:
Each ofred,green, andblueis an enumeration constant. It is a constant of typeint, and its size is that of anintin your C implementation.The enumeration type,enum color, could bechar,signed short,unsigned int, or other possibilities.
|
I'm trying to print an int array, but it gives me an error.
error: lvalue required as increment operand
```
int *a[] = {1,2,3,4,5};
for(int i=0;i<5;i++)
{
printf("%d",*a);
a++;
}
```
|
int *a[]means an array of pointers to ints. You want an array of ints here, so useint a[].
You can't incrementabecauseais an array, not a pointer. Arrays sometimes decay to pointers to the first element, but you can't modify that pointer. Instead, make a pointer pointing to the elements in the array likeint *p = aor use the subscript operator likea[i]to access the elements.
|
Is it possible to undefine a macro at run time?
This is what I tried:
```
for(int i=2; i<argc; i++){
if(strcasecmp(argv[i], "+debug")==0){
puts("+debug");
#ifndef DEBUG
#define DEBUG
#endif
}
if(strcasecmp(argv[i], "-debug")==0){
puts("-debug");
#ifdef DEBUG
#undef DEBUG
#endif
}
```
I compiled the code with the macroDEBUGdefined. What it does is, it will display all messages on standard output. If not defined, it will not display those messages. So when I run the application with the option-debug, it should undefine the macro. But it did not! I still get messages on console!
Anyone care to help?
|
No you can't. Macros are replaced at thepreprocessorstage so never make it into the final program.
|
After defining the type student (which is a struct made of two arrays of characters and an int), I've created an array of pointers to student, which I need in order to modify its content inside of a series of functions.
```
int main(void)
{
student* students[NUMBER_OF_STUDENTS];
strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;
return EXIT_SUCCESS;
}
```
My problem is that this simple piece of code returns -1 as exit status after running. Why is that?
|
The pointerstudents[0]is uninitialized. Dereferencing it results in undefined behavior.
Initialize it with the address of a valid object before attempting to access it.
```
student test;
students[0] = &test;
strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;
```
|
I need to call a series of functions that require a list in an input array as following:
```
1st call to func:
custom_type_t inarray = {1,2,3,4,5,6,7,8,9,10};
2nd call to func:
custom_type_t inarray = {11,12,13,14,15,16,17,18,19,20};
...
```
How can I pack this into a function that I can call with a particular argument, that will extract the numbers and populate the array accordingly?
Should I use the precompiler accordingly? Thanks for any ideas!
|
```
for(int i = 1; i < 11; i++) inarray[i - 1] = i;
for(int i = 11; i < 21; i++) inarray[i - 11] = i;
```
|
Is it possible to undefine a macro at run time?
This is what I tried:
```
for(int i=2; i<argc; i++){
if(strcasecmp(argv[i], "+debug")==0){
puts("+debug");
#ifndef DEBUG
#define DEBUG
#endif
}
if(strcasecmp(argv[i], "-debug")==0){
puts("-debug");
#ifdef DEBUG
#undef DEBUG
#endif
}
```
I compiled the code with the macroDEBUGdefined. What it does is, it will display all messages on standard output. If not defined, it will not display those messages. So when I run the application with the option-debug, it should undefine the macro. But it did not! I still get messages on console!
Anyone care to help?
|
No you can't. Macros are replaced at thepreprocessorstage so never make it into the final program.
|
How can I make an iterator over a dynamic array (in a struct)?
|
Your dynamic array, as represented by typestruct _Lista,does notcontain "elements of any type". At least not directly. It contains only and exactly elements of typevoid *. Pretty much everything you've written will work if you change typeiteratoraccordingly, to adoublepointer:
```
typedef void **iterator;
```
Do note, however, that this iterator implementation has a severe flaw: it does not carry any information about the bounds of the list. That may be OK if you ensure that there is a sentinel value after the last valid element (and maybe before the first, too), but otherwise you'll need a more complex data structure than just one pointer.
|
I'm try to connect my ESP8266 to wifi router usingAT+CWJAPbut I have a problem cannot read esp8266 response to my arduino.
When I try to sendATto esp from arduino code it can't readOKResponse from esp8266Serial.find("OK")not working. I change the baud rate into 115200 it didn't work too
This is serial capture:
```
> 14:04:45.882 -> AT
> 14:04:51.868 -> NOT OK!
> 14:04:51.901 -> AT+CIPSTART="TCP","184.106.153.149",80
> 14:04:54.899 -> AT+CIPSEND=55
> 14:04:55.873 -> AT+CIPCLOSE
```
This is the arduino code:
```
void setup()
{
Serial.begin(9600); //or use default 115200.
Serial.println("AT");
delay(5000);
if(Serial.find("OK")){
connectWiFi();
}
else{
Serial.println("NOT OK!");
}
}
```
It should runConnectWiFi()Function but the output is "NOT OK!"
|
Your baudrate isincorrect. It should be115200.
|
Disclaimer: I'm not writing code like this, I know it's ugly and unreadable.
I'm generating C, and I need everything to be in one expression.
This works:
```
#define true 1
int a = (true) ? ( (true) ? (puts("a"), puts("b"), 1) : (2) ) : (3);
printf("%d\n", a);
```
```
a
b
1
```
But I also need to have statements, not just expressions. This fails to compile:
```
int a = (true) ? ( (true) ? (puts("a"), puts("b"), (if (true) puts("c");), 1) : (2) ) : (3);
```
```
error: expected expression
```
Is it impossible to achieve in C?
|
Using thegcc extension, you can wrap around the statements in braces, like
```
int a = (true) ? ( (true) ? (puts("a"), puts("b"), ({if (true) puts("c");}), 1) : (2) ) : (3);
```
|
I need a function or API to get a word after a particular word and store it in a string in C?For example:
```
char str[] = "This is a sample sentence for demo";
char x[10];
```
Now I need to store the word between"sample"and"for"(i.e. sentence) in stringx. How can I do that?
|
How to get a word in a string after a particular word?
Step 1, find the position of"sample"instr.
```
const char *pos = strstr(str, "sample");
```
Step 2: scan from there looking for the next "word"
```
char x[10];
// v-v--------- "sample"
// v-v----- Next word
if (pos && sscanf(pos, "%*s %9s", x) == 1) {
printf("Success <%s>\n", x);
} else {
printf("Key or following word not found\n", x);
}
```
|
I'm trying to make the terminal wait an x numbers of seconds before printing something on screen. I literally copied the code from somewhere else online but my terminal just doesn't wait any time at all and executes everything altogether as it normally would.
Do you guys know why this happens?
```
for(int i = 0; i < 5; i++){
delay(5);
printf(". ");
}
void delay(int number_of_seconds)
{
// Converting time into milli_seconds
int milli_seconds = 1000 * number_of_seconds;
// Stroing start time
clock_t start_time = clock();
// looping till required time is not acheived
while (clock() < start_time + milli_seconds)
;
}
```
|
There's a "sleep" function, on unistd.h
```
#include <unistd.h>
//something your code
sleep(seconds);
```
Hope that helps
|
I want to have deprecation warnings(C4996, the ones caused by calling functions like strcpy) disabled by default in all C/C++ projects in Visual Studio 2019.
There are several ways on the internet on how to do it, but they are all on a per-project basis, the most straightforward way is to add _CRT_SECURE_NO_WARNINGS to the preprocessor definitions. But I want to achieve this effect automatically, without having to fiddle with the project setting each time I make a new project.
I know there must be a way. I don't care how "hacky" the method is. Using the safe variants of the functions isn't an option for me.
|
You can create custom project templates in Visual Studio, so you should be able to create one of these with whatever#definesyou want pre-configured in the properties page.
MS documentation ishereand a guy called Srinivasa Rao Dhulipalla has blogged about ithere
|
I'm try to connect my ESP8266 to wifi router usingAT+CWJAPbut I have a problem cannot read esp8266 response to my arduino.
When I try to sendATto esp from arduino code it can't readOKResponse from esp8266Serial.find("OK")not working. I change the baud rate into 115200 it didn't work too
This is serial capture:
```
> 14:04:45.882 -> AT
> 14:04:51.868 -> NOT OK!
> 14:04:51.901 -> AT+CIPSTART="TCP","184.106.153.149",80
> 14:04:54.899 -> AT+CIPSEND=55
> 14:04:55.873 -> AT+CIPCLOSE
```
This is the arduino code:
```
void setup()
{
Serial.begin(9600); //or use default 115200.
Serial.println("AT");
delay(5000);
if(Serial.find("OK")){
connectWiFi();
}
else{
Serial.println("NOT OK!");
}
}
```
It should runConnectWiFi()Function but the output is "NOT OK!"
|
Your baudrate isincorrect. It should be115200.
|
Disclaimer: I'm not writing code like this, I know it's ugly and unreadable.
I'm generating C, and I need everything to be in one expression.
This works:
```
#define true 1
int a = (true) ? ( (true) ? (puts("a"), puts("b"), 1) : (2) ) : (3);
printf("%d\n", a);
```
```
a
b
1
```
But I also need to have statements, not just expressions. This fails to compile:
```
int a = (true) ? ( (true) ? (puts("a"), puts("b"), (if (true) puts("c");), 1) : (2) ) : (3);
```
```
error: expected expression
```
Is it impossible to achieve in C?
|
Using thegcc extension, you can wrap around the statements in braces, like
```
int a = (true) ? ( (true) ? (puts("a"), puts("b"), ({if (true) puts("c");}), 1) : (2) ) : (3);
```
|
I need a function or API to get a word after a particular word and store it in a string in C?For example:
```
char str[] = "This is a sample sentence for demo";
char x[10];
```
Now I need to store the word between"sample"and"for"(i.e. sentence) in stringx. How can I do that?
|
How to get a word in a string after a particular word?
Step 1, find the position of"sample"instr.
```
const char *pos = strstr(str, "sample");
```
Step 2: scan from there looking for the next "word"
```
char x[10];
// v-v--------- "sample"
// v-v----- Next word
if (pos && sscanf(pos, "%*s %9s", x) == 1) {
printf("Success <%s>\n", x);
} else {
printf("Key or following word not found\n", x);
}
```
|
I'm trying to make the terminal wait an x numbers of seconds before printing something on screen. I literally copied the code from somewhere else online but my terminal just doesn't wait any time at all and executes everything altogether as it normally would.
Do you guys know why this happens?
```
for(int i = 0; i < 5; i++){
delay(5);
printf(". ");
}
void delay(int number_of_seconds)
{
// Converting time into milli_seconds
int milli_seconds = 1000 * number_of_seconds;
// Stroing start time
clock_t start_time = clock();
// looping till required time is not acheived
while (clock() < start_time + milli_seconds)
;
}
```
|
There's a "sleep" function, on unistd.h
```
#include <unistd.h>
//something your code
sleep(seconds);
```
Hope that helps
|
I want to have deprecation warnings(C4996, the ones caused by calling functions like strcpy) disabled by default in all C/C++ projects in Visual Studio 2019.
There are several ways on the internet on how to do it, but they are all on a per-project basis, the most straightforward way is to add _CRT_SECURE_NO_WARNINGS to the preprocessor definitions. But I want to achieve this effect automatically, without having to fiddle with the project setting each time I make a new project.
I know there must be a way. I don't care how "hacky" the method is. Using the safe variants of the functions isn't an option for me.
|
You can create custom project templates in Visual Studio, so you should be able to create one of these with whatever#definesyou want pre-configured in the properties page.
MS documentation ishereand a guy called Srinivasa Rao Dhulipalla has blogged about ithere
|
The ISO C standard says that:
```
sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long)
```
I am using GCC-8 on BIT Linux mint (19.1) and the size oflong intis8.
I am using an app which uses GCC 7 and the compiler is 64-bit.
The size oflong intis4.
Does the compiler or the operating system define the size of along int?
|
The compiler calls all the shots. The operating system just runs the resulting binary.
That being said, the compiler will normally make an executable the operating system can use, so there's some interplay here. Since things like the size ofintdon't really matterso long as they're consistent, you will see variation.
In other words, if the kernel expectslong intto be 8 bytes because of how it was compiled, then you'll want to compile that way to match or your compiled code won't match and none of the shared libraries will work.
|
What does this statement mean in C language (assuming s1 and s2 are character arrays)?
```
(s1[i] = s2[i]) != '\0'
```
|
Consideringstrings are\0terminated by the standard.
```
(s1[i] = s2[i]) != '\0'
```
it will assigns2[i]tos1[i]then it will compare whether assigned value is\0or not.
It is usually used to break the loop while copying contents from one string to another.
|
I am using a bunch of macros of type:
```
#define Q31_TO_Q30 (31-30)
#define Q31_TO_Q20 (31-20)
#define Q25_TO_Q15 (25-15)
etc.
```
I would like to generalize this without having to manualy add each case.Qs go from 1 to 31, so there would be huge number of lines to cover all cases.
#define Q_TO_Q(x,y) (x-y)seems easy, but I would like to continue using the sameQx_TO_Qysyntax because of the "backwards compatibility".
Is some kind of macro magic possible that would achieve this?
|
Sadly, no. Macros cannot define other macros.
|
I am using a struct like:
```
struct{
int a;
char b[100];
}name;
```
I want to usestaticstorage class specifier onname.
How can I do that?
|
use the wordstaticin front of it:
```
static struct{
int a;
char b[100];
} name;
```
This will declare a variable namednamewith the typestruct { ... }and the storage class specifierstatic.
To initialize the member of thestruct, you can use
```
static struct{
int a;
char b[100];
} name = {5};
```
|
I have an input texture in a certain resolution, and a target texture (attached asGL_COLOR_ATTACHMENT0) which is in a bigger resolution. I am usingglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)to upscale the input and draw some stuff on the target.
I have a buffer which is in the same resolution as my input that I would like to use asGL_STENCIL_ATTACHMENT.
Is it possible to attach it somehow without getting an error ofGL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS?
|
It is not possible to attach textures with different sizes to a framebuffer.
TheOpenGL-ES 2.0 Specstates in Section 4.4:
The framebuffer object target is said to be framebuffer complete [...] if all the following conditons are true:All attached images have the same width and height.
If this is not the case, the framebuffer status has to returnFRAMEBUFFER_INCOMPLETE_DIMENSIONS.
|
I am learning Structures and linked lists. When using a double structure pointer as head , I can't make it to direct to next element without using another structure pointer.
```
void pop(struct stack **headref,int element)
{
struct stack *pop1=*headref;
if(pop1==NULL)
{
return 0;
}
if(r==0)
{
printf("%d %d",*headref,pop1);
//*headref=*headref->next why doesnt this line work?
*headref=pop1->next;
free(pop1);
return 1;
}
}
```
|
->has higher precedence than*.
*headref->nextmeans*(headref->next), whilepop1->nextis equivalent to(*headref)->next.
In other words, you don't needpop1if you add a pair of parentheses.
|
The ncurses library has a functions that change local scope variables without any pointers. For example:
```
int x, y;
getyx(stdscr, y, x); //to get the current position of the cursor
```
How does this happen?
|
getyxis not a function, but a macro.
(Ignore the very confusingvoidreturn type on that manpage; the prose underneath tells us the truth!)
NotesAll of these interfaces are macros. A "&" is not necessary before the variablesyandx.
It does not introduce or use a new scope, so has direct "access" toxandyas they are.
As an analogy, consider how the following works without a&:
```
#define doubleIt(x) x *= 2
int main()
{
int x = 1;
doubleIt(x);
}
```
|
If the size of a buffer array is 100 and I read 100 bytes from a file usingread(), can there be a possibility of overflow as there is no null terminating byte? I am reading from a file and then writing to standard output.
```
int incoming_bytes = read(filedes, buffer, 100);
write(1, buffer, incoming_bytes);
```
|
read()andwrite()don't work with strings, but with buffers, and as such they don't need to know their contents, just their size.
As long as you only use the buffer towriteintostdout, you won't have any overrun problems.
'\0'is only needed for strings.
The problem may come if you later treat that buffer as a string. In that case, you will most probably overrun it.
|
I'm running a simple calculation in C, for which, sometimes, the result is exactly 0. I then print these results using something likeprintf("%0.4g", result). If the result is not 0, it does what I want it do, e.g., the output may be1.796e+04. However, if the result is exactly 0, which it often is, the output will be0.
My question is, what can I do to print0.0000, with 4 decimals, even though the number there might be exactly 0?
|
To have 4 decimals, you have to specify.5. To have0print as0.0, you have to add#.
```
printf("%#.5g", 0.0);
```
Note that this will print4decimal places, unlike%0.4g, that will print 3 decimal places.
The0before the dot.is unneeded. It is used to specify, that the field should be prefixed with zeros not with spaces when matching a field length. But you don't specify the field length, so no prefixing takes place, so the0can be left out.
|
I want to print a line:
```
for(i=0;i<n;i++)
printf("this is iteration number %d\n", i);
```
From this I will get output as:
this is iteration number 0
this is iteration number 1
...
But I want that only one line is printed and the value changes.
That is I want to overwrite each line.
Now if I print some another line (lets call it line2) but I need to overwrite the previous line without affecting the line2.
|
Not the most refined solution, but you can use a "carriage return"\rand flushstdoutlike this:
```
#include <stdio.h>
#include <unistd.h>
int main()
{
for (int i = 0; i < 10; i++) {
printf("\rValue of i is: %d", i);
fflush(stdout);
sleep(1);
}
}
```
|
I have a program that went like this:
```
//this is main.c
#include <stdio.h>
#include <stdlib.h>
...
#include "fileA.c"
#include "fileB.c"
...
//rest of main file
```
which worked fine but now when I replicated the exact same project (in VS) all the other files in the project don't seem to recognize the standard library #includes from some reason.
any help please?
|
Other files are independent files. As such, you must include the relevant header files in those files as well. Also, it is not considered a good practice to include .c files as it can easily result in linking errors due to multiple definitions.
|
Hey all I've been working on a program using two queues. Where a stream of numbers enters one queue and is then dequeued from the first queue and enqueues to a second queue.
I've tried everything I can think of but nothing seems to work, I can't find anything online either.
|
Assuming you are queueing and dequeueing NODE structs containing the actual data, consider the following:
The dequeue function of your queue data structure should return the dequeued struct (or a pointer to it). By doing this you can simply write
```
NODE *node_dequeued_from_queue1 = Dequeue(&queue1);
Enqueue(&queue2, node_dequeued_from_queue1->data);
```
Wheredequeued_datais a node struct containing a member data of type int.
|
Actually i compiled this in a online c compiler, the output of the code was 5... how did the processing take place??
```
#include <stdio.h>
int main()
{
struct ab {char a,b;};
union abcd
{
int c;
struct ab d;
}k;
k.d.a=5;
k.d.b=0;
printf("%d",k.c);
}
```
|
you have an union between an integer and a structure containing 2 chars.
The code is changing the first char of the structure. Because of the union, it affects the first byte of the other union member, which is the integer.
On a little-endian machine, setting the first byte of an integer to 5 makes this integer 5 and that's what you're seeing here.
On a big-endian machine you end up with a very big value depending of the actual size of an integer.
|
As homework, I have to write a function that changes an array's size usingmallocandfreefunctions only.
I know how to do it withrealloc, but I don't know how to do it withmalloc.
```
typedef struct{
int *tab;
int size;
}arr;
```
and I need to write this function :
```
void changeSizeDyn(arr *Dyn_arr, int size){
//
}
```
As mentioned in the homework: it requires only one reallocation and only one memory release, and only one copy of the elements from the old array.
I searched a lot but only found results usingrealloc.
Is it even possible to do that without usingrealloc?
|
Allocate memory of the new size using malloc.Copy all bytes from the old memory to the new memory. You can do that in a loop, you don't actually need to use functions for this (if that is the assignment).Free the old memory.
|
I tried to play multiple sounds simultaneously using Media Foundation. I created multiple Media Sessions and loaded multiple IMFMediaSources. But the problem is that IMFMediaSource can't be used again during playback. Is there any better way to allow simultaneous playback? Multiple audio or repeat one of them?
|
Could you elaborate a bit more ?
For example, you can restart a IMFMediaSource to reapeat it :
IMFMediaSource::Start:
Starts, seeks, or restarts the media source by specifying where to start playback.
Or you can simply stop the source and then start again :
IMFMediaSource::Stop
When a media source is stopped, its current position reverts to zero. After that, if the Start method is called with VT_EMPTY for the starting position, playback starts from the beginning of the presentation.
PS : I agree with Mgetz, if you only play simple wav files, XAudio2 is an option. Tell us your audio file format.
|
I learned pointers and arrays already but I don't know what ** or && is used for and when trying to understand this line im not sure what this is.
```
int main() {
srand(time(NULL));
int n, m, option, row, col, flagCount = 0;
char **flags, **board;
```
im not sure what's being declared in the 4th row also those pointers at list I think they are are later in the program being sent to this function .
```
char **creatArray(int n)
```
what is this (**) used for in the function type?
|
*is a pointer type,**is a pointer type to a pointer, for example:int* p;, meaning thatpis a pointer type that points toint, and if you need a pointer type to thisppointer, you can do the following definition:int** test = &p;At this pointtestis a pointer top, its type isint**.
|
I want to create a function in C with variable length arguments in which I may not want to pass any variable at some point. I such a thing possible in C? I would like some code snippets if possible. Also, I have to mention that the function will have passed only char* variables when there are passed some variables.
|
A function with variable arguments must have at least one names argument in order to read the others.
For your particular case, since you want to pass a list ofchar *arguments you can use NULL to denote the end of the argument list. So in the case where there is nothing to pass, you just pass a singe NULL argument.
|
I want to save some characters from one string to another.
I tried going from character to character from one string and saving them to the other string.
```
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *sent, *rec;
int i, a;
sent = malloc(100);
rec = malloc(100);
gets(sent);
a = strlen(sent);
for (i = 0; i < 3; i++)
*(rec + i) = *(sent + i);
a = strlen(rec);
rec = realloc(rec, 4);
puts(rec);
}
```
If I input "Hello world" the expected output should be"Hel", but it is "Hel" and some random characters.And also I dont understand why is the lenght of rec equal to 14.
|
```
memcpy(rec,sent,3)
rec[3] = 0;
```
or more general
```
memcpy(rec,sent,len)
rec[len] = 0;
```
|
This question already has answers here:Why is *p++ different from *p += 1?(4 answers)C - pointer behavior with pre and post increment(7 answers)Closed4 years ago.
In my program i have tried to increment pointer but i am not sure why that when i use *pointer++ it does nor seem to work and it returns 1 as the new value.
I tried using "*pointer++" in my program like you would use a pointer as an array
using*pointer=*pointer+1.but it seems that when i use just "*pointer++" the value changes to one
but when i use(*pointer)++it works .why?
```
Node=(node *)malloc(num*sizeof(node));
printf("%d",Node);
Node++;
printf("%d",Node);
```
|
*pointer++dereferences the object and increases thepointeritself and after the sequence point it points (references) to the next object.
(*pointer)++dereferences thepointerand increases (after the sequence point) only the referenced object and leaves thepointernot changed
|
Say you have a several function like this:
```
void Inventory(int index, char input[], int qty)
void AddItem(){
int index = Inventory(index);
if (int i = 0; i < index; i++){
...
}
}
```
But it gave me an error 'A value of type "Void" cannot be used to initialize an entity of type "int"'
Can someone explain to me in detail since im new to programming too.
|
You're trying to initializeindexas anintwhose value is returned by callingInventory(index). But theInventoryfunction you provided has a return type ofvoid, not the expectedint, so there's no way to get that value.
Also, your call toInventoryis missing an argument to thechat input[]andint qtyparameters. Additionally,indexis uninitialized at the time that you're trying to use it (within the definition ofindex).
|
Why isn't it the same memory address? This is in C.
```
int *pa;
int a = 80;
pa = &a; //save memory address from a to pa
*pa = 1000; //assign value to that address; *pa and a have now the same value
%p... memory address
%d... decimal
printf ("a: %d \n", a); //100
printf ("*pa: %d \n", *pa); //100
printf ("pa: %p \n", pa); //0x7ffcd1370c54
printf ("&a: %p \n", &a); //0x7ffcd1370c54
printf ("&pa: %p \n", &pa); //0x7ffcd1370c60
```
&pa has always "6" more than pa.
Shouldn't pa, &pa, &a have the same address?
|
&pais actually the address of pa,pais the value of pa, thus the address of a
They are different.
|
I want to keep forking a process until I'm almost out memory. How Do I know how many times I can fork a process without crashing?
|
Here is program to calculate estimate (using Linux API's):
```
#include <sys/resource.h>
#include <sys/sysinfo.h>
#include <stdio.h>
unsigned long maxmem() {
struct sysinfo info;
if (sysinfo(&info) < 0)
return 0;
return info.freeram;
}
long getmem(void) {
struct rusage r_usage;
getrusage(RUSAGE_SELF,&r_usage);
return r_usage.ru_maxrss;
}
int main() {
printf("Can fork %d times. Mfm: %d, upp: %d\n", maxmem() / 1024 / getmem(), maxmem() / 1024, getmem());
return 0;
}
```
Please note that this is just an estimate, you may need to run this code inside your application when it reaches peak memory usage.
|
As per my understanding
each thread of a process gets a stack, while there's typically only one heap for the process.There is default stack max size limit set by OS.Windows-64 bit : 1MBLinux-64 bit : 8MB
Is this limit applicable at process level or each thread can have 1MB/8MB stack?
And what happens to the memory allotted to stack after thread exit?
|
each thread of a process gets a stack, while there's typically only
one heap for the process.
That's correct.
Is this limit applicable at process level or each thread can have
1MB/8MB stack?
Each thread gets its own stack; the stack-size-limit is per-thread (i.e. it is not a shared limit for all threads in the process)
And what happens to the memory allotted to stack after thread exit?
The memory pages are released and become available for use by other code in the future.
|
Why isn't it the same memory address? This is in C.
```
int *pa;
int a = 80;
pa = &a; //save memory address from a to pa
*pa = 1000; //assign value to that address; *pa and a have now the same value
%p... memory address
%d... decimal
printf ("a: %d \n", a); //100
printf ("*pa: %d \n", *pa); //100
printf ("pa: %p \n", pa); //0x7ffcd1370c54
printf ("&a: %p \n", &a); //0x7ffcd1370c54
printf ("&pa: %p \n", &pa); //0x7ffcd1370c60
```
&pa has always "6" more than pa.
Shouldn't pa, &pa, &a have the same address?
|
&pais actually the address of pa,pais the value of pa, thus the address of a
They are different.
|
I want to keep forking a process until I'm almost out memory. How Do I know how many times I can fork a process without crashing?
|
Here is program to calculate estimate (using Linux API's):
```
#include <sys/resource.h>
#include <sys/sysinfo.h>
#include <stdio.h>
unsigned long maxmem() {
struct sysinfo info;
if (sysinfo(&info) < 0)
return 0;
return info.freeram;
}
long getmem(void) {
struct rusage r_usage;
getrusage(RUSAGE_SELF,&r_usage);
return r_usage.ru_maxrss;
}
int main() {
printf("Can fork %d times. Mfm: %d, upp: %d\n", maxmem() / 1024 / getmem(), maxmem() / 1024, getmem());
return 0;
}
```
Please note that this is just an estimate, you may need to run this code inside your application when it reaches peak memory usage.
|
As per my understanding
each thread of a process gets a stack, while there's typically only one heap for the process.There is default stack max size limit set by OS.Windows-64 bit : 1MBLinux-64 bit : 8MB
Is this limit applicable at process level or each thread can have 1MB/8MB stack?
And what happens to the memory allotted to stack after thread exit?
|
each thread of a process gets a stack, while there's typically only
one heap for the process.
That's correct.
Is this limit applicable at process level or each thread can have
1MB/8MB stack?
Each thread gets its own stack; the stack-size-limit is per-thread (i.e. it is not a shared limit for all threads in the process)
And what happens to the memory allotted to stack after thread exit?
The memory pages are released and become available for use by other code in the future.
|
I want to keep forking a process until I'm almost out memory. How Do I know how many times I can fork a process without crashing?
|
Here is program to calculate estimate (using Linux API's):
```
#include <sys/resource.h>
#include <sys/sysinfo.h>
#include <stdio.h>
unsigned long maxmem() {
struct sysinfo info;
if (sysinfo(&info) < 0)
return 0;
return info.freeram;
}
long getmem(void) {
struct rusage r_usage;
getrusage(RUSAGE_SELF,&r_usage);
return r_usage.ru_maxrss;
}
int main() {
printf("Can fork %d times. Mfm: %d, upp: %d\n", maxmem() / 1024 / getmem(), maxmem() / 1024, getmem());
return 0;
}
```
Please note that this is just an estimate, you may need to run this code inside your application when it reaches peak memory usage.
|
As per my understanding
each thread of a process gets a stack, while there's typically only one heap for the process.There is default stack max size limit set by OS.Windows-64 bit : 1MBLinux-64 bit : 8MB
Is this limit applicable at process level or each thread can have 1MB/8MB stack?
And what happens to the memory allotted to stack after thread exit?
|
each thread of a process gets a stack, while there's typically only
one heap for the process.
That's correct.
Is this limit applicable at process level or each thread can have
1MB/8MB stack?
Each thread gets its own stack; the stack-size-limit is per-thread (i.e. it is not a shared limit for all threads in the process)
And what happens to the memory allotted to stack after thread exit?
The memory pages are released and become available for use by other code in the future.
|
I have aGDataOutputStream*and now I need to close the underlyingGOutputStream*manually (by callingg_output_stream_close()).
Is it safe to just castGDataOutputStream*toGOutputStream*? Or do I need to get the underlying stream some other way?
|
Yes, that’s the right way to do things:
```
g_autoptr(GError) local_error = NULL;
if (!g_output_stream_close (G_OUTPUT_STREAM (my_data_stream), NULL, &local_error))
{
/* handle the error, for example: */
g_warning ("Error closing stream: %s", local_error->message);
}
```
|
We know that struct objects can be declared at the end of structure definition like so :
```
struct vertex
{
float x,y,z;
}v1;
```
Is such a declaration of an object likev1possible while using typedef struct?
```
typedef struct vertex
{
float x,y,z;
} vertex;
```
Is it mandatory to declare objects separately now with
```
vertex v1;
```
can they not be appended at the end of struct definition in this case?
|
No, it cannot be.
typedefis used for creation of an alias / synonym for another type. It cannot be used for declaration of variables.
```
typedef struct ver
{
float x,y,z;
} vertex;
```
Here,vertexis same asstruct ver(I changed the name slightly for better understanding).
Once the type (alias) is created, you use that to create a variable using another identifier, like
```
vertex v;
struct ver v1;
```
|
I'm reading in a binary file using fread, but in the process of this operation, another character string is changed into (null). Below is the part of the code that seems to cause the problem. The entire code is much longer, and my suspicion is that I'm running into problems with the available stack memory, but I don't know how to verify that.
```
char *foo;
foo = argv[1];
double *array;
array= malloc(npts*sizeof(double)); //npts - number of points
FILE *fo = fopen(ofile, "r");
printf("String: %s\n",foo);
fread(&array,8,npts,fo);
printf("String: %s\n",foo);
```
The first occurence of the print statement returns the previously assigned value 'bar', but the second returns '(null)'.
I expected both of the print statements to return 'bar'.
|
The&arrayinfread(&array,8,npts,fo);is wrong; that is the address of the pointer. You should pass the pointer:fread(array,8,npts,fo);.
|
I'm reading in a binary file using fread, but in the process of this operation, another character string is changed into (null). Below is the part of the code that seems to cause the problem. The entire code is much longer, and my suspicion is that I'm running into problems with the available stack memory, but I don't know how to verify that.
```
char *foo;
foo = argv[1];
double *array;
array= malloc(npts*sizeof(double)); //npts - number of points
FILE *fo = fopen(ofile, "r");
printf("String: %s\n",foo);
fread(&array,8,npts,fo);
printf("String: %s\n",foo);
```
The first occurence of the print statement returns the previously assigned value 'bar', but the second returns '(null)'.
I expected both of the print statements to return 'bar'.
|
The&arrayinfread(&array,8,npts,fo);is wrong; that is the address of the pointer. You should pass the pointer:fread(array,8,npts,fo);.
|
Is there any chance that a threadtwaiting on a conditional variablecondgets woken up by another threadt'(wheret'might actually bet) signaling beforetwas waiting ?
I've tried making a C program that does this 1000 of times but it never occurs, also I've read the man pages about signal and wait but I can't find an answer.
Here's an example of what it might look like on a single thread
```
pthread_cond_signal(&cond);
pthread_cond_wait(&cond, &mutex); //Is there a chance that this wait gets cancelled by the signal above
```
Thanks for your help!
|
Can a thread waiting on a conditional variable be woken up by a signal emitted before he was waiting.
It can't. However, it can be woken up by aspurious wakeupand one won't know the difference.
The waiting code must wait for a change in the shared state, condition variable wakeup is a hint that the shared state may have changed and must be re-evaluated.
|
I have a header file that selects between two platforms:
```
#pragma once
#ifdef _WINDOWS
#define PAR_CLASS TestPar
#define PAR_INCLUDE_FILE "TestPar.h"
#else
#define PAR_CLASS Par
#define PAR_INCLUDE_FILE "Par.h"
#endif
```
With this I can use the following line to include a header file:
```
#include "ClassNames.h"
#include PAR_INCLUDE_FILE
```
However, I expect more classes and for the PAR_CLASS and PAR_INCLUDE_FILE, the only different is the " and the .h
What I would like is to use the PAR_CLASS inside the#include, something like:
```
#include "PAR_CLASS.h"
```
But this does not work... Is something like this possible?
I want it to work in both Visual Studio (2019) and Arduino IDE.
|
You can implement it using the following macro structure:
```
#define stringify(x) #x
#define GEN_INC_PATH(a) stringify(a.h)
#include GEN_INC_PATH(PAR_CLASS)
```
|
I have the following C code
```
#include <fftw3.h>
int main() {
return 0;
}
```
If I compile it in visual studio code with the c/c++ extension it returns
no such file or directory for fftw3.h
I installed fftw3 in /home/usr/ and the fftw3.h file's path is /home/myname/usr/include/fftw3.h
I added the path /home/myname/usr/include/ to visual studio code in c/c++ confuguration and it shows up in the c_cpp_properties.json file in
```
"includepath": = ["/home/myname/usr/include/"]
```
If I run it whth gcc on the terminal with gcc -I/home/myname/usr/include -c test.c
it compiles without a problem.
Any idea why Visual studio code is not accepting this header file?
|
Fixed it. I installed the wrong fftw3. you need to install fftw3-dev. I don't really know why it worked on the terminal. Answer taken from herehttps://ubuntuforums.org/showthread.php?t=1274884
|
I would like to calculate a 3bytes CRC value using the crc calculation unit of the Nucleo L053R8.
The generator Polynomial is the following: g(X)=x^24 + x^10 + x^9 + x^6 + x^4 + x^3 + x + 1
It seems that using this CRC calculation unit I can only generate a 32bits length CRC and smaller values are just the LSBS of the 32bit result.
I also know that the LSB of CRC32 in not equal to a CRC16.
Any idea on what operations I should perform on the input/output data to get the correct CRC24 I want ?
|
Multiply the generator polynomial by x^8, by shifting it left 8 bits. If you have an initial value, also multiply it by x^8, by shifting it left 8 bits. Use the 32 bit CRC code with the shifted polynomial and initial value, then shift the resulting 32 bit CRC right by 8 bits.
```
g(X)*x^8 = x^32 + x^18 + x^17+ x^14 + x^12 + x^11 + x^9 + x^8
```
|
Let's say we have this line of code:
```
printf("%hi", 6);
```
Let's assumesizeof(short) == 2, andsizeof(int) == 4.
printfexpects ashort, but is given anint, which is wider. Is this undefined behaviour?
The same with%hhi.
|
printf()doesn't actually expect the argument to be ashortwhen you use%hi. When you call a variadic function, all the arguments undergodefault argument promotion. In the case of integer arguments, this means integer promotions, which means that all integer types smaller thanintare converted tointorunsigned int.
If the corresponding argument is a literal, all that's required is that it be a value that will fit into ashort, you don't actually have to cast it toshort.
Thestandardsection 7.21.6.1.7 explains it this way:
the argument will
have been promoted according to the integer promotions, but its value shall
be converted toshort intorunsigned short intbefore printing
|
I need to pass a variable of typeint[][3]to a callback function which only acceptsvoid*as parameter. How can I do that?
The below code does not compile:
```
void myfunc(void *param) {
int i[][3];
i=*param;
printf("%d\n",i[1][2]);
}
int main(int argc, char *argv[])
{
int i[][3]={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
myfunc(i);
}
```
|
Use:
```
int (*i)[3] = param;
```
Then use it as before. That’s a pointer to an array of integers.
|
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 know how to quickly find hidden processes in the Windows OS.
How to find hidden processes that are currently in use.
Find the PID in multiples of 4 using the BroutForce method.Compare with the list found with CreateToolHelp32Snapshot API.
Is there a way to find it faster than the current use?
|
A rootkit hidden process will probably use a driver and unhook itself from the list of processes. I doubtOpenProcesswill work even if you know the pid. Fighting a kernel-rootkit from usermode is nearly impossible.
|
This question already has answers here:Getting a stack overflow exception when declaring a large array(8 answers)Closed4 years ago.
This is my struct
```
struct Entry {
int a;
int b;
};
int main() {
struct Entry data[260000]; //ok
struct Entry data[262144]; //crash
return 0;
}
```
I want to declare an array of Entry with the size is 2^18 (262144 elements) But I'm not able to do so. It seems like I go beyond the max. Is there another way to do this?
|
There is not ehough room in theautocontext (on the stack) for that array,
declare it static or as a global, or allocate it dynamically.
|
This question already has answers here:Getting a stack overflow exception when declaring a large array(8 answers)Closed4 years ago.
This is my struct
```
struct Entry {
int a;
int b;
};
int main() {
struct Entry data[260000]; //ok
struct Entry data[262144]; //crash
return 0;
}
```
I want to declare an array of Entry with the size is 2^18 (262144 elements) But I'm not able to do so. It seems like I go beyond the max. Is there another way to do this?
|
There is not ehough room in theautocontext (on the stack) for that array,
declare it static or as a global, or allocate it dynamically.
|
I'm trying to implement ElGamal cryptosystem and I decided to use OpenSSL to generate big primes. I've seen several functions that generate big random numbers but I haven't found a function to generate prime numbers. What function should I use?
|
That's a function of the underlying Big Number (BN) implementation rather than a specific high level crypto function, so I guess you'd useBN_generate_prime_ex.
|
I don't quite understand the necessity of this code here.
```
// skip over padding, if any
fseek(inptr, padding, SEEK_CUR);
// then add it back (to demonstrate how)
for (int k = 0; k < new_padding; k++)
{
fputc(0x00, outptr);
}
if (repeat < n - 1)
{
fseek(inptr, - (bi.biWidth * 3 + padding), SEEK_CUR);
}
```
|
It is difficult to confirm the correctness or even the pertinence of this code fragment without the full context.
fseekmoves the input stream's pointer forward bypaddingbytes.
The program then outputsnew_paddingnull bytes to the output stream, presumably a different amount frompadding. Microsoft's BMP file format requires some padding in various places, for easier reading into memory.
Finally,fseekis used again to set the input stream pointer backward to the beginning of the row of pixels (3 bytes per pixel) plus the padding it skipped, but only if(repeat < n - 1).
|
So I am a beginner to C.
I was going through text about l-value and r-value when I came across this in one of my study materials:
"We talk about l-value and r-value with respect to assignment operator =.
The only operator which gives a value back is the dereferencing
operator."
This confuses me because don't the increment/decrement operators also give a value? Then how is dereferencing the only operator that gives a value back?
|
I think this is a typo and is supposed to say
The only operator which givesan l-valueback is the dereferencing operator.
It isn't strictly true. For example, the[],.and->operators also give back lvalues (the standard spells it without a hyphen) so that you can write
```
a[5] = 17;
s.x = 42;
p->y = 17;
```
|
I'm making a program in C (simple snake game).
I'm using window.h and came across an inconvenience.
I'm using COORD's and SetConsoleCursorPosition to move about the cursor.
However, moving one y coordinate is almost the same as moving two x coordinates in terms of how many pixels each represents.
For example, this square window has a width of 80 and height of 40 in terms of the cursor position coordinates.
Also, you can clearly see the contraction (and therefore reduction of apparent speed of the snake) when moving sidewards in the images below.
Is there any efficient solution to this so that the pixel size of one move in the x direction is the same as one move in the y direction.
Many thanks.
[
|
TheSetCurrentConsoleFontExfunction lets you specify the console font size in thelpConsoleCurrentFontEx'sdwFontSizemember. There you can set the font width and height be the same.
|
This question already has answers here:Pointer initialisation gives segmentation fault(5 answers)Closed4 years ago.
Trying to understand what exactly happens in the memory during the execution of this code and why it causes a segmentation error.
```
#include <stdio.h>
int main() {
int* ptr;
*ptr = 5;
printf("%d", *ptr);
return 0;
}
```
|
All variables must first be initialized to a valid value before you can use them in an expression like*p. For pointers, this means assigning an address to point to. You can do this either by taking the address of another variable or by dynamically allocating memory withmalloc().
When you try to dereference an uninitialized pointer with*p, it will use whatever memory address happens to be stored inpat that time. Most likely this address is invalid for you to use and so you get a segfault.
|
I am trying to print float value299792450with the following code:
```
#include <stdio.h>
int main()
{
printf("%f\n", 299792450.0f);
return 0;
}
```
According toIEEE 754 Calculator, this is exactly representable floating point value in binary32 format. However I am getting another value in output:
```
$ ./a.out
299792448.000000
```
Why it is not equal to299792450? I expected it to be299792450because it is exactly representable and there should be no loss of precision.
|
Assuming afloatis a IEEE754 single precision floating point number, 299792450cannotbe represented exactly.
This value requires at least 28 bits of precision, but afloathas at most 24 bits of precision. So the value gets rounded to the closest possible value that can be represented.
If you used adoublewhich has 53 bits of precision, you would see the exact value.
```
printf("%f\n", 299792450.0);
```
|
This question already has answers here:Pointer initialisation gives segmentation fault(5 answers)Closed4 years ago.
Trying to understand what exactly happens in the memory during the execution of this code and why it causes a segmentation error.
```
#include <stdio.h>
int main() {
int* ptr;
*ptr = 5;
printf("%d", *ptr);
return 0;
}
```
|
All variables must first be initialized to a valid value before you can use them in an expression like*p. For pointers, this means assigning an address to point to. You can do this either by taking the address of another variable or by dynamically allocating memory withmalloc().
When you try to dereference an uninitialized pointer with*p, it will use whatever memory address happens to be stored inpat that time. Most likely this address is invalid for you to use and so you get a segfault.
|
I am trying to print float value299792450with the following code:
```
#include <stdio.h>
int main()
{
printf("%f\n", 299792450.0f);
return 0;
}
```
According toIEEE 754 Calculator, this is exactly representable floating point value in binary32 format. However I am getting another value in output:
```
$ ./a.out
299792448.000000
```
Why it is not equal to299792450? I expected it to be299792450because it is exactly representable and there should be no loss of precision.
|
Assuming afloatis a IEEE754 single precision floating point number, 299792450cannotbe represented exactly.
This value requires at least 28 bits of precision, but afloathas at most 24 bits of precision. So the value gets rounded to the closest possible value that can be represented.
If you used adoublewhich has 53 bits of precision, you would see the exact value.
```
printf("%f\n", 299792450.0);
```
|
I have an input which comes over UART.
```
uint8_t uartRX_data[UART_RX_BUF_SIZE]="";
```
I need to pass this data to a function. And, in this function I want to compare it with predefined strings like:
```
char RESP_OK[] = "OK";
char RESP_ERROR[] = "ERROR";
char RESP_FAIL[] = "FAIL";
```
What is the easiest way to do that?
EDIT: My problem is only about the data comparison and data passing to a function.
|
As long as the string inuartRX_datais NULL terminated you should be able to usestrcmplike so:
```
if (strcmp((const char *)uartRX_data, RESP_OK) == 0)
{
// handle OK
}
else if (strcmp((const char *)uartRX_data, RESP_ERROR) == 0)
{
// handle ERROR
}
else if (strcmp((const char *)uartRX_data, RESP_FAIL) == 0)
{
// handle FAIL
}
else
{
// handle unknown response
}
```
|
This question already has answers here:How do you implement a class in C? [closed](16 answers)Closed4 years ago.
After reading this page, I already know how to implement non-copyable
classes in C++.
(How do I make this C++ object non-copyable?)
Now I want implement non-copyable in C,
But I don't find similar code in C.
So I want to ask how to implement in C.
|
You can do this usingopaque pointers. The idea is:
You define a struct somewhere and you define all of its operations in terms of a pointer to that struct. That would probably be a standalone compilation unit.The consumers of your struct only get a declaration but not the full definition of that struct, which means that they don't know the layout or even the size of the struct. It follows that they are able to receive, store, and pass around anypointersto that struct, but notvaluesof it.
|
To get integer arguments into from the script into my C code, I can useluaL_checknumber(), but there is no function calledluaL_checkboolean()that would allow me to getboolarguments. Is there any workaround for this?
|
You can usedlua_toboolean.
Just remember any value, in lua, other thenfalseandnilevaluate astrue
If necessary you can validate the value is a bool usinglua_isbooleanbeforelua_toboolean
Reference:https://www.lua.org/manual/5.3/manual.html#lua_toboolean
|
what's the difference between:
```
while(*s++ != '\0') {}
```
and
```
while(*s != '\0') {
s++;
}
```
sis achar *. The latter works OK. but at the end of first loop,*sis not equal to'\0'.
|
In case of
```
while(*s++ != '\0') {}
```
the increment is done as a post increment operator, in the condition-check statement itself. In this case, the value change (increment) is the side effect after the value computation for the operator. Thus, after the value is used (in comparison),sgets incremented.
On the other hand,
```
while(*s != '\0') {
s++;
}
```
the increment takes place as post-increment inside the conditional block, which will only execute if the condition is TRUTHY. Once the condition is evaluated to be false,sis not incremented.
|
Let say I have
```
struct student
{
char* first_name;
};
typedef struct
{
struct student name;
} Person;
char* first_name_of_someone = "John";
```
Why do I have to malloc and then strcpy to put John in first_name? Why can't I just assign it like this
```
Person* person = malloc(sizeof(Person));
struct student s;
s.first_name = "John";
person->name = s;
```
|
If you know what value to copy before hand then you don't needmalloc
```
s.first_name = "John";
```
What if you are getting to know what value to copy during run time?
In that case you needmallocandstrcpy.
```
fgets(tempbuf, sizeof tempbuf, stdin);
s.first_name = malloc(somelength);
strcpy(s.first_name, tempbuf);
```
or
```
s.first_name = tempbuf;
```
In latter casefirst_namewill be always be pointing to latest value stored intempbuf.
|
I have defined the following static const array:
```
const int arr[197] = { 55, -63, 12, -17, 121 , ... };
```
The array never changes. It contains some specific numerical pattern eligible for my program.
This array is used in three different files:
foo1()infile1.cfoo2()infile2.cfoo3()infile3.c
everytime passing the array to a function as an argument.
Because the definition of this array is quite long and extensive, I want to create separate file just to define and keep that array in there.
How should that be done properly? Should I define that array in let's sayarr.hand then put#include <arr.h>inside.cfiles that use this array?
|
Defineconst int arr[197] = ...inarr.c.
Declareextern const int arr[197];inarr.h
Only includearr.hinarr.c, file1.c, file2.c, file3.cwith#include "arr.h", not#include <arr.h>almost like@weno
|
I have a binary mask which at some point I'm updating. It's ok for 1s in my old mask to become 0s but the other way around is not allowed. How can I assert using some binary operations that none of the 0s in the mask have turned into 1s?
|
```
if (~old & new)
```
If you also want to know which bits changed from 0 to 1, just read each bit inbits = ~old & new;. If you just want to know if any 0s became 1s, that first line of code will do.
|
what's the difference between:
```
while(*s++ != '\0') {}
```
and
```
while(*s != '\0') {
s++;
}
```
sis achar *. The latter works OK. but at the end of first loop,*sis not equal to'\0'.
|
In case of
```
while(*s++ != '\0') {}
```
the increment is done as a post increment operator, in the condition-check statement itself. In this case, the value change (increment) is the side effect after the value computation for the operator. Thus, after the value is used (in comparison),sgets incremented.
On the other hand,
```
while(*s != '\0') {
s++;
}
```
the increment takes place as post-increment inside the conditional block, which will only execute if the condition is TRUTHY. Once the condition is evaluated to be false,sis not incremented.
|
Let say I have
```
struct student
{
char* first_name;
};
typedef struct
{
struct student name;
} Person;
char* first_name_of_someone = "John";
```
Why do I have to malloc and then strcpy to put John in first_name? Why can't I just assign it like this
```
Person* person = malloc(sizeof(Person));
struct student s;
s.first_name = "John";
person->name = s;
```
|
If you know what value to copy before hand then you don't needmalloc
```
s.first_name = "John";
```
What if you are getting to know what value to copy during run time?
In that case you needmallocandstrcpy.
```
fgets(tempbuf, sizeof tempbuf, stdin);
s.first_name = malloc(somelength);
strcpy(s.first_name, tempbuf);
```
or
```
s.first_name = tempbuf;
```
In latter casefirst_namewill be always be pointing to latest value stored intempbuf.
|
I have defined the following static const array:
```
const int arr[197] = { 55, -63, 12, -17, 121 , ... };
```
The array never changes. It contains some specific numerical pattern eligible for my program.
This array is used in three different files:
foo1()infile1.cfoo2()infile2.cfoo3()infile3.c
everytime passing the array to a function as an argument.
Because the definition of this array is quite long and extensive, I want to create separate file just to define and keep that array in there.
How should that be done properly? Should I define that array in let's sayarr.hand then put#include <arr.h>inside.cfiles that use this array?
|
Defineconst int arr[197] = ...inarr.c.
Declareextern const int arr[197];inarr.h
Only includearr.hinarr.c, file1.c, file2.c, file3.cwith#include "arr.h", not#include <arr.h>almost like@weno
|
I have a binary mask which at some point I'm updating. It's ok for 1s in my old mask to become 0s but the other way around is not allowed. How can I assert using some binary operations that none of the 0s in the mask have turned into 1s?
|
```
if (~old & new)
```
If you also want to know which bits changed from 0 to 1, just read each bit inbits = ~old & new;. If you just want to know if any 0s became 1s, that first line of code will do.
|
I have predefined HEX values in my code. One of them is in the following.
```
#define ADDRESS1 0xD445556BD557
#define ADDRESS2 0xED612BDF113B
```
I also have an uint8_t array. Like
```
uint8_t MAC[6];
```
How can I compare this two things without writing a new function?
I have already tried
```
if(MAC == ADDRESS2)
```
|
Maybe you should use uint8_t array for ADDRESS* also, and usememcmp():
```
static const uint8_t ADDRESS1[] = {0xD4, 0x45, 0x55, 0x6B, 0xD5, 0x57};
if (memcmp(MAC, ADDRESS1, sizeof(ADDRESS1)) == 0)
```
|
```
int main() {
for(3;2;1)
printf("hello\n")
}
```
I thought this loop wouldn't even be executed. AFAIK we have to define a variable; put a condition; increase/decrease. However in this code none of the things I counted exists. So I think this program should crash. But it goes on forever.
|
Because the exit condition (2) is always true.
This works because the format of aforstatement is
```
for (clause-1;expression-2;expression-3)
```
Whereclause-1can be a declaration (e.g.int i = 0) or an expression.
In your case you have three expressions, so the statement is still syntactically valid.
The loop exits whenexpression-2evaluates to false (0) which, in your case, it never does since it's a non-zero constant (2).
|
Which one is more efficient (= fastest) implementation for transferring data through USB and writing it on memory for further processes:
reading a little data from USB and write on memory repeatedly multiple times.reading one huge data from USB and write it on memory.
|
In my Experience it's better to read a lot of data from USB in order to reduce latency from OS.
Long time ago I was writing an application which had to write data to a device using USB in raw mode. The device was using a 128 bytes array to store data from the other part (Windows in my case). When I increased tha data size on the the device part, allocating 1 MB of space, I got a great increase of performance
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.