question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am working on a project where half my code is in c and half is in c++.
Now I want to include the cprogram.c in my cppprogram.cpp.
When including a c file inside a c program you can use
```
#include "cprogram.c"
```
Anyways to do that in c++ for including a c program.
|
Besides from that you normallydon't include.cfiles, but.hfiles instead, and that the following isbad practice, you can include C files into.cpp/.hppfiles by wrapping the include into anextern "C":
cppprogram.cpp
```
extern "C" {
#include "cprogram.c"
}
```
Seeherefor some examples.
|
I found out after reading online that if i use "%c "(with a trailing space) that scanf would read newline character but on trying it out its asking me for input thrice rather than just twice . Please tell me where i went wrong and why I am getting the answer that i am getting now
```
main()
{
double e = 5.32 ;
int ... |
scanf("%c ")is going to attempt to consume one character and then all possible whitespace. When the input stream begins withP\nA\nand has not yet been closed,scanfis going to continue to try reading from the input stream until it sees either the end of input or it sees a non-whitespace character.
If you are new to C... |
If I had a project that contained two controllers and made communication between them using SPI and I configured one of them as a master and the other as a slave, then changed the master to a slave, can the slave find out byitselfthat he has to become the master?
|
if changed the master to a slave can the slave find out by himself that he has to become the master ?
No. SPI is a very simple protocol specification. Or maybe "protocol" is too much - it's a specification how to transfer bits. The master initiates the transfer and provides clock signal. Without clock there's no comm... |
Is there a way (using gcc) to set the stack size of a shared library ?I build a.sothat contain a single function that uses a big buffer as local variable.Something like that:
```
void foo ( void )
{
int table [1000000] ; // 4 millions bytes table !
...
}
```
I added the option-Wl,-z,stack-size=410000... |
No, this is not possible - functions from shared library work in the context of thread which calls them and that thread will either be a main application thread (which started inmain) or a thread created with Pthreads (which will have stack allocated at thread creation time inpthread_create).
-Wl,-z,stack-sizeflag is... |
Is there a way (using gcc) to set the stack size of a shared library ?I build a.sothat contain a single function that uses a big buffer as local variable.Something like that:
```
void foo ( void )
{
int table [1000000] ; // 4 millions bytes table !
...
}
```
I added the option-Wl,-z,stack-size=410000... |
No, this is not possible - functions from shared library work in the context of thread which calls them and that thread will either be a main application thread (which started inmain) or a thread created with Pthreads (which will have stack allocated at thread creation time inpthread_create).
-Wl,-z,stack-sizeflag is... |
In C, is there a way to declare an implicit type conversion for the following union type:
```
enum COMP {
LessThan,
Equal,
GreaterThan
};
```
mapping it to, say, an integer:
```
enum COMP {
LessThan : 1,
Equal : 0,
GreaterThan : -1
};
```
|
What you have is anenum, not aunion. And what itseemslike you're asking is if you can assign specific values to enum constants. You can do so like this:
```
enum COMP {
LessThan=-1,
Equal=0,
GreaterThan=1
};
```
Also, enums are considered integer types, so you can safely convert to or fromint.
|
This function is reversing the the order of chars in a given string. Its called by inputing its start and end pointers. for example the function called like so
```
reverse(str, str + strlen(str));
```
I don't understand why the while condition works, or more precisely what are we comparing by(start<--end).
```
void... |
startandendare pointers to the start and end of the string.start + strlen(str)is actually one character past the last character to be swapped, soendis decremented before being compared, while start is incremented after. The reverse is done when the two pointers meet in the middle of the string. The null byte at the ... |
Linker question:
if I had a file. c that has no includes at all, would we still need alinker?
|
Although the linker is so-named because it links together multiple object files, it performs other functions as well. It may resolve addresses that were left incomplete by the compiler. It produces a program in an executable file format that the system’s program loader can read and load, and that format may differ fro... |
I am new to servers and networking so pardon my ignorance.
I have a Heroku application running a NodeJS server. I am usingconsole.log()to output the port its using to the console. But when i use the port to try to perform a GET request from my browser it keep loading forever. My request is something this:
https://ex... |
As suggested by @tadman using the default https port443solved the issue.
|
I have a function with two strings parameters. I have to check if both strings contains any non-null characters. Here is an example code:
```
void fun(const char* str1, const char* str2)
{
if (!str1 || !str1[0] || !str2 || !str2[0])
{
return;
}
// process
}
```
Is that a standard approach in... |
It is enough to write the condition like
```
if ( !str1[0] || !str2[0] )
```
that is when the function follows the convention of C Standard string functions when passing a null-pointer invokes undefined behavior.
It is the caller of the function that shall guarantee that the passed pointers are not null pointers.
|
Say I have the following code:
```
int main(int argc, char *argv []) {
pid_t pid = fork();
if (pid > 0) {
execv(*argv, argv);
}
int state=0;
wait(&state);
return state;
}
```
Does the child simply ignore the wait and skip over since it's not the calling process?
|
It will return-1and seterrnotoECHILDsince the child process has no children of its own to wait on. From thewait(2) man page:
Return valuewait(): on success, returns the process ID of the terminated
child; on error,-1is returned....Each of these calls setserrnoto an appropriate value in the case of an error.ErrorsECHI... |
I have two files in Arduino IDE. One is the.inofile and one is a.cfile.
main.ino:
```
#include "somefile.c"
void setup(){
Serial.begin(9600);
// Do something
}
void loop(){
// Do something
}
```
And insomefile.cI want to callSerial.print(). How can I do that? Thanks!
|
create a my_logging.h file with
```
void my_log(const char *msg);
```
create a my_logging.cpp file with
```
#include <Arduino.h>
extern "C" {
#include "my_logging.h"
}
void my_log(const char *msg) {
Serial.println(msg);
}
```
then in in your c file include the my_logging.h file and you can use themy_logfuncti... |
For public functions I'll put those in a header file such as:
```
// tree.h
bool TreeIsEmpty(const Tree *ptree);
bool TreeIsFull(const Tree *ptree);
size_t TreeItemCount(const Tree *ptree);
```
However, what about internal implementation items? Do those only go in mytree.cfile or do I also put those into mytree.hfil... |
static bool TreeItemCountInternal(...);hasinternal linkage, so you wouldn't put anything in the header file.
|
Follow-up question forthisanswer.
Is there any hosted C implementations (__STDC_HOSTED__is 1) which haveCHAR_BIT > 8?
If so, then which ones?
UPD. Fix typo: before:__STDC_HOSTED__is0, after:__STDC_HOSTED__is1.
|
I don't know if there was ever a post-standardisation version, but various Cray 64-bit vector supercomputers had a C compiler in whichsizeof(long) == sizeof(double) == 1, a.k.a.everything is 64 bits wide.
|
I have aQueuewhich is defined around anItemtype. For example, if I want a queue of integers I have the following:
```
// queue.h
typedef int Item;
```
However, I'd like the end-user to define what theItemis, and so not have it hardcoded in the header file. Is there a way to do something like the following?
```
// q... |
Use a void pointer (void *) type.
```
typedef void* Item;
```
If you look at theGLib, they have something calledgpointerwhich is what is used refer to arbitrary types a user might want to use in a collection.
Also checkoutGQueue, which might be a good reference for your implementation.
|
Let's say I have the following I'm using to call a function:
```
Item dummy;
while (!QueueIsEmpty(pq))
DeQueue(pq, &dummy);
```
Is there a way to put thedummyparameter into the call itself? Something like:
```
while (!QueueIsEmpty(pq))
DeQueue(pq, &(Item)NULL);
```
|
It looks like the method dequeues an object and copies its value to the dummy variable. Where would you expect it to be copied without providing a place to copy it to?
Do you want to just throw it away and clear the queue this way?
If so I would expect that you have to pass it inside unless there is another method th... |
I'm working with a game engine that uses escape codes in strings to perform commands such as setting color. eg to set the color to red, you write"Red text:\x81\xFF\x00\x00\xFFhello!"(0x81, red, green, blue, alpha).
Is it possible to create a macro likeTEXT_COLOR(r,g,b,a)such thatTEXT_COLOR(255,0,0,255)would expand to... |
It takes a mix of token pasting and stringification in different macros, but, yeah, it's possible using base-16 numbers:
```
#include <stdio.h>
#define TEXT_COLOR2(r,g,b,a) "\x81" #r #g #b #a
#define TEXT_COLOR(r,g,b,a) TEXT_COLOR2(\x ##r, \x ##g, \x ##b, \x ##a)
int main(void) {
char s[] = "Red text:" TEXT_COLOR... |
This question already has answers here:What is bit masking?(6 answers)Closed2 years ago.
A struct I'm dealing with has a field defined asuint8_t. The spec also states that all multiple-byte fields are represented in host-endian format.
Bits 0:3 contain the information that I need (also an unsigned integer). Using pl... |
unit8_t a;
unit8_t b;
a = input data;
b = a & 0x0F; // b contains a number from 0 to 15
|
```
#include <stdio.h>
void add(int num){
while(num < 6){
add(num+1);
}
printf("\n%d",num);
}
void main(){
int a = 1;
add(a);
}
```
Can any one explain me why its going Infinite
6
6 6
6....
And not only
6
single time.
|
In your loop:
```
while(num < 6){
add(num+1);
}
```
You never modifynum. So the loop never exits. You eventually end up via recursion with a call toadd(5). That callsadd(6)which prints the value 6 and returns. Then the prior recursive call callsadd(6)again because of the loop, and so forth.
Given that you... |
This question already has answers here:If char*s are read only, why can I overwrite them?(9 answers)Closed2 years ago.
So if I do this, I get segmentation fault:
```
#include <stdio.h>
#include <cs50.h>
int main(void)
{
string word = "WORD";
for(int i = 0; word[i] != 0; i++) {
word[i] += 32;
... |
stringis not a standard C symbol, and is likely defined in yourcs50.hheader file as:
```
typedef char* string;
```
This means that variablewordis a reference toconstantdata, data that cannot be changed. So when you try to do the line:
```
word[i] += 32;
```
You are trying to change data that cannot be written to... |
I have the following code, but why doesn't the second while loop run? Any changes to make it run?
```
#include<stdio.h>
int main() {
int a,b,c,d,e,f;
while(scanf("%d,%d,%d",&a,&b,&c)==3){
printf("ok\n");
}
while(scanf("%d,%d,%d",&d,&e,&f)==3){
printf("OK\n");
}
return 0;
}
```
... |
Let's say you input "1,5,7,4,8,7<ENTER>" for thescanf()in the 1stwhile.
Thescanf("%d,%d,%d", &a, &b, &c);reads 1 intoa, 5 intob, 7 intocand returns3keeping",4,8,7<ENTER>"in the input buffer.
In the 2nd time through the loop, scanf finds the comma and returns0which terminates thewhile.
Immediately after that, in the... |
The following code gives me aterminated by signal SIGSEGV (Address boundary error):
```
void rec(int x, int *arr, int *size) {
if (x < 0) {
rec(-x, arr, size);
return;
}
arr = realloc(arr, sizeof(int) * ++(*size));
*(arr + (*size) - 1) = x % 10;
if (x % 10 != x)
rec(x / 10, arr, size);
}
... |
Notice that you are passingNULLas third argument:
```
rec(20, arr, 0); // 0 is NULL
```
and you get a segfault dereferencing it:
```
arr = realloc(arr, sizeof(int) * ++(*size)); // here size is `NULL`
```
try with
```
rec(20, arr, size);
```
|
I'm writing some kernel modules, but for debug output I'd like to (automatically) print out which kernel module is producing the output. Is there a function or variable I can use to get the name of the module that's executing?
|
Inside the code of the kernel module,THIS_MODULEpoints to the structure representing this module. You may usenamefield of this structure for extract the current module name:
```
printk("Current module name: %s\n", THIS_MODULE->name);
```
If your code could be compiled (depending on configuration) either as amoduleor... |
There must be two variables for example A and B, these two will either take the values 0 0, 0 1 , 1 0 or 1 1. I need to check these two variables and return a value between 0 to 3, is there a better way to this than doing fourifstatements like:
```
if(B == 0 && A == 0){
return 0;
}
if(B == 0 && A == 1){
return 1;... |
The four conditions you have shown could be addressed with the single line:
```
return A + B * 2;
```
That is, of course, if theAandBvalues willneverbe anything other than0or1.
|
I want to create a CountDownUP program but the code is not working, I want it to output5 4 3 2 1 0 1 2 3 4 5but it only outputs5 4 3 2 1 0 1
```
void countDownUp (unsigned int k){
printf("\n");
for (int i = 0; i < k; i=1){
k = k - i;
printf("%d ", k);
}
for (int n = 0; n <= k; n++){
... |
The firstforloop decrementskeach time through the loop, and stops whenk == 1. So the second loop just iterates from0to1.
You shouldn't modifykin the first loop, you should decrementi.
```
for (int i = k; i > 1; i--) {
printf("%d ", i);
}
```
|
There must be two variables for example A and B, these two will either take the values 0 0, 0 1 , 1 0 or 1 1. I need to check these two variables and return a value between 0 to 3, is there a better way to this than doing fourifstatements like:
```
if(B == 0 && A == 0){
return 0;
}
if(B == 0 && A == 1){
return 1;... |
The four conditions you have shown could be addressed with the single line:
```
return A + B * 2;
```
That is, of course, if theAandBvalues willneverbe anything other than0or1.
|
I want to create a CountDownUP program but the code is not working, I want it to output5 4 3 2 1 0 1 2 3 4 5but it only outputs5 4 3 2 1 0 1
```
void countDownUp (unsigned int k){
printf("\n");
for (int i = 0; i < k; i=1){
k = k - i;
printf("%d ", k);
}
for (int n = 0; n <= k; n++){
... |
The firstforloop decrementskeach time through the loop, and stops whenk == 1. So the second loop just iterates from0to1.
You shouldn't modifykin the first loop, you should decrementi.
```
for (int i = k; i > 1; i--) {
printf("%d ", i);
}
```
|
```
#include<stdio.h>
enum color {b,g,i,k};
void main()
{
int b=100; //line 7
enum color out=b; //line 8
printf("%d\n",out);
}
```
Inline 8thebwhich i am referring to iscolor.bnot the one which declared atline 7.InC++i can referb from colorascolor::b, inCHow do i do this?
|
As a comment already mentioned, enumerations are part of the global scope. Usually, a prefix is used to distinguish them, for example:
```
enum color {
cB, cG, cI, cK
}
```
|
Given the following two statements to usefgetsand strip the newline:
```
puts("Enter the name.");
fgets(temp.name, 40, stdin);
temp.name[strcspn(temp.name, "\n")] = 0;
```
Is the following macro sufficient to take the place of this?
```
#define FGETS(str, len) fgets(str, len, stdin); str[strcspn(str, "\n")] = 0
FG... |
File input/output is a back-hole of time. Little to gain using a macro over a clean function.
Perhaps a function to do the prompt too?
Code uses a leading size perC2x priciple.
```
char *getaline(int size, char *s, const char *prompt) {
if (prompt) {
fputs(prompt, stdout);
}
if (fgets(s, size, stdin)) {
... |
I am trying to write address of array buffer in address.txt file.
I do not know why the following code does not work. The following is the code I have:
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int func(char *str)
{
int variable_a;
char buffer[12];
FILE *fp;
fp = fopen( "address.tx... |
If you want to write an address, use%pto format to pointer address
```
fprintf(fp, "%p", &buffer);
```
Will do the trick
|
```
#include <stdio.h>
int main() {
if (~0 == 1)
printf("yes\n");
else
printf("no\n");
}
```
why is theifstatement false? can anyone explain?
|
~Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
So when you do~0 == 1it will check for-1 == 1which is false
|
How to find size of char** array, I have been doing
```
int getSize(char** args)
{
int size = (int)sizeof(args)/ (int)sizeof(arg[0]);
return size;
}
```
But it is only returning the value 1. I cant seem to figure out how to find out how many elements are in my array of char*.
|
The standard way is used byargvand the environment table (in most implementations): terminate an array ofchar *pointers to strings with aNULL:
```
Array element Points to
0 -> "string 0"
1 -> "string 1"
2 -> "string 2"
. -> .
. -> .
. -> ... |
If i have a char array of 4 bytes in size and i try to cast him into a unsigned int(4 bytes too), the compiler give me an errorwarning: cast from pointer to integer of different size [-Wpointer-to-int-cast] no_pointer = (unsigned int) char_array;Why give me this error if both variables have 4 bytes in size?
Code:
``... |
You cannot assing arrays by value because they get converted to address to first element. Your code is equivalent to:
```
no_pointer = (unsigned int) &char_array[0];
```
Usememcpyinstead:
```
_Static_assert(sizeof no_pointer == sizeof char_array, "Size mismatch"); // Extra safety check to make sure that size match
... |
Is there any simple way-library to efficient (max possible speed) implement linear algebra on an ARM CortexA9 dual core usingXilinx SDK?
I am using a zybo z7 developememt board with a dual core Arm proccesor and i want to implement a simple neural network with one convolution layer followed by a dense one, on Xilinx ... |
You can try theEigenlibrary used by Tensorflow to implement the matrix calculations, or you can even try to useTensorFlow litewhich is already tested with the ARM-Cortex M series of processors.
|
Looking for an understanding of what is happening here as both statements appear the same.
So while thec >> 1output is what I was expecting, shifting the wrapped uint in-place changes the result.
```
#include <stdio.h>
#include <stdint.h>
int main() {
uint16_t a, b, c;
a = 20180;
b = 4106;
c = b - a... |
The "in-place" operation promotes a and b to int, and the result will also be an int that you then shift.
In your assignment of c = b - a, the operation is first promoted to int operation, executed, then type casted back to uint (to be set in c).
The keyword to search for is "integer promotion"
|
For some reason, this program compiles in C:
```
int x;
x = 3+-+-5+-5;
printf("%d\n",x);
```
And in general, alternating "+" and "-" compiles. It seems like if there are odd "-" then it'll subtract, otherwise, add.
What in the world is this?
|
In cases such as these, the first + or - to the right of the left-hand operand indicates the binary operation to perform; the other + and - after that are the unary + and - operators applied to the right-hand operand. The unary + operand does nothing and - changes the sign. This gives rise to the behavior you see: an ... |
How the extracted JSON o/p of Jmeter response to be fed to external Go/C/Java application?
My requirement is to analyze the o/p of Jmeter by external program and log the analysis result ( o/p of external program), basically Jmeter response will provide input parameters to the external program.
|
If you want to save response of a JMeter'sSamplerinto a file - just addSave Responses to a filelistener and specify the desired file location:
Example configuration:
Once you run your request and get the response - JMeter will store it into a file under the given path so you will be able to "feed" it to an externa... |
I thought I understood how memory works until I run this code, is memory backwards ? or I'm missing something ?
Code:
```
#include <stdio.h>
int main()
{
int a = 0x12345678;
char *c = (char *)&a;
for (int i = 0; i < 4; i++)
{
printf("c[%d]=%x \n", i, *(c + i));
}
return 0;
}
```
O... |
What you have just done is demonstrate which "endian" your computer's architecture is using (i.e., your computer uses "little endian", not "big endian").
If your computer's architecture had instead been "big endian", then your output would instead have been this:
```
c[0] = 12
c[1] = 34
c[2] = 56
c[3] = 78
```
You ... |
I can't figure out how to get the input to show-up after Enter a Character. Would appreciate if someone can help me figureout how.
```
#include <stdio.h>
#include <conio.h>
const int ESC = 27;
char change_case(char cIn);
int main() {
char ch;
do {
printf("Enter a character: \n");
ch = _g... |
_getch()/getch()does not echo the keyboard input. Use_getche()instead - it does echo input.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed2 years ago.Improve... |
Not in standard C, but GCC and clang provide the__typeof__extension which does what you want.
|
So I've been trying to do this but I just can't think of a solution for this. I've got this bit of code but it outputs it backwards(if the answer is 11110 I get 01111):
```
#include <stdio.h>
int base(int n)
{
if(n==0)
return 0;
else
{
printf("%d",n%2);
}
return base(n/2);
}
int... |
As@ricistated, a very simple fix is to print after the recursive call:
```
#include <stdio.h>
void base(int n){
if(n==0)
return;
base(n/2);
printf("%d",n%2);
}
int main() {
int n;
scanf("%d",&n);
base(n);
return 0;
}
```
|
How a C compiler like GCC defines the preprocessor macro to detect the current OS?
I looked into GCC's source code and foundthisbuiltin_define ("_WIN32");but I'm not sure if this is where the macros are defined.
|
TL;DR: Basically, yes. The built-in macros are defined in a target description header file.
There is so often a Fine Manual To Read; in this case, it's theGCC internals manual. (Specifically, in the section onRun-time target specification, but don't start reading there; you'll need some context.)
There is acomplete ... |
How the extracted JSON o/p of Jmeter response to be fed to external Go/C/Java application?
My requirement is to analyze the o/p of Jmeter by external program and log the analysis result ( o/p of external program), basically Jmeter response will provide input parameters to the external program.
|
If you want to save response of a JMeter'sSamplerinto a file - just addSave Responses to a filelistener and specify the desired file location:
Example configuration:
Once you run your request and get the response - JMeter will store it into a file under the given path so you will be able to "feed" it to an externa... |
I thought I understood how memory works until I run this code, is memory backwards ? or I'm missing something ?
Code:
```
#include <stdio.h>
int main()
{
int a = 0x12345678;
char *c = (char *)&a;
for (int i = 0; i < 4; i++)
{
printf("c[%d]=%x \n", i, *(c + i));
}
return 0;
}
```
O... |
What you have just done is demonstrate which "endian" your computer's architecture is using (i.e., your computer uses "little endian", not "big endian").
If your computer's architecture had instead been "big endian", then your output would instead have been this:
```
c[0] = 12
c[1] = 34
c[2] = 56
c[3] = 78
```
You ... |
I can't figure out how to get the input to show-up after Enter a Character. Would appreciate if someone can help me figureout how.
```
#include <stdio.h>
#include <conio.h>
const int ESC = 27;
char change_case(char cIn);
int main() {
char ch;
do {
printf("Enter a character: \n");
ch = _g... |
_getch()/getch()does not echo the keyboard input. Use_getche()instead - it does echo input.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed2 years ago.Improve... |
Not in standard C, but GCC and clang provide the__typeof__extension which does what you want.
|
So I've been trying to do this but I just can't think of a solution for this. I've got this bit of code but it outputs it backwards(if the answer is 11110 I get 01111):
```
#include <stdio.h>
int base(int n)
{
if(n==0)
return 0;
else
{
printf("%d",n%2);
}
return base(n/2);
}
int... |
As@ricistated, a very simple fix is to print after the recursive call:
```
#include <stdio.h>
void base(int n){
if(n==0)
return;
base(n/2);
printf("%d",n%2);
}
int main() {
int n;
scanf("%d",&n);
base(n);
return 0;
}
```
|
How a C compiler like GCC defines the preprocessor macro to detect the current OS?
I looked into GCC's source code and foundthisbuiltin_define ("_WIN32");but I'm not sure if this is where the macros are defined.
|
TL;DR: Basically, yes. The built-in macros are defined in a target description header file.
There is so often a Fine Manual To Read; in this case, it's theGCC internals manual. (Specifically, in the section onRun-time target specification, but don't start reading there; you'll need some context.)
There is acomplete ... |
Im learning about typecasting in void pointers
and the part of *((typecasting) void_pointer) i am not undestanting why need this *( before the real type casting.
Can someone explain me this part of code:
```
printf("[int pointer] points to %p, which contains the int %d\n", void_pointer, *((int *) void_pointer));
```... |
I'm assuming thatvoid_pointeris of typevoid *. Void pointers can point to any type, you can't dereference them directly. So let's break down*((int *) void_pointer. First, it is casted to anintpointer (this is what(int *) void_pointer) does. Then, the pointer is dereferenced in order to get the value it points to. You ... |
I need to read specific charters from terminal, How can I do this? I need reading this characters[,],{,},(,). Is there any way to do this usingscanf?
I triedscanf("%[(,),[,]]s", string), but it does not work.
|
You need to include]first in the list of characters to match so that it is not taken as terminating the conversion specifier. Also, unless you want to match commas, don't include them. And unless you want to match a literals, don't put thesin the format string. The conversion specifier ends with]. I think you're ... |
According to BSON specification an int32_t is used for the total number of bytes comprising the document.
I can also see that mongo-c-driver is using Libbson and it's using int32_t.
But what is the reason to usesignedinteger instead ofunsignedinteger?
the document size will never be below 0. Can someone please expl... |
Document size is limited to 16 MB, which fits in a signed 32-bit integer with room to spare.
While document size limits larger than 16 MBwereconsidered, my guess is there was no serious consideration of document sizes exceeding 2 GB, therefore the difference in range afforded by using unsigned 32-bit integers for len... |
Trying to get an struct initializer from a tertiary operator in a macro function doesn't work, it gives a bunch of errors, what should be the right way to do this:
```
#define newVar(name, type, value) (( (type) == _STRING ) ? { name, type, (long)value }) : ({ name, type, (double)value } )
```
Edit:
Sorry, i wrote a... |
You may not use the ternary (conditional) operator such a way in an initialization because the operator expects three expressions. However these constructions{ name, type, (long)value }and{ name, type, (double)value }are not expressions. They are initializer lists.
For example you may write
```
int x = { 10 };
```
... |
I am working fixing on some coverity issues and i am confused about how to solve toctou for stat a directory and make a directory.
```
////////////////////////////////////
// Make sure storage dir exists. If
// not, create it.
if( stat( dir, &statBuff ) != -1 )
{
if( S_ISDIR( statBuff.st_mode ) )
{
if... |
Just domkdir(). If the directory already exists,EEXISTwill tell you. Accept either zero or this return-code to indicate that you have, one way or the other, now accomplished your objective. "Race conditions" cease to be an issue sincemkdir()has taken care of that for you.
|
I have the following code:
```
int main(int argc,char **argv){
char *flags=malloc(1*sizeof(char));
flags[0]='a';
printf("%s\n",flags);
free(flags);
return 0;
}
```
No more, no less.
If I comment out the printf, no error occurs.
Why does it give me this error and how can I solve it?
|
Withprintf("%s\n",flags);,flagsshould point to memory that contain astring.
flagsmemory does not contain anull chracter, so is not a string.
Either 1, make allocated memory assigned toflagsbigger and append a'\0'or 2, use a limited print:printf("%.1s\n",flags);or 3) print achar:printf("%c\n",*flags);
|
Trying to get an struct initializer from a tertiary operator in a macro function doesn't work, it gives a bunch of errors, what should be the right way to do this:
```
#define newVar(name, type, value) (( (type) == _STRING ) ? { name, type, (long)value }) : ({ name, type, (double)value } )
```
Edit:
Sorry, i wrote a... |
You may not use the ternary (conditional) operator such a way in an initialization because the operator expects three expressions. However these constructions{ name, type, (long)value }and{ name, type, (double)value }are not expressions. They are initializer lists.
For example you may write
```
int x = { 10 };
```
... |
I am working fixing on some coverity issues and i am confused about how to solve toctou for stat a directory and make a directory.
```
////////////////////////////////////
// Make sure storage dir exists. If
// not, create it.
if( stat( dir, &statBuff ) != -1 )
{
if( S_ISDIR( statBuff.st_mode ) )
{
if... |
Just domkdir(). If the directory already exists,EEXISTwill tell you. Accept either zero or this return-code to indicate that you have, one way or the other, now accomplished your objective. "Race conditions" cease to be an issue sincemkdir()has taken care of that for you.
|
I have the following code:
```
int main(int argc,char **argv){
char *flags=malloc(1*sizeof(char));
flags[0]='a';
printf("%s\n",flags);
free(flags);
return 0;
}
```
No more, no less.
If I comment out the printf, no error occurs.
Why does it give me this error and how can I solve it?
|
Withprintf("%s\n",flags);,flagsshould point to memory that contain astring.
flagsmemory does not contain anull chracter, so is not a string.
Either 1, make allocated memory assigned toflagsbigger and append a'\0'or 2, use a limited print:printf("%.1s\n",flags);or 3) print achar:printf("%c\n",*flags);
|
I'm trying to format a string like this:
```
printf("%d%c", buffer[i], i == num_ints-1? '': ',');
```
So that the numbers print like this:
```
123,929,345
```
Yet doing''is invalid. Is it possible to simulate a 'nothing-char' or just not do anything in the ternary?
|
You can't have an empty char, but you can have empty strings. So use%s.
```
printf("%d%s", buffer[i], i == num_ints-1? "": ",");
```
|
I know this may sound stupid but, why is this function I implemented not working properly?
I get the following error in the terminal:
```
cerinta3.c: In function ‘void realocare_memorie(student**, int)’:
cerinta3.c:9:19: error: invalid conversion from ‘void*’ to ‘student*’ [-fpermissive]
9 | *vector = realloc(*... |
You compiled your C code through a C++ compiler (g++by the error message). This is the signature error of making that mistake. Invokegccinstead.
|
I know this may sound stupid but, why is this function I implemented not working properly?
I get the following error in the terminal:
```
cerinta3.c: In function ‘void realocare_memorie(student**, int)’:
cerinta3.c:9:19: error: invalid conversion from ‘void*’ to ‘student*’ [-fpermissive]
9 | *vector = realloc(*... |
You compiled your C code through a C++ compiler (g++by the error message). This is the signature error of making that mistake. Invokegccinstead.
|
I see that when I use that code:
```
char c,d;
scanf("%s",&c);
scanf("%s",&d);
printf("%c%c",c,d);
```
seems fix the problem of save ENTER character indvariable.
It's a good way or compiler add the string terminator in the memory address next tocvariable (equals fordvariable)?
|
No, because it will also want to null-terminate the string. In other words, write to*(d + 1)(at least!), and that's undefined behavior (namely, overflow).
|
I'm trying to port some code from C to Python.
I have in C:
```
unsigned char bPort = 7777 ^ 0xCC;
printf("\n %d \n", bPort);
```
Which prints 173
But then in Python
```
bPort = 7777 ^ 0xCC
print(bPort)
```
this prints 7853
|
```
unsigned char bPort = 7777 ^ 0xCC;
```
is equivalent to
```
unsigned char bPort = the least significant 8 bits of 7777 ^ 0xCC;
```
unsigned charonly stores 8 bits.
The same is not true of Python. I'm not an expert on the numerical types in Python, but I suspect that's either a 32 bit integer or a floating poi... |
I am using the following code to calculate pi in C but the answer is only being printed to 6dp.
code:
```
#include<stdio.h>
#include<stdlib.h>
long double calc_pi(int terms) {
long double result = 0.0F;
long double sign = 1.0F;
for (int n = 0; n < terms; n++) {
result += sign/(2.0F*n+1.... |
You can add a precision specifier to yourprintf()format specifier to have it print more digits.
```
int main(int argc, char* args[]) {
long double pi = calc_pi(atoi(args[1]));
printf("%.30LF", pi); /* have it print 30 digits after the decimal point */
}
```
|
I am so confused about the return of getopt. When does it return (-1) ?
When I assign it to an int variable, it returns (-1) if I don't write any options in the terminal window. Whereas it returns the first option character in ascii even if I write more than one option.
But when using it without assigning, it return... |
In your example with 2 arguments getopt will return a different value each time you will call it. The first time it will return 'a' then it will return 'b' and the last time it has no more options to read from and will return -1
It should be handled within a loop like thishttps://www.tutorialspoint.com/getopt-functio... |
I am so confused about the return of getopt. When does it return (-1) ?
When I assign it to an int variable, it returns (-1) if I don't write any options in the terminal window. Whereas it returns the first option character in ascii even if I write more than one option.
But when using it without assigning, it return... |
In your example with 2 arguments getopt will return a different value each time you will call it. The first time it will return 'a' then it will return 'b' and the last time it has no more options to read from and will return -1
It should be handled within a loop like thishttps://www.tutorialspoint.com/getopt-functio... |
I did research trying to visualise how complex number in <complex.h> are stored in RAM. I know for integers, floating points but not for complex. Is it just 2 number like in complex struct ?
|
The layout is specified in C11 6.2.5/13:
Each complex type has the same representation and alignment requirements as an array
type containing exactly two elements of the corresponding real type; the first element is
equal to the real part, and the second element to the imaginary part, of the complex
number.
|
When the user inputs a sentence with ECE in it, the program should output ECE found!, but when ECE is the only input the program does not detect it.
I believe that all of the other cases work.
I can not use arrays or strings for this program.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input;
... |
Don't put commas in between the%c %c %c. They are not needed.
Scanf()does something weird with characters in the%carea.
|
I am writing a GTK+ frontend program that shreds files. The programshredfrom GNU Coreutils is the backend. The programming language is C.
So, I have a progress bar that show how much of the shredding is finished. But, in order to give the user accurate data on how much is shredded, the output of shred must be analyze... |
The easiest solution is using unix redirection. You can callsystem("shred -v file_to_shred > somefile.txt")and the output will be redirect to the file. You can then read from the file using POSIX read or some other file reading method. Run thesystem()call in a seperate thread, and the just incremently check the file i... |
```
using namespace std;
int main() {
int input;
int i=0;
while (1){
scanf("%d", &input);
printf("%d input:%d\n", i, input);
i++;
}
}
```
Stdin Inputs:
10
65
100
30
95
.
.
.
Is there a way to stop the code and escape from while loop after hitting the last Input?
Amount o... |
```
using namespace std;
int main() {
int input;
int i=0;
while (1){
scanf("%d", &input);
printf("%d input:%d\n", i, input);
i++;
if (i >= 5) break; //change 5 to your desired amount of inputs
}
}
```
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed2 years ago.Improve... |
Replace the following line:
```
scanf(" %f", &N);
```
fstands for your float.
|
I'm trying to loop through a string by using a pointer and[]for the string, and the pointer should get on each iteration the char address, from tail to head:
```
int main(void)
{
char* s = "somestring";
char* s_p;
int len = strlen(s);
for (s_p = &s[len - 1]; s_p = &s[1]; s_p--)
{
//do some... |
Loop condition should use comparison operator, not assignment operator=.
I guess the intention was to use!=.
```
s_p = &s[1] --> s_p != &s[1]
```
|
In our development, we switched from IAR ARM V7.40 to IAR ARM V8.40
We are using the python packagepyelftoolsfor postprocessing of the debug information. Unfortunately, this seems to be broken now, as the V8-compiler seems to use DWARF4 syntax, which is not fully covered by pyelftools. The V7-compiler used DWARF3 whi... |
There is a hidden compiler option--no_dwarf4which disables DWARF4. This works fine for our problem.
Unfortunately, this compiler option is neither documented in theIAR C/C++ Development Guidenor listed in the command line help ($ iccarm --help) for the compiler.
|
So I have to make an add method that will take two 16 bit integers and return that result without using arithmetic operators. Unfortunately when inputting two numbers like 5 and 10, it returns 0 instead of 15. Is there anything I'm doing wrong in my code? The code is given below and is done in C
```
addition_subtract... |
You returnaddition(hopefully by value) and the only thing you set isaddition.overflow = false;
|
I have the following code:
```
ll_data_comp sh_program_comp(int pid) {
int comp(void* d) {
sh_program_t* p = d;
return p->pid == pid;
}
return comp;
}
```
Sincecompis declared insh_program_comp, does that mean it's declared on the stack?If so, does that mean there's potential for a seg fault if it's us... |
I have the following code:
And you have tagged your question withC99. The following code is invalid - it's not possible to define a function within a block scope.
The code may be compiled with GNU gcc compiler withNested Functionsextensionto the C language. But from the documentation:
If you try to call the nested... |
I'm trying to get a copy of the RGBTRIPLE image array
```
void blur(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE arrayCopy = image[height][width];
for (int i = 0; i < height; i++)
{
for (int w = 0; w < width; w++)
{
printf("%i", arrayCopy[i][w].rgbtRe... |
A copy of the whole 2D array?
```
RGBTRIPLE arrayCopy[height][width];
memcpy(arrayCopy, image, sizeof arrayCopy);
//not sizeof image, it is a pointer to an array, not an array
```
or just a pointer toimage?
```
RGBTRIPLE (*arrayCopy)[width] = image;
```
usage is the same as you already did.
|
when declaring for example a malloc and then checking if it is NULL to see if it has been properly allocated, should I free the memory if it is null, example:
```
int *p;
p = (int *)malloc(sizeof(int));
if (p == NULL)
{
free(p); //Should I free here or will it create an error?
return NULL;... |
Ifmallocreturns a null pointer it has failed to allocate anything at all, and there's nothing to free.
With that said, passing a null pointer tofreedoes nothing, so it's safe.
On a related note, in C you shouldn't reallycast the result ofmalloc.
|
Let's take two examples of having 'stuff' between a keyword:
```
#include <stdio.h>
int main(void)
{
printf("OK\n");
pri\
ntf("OK\n"); // version 1
pri/**/ntf("Hi"); // version 2
return 0;
}
```
That is, having a comment/* ... */and a\/n. How are these two supposed to be treated, or i... |
I save the code in file a.cpp,
then pre-compile the code:
```
gcc -E a.cpp
```
The output is:
```
int main(void)
{
printf("OK\n");
printf("OK\n");
pri ntf("Hi");
return 0;
}
```
The first case can pass the compile. but for the second case, gcc will replace/**/to blank, then compile will fail.
gcc... |
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed2 years ago.
```
#include<stdio.h>
int main()
{
int i = 1;
printf("%d %d %d",++i,i++,i);
return 0;
}
```
|
(not an answer, but further discussion)
It really seems like an interesting question (at least for me, as I am also a C newby).
I tried the followingsnippet:
```
//gcc 7.4.0
#include<stdio.h>
int main() {
int i = 1;
printf("%d %d %d\n",pr(++i),pr(i++),pr(i)); // 3 1 1
i=1;
printf("%d %d %d",++i,i++,i); // 3 1 3
re... |
I'm learning C but I don't understand why the error appears on line number 9
---> scanf("%[^\n]s",&cadena); // i tried with "%s" but still doesnt work.
```
#include <stdio.h>
int main(void)
{
char cadena[40];
printf("Ingrese cadena: ");
fflush(stdin);
scanf("%[^\n]s",&cadena);
printf("La... |
Remove the ampersand on cadena in scanf
```
scanf("%[^\n]", cadena);
```
An array decays to a pointer so you were actually passing a pointer to a pointer in that case.
Also you can just write it like this
```
scanf("%s",cadena);
```
Depends on your end goal though.
|
I wrote following C function:
```
unsigned long long int myfunction(unsigned long long int number)
{
return number;
}
```
and after making a shared library I want to calling it from python:
```
from pathlib import Path
from ctypes import CDLL, c_ulonglong
cwd = Path.cwd()
so_file = Path.joinpath(cwd, Path("myl... |
They python code assumes the c function returns an int. You can fix it by adding:
```
c_func.restype = c_ulonglong
```
|
I work on Linux. In have a legacy OpenGL application which includes gl.h. I would like to define a function pointer for storing glXGetProcAddress result:
```
typedef void (GLACTIVETEXTUREARB)(GLenum texture);
extern GLACTIVETEXTUREARB glActiveTextureARB;
```
but I get the following error:redefinition of glActiveTex... |
Use a define to rewrite the original name:
```
#define glActiveTextureARB glh__glActiveTextureARB
#include<gl.h>
#undef glActiveTextureARB
```
By the way, yourgl.hprobably already hasPFNGLACTIVETEXTUREARBPROCdefined as the function pointer type you want to have, so you don't need to redefine it.
|
This question already has answers here:How should character arrays be used as strings?(4 answers)Closed2 years ago.
```
#include <stdio.h>
int main() {
char str3[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
char str4[ ] = {'h', 'e', 'l', 'l', 'o'};
printf("%s, %s", str3, str4);
return 0;
}
```
The ou... |
str4has no 0-terminator, soprintfkeeps reading out of bounds of the array and by luck (or not) there seems to bestr3directly behindstr4, so it reads till the 0-terminator ofstr3.
In the end ==> undefined behavior, don't rely on that.
|
If you input even numbers, only the odd numbers will be printed until it reaches 0. (0 will not be printed). For example, if you input 10, the output would be 9, 7, 5, 3, 1.
This is what I came up with. I'm wondering what should I decrement x by to get the desired output.
```
int x;
scanf("%d", &x);
while (x >= 0) {... |
I'm wondering what should I decrement x by to get the desired output.
Subtracting 2 is fine, as long as you always start from an odd number. So you could change the loop into something like this:
```
for ( int i = x % 2 ? x : x - 1; // Is x odd? good.
// Otherwise, start from the pr... |
So I got a function that passes in bool as an input that I declared withvoid check_Winner(bool locked_[9][9]);
The error happens when I call it in "print_Winner" function:
```
bool locked[9][9];
void print_Winner(void)
{
for (int j=0;j<pair_count;j++)
{
check_Winner(locked[0][j]);
}
... |
The function is taking in parameter an array:
```
void check_Winner(bool locked_[9][9]);
```
But the function call is providing a bool (locked[0][j]is a bool):
```
check_Winner(locked[0][j]);
```
|
So I got a function that passes in bool as an input that I declared withvoid check_Winner(bool locked_[9][9]);
The error happens when I call it in "print_Winner" function:
```
bool locked[9][9];
void print_Winner(void)
{
for (int j=0;j<pair_count;j++)
{
check_Winner(locked[0][j]);
}
... |
The function is taking in parameter an array:
```
void check_Winner(bool locked_[9][9]);
```
But the function call is providing a bool (locked[0][j]is a bool):
```
check_Winner(locked[0][j]);
```
|
When using realloc, it's better to check against possible null pointers, as:
```
int *tempPtr=realloc(ptr1,size);
if(tempPtr==NULL){
fprintf(stderr,"Error allocating memory at line %d\n",__LINE__);
exit(-1);
}
ptr1=tempPtr;
```
The problem with this approach is that it creates a new variable and if this isn't in... |
You can place these expressions in a block scope of its own. Essentially just encapsulate the expression within braces, ie:
```
{
int *tmpptr = realloc(ptr1, size);
if (tmpptr == NULL) {
panic("allocation failed");
}
ptr1 = tmpptr;
}
// Continue executing code here
// note that moving forwards... |
Checksumof a number is the sum of all its digits.I wrote the following program to find the checksum of a number:
```
#include <stdio.h>
int read(){
int read;
printf("number between 1000 and 100.000: ");
scanf("%d", &read);
return read;
}
int calcSum(int num){
int a;
if (num < 10)
retur... |
Ifa > 10, you are performing the same operation multiple times. Just do:
```
int calcSum(int num) {
int a;
if (num < 10)
return num;
a = calcSum (num / 10) + num % 10;
return a;
}
```
|
How can I use struct pointers with designated initialization? For example, I know how to init the struct using the dot operator and designated initialization like:
```
person per = { .x = 10,.y = 10 };
```
But If I want to do it with struct pointer?
I made this but it didn't work:
```
pper = (pperson*){10,5};
```
|
Ifpperis aperson *that points to allocated memory, you can assign*ppera value using a compound literal, such as either of:
```
*pper = (person) { 10, 5 };
*pper = (person) { .x = 10, .y = 5 };
```
If it does not already point to allocated memory, you must allocate memory for it, after which you can assign a value:
... |
I'm trying to run some python code from my c program by using the python.h header but I keep gettingfatal error: Python.h: No such file or directory
After checking my anaconda environment, I have found a Python.h file in...Anaconda/envs/myenv/includeI tried adding this path to my system variable's PATH but it didn't ... |
PATHis only used for executables, not C headers. Tell your compiler or build system to add this path. On gcc and clang, for example, it's the-Iflag.
|
I have two integer variables:
int i1 = 0xdeadbeefandint i2 = 0xffffbeef.
(11011110101011011011111011101111 or 37359285591and111111111111111110111110111011111 or 4294950639respectively).
(int) (float) i1 == i1evaluates as false, yet(int) (float) i2 == i2evaluates as true.
Why is this? In this system, bothintsandf... |
This is becausefloathas far less precision thanint, it can't store all possibleintvalues without them suffering some damage. Sometimes this damage just rounds your value, sometimes your rounded value matches precisely.
A32-bitfloatcan only store 24 "significand bits", or numerical data. Other bits are reserved for th... |
I'm playing around with C strings as in the following programme:
```
#include <stdio.h>
int main(void){
char *player1 = "Harry";
char player2[] = "Rosie";
char player3[6] = "Ronald";
printf("%s %s %s\n", player1, player2, player3);
return 0;
}
```
Which prints the following:
```
Harry Ro... |
Ronaldhas 6 letters, sochar player3[6]leaves no space for the null-terminator character'\0'.
In your case, it printed whatever comes afterRonaldin memory until a'\0'was encountered. That happened to beRosie. You might not always be so lucky and run into an error (e.g. memory protection) before finding a'\0'.
One sol... |
I'm playing around with C strings as in the following programme:
```
#include <stdio.h>
int main(void){
char *player1 = "Harry";
char player2[] = "Rosie";
char player3[6] = "Ronald";
printf("%s %s %s\n", player1, player2, player3);
return 0;
}
```
Which prints the following:
```
Harry Ro... |
Ronaldhas 6 letters, sochar player3[6]leaves no space for the null-terminator character'\0'.
In your case, it printed whatever comes afterRonaldin memory until a'\0'was encountered. That happened to beRosie. You might not always be so lucky and run into an error (e.g. memory protection) before finding a'\0'.
One sol... |
I've been stuck with this for a while. I can't really figure out why I'm getting this message:
I get the error message: "Segmentation fault (core dumped)" when I first compile gcc my_program.c and then run it ./a.out my_program.c
Main file:https://i.stack.imgur.com/usdsc.jpgHeader file:https://i.stack.imgur.com/jJeuu... |
It's probably line 37 in the main file. You should change printlist(node) to printnod(node). That ought to fix it.
|
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU.
I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9
Below is the Query and response.
query : 33 02 00 00 00 47 3C 2A
resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68
|
You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.
|
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU.
I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9
Below is the Query and response.
query : 33 02 00 00 00 47 3C 2A
resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68
|
You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.
|
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.Closed2 years ago.Improve this question
This is my code. When i run the code it sends me an error:
```
helloworld.c:8:16: error: storage size of '... |
The initializer of a static variable must be known at compilation time. That's why the declaration ofbinis rejected. Instead you need to declarebinas a pointer to an integer and allocate memory dynamically, that is at run-time:
```
int *bin = malloc(size * sizeof *bin);
```
As pointed out by rioV8, you should also f... |
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed2 years ago.Improve this question
my teacher gave me this program for assignment. I did my assignment but cant understood w... |
Macros are just text replacement (info for nitpickers: I know about tokens). Macros are processed before compilation (thus term preprocessing),
The compiler is compiling the code after all the macros are replaced:
```
int main(){
printf("%sABCDE","%sABCDE");
return 0;
}
```
I think that now everything is clear.... |
Is it required, or recommended, that every pointer in C be allocated on the heap? For example, is it likely or possible that the following code could produce a segmentation fault?
```
#include <stdio.h>
int main(void) {
int* p;
*p = 16;
printf("Pointer p = %d\n", *p);
return 0;
}
```
|
This code will likely segfault becausepis uninitialized and therefore doesn't point to a valid address.
A pointer doesn't necessarily have to point to heap memory. It just needs to point to a valid object. For example:
```
int x = 4;
int *p = &x;
*p = 5;
printf("x=%d\n", x); // prints 5
```
|
i want to set rise the priority and the affinity of irq processes (spi, gpiod) in linux, from a program written in C/C++. To set the priority of my own process I usepthread_setschedparamto set the affinity of my own process I usepthread_setaffinity_np. I use pthread_self() for this functions. However especially the gp... |
I solved it by using libprocps. It is possible to get the pid of the irq via the name of the gpio or of the spi device and then to set the cpu affinity/priority of the irq.
|
Trying to do a rank based voting algorithm. Rank tells order of voter preference. For example if rank is 0, this is the first choice of the voter. I'm trying to save the order of names to the array but it doesn't work.
Error is at the ranks[rank] = name;
```
bool vote(int rank, string name, int ranks[])
{
for (i... |
Your are trying to store a String value in int array.
Either change the type of ranks array to String or change type of name to int.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.