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 ',' num... |
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 produ... |
I'm reading the source code for a text editor application (Torvalds/uemacs on GitHub.com). There is a certain file (termio.c) that#includesthe contents of files such as: stsdef.h, ssdef.h, descript.h, iodef.h, ttdef.h and tt2def.h. I have absolutely no clue what these header files contain or what they are used for. Ca... |
These headers are specific for the VMS operating system. They're guarded byboth#ifndef POSIXand#ifdef VMS. They contain theterminal bps settings and alikeforthis operating system. The files do not exist in Unixen or Windows, and are not needed there to compile uemacs.
|
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 ',' num... |
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 produ... |
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:
```
... |
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: ... |
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... |
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 ... |
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 struc... |
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... |
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 ... |
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... |
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... |
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 para... |
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... |
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 para... |
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... |
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 ... |
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 < 1... |
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 eith... |
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 eith... |
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, th... |
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 ... |
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
}
```
... |
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, "t... |
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 arg... |
```
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
}
```
... |
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 ... |
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:
```
... |
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 statement... |
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... |
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 < ... |
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 ... |
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:
```
... |
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 statement... |
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... |
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 < ... |
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 ... |
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... |
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.
... |
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 ea... |
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... |
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 fra... |
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==... |
->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.
A... |
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. ... |
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.... |
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... |
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 ano... |
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 l... |
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(&queue... |
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 an... |
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 si... |
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, it... |
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 als... |
*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);
ge... |
```
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... |
*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"'
Ca... |
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,i... |
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
... |
&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... |
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 ... |
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 ... |
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
... |
&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... |
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 ... |
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 ... |
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... |
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 ... |
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 ... |
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 w... |
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 ... |
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... |
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... |
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 answ... |
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 ... |
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:... |
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... |
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 th... |
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 +... |
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... |
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},
... |
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 a... |
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 d... |
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 d... |
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 re... |
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 inc... |
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 ... |
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;
pr... |
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 uniniti... |
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... |
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 b... |
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;
pr... |
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 uniniti... |
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... |
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 b... |
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[] ... |
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)
{
/... |
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... |
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 t... |
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 o... |
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 stu... |
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);
... |
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 ... |
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 o... |
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 stu... |
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);
... |
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 ... |
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 == ADDRESS... |
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 exi... |
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.