question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I am reading Carnegie Mellon slides on computer systems for my quiz. In theslidepage 49 :
Counting Down with UnsignedProper way to use unsigned as loop indexunsigned i;
for (i = cnt-2; i < cnt; i--)
a[i] += a[i+1];Even bettersize_t i;
for (i = cnt-2; i < cnt; i--)
a[i] += a[i+1];
I don't get why it's not going to be infinite loop. I am decrementingiand it is unsigned so it should be always less thancnt. Please explain.
|
The best option for down counting loops I have found so far is to use
```
for(unsigned i=N; i-->0; ) { }
```
This invokes the loop body with i=N-1 ... 0. This works the same way for both signed and unsigned data types and does not rely on any overflows.
|
I'm trying to attach an interrupt to a pin using wiringPI'swiringPilSR. My code looks like this:
```
#include <wiringPi.h>
#include <stdio.h>
int inPin = 3;
void myInterrupt();
int main(vodi){
wiringPilSetupGpio();
pinMode(inPin, INPUT);
wiringPilSR(inPin, INT_EDGE_RISING, &myInterrupt);
while(1){
printf("Cycle repeated\n");
delay(1000);
}
return 0;
}
void myInterrupt(){
printf("Interrupted");
return 0;
}
```
When I try to build the code in Geany, I get a warning "implicit declaration of function 'wiringPilSR'" and error "undefined reference to 'wiringPilSR'". I have set the build commands as shown in thistutorial on sparkfun
|
The functionwiringPilSRisn't spelled with a lowercaseL (l), instead its 9th character is an uppercasei (I)
There goes one hour for figuring it out
|
I need to get the remaining value of a 3d vector "v[3]"
I have a function that returns the remaining axis having the other two as parameters:
```
static get_remain_axis(const short a, const short b) {
if (a == 0) {
if (b == 1)
return 2;
else
return 1;
}
else if (a == 1) {
if (b == 0)
return 2;
else
return 0;
}
else {
if (b == 0)
return 1;
else
return 0;
}
}
```
So I could do so:
```
v[get_remain_axis(a, b)]
```
But I need efficiency in this operation, and if possible, it would be nice if it were atomic.
How to do this function more efficiently?
|
At least as I read things, you have axes0,1and2. The inputs are two of those, and you want to return the third one.
Assuming that's the case, the three numbers need to add up to 3, so you can just do:return 3 - (a + b);
|
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.Closed6 years ago.Improve this question
How to use<graphics.h>functiondrawpoly(int numpoints, int *polypoints)with array of float coordinates?
(I guess that's the reason polygon degenerates rotating or zooming)
Or do I need to make a function which draw a polygon with standardline(...)-function?
|
If you mean THE graphics.h from Turbo C, CPU's of that age may not even be able to do floating point operations. One have to emulate fp operations with integral one, which is very slow. So, you are hoping too much.
You could live with those little errors, or just switch to some morden graphics API's.
And I don't think line() accepts float.
|
I have aconditionand three variables.
```
// Assume these variables are all initialized.
int *a;
int *b;
const int c;
const bool condition;
if (condition)
*a = c;
else
*b = c;
```
I want theifblock to be on one line through a ternary conditional operator.
```
(condition ? *a : *b) = c;
```
I don't see why that's not allowed as I'm not breaking the rule of ternary conditional operators. Both*aand*breturn the same type.
|
This is not allowed in C because*ais anintvalueaftera pointer dereference and a conditional; is not anlvalue, i.e. not assignable. However, this is allowed:
```
*(condition ? a : b) = c;
```
Now that the conditional produces a pointer, and the dereference happens outside of it, the overall expression is an assignable lvalue.
You can expand this to two conditions and three pointers:
```
*(condition1 ? a : (condition2 ? b : c)) = d;
```
|
Is it normal that there will be no packet losses in a UDP client-server if both are on the same machine? I'm currently calculating packet loss by taking the difference between the bytes obtained from thesendtoandrecvfromfunctions on the client side ? Am I doing something wrong ?
|
I would beverysurprised if there was any packet loss in such a case. But on the other hand you use the wrong way to calculate any loss.
Remember that UDP is apacket orientedprotocol, which means that what you send will be a packet, and what you receive will be a packet, and there will be no difference in the size of what you send and receive. If you send a 512-byte packet, the receiver will always receive the full 512-byte packet, or nothing at all.
That means you should count the number of times you callsendto, and compare the number of times thatrecvfromreturns with a packet.
|
I looked on the Linux man pages for the answer but can't seem to find it. I know thatread()is blocking but I'm still not sure aboutwrite().
Can anyone point me to any documentation for clarification?
|
Read POSIX onread()andwrite(). See also functions such asopen()andpipe().
It depends on the attributes of the file descriptor you're reading from or writing to (thinkO_NONBLOCK, for example), and on the underlying file type (disk file vs pipe vs FIFO vs socket vs character or block special), and so on.
Succinctly, bothread()andwrite()can be blocking or non-blocking, depending on circumstances.
|
Hey I am currently learning C and tried to divide my code in multiple files. But when it comes to compile the project, I got this error :
```
mingw32-gcc.exe -Wall -g -c D:\IDE\CodeBlocks\Projects\Tuto\main.c -o obj\Debug\main.o
mingw32-g++.exe -o bin\Debug\Tuto.exe obj\Debug\dico.o dico.h.gch obj\Debug\main.o
dico.h.gch: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status
```
I tried to clean and/or rebuild my project but nothing goes through this issue. Can anyone help me please ??
|
dico.h.gchis a precompiled header. You aren't supposed to link it with your objects. Remove it from the line that createsTuto.exe.
|
As my topic says, I want to know a method to send a value to a function which is called by another function. For example:
```
int main(){
int sendingvalue=funtionreturningvalue();
int x=0;
function1(x);
}
function1(int x){
//some code here
function2(x);
}
function2(int y){
//again some code here
function3();
}
function3(){
//here I need the top value sendingvalue
}
```
It is so useless to explicitly pass thatint sendingvalueagain and again in all the functions until it reachesfunction3. So what is the best option to pass this value?
|
There are 2 options. You either make it a global variable, or you pass it through each function.
To make it a global variable, add the following line outside all of your function definitions:
```
int sendingvalue;
```
Then you access modify and read it from any function. If you don't want to use a global variable, you'll have to pass it along the stack.
|
This question already has answers here:What API do I call to get the system uptime?(5 answers)Closed6 years ago.
I want to find a way to find the linux system's uptime.
I do not want to read the uptime file in/proc/.
Any other way?
|
```
#include <stdio.h>
#include <sys/sysinfo.h>
int main(void)
{
struct sysinfo sys_info;
sysinfo(&sys_info);
printf("Seconds since uptime: %lu\n", sys_info.uptime);
return 0;
}
```
This should get you started. If you need more help, typeman sysinfointo the terminal.
|
I'm trying to compile some old source code which makes use of both ieee754.h and ieee854.h in it's Make dependencies.
Problem is, I can't find ieee854.h in any new, official repositories. From what I understood, ieee754.h superseded 854.
Now, I'm not sure whether to just copy and paste ieee854.h from somewhere else and use it, replace it instead with 754, or deleted links to 854 altogether
|
Solved it.
Since IEEE754 superseded 854, it only made sense to remove any links to 854 and keep the 754 calls, or replace them with 754.
I also changed some floating point and math functions inside files requiring them as there were some errors.
Everything compiles and works as it should now.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
I have a drive called "E". How do I check if it is removable from my c program?
|
Here is the code for achieving what you want:
```
#include <FileAPI.h>
//
//
if(GetDriveType("E:\\") == DRIVE_REMOVABLE)
{
// Above mentioned drive is a removable drive
}
```
Refer:https://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx
|
As my topic says, I want to know a method to send a value to a function which is called by another function. For example:
```
int main(){
int sendingvalue=funtionreturningvalue();
int x=0;
function1(x);
}
function1(int x){
//some code here
function2(x);
}
function2(int y){
//again some code here
function3();
}
function3(){
//here I need the top value sendingvalue
}
```
It is so useless to explicitly pass thatint sendingvalueagain and again in all the functions until it reachesfunction3. So what is the best option to pass this value?
|
There are 2 options. You either make it a global variable, or you pass it through each function.
To make it a global variable, add the following line outside all of your function definitions:
```
int sendingvalue;
```
Then you access modify and read it from any function. If you don't want to use a global variable, you'll have to pass it along the stack.
|
This question already has answers here:What API do I call to get the system uptime?(5 answers)Closed6 years ago.
I want to find a way to find the linux system's uptime.
I do not want to read the uptime file in/proc/.
Any other way?
|
```
#include <stdio.h>
#include <sys/sysinfo.h>
int main(void)
{
struct sysinfo sys_info;
sysinfo(&sys_info);
printf("Seconds since uptime: %lu\n", sys_info.uptime);
return 0;
}
```
This should get you started. If you need more help, typeman sysinfointo the terminal.
|
I'm trying to compile some old source code which makes use of both ieee754.h and ieee854.h in it's Make dependencies.
Problem is, I can't find ieee854.h in any new, official repositories. From what I understood, ieee754.h superseded 854.
Now, I'm not sure whether to just copy and paste ieee854.h from somewhere else and use it, replace it instead with 754, or deleted links to 854 altogether
|
Solved it.
Since IEEE754 superseded 854, it only made sense to remove any links to 854 and keep the 754 calls, or replace them with 754.
I also changed some floating point and math functions inside files requiring them as there were some errors.
Everything compiles and works as it should now.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
I have a drive called "E". How do I check if it is removable from my c program?
|
Here is the code for achieving what you want:
```
#include <FileAPI.h>
//
//
if(GetDriveType("E:\\") == DRIVE_REMOVABLE)
{
// Above mentioned drive is a removable drive
}
```
Refer:https://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx
|
This question already has answers here:Undefined, unspecified and implementation-defined behavior(9 answers)Closed6 years ago.
I can understand leaving something implementation defined, so that the particular people implementing it would know what's best to happen, but why would something ever be undefined behavior? Why not just say, anything else is implementation defined?
|
There are a lot of cases in which ensuring an implementation defined behavior inevitably incurs overhead.
For example, how to make buffer overflow an implementation defined behavior? Maybe throw exception when it's detected, or maybe terminate the program? But doing that always requires bounds-checking.
C++ is designed in such a way that performance is almost never compromised.
There are languages like Go, Rust, and Java which do bounds-checking. And they all incur overhead to pay the price for the safety.
|
I'm trying to compile some old source code which makes use of both ieee754.h and ieee854.h in it's Make dependencies.
Problem is, I can't find ieee854.h in any new, official repositories. From what I understood, ieee754.h superseded 854.
Now, I'm not sure whether to just copy and paste ieee854.h from somewhere else and use it, replace it instead with 754, or deleted links to 854 altogether
|
Solved it.
Since IEEE754 superseded 854, it only made sense to remove any links to 854 and keep the 754 calls, or replace them with 754.
I also changed some floating point and math functions inside files requiring them as there were some errors.
Everything compiles and works as it should now.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
I have a drive called "E". How do I check if it is removable from my c program?
|
Here is the code for achieving what you want:
```
#include <FileAPI.h>
//
//
if(GetDriveType("E:\\") == DRIVE_REMOVABLE)
{
// Above mentioned drive is a removable drive
}
```
Refer:https://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx
|
This question already has answers here:Undefined, unspecified and implementation-defined behavior(9 answers)Closed6 years ago.
I can understand leaving something implementation defined, so that the particular people implementing it would know what's best to happen, but why would something ever be undefined behavior? Why not just say, anything else is implementation defined?
|
There are a lot of cases in which ensuring an implementation defined behavior inevitably incurs overhead.
For example, how to make buffer overflow an implementation defined behavior? Maybe throw exception when it's detected, or maybe terminate the program? But doing that always requires bounds-checking.
C++ is designed in such a way that performance is almost never compromised.
There are languages like Go, Rust, and Java which do bounds-checking. And they all incur overhead to pay the price for the safety.
|
I am trying to pass some data to openssl like this:
```
int fd[2];
char buff[MAXBUFF];
pid_t childpid;
pipe(fd);
childpid = fork();
if (childpid == 0){
dup2(0, fd[0]);
close(fd[1]);
execlp("openssl", "s_client", "-connect", "imap.gmail.com:993", "-crlf", NULL);
}
else {
close(fd[0]);
dosomething(buff);
write(fd[1], buff, strlen(buff) + 1);
sleep(4);
}
```
But it seems like openssl does not get data from buff, it just hangs waiting for some input I think.
If I do same thing with bash
a.sh:
```
.
.
.
echo $data
sleep 3
.
.
.
```
b.sh:
```
openssl s_client -connect imap.gmail.com:993 -crlf
```
./a.sh | ./b.sh
everything works fine.
|
You switched the arguments ofdup2().
The prototype is:
```
int dup2(int oldfd, int newfd);
```
so you should do
```
dup2(fd[0], 0);
```
to setfd[0]as stdin of the child process. Then it should work as expected.
|
The question is very simple and direct, but I could not find an answer on thedocumentation. If I have
```
mpfr_t a, b;
```
Can I do something like
```
mpfr_add(a, a, b, rnd);
```
This would compute the sum ofaandband store the result ona. I don't know if this results in an aliasing problem, potentially invalidating the result, or if this is fine.
|
Never mind, it's in section 4.3 of the linked document.
MPFR allows you to use the same variable for both input and output in the same expression. For example, the main function for floating-point multiplication, mpfr_mul, can be used like this: mpfr_mul (x, x, x, rnd). This computes the square of x with rounding mode rnd and puts the result back in x.
|
When callingWSASend(), I have to pass it aWSAOVERLAPPEDinstance, and I cannot re-use thisWSAOVERLAPPEDinstance until the previousWSASend()operation has been completed (i.e. when a completion packet has been placed in the completion port).
Is there a way I can know if theWSASend()operation has been completed without callingGetQueuedCompletionStatus()?
|
you need bind own socket to system created IOCP as result when operation finished your callback will be called automatic. you have 2 options here:
useBindIoCompletionCallback- this will be work from Windows
XP (really even from win2000)useCreateThreadpoolIo- work from Windows Vista
after you create socket by
```
SOCKET socket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 0, WSA_FLAG_OVERLAPPED)
```
you need callBindIoCompletionCallback((HANDLE)socket, *,0)orCreateThreadpoolIo((HANDLE)socket, *, 0, 0);
and all. you not need callGetQueuedCompletionStatus()or wait at all
|
This question already has answers here:How to disable Warnings of Visual Studio 2012?(2 answers)Closed6 years ago.
I just started to work with files so I made this program that just opens a file but i get the error:
```
error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
```
here is the code:
```
#include <stdio.h>
int main()
{
FILE* f = fopen("myFile.txt", "w");
if (f == NULL)
{
printf("error\n");
return;
}
fclose(f);
}
```
|
You need to place a definition of#define _CRT_SECURE_NO_DEPRECATEbefore your include. Like,
```
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
```
|
Im new to programming with C and I'm having a hard time coming up with the proper formula to where it ignores, spaces, tabs, and new lines when I enter a string
My Current Code
|
Replaceelse specialCharacter++;withelse if(!isspace(str[x])) specialCharacter++;.
|
I am compiling a program and was getting an "undefined reference" to a constant variable defined in a C file in lib1 which is used in lib2. I get the error if I compile as:
```
clang myfile.c -L. -L../lib2dir -llib1 -llib2
```
I remembered from my Unix days that sometime you have to add a library again. So I did:
```
clang myfile.c -L. -L../lib2dir -llib1 -llib2 -llib1
```
and it linked. Why is this still necessary or am I doing something wrong and it shouldn't be necssary?
|
The libraries are linked in the order in which they are placed on the command line. When a library is linked, only the missing symbols are resolved from it. Since the symbol that you mention is inlib2, it will not be resolved fromlib1, because the linker does not know yet that it will be needed later. So, put-llib2in front of-llib1.
|
For a class project I am writing, my teacher's style guide for functions says that "input parameters must appear before out parameters." I am not too sure what they mean by this?
|
If I have a function
```
void foo(int a, int b, int* c)
{
*c = a+b;
}
```
In the above case a and b are inputs while c is an output.
Generally you use "outputs" in this way if you are returning an array.
|
I'm in confusion!
I have a simple chardev and user space app that sends/receives a buffer to/from chardev viaioctl.
When I allocate the buffer (in user space) viamalloc(on heap) I sometimes have a segmentation fault in user space app onfree()or kernel panic.
And every time something one of them.
But, If I replacemalloc()byalloca()(allocate buf on stack) everything works fine every time.
Also I triedmemset(buf, 0x42, buf_len)after callingmalloc(to avoid compiler optimization or lazy allocation / copy on write)
and it doesn't help.
Could you please explain such behavior?
What is the problem withmalloc/ what am I doing wrong?
|
Thanks for suggestions!
The problem was in the user space side (classic user-space memory corruption symptoms).
So, it is safe to use malloced buffers in kernel space <-> user space communication.
I just thought that there is some special rules to put buffer on heap into the kernel space.
|
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.Closed6 years ago.Improve this question
How can I format fonts in a Linux terminal using C?
|
Fonts do not exist in the standardC11orC99programming language specification(s).
If you are writing a graphical application in C for Linux, consider using some library likeGTK,libSDL, etc...
If you want to do someAscii Artin a terminal (read thetty demystifiedwebpage), be aware ofANSI escape codesand consider using some terminal output library likencurses.
|
I try to get the name of the folder / file pointed by the symbolic link.
For example, when you dols -lYou can get this result
```
-rw-r--r-- 1 macos staff 0 Feb 22 12:05 test
lrwxr-xr-x 1 macos staff 7 Feb 19 11:05 sl -> test
```
How could I do, if I know the path of sl to get the file/folder here it pointed to ?
I want to do it usingstatif possible.
Any suggestion ?
|
So to summarize :
It's impossible to get the name of the file/folder pointed by a symbolic link, usinglstatorstat.
The function readlink can do the job => Man :http://man7.org/linux/man-pages/man2/readlink.2.html. You will get example in the man
Thank you for helping me solve my problem
|
I need Mysql-connector-odbc library to include in my project without any need to GUI. But when I use cmake to configure and then make library, I get error that I have not any gtk or gtk.h installed on my system like this:
```
fatal error: gtk/gtk.h: No such file or directory
```
So, the question is, how to disable GUI in mysql odbc?Thanks.
|
After reading some of CMakefiles and Readme files inside the library, I got that the simplest way to disable gui in mysql odbc is using of cmake parameters.For this, you can just addDISABLE_GUIand set it to1. So you disallow Cmake to make GUI and other related library depend on gtk.h header file.You can see a simple Cmake command to do this:
cmake -DDISABLE_GUI=1
|
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.Closed6 years ago.Improve this question
I want to find the midpoint of an array in C say:{2,5,7,23,1,8,3,8,2}with an expected result of 1. Also if the array is even in the case of{2,6,9,231,62,3}, I expect to get any of the middle values -9or231in this case.
I am completely unsure how to go about this.
|
As per your problem description, regardless of whether your array has even or odd number of elements, the middle element index is always length/2.
```
int main() {
int a[] = {2,5,7,23,1,8,3,8,2};
//Figure out the size of the array
int n = sizeof(a) / sizeof(int);
printf("The mid point is %d", a[n/2]);
}
```
|
For this quote:
An identifier list in a function declarator that is not part of a
definition of that function shall be empty.
what is the difference between identifier list and parameter list and can someone provide an example for this quote.
|
The "identifier list" is only used in obsolete "K&R style" functions. New code written today would never use it. You can see more details here:https://stackoverflow.com/a/3092074/4323
It's something like this:
```
void func(identifier-list)
declaration-list
{
body
}
```
When they say it shall be empty, they mean that even admitting the possibility of ancient code, you are not allowed to have this in a declaration which does not define a function. So for example this is not allowed:
```
void func(x) int x;
```
|
This question already has answers here:Alternative for-loop syntax [duplicate](2 answers)Closed6 years ago.
```
for ( declaration expressionopt ; expressionopt ) statement
```
This second syntax of for loop is only with one semicolon but whenever I try to use it, it generates an error saying that:
```
error: expected `;` before `)` token
```
|
The C11 standard specifies two forms for theforloop (§6.8.5 Iteration statements):
for(expressionopt;expressionopt;expressionopt)statementfor(declarationexpressionopt;expressionopt_)statement
The rule for 'declaration' ends with a semicolon, so there must be two semicolons in the control section of aforloop.
§6.7Declarationsdeclaration:declaration-specifiersinit-declarator-listopt;static_assert-declaration
|
I did not understand why this works:
```
if(1)
{
int i;
}
```
and this not:
```
if(1)
int i;
```
error: expected expression before int
If you could supply some standard reference.
|
In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).
|
I did not understand why this works:
```
if(1)
{
int i;
}
```
and this not:
```
if(1)
int i;
```
error: expected expression before int
If you could supply some standard reference.
|
In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).
|
When I run my C code that includes
```
#include <math.h>
```
and later down in a for loop
```
distance[i] = (float) pow((float) pow(X1[i] - xpos[i],2)+(float) pow(X2[i] - ypos[i],2),0.5);
```
and attempting to compile with
```
gcc test.c -o test -1m
```
I get the error
```
gcc: error: unrecognized command line option ‘-1m’
```
Do I need to download something onto my computer or something?
When I have a different maths expression in the for loop (one that doesn't need math.h) my code compiles and run perfectly.
|
That's supposed to be-lmwith a lowercase L for "library". You're linking the math library.
|
Got this
```
char array1[10][10];
```
Is it possible to get address of array1 ? In which type could I stock it ?
Already tried the following:
```
char *hold[10][10];
hold = &array1;
```
But doesnt work, ideas?
|
What you have now is a 2D array ofchar *. You need some parenthesis in this type.
```
char (*hold)[10][10];
```
This is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.
|
Can someone please explain to me the difference between saya=1and*a=1in C. I'm having difficulty conceptualizing how pointers are used.
|
a = 1assigns1toa.
*a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
I want to compile C/C++ programs that are supposed to run on MS-DOS, can I do this without actually installing DOS?
If I can not, can I use a virtual machine as a work-around? (I tried this before asking but I can't see if they will work on an actual DOS on a physical machine)
|
Yes -- there are compiler toolchains likeDJGPPandOpenWatcomwhich can build DOS executables on a Windows (or even Linux!) system.
Alternatively, if you already have a DOS toolchain that you want to use, you can certainly run that under an emulator likeDOSBox.
|
I have an embedded C program in a constrained system which reads sensor measurements. I would like to calculate a running average during the last N sensor readings from the time that some event takes place. I want the calculation to use only integer operations (no floating point). Also I don't have enough storage to maintain all N readings so I want to create a running average total somehow and add to that total each time I get a new reading. One formula that I have seen to approximate this is
```
avg = ((avg * (n-1)) + currentReading) / n;
```
When I coded and tested this, however the calculated average was always less than if I add all the N readings and divided by N. How to improve this?
|
Just keep the running total along the number of values - two integers required. Simple sum at the end (or whenever you want).
|
I need to create a binary search tree in c. Inside the tree is a list of words organized by the first letter. Each node contains the letter and a list of words(strings) beginning with that letter, as well as pointers to the other nodes. I'm not sure how I should do the list of words inside the structure. Should I create a new structure to do the list? What's the best way?
So far my structure is:
```
typedef struct Node {
char letter;
//where the list of words begginning with letter should be
struct Node *left;
struct Node *right;
} Node;
```
|
You can create another struct for the list that you include in the node. Then you can create separate functions to manipulate the list:
```
struct LIST {
char *word;
struct LIST *next;
};
typedef struct Node {
char letter;
struct LIST *words;
struct Node *left;
struct Node *right;
} Node;
```
|
```
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *bannerViewAdUnitID = [defaults valueForKey:@"admobBannerViewID
```
give "Declaration shadows a local variable warning"
"Previous declaration is here:"
```
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL admobStatus = [defaults integerForKey:@"admobTurnedOn"];
```
should I remove first instance? or how I can fix this warning?
|
Remove the second
```
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
```
instance. The firstdefaultsinstance should still be available, so you don't need the second call to[NSUserDefaults standardUserDefaults];.
|
Got this
```
char array1[10][10];
```
Is it possible to get address of array1 ? In which type could I stock it ?
Already tried the following:
```
char *hold[10][10];
hold = &array1;
```
But doesnt work, ideas?
|
What you have now is a 2D array ofchar *. You need some parenthesis in this type.
```
char (*hold)[10][10];
```
This is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.
|
Can someone please explain to me the difference between saya=1and*a=1in C. I'm having difficulty conceptualizing how pointers are used.
|
a = 1assigns1toa.
*a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
I want to compile C/C++ programs that are supposed to run on MS-DOS, can I do this without actually installing DOS?
If I can not, can I use a virtual machine as a work-around? (I tried this before asking but I can't see if they will work on an actual DOS on a physical machine)
|
Yes -- there are compiler toolchains likeDJGPPandOpenWatcomwhich can build DOS executables on a Windows (or even Linux!) system.
Alternatively, if you already have a DOS toolchain that you want to use, you can certainly run that under an emulator likeDOSBox.
|
I have an embedded C program in a constrained system which reads sensor measurements. I would like to calculate a running average during the last N sensor readings from the time that some event takes place. I want the calculation to use only integer operations (no floating point). Also I don't have enough storage to maintain all N readings so I want to create a running average total somehow and add to that total each time I get a new reading. One formula that I have seen to approximate this is
```
avg = ((avg * (n-1)) + currentReading) / n;
```
When I coded and tested this, however the calculated average was always less than if I add all the N readings and divided by N. How to improve this?
|
Just keep the running total along the number of values - two integers required. Simple sum at the end (or whenever you want).
|
I need to create a binary search tree in c. Inside the tree is a list of words organized by the first letter. Each node contains the letter and a list of words(strings) beginning with that letter, as well as pointers to the other nodes. I'm not sure how I should do the list of words inside the structure. Should I create a new structure to do the list? What's the best way?
So far my structure is:
```
typedef struct Node {
char letter;
//where the list of words begginning with letter should be
struct Node *left;
struct Node *right;
} Node;
```
|
You can create another struct for the list that you include in the node. Then you can create separate functions to manipulate the list:
```
struct LIST {
char *word;
struct LIST *next;
};
typedef struct Node {
char letter;
struct LIST *words;
struct Node *left;
struct Node *right;
} Node;
```
|
```
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *bannerViewAdUnitID = [defaults valueForKey:@"admobBannerViewID
```
give "Declaration shadows a local variable warning"
"Previous declaration is here:"
```
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL admobStatus = [defaults integerForKey:@"admobTurnedOn"];
```
should I remove first instance? or how I can fix this warning?
|
Remove the second
```
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
```
instance. The firstdefaultsinstance should still be available, so you don't need the second call to[NSUserDefaults standardUserDefaults];.
|
This question already has answers here:Can I share a file descriptor to another process on linux or are they local to the process?(6 answers)Closed6 years ago.
```
int fd = socket(//arguments);
```
Can this descriptor be passed to another process via IPC and still be valid or is it local to the process that created it?
|
File descriptors are local to the process. For instance, every process will have its standard input, output, and error on file descriptors 0, 1, and 2.
It is possible to pass a file descriptor to another process over a UNIX domain socket.When this is done, each process will have a copy of the file descriptor, possibly under a different FD number. It's a kind of messy API, though, and is rarely used.
|
Can anyone explain what $(%SYMBOLIC) means in the make file target below?
```
R_all: $(%SYMBOLIC)
$(CD_MAKE) $(BASE_ROOT) R_all
```
|
That's just a variable called%SYMBOLIC. Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve
|
Below is the code
```
char* StrStr(const char *str, const char *target) {
if (!*target) return str;
char *p1 = (char*)str;
while (p1 != NULL) {
char *p1Begin = p1, *p2 = (char*)target;
while (*p1 && *p2 && *p1 == *p2) {
p1++;
p2++;
}
if (!*p2)
return p1Begin;
p1 = p1Begin + 1;
}
return NULL;
}
```
If I use if(p2==NULL) instead of if(!*p2) then I get segmentation fault. Why?
Line 14http://codepad.org/ZUqXVCJ9
Is if(!*p2) is same as if(p==NULL)?
Why I am getting segmentation fault.
|
Nop2 == NULLis not the same as!*p2. If anything,p2 == NULLis equivalent to!p2.
When you do!*p2you firstdereferencethe pointerp2, and then check if the valuep2ispointingto is "false". Ifp2is a null pointer, that dereference will not be valid.
|
This question already has answers here:Can I share a file descriptor to another process on linux or are they local to the process?(6 answers)Closed6 years ago.
```
int fd = socket(//arguments);
```
Can this descriptor be passed to another process via IPC and still be valid or is it local to the process that created it?
|
File descriptors are local to the process. For instance, every process will have its standard input, output, and error on file descriptors 0, 1, and 2.
It is possible to pass a file descriptor to another process over a UNIX domain socket.When this is done, each process will have a copy of the file descriptor, possibly under a different FD number. It's a kind of messy API, though, and is rarely used.
|
Can anyone explain what $(%SYMBOLIC) means in the make file target below?
```
R_all: $(%SYMBOLIC)
$(CD_MAKE) $(BASE_ROOT) R_all
```
|
That's just a variable called%SYMBOLIC. Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve
|
Below is the code
```
char* StrStr(const char *str, const char *target) {
if (!*target) return str;
char *p1 = (char*)str;
while (p1 != NULL) {
char *p1Begin = p1, *p2 = (char*)target;
while (*p1 && *p2 && *p1 == *p2) {
p1++;
p2++;
}
if (!*p2)
return p1Begin;
p1 = p1Begin + 1;
}
return NULL;
}
```
If I use if(p2==NULL) instead of if(!*p2) then I get segmentation fault. Why?
Line 14http://codepad.org/ZUqXVCJ9
Is if(!*p2) is same as if(p==NULL)?
Why I am getting segmentation fault.
|
Nop2 == NULLis not the same as!*p2. If anything,p2 == NULLis equivalent to!p2.
When you do!*p2you firstdereferencethe pointerp2, and then check if the valuep2ispointingto is "false". Ifp2is a null pointer, that dereference will not be valid.
|
I am trying to put the result from:
```
system("/14/test");
```
into a variable named "ZZZ" and thenprintfit.
```
#include <stdio.h>
#include <stdlib.h>
char ZZZ[10];
int main()
{
char * ZZZ = system("/14/test");
printf(ZZZ);
}
```
Error:
warning: initialization makes pointer from integer without a cast
[-Wint-conversion]
|
system()doesn't capture the output of the command it runs - just the return code of command is returned by it.
Usepopen()and read from theFILE*usingfgets(). Something like:
```
char buf[1024];
FILE *fp = popen("/14/test", "r");
while(fgets(fp, buf, sizeof buf)) {
printf("%s\n", buf);
}
```
|
Below is the code
```
char* StrStr(const char *str, const char *target) {
if (!*target) return str;
char *p1 = (char*)str;
while (p1 != NULL) {
char *p1Begin = p1, *p2 = (char*)target;
while (*p1 && *p2 && *p1 == *p2) {
p1++;
p2++;
}
if (!*p2)
return p1Begin;
p1 = p1Begin + 1;
}
return NULL;
}
```
If I use if(p2==NULL) instead of if(!*p2) then I get segmentation fault. Why?
Line 14http://codepad.org/ZUqXVCJ9
Is if(!*p2) is same as if(p==NULL)?
Why I am getting segmentation fault.
|
Nop2 == NULLis not the same as!*p2. If anything,p2 == NULLis equivalent to!p2.
When you do!*p2you firstdereferencethe pointerp2, and then check if the valuep2ispointingto is "false". Ifp2is a null pointer, that dereference will not be valid.
|
I am trying to put the result from:
```
system("/14/test");
```
into a variable named "ZZZ" and thenprintfit.
```
#include <stdio.h>
#include <stdlib.h>
char ZZZ[10];
int main()
{
char * ZZZ = system("/14/test");
printf(ZZZ);
}
```
Error:
warning: initialization makes pointer from integer without a cast
[-Wint-conversion]
|
system()doesn't capture the output of the command it runs - just the return code of command is returned by it.
Usepopen()and read from theFILE*usingfgets(). Something like:
```
char buf[1024];
FILE *fp = popen("/14/test", "r");
while(fgets(fp, buf, sizeof buf)) {
printf("%s\n", buf);
}
```
|
I have a GtkEntry which GtkEntryCompletion is completed with actions. Those actions are added dynamicaly with (ie their numbers and name can vary) with :
https://developer.gnome.org/gtk3/stable/GtkEntryCompletion.html#gtk-entry-completion-insert-action-text
In the documentation, there is a function in order to remove an action based on its index. Since I don't keep tracks of the indexes and I don't want to, is there a way to remove all the actions in order to add new ones ?
|
It seems that there is no another way than to save the number of actions I add. I use it when I need to remove all the actions like this :
```
for (guint i = 0; i < num_actions; i++) {
gtk_entry_completion_delete_action (entry_completion, 0);
}
```
The 0 value is the index. Since this index is relative, I just have to remove the action 0 n times.
|
So , i am trying to create a function that takes a linked list and an integer x as parameters , and searches the list for that x and when it finds it , makes the node that contains it head of the list and returns the place where it found x, this is what i have created so far but the results it gives are wrong
```
int searchMF(list &l,int x){
node *curr,*temp;
curr=l.front;
temp=curr;
int i,place=0;
if (l.front->info == x ) return 1;
else{
FOR (i,1 TO size(l)) {
if (curr->info == x) {
temp->next=curr->next;
curr->next=l.front;
place=i;
break;
}
temp=curr;
curr=curr->next;
}
return place;
}
}
```
Any recommendations would be appreciated
|
Aftercurr->next=l.front;you need to update thel.frontto point tocurr.
```
curr->next=l.front;
l.front = curr;
```
Also pureCcode would have been more helpful in debugging the problem.
|
I have readthis question, but I would like to get better timing precision than a second: is this possible with some function of libc?
This is to use insidewith nogil, so of course no Python is allowed...
|
You can use POSIXclock_gettime():
```
from posix.time cimport clock_gettime, timespec, CLOCK_REALTIME
cdef timespec ts
cdef double current
clock_gettime(CLOCK_REALTIME, &ts)
current = ts.tv_sec + (ts.tv_nsec / 1000000000.)
```
This snippet store incurrentthe number of seconds since epoch with up to a nanosecond precision (depending on your system).
You can also usegettimeofday(), but it is now deprecated:
POSIX.1-2008 marks gettimeofday() as obsolete, recommending the use of clock_gettime(2) instead.
|
I find myself in many situations that I should have stored an array or bunch of structures in ROM instead of RAM. Then I go through all the code and make changes like adding PROGMEM, pgm_read_word(), pgm_read_byte(). It is a hard task to do especially after writing like 4000 lines of code.
Is there a trick that could be done to do this easier?
|
You should look into using GCC'snamed address spacesfeature. This feature was enabled for AVRs in GCC 4.7, so you'll have to make sure you are using GCC 4.7 or later. This will allow you to specify to the compiler what memory space your variables are in, and what memory space your pointers point to. Then you can access the variables with regular C syntax instead of using functions likepgm_read_byte.
Note:As of GCC 4.9.2, the named address spaces are only supported in the GNU C compiler,notthe C++ compiler, which the Arduino IDE uses.
|
I have been told that "%a" used in C's printf would display hexadecimal format of a number. To test it, I print out the representation of 2^10:
```
printf ("%a", pow(2.0,10));
```
which gives
```
0x1p+10
```
I am confused because the exponent part "+10" looks more like a decimal format rather than a hexadecimal format. A hexadecimal format should have been1pA. Where am I wrong?
|
It's correct, that format is called hexadecimal fordoubles.
The man page says:
Foraconversion, thedoubleargument is converted to hexadecimal
notation (using the lettersabcdef) in the style[-]0xh.hhhp[+-]d[...]
the exponent consists of a positive or negative sign followed by a
decimal number representing an exponent of 2.
So it's correct that while the mantissa is in hex, the exponent is still decimal.
|
I came to this question when I wrote one "unintended" piece of code, and compiled it successfully and got the desired behavior. Later I noted the oddity of the change and realized that I used a complete reverse order of doing typedef of function pointers. Now I am confused if the "unintended" mistake is actually syntactically correct.
Usual convention:
```
typedef void* (*_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
_malloc_fail_handler_ptr _malloc_fail_handler = NULL;
```
My "unintended" code:
```
typedef void* (_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
_malloc_fail_handler_ptr* _malloc_fail_handler = NULL;
```
|
It's correct syntax. For the 2nd case, the type of_malloc_fail_handler_ptris function, not function pointer. Then the type of_malloc_fail_handler_ptr*is pointer to function. So for both the 1st and 2nd cases, the type of the variable_malloc_fail_handleris the same.
|
```
#include <stdio.h>
int main(){
int c, nl=0;
while((c = getchar()) != EOF)
if(c=='\n')
nl++;
printf("%d",nl+1);
return 0;
}
```
On Ubuntu 18.04, GCC 7.3.0
There's no output on console when thegetchar()comparison is made withEOF. it works fine with other characters. UsingCTRL^Dexits the program with 'code 0' without any output on console. I've tried running it in bash but still no output.
input:
line 1line 2line 3line 4line 5
expected output:
5
actual output:
program exited with code 0
|
On *nix systemsEOFis generated byCtrl^Dwhereas on Windows systemEOFis generated byCtrl^Z. I am assuming that you are using Windows system. Seehttps://en.wikipedia.org/wiki/End-of-file
|
This question already has answers here:string comparison inside if condition malfunctioning [duplicate](2 answers)Closed6 years ago.
I am trying to implement anIF STATEMENTin myC-Server.
```
read(client_fd,received_data,100);
printf("%s",received_data);
```
I want to print "ooo" if the received data equals to "test"
```
if (received_data == "test") {
printf('ooo');
}
```
?
The above example results in errors. (can't compile)
I don't know much C.
UPDATE :
Now I can compile fine ( after changing'ooo'to"ooo")But although I am sending "test" to it.. if statement is not doing anything i think.
|
The==doesn't work forconst char *.
Usestrcmpinstead.
|
This question already has answers here:C Programming: Forward variable argument list(3 answers)Closed6 years ago.
Say I want to implement a function
```
void myprintf(const char* format, ...){
printf("Hello world!\n"),
printf(format, ...);
}
```
I.e. I want to pass along the varargs list to printf. Is there any convenient way to do this?
|
No. However the library functions in theprintffamily offer avprintfvaraintthat accepts ava_listas an argument instead of ellipsis. And it is in fact a good practice to offer such a variant if you happen to be writing your own variable argument function.
Your wrapper would then be something like this:
```
void myprintf(const char* format, ...){
printf("Hello world!\n"),
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
```
|
I will take hex input from user intobufferarray, but i don't take it,scanfdoes not appropriate. Input data like this (0x 06 41 42 43 0f 52 53). Also then i want to transform string to integer type some part of array. I usedatoi, what is best way for it?
```
#include <stdio.h>
int main(){
char buffer[1000];
char dest[3];
int x;
//scanf("%s",buffer);
x=atoi(strncpy(dest,buffer+1,4))
}
```
|
The following simple function converts a string with a hexadecimal number to an integer:
```
int atox(const char *s)
{
int x= 0;
while (*s) {
x= x*16+(*s>'9'?(toupper(*s)-'A'+10):*s-'0');
s++;
}
return x;
}
```
and call it like:
```
printf("%02x\n",atox("42"));
printf("%02x\n",atox("a1"));
printf("%02x\n",atox("A1"));
```
Note that the string must be exactly the string to convert, so no spaces or whatever.
|
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.Closed6 years ago.Improve this question
I've had that doubt for several days. Does anyone have any experience to tell about it? Thanks in advance.
|
For example if you have your function namedsomeFuncWhichReturnsLongwhich returnslongand then somewhere you assign result of it toint, you might get a warning thatlongmight not fit insideint- however, if you know thatin your casethat functionsomeFuncWhichReturnsLongnever returns value larger thanint, you can ignore that warning.
On the other hand if you get a warning that you are using an incorrect format specifier say inprintf, ignoring this will end up in undefined behavior.
In general you should never ignore warnings, and check what it is trying to say.
|
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.Closed6 years ago.Improve this question
I am looking for a way to backupMySqldatabase use aCprogram. DoesMySqlprovide API for backup?
|
No, mysql does not provide any dpecific api to back a database up.
Mysql does provide themysqldumputility that can be called from the command line to back up a database and also provides ageneral C apito access a mysql server. The heneral api can be used to write your own backup program if you are unhappy with mysqldump.
|
I wrote a function to find binary value of an integer.
```
int binary(int n)
{
if(n>0)
{
int x=n%2;
binary(n/2);
printf("%d",x);
}
}
```
This gives the correct output while the below one gives an infinite loop.
```
int binary(int n)
{
while(n>0)
{
int x=n%2;
binary(n/2);
printf("%d",x);
}
}
```
Why is this happening?
|
Every time you call recursive function binary, you send new value which is2times smaller than previous. At one point, that value will reach0, andn>0will be false, so you won't get into loop and you will return from last recursive function. Since you haven't changed value ofnwhen you called function again,nstill has value of 1, and from this point, it won't ever be changed.1is always greater than0, so you will be stack into infinite loop.
|
This question already has answers here:Two semicolons inside a for-loop parentheses(4 answers)Closed6 years ago.
I'm analyzing a C program and i find this loop that i can't understand. There is no counter or limit or variable.
```
/* ioloop */
for (;;)
{
// statements
}
```
is this an infinite loop ?
|
It's an idiomatic way of writing a potentially infinite loop in C.
Alternatives such aswhile(1)often issued a compiler warning.
|
I was reading the source code of zmq, and came across the followingtypedef
```
typedef struct {unsigned char _ [32];} zmq_msg_t;
```
I don't understand what the underscore means in this definition. Could someone please help shed some light?
|
An underscore (_) is a valid identifier, in this case, a name of the member of the structure. It does not have anyspecialmeaning, as such.
QuotingC11, chapter §6.4.2.1,Identifiers
An identifier is a sequence of nondigit characters (including the underscore_, the
lowercase and uppercase Latin letters, and other characters) and digits, which designates
one or more entities [....]
AFAIR, this is true in case of C++, also, refer chapter 2.11, C++14.
|
This question already has answers here:string comparison inside if condition malfunctioning [duplicate](2 answers)Closed6 years ago.
I am trying to implement anIF STATEMENTin myC-Server.
```
read(client_fd,received_data,100);
printf("%s",received_data);
```
I want to print "ooo" if the received data equals to "test"
```
if (received_data == "test") {
printf('ooo');
}
```
?
The above example results in errors. (can't compile)
I don't know much C.
UPDATE :
Now I can compile fine ( after changing'ooo'to"ooo")But although I am sending "test" to it.. if statement is not doing anything i think.
|
The==doesn't work forconst char *.
Usestrcmpinstead.
|
This question already has answers here:C Programming: Forward variable argument list(3 answers)Closed6 years ago.
Say I want to implement a function
```
void myprintf(const char* format, ...){
printf("Hello world!\n"),
printf(format, ...);
}
```
I.e. I want to pass along the varargs list to printf. Is there any convenient way to do this?
|
No. However the library functions in theprintffamily offer avprintfvaraintthat accepts ava_listas an argument instead of ellipsis. And it is in fact a good practice to offer such a variant if you happen to be writing your own variable argument function.
Your wrapper would then be something like this:
```
void myprintf(const char* format, ...){
printf("Hello world!\n"),
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
```
|
```
#include <stdio.h>
int main(void)
{
char ch;
setbuf(stdout, NULL);
while ( (ch = fgetc(stdin) ) != '\n' && ch != EOF){
fputc(ch, stdout);
fflush(stdout);
};
return 0;
}
```
Why I see is not a character to enter a character on the console, but in the press the Enter key together after all the output, the key is that I close the output buffer and refresh the output buffer.
|
By default, terminals are incanonical mode, where the input is passed to the program only when a line delimiter (newline, end of input at the start of a line, and so on) is typed.
The way to manipulate the terminal -- for example, to get keypresses immediately when they occur -- varies between operating systems. The Curses libraries (PDCursesfor Windows, ncurses for just about all others) hide the differences under a single interface, so you might wish to look into that.
|
What's the exact difference betweenprintkandpr_infofunctions ? And under what conditions, should I choose one over the another ?
|
Thekernel's printk.hhas:
```
#define pr_info(fmt,arg...) \
printk(KERN_INFO fmt,##arg)
```
Just like the name,pr_info()isprintk()with theKERN_INFOpriority.
|
```
#include <stdio.h>
int main(void)
{
char ch;
setbuf(stdout, NULL);
while ( (ch = fgetc(stdin) ) != '\n' && ch != EOF){
fputc(ch, stdout);
fflush(stdout);
};
return 0;
}
```
Why I see is not a character to enter a character on the console, but in the press the Enter key together after all the output, the key is that I close the output buffer and refresh the output buffer.
|
By default, terminals are incanonical mode, where the input is passed to the program only when a line delimiter (newline, end of input at the start of a line, and so on) is typed.
The way to manipulate the terminal -- for example, to get keypresses immediately when they occur -- varies between operating systems. The Curses libraries (PDCursesfor Windows, ncurses for just about all others) hide the differences under a single interface, so you might wish to look into that.
|
I am working on a project in the X11 API, and I have a Window based custom control consistently rendering. But for some reason, when I re-size the window, the control does not redraw unless I interact with the control directly, or move the entire main window.
|
I found the solution to my problem. I just needed to add the Structure Notify Mask to my custom window input.
```
XSelectInput(display, CustomWindow, StructureNotifyMask);
```
|
I have this simple C code with a Macro:
```
#include <stdio.h>
#define MAX(x, y) x>y ? 1 : 0
int main() {
int i = 9;
printf("%d\n", MAX(10, i) + 1);
return 0;
}
```
Now as I understand the macro function if the value of x (which is 10) is greater than the value of y (which is 9 in this case) then the macro returns 1 other wise zero. So shouldn't the output above be 2 instead of 1 in this case after adding 1 to the final result of the macro?
|
MAX(10, i) + 1is replaced exactly with10>i ? 1 : 0 + 1which gives 1 in either case, due to higher precedence of+over?:.
As a general rule, put()around the replacementandaround the variables
```
#define MAX(x, y) ((x)>(y) ? 1 : 0)
```
to avoid precedence issues.
|
As VLAs are assigned memory on the stack, will they cause any problem if we inlined the function containing them? I think, because of the same behavior of alloca i.e. storing objects on the stack, compilers avoids inlining such functions(?).
|
Whereas (the nonstandard)allocafunction yields an object whose lifetime is the callingfunction, a VLA's lifetime is the block in which it is declared. However inlining is not relevant to either of them. A function call whose body happens to get inlined is still a function call, and objects it obtains byallocacease to exist when it semantically returns, not when the cpu executes a ret instruction or equivalent.
|
I have the contents of a.icofile in memory as aconst char*, and I wish to create aHICONfrom this data. My current approach is to write the data to a temporary file and then useLoadImage. Is it possible to instead create the icon directly from memory?
|
WithCreateIconyou can certainly create icons but I'm not really sure you can feed it with a png-format image data.
I had success withCreateIconFromResourceEx(sorry for using other language, but take it as an example, you can use that function directly in C) :
```
from ctypes import *
from ctypes.wintypes import *
CreateIconFromResourceEx = windll.user32.CreateIconFromResourceEx
```
size_x, size_y = 32, 32
LR_DEFAULTCOLOR = 0
```
with open("my32x32.png", "rb") as f:
png = f.read()
hicon = CreateIconFromResourceEx(png, len(png), 1, 0x30000, size_x, size_y, LR_DEFAULTCOLOR)
```
Hope it helps you.
|
Let's say I want to swap variablesaandbusing XOR-swap.
```
a = a ^ b;
b = a ^ b;
a = a ^ b;
```
Could this cause an overflow, and can I swap those numbers when they are of type float or double?
|
This will have undefined behaviour; it could cause any number of problems.
Even assuming you found a reliable way to get the bit representation of the floating point number as an integer of the same size, you might still manage to create a floating point trap representation when you do the intermediate XOR, so storing that into the floating point value could be problematic.
The XOR hack is passé. Use a temporary. Your computer probably has alotof floating point registers, and using them is really fast.
|
Can anybody tell me where why the correct value of input is not being stored in this program?
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, sum=0;
printf("Enter the number: ");
while(num!=0)
{
sum = sum+num;
scanf("%d", &num);
}
printf("Answerr = %d", sum);
return 0;
}
```
Here's the output:
Enter the number: 2
0
Sum = 10
|
Better do:
```
num= 0;
do
{
scanf("%d", &num);
sum = sum+num;
} while(num!=0);
```
Note the initialization ofnumis still needed asscanfcould fail which would not affectnum.
|
```
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
int fd;
if ((fd = open("/home/zhangke", O_DIRECTORY | O_RDWR)) ==-1)
{
printf("error %s\n", strerror(errno));
return -1;
}
return 0;
}
```
/home/zhangkeisa directory andit exists. I get errorIs a directory, so, how can I useopen()to get afdof a directory correctly?
|
UseO_RDONLYinstead ofO_RDWRas the access mode. From theopen(2)error list:
EISDIRpathname refers to a directory and the access requested involved writing (that is,O_WRONLYorO_RDWRis set).
As far as I can tell, there's no way to create and open a directory atomically. TheO_CREATflag always creates a regular file.O_DIRECTORYis only meaningful when opening an existing name, it checks that the name refers to a directory.
|
This question already has answers here:What is the effect of trailing white space in a scanf() format string?(4 answers)Closed6 years ago.
```
#include <stdio.h>
int main() {
float change = 0.0;
printf("O hai! ");
while (change <= 0) {
printf("How much change is owed?\n");
scanf("%f\n", &change);
}
return 0;
}
```
and the result if input is a negative is endless "How much change is owed?"
|
scanfis actually entered, but due to the\nin format string"%f\n", after having entered a number,scanfwaits for the next non-whitespace character to return. Note that a white space in format specifier letsscanfconsumea sequenceof any white space characters, not only one, and so it "hangs" as long as only white space characters are provided by the stream.
Changescanf("%f\n",&change)intoscanf("%f",&change).
|
I have noticed thatfscanfis not working with determined C compilers (Intel, Cray), so I want to usefgetsto read a simple input file that contains strings and integers
```
$cat input.txt
st 10 167 POP 456 244 NONE ENERGY
```
I could do something like this
```
int main()
{
FILE *ptr_file;
char buf[1000];
ptr_file = fopen("input.txt", "r");
if (!ptr_file)
return 1;
for (int i = 0; i < 8; i++) {
fgets(buf, 1000, ptr_file);
printf("%s", buf);
}
fclose(ptr_file);
return 0;
}
```
to read the file and then create aswitch caseto either store the value ofbufin anintegeror astring. This is obviously not very efficient and I was wondering if anyone has a better idea.
|
Consider using sscanf, essentially something like this
```
// st 10 167 POP 456 244 NONE ENERGY
sscanf(buf, "%s %d %d %s %d %d %s %s", var1, &var2....);
```
|
I'm trying to figure out what happens if in some program we'll have like that:
```
extern int x;
void foo(){...}
void bar(){...}
void main(){
foo();
bar();
}
int x=0;
```
So what is suppose to happen?Why is it allowed to have two such variables with the same name?are they different?
|
They are not "two" variables. They are thesame.
```
extern int x;
```
is a declaration ofx.
and
```
int x=0;
```
provides the definition forx. This is perfectly fine and valid.
You can have multiple declarations like:
```
extern int x;
extern int x;
```
too and it'll compile as well.
Note when you are providing the multiple declarations for the same identifier, the rules are somewhat complex. See:6.2.2 Linkages of identifiersfor details.
Seestatic declaration of m follows non-static declarationfor an example.
|
i dont really have much experience with c but how would i go about storing two pieces of info about a user when you have multiple users in c. Im getting player name and player type. I need to shuffle them individually e.g. sort names alphabetically etc. Thanks in advance :)
|
Define a record type:
```
typedef struct Info_s {
char n[6];
int a;
int b;
} Info_t;
```
Define an array type:
```
typedef Info_t allInfo_t[12];
```
Declare a variable of that type:
```
allInfo_t myInfo;
```
Take a look atqsort()to maintain the array sorted andbsearch()to search quickly into the array. Don't forget to implement a function to compareInfo_t.
|
I have narrowed the issue of a larger bug to something seemingly simple.
```
uint8_t *vald;
*vald=46;
```
This couplet of code leads to a hard fault on my platform (Atmel Studio, GCC)
What am I doing wrong?
|
vald is uninitialized, which means it's either zero or undefined depending on whether your compiler clears the stack frame for local variables. Writing to address zero is always an error, and writing to an undefined address is almost always an error.
```
*((uint8_t*)0) = 46;
```
|
Regarding c variables, I want to know what the x does in:
```
int var[x]
```
|
This is a declaration of aVariable Length Array(VLA).
The value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.
|
Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?
|
Yes it exactly the same. According to theposixstandard
The dup() function provides an alternative interface to the service
provided by fcntl() using the F_DUPFD command. The call dup(fildes)
shall be equivalent to:fcntl(fildes, F_DUPFD, 0);
dup()is shorter and easier to read, I would use that.
|
I'm trying to figure out what happens if in some program we'll have like that:
```
extern int x;
void foo(){...}
void bar(){...}
void main(){
foo();
bar();
}
int x=0;
```
So what is suppose to happen?Why is it allowed to have two such variables with the same name?are they different?
|
They are not "two" variables. They are thesame.
```
extern int x;
```
is a declaration ofx.
and
```
int x=0;
```
provides the definition forx. This is perfectly fine and valid.
You can have multiple declarations like:
```
extern int x;
extern int x;
```
too and it'll compile as well.
Note when you are providing the multiple declarations for the same identifier, the rules are somewhat complex. See:6.2.2 Linkages of identifiersfor details.
Seestatic declaration of m follows non-static declarationfor an example.
|
i dont really have much experience with c but how would i go about storing two pieces of info about a user when you have multiple users in c. Im getting player name and player type. I need to shuffle them individually e.g. sort names alphabetically etc. Thanks in advance :)
|
Define a record type:
```
typedef struct Info_s {
char n[6];
int a;
int b;
} Info_t;
```
Define an array type:
```
typedef Info_t allInfo_t[12];
```
Declare a variable of that type:
```
allInfo_t myInfo;
```
Take a look atqsort()to maintain the array sorted andbsearch()to search quickly into the array. Don't forget to implement a function to compareInfo_t.
|
I have narrowed the issue of a larger bug to something seemingly simple.
```
uint8_t *vald;
*vald=46;
```
This couplet of code leads to a hard fault on my platform (Atmel Studio, GCC)
What am I doing wrong?
|
vald is uninitialized, which means it's either zero or undefined depending on whether your compiler clears the stack frame for local variables. Writing to address zero is always an error, and writing to an undefined address is almost always an error.
```
*((uint8_t*)0) = 46;
```
|
Regarding c variables, I want to know what the x does in:
```
int var[x]
```
|
This is a declaration of aVariable Length Array(VLA).
The value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.
|
Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?
|
Yes it exactly the same. According to theposixstandard
The dup() function provides an alternative interface to the service
provided by fcntl() using the F_DUPFD command. The call dup(fildes)
shall be equivalent to:fcntl(fildes, F_DUPFD, 0);
dup()is shorter and easier to read, I would use that.
|
I am integrating asn1c code into Xcode project. Currently I am getting this error:
```
/asn1c/converter-sample.c:76:1: error: expected identifier or '('
DEBUG(const char *fmt, ...) {
^
```
Source code:
```
/* Debug output function */
static inline void
DEBUG(const char *fmt, ...) { // 76th line
va_list ap;
if(!opt_debug) return;
fprintf(stderr, "AD: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
```
What is the way to fix this build error?
I did look into similar questions in StackOverflow, but could not found answer which could help me.
|
i think definitely there is a redeclaration of DEBUG or #defined as @ammoQ was saying. please check the other location and see that there are no same RE declarations
just change it as DEBUG1 AND try it
|
Is it possible use anintvector instead of usingdoublevectors for fft calculation?
|
No, not using FFTW (which you tagged in the question). There are other libraries, but to be useful in practice you will need to give some thought to the fixed point representation of your choice.
Note that floating point additions and multiplications, what's used in an FFT, is just as fast on modern x64 chips as integer operations of corresponding word size. The extra care needed to create an integer FFT result with reasonable precision would maybe even cause a slowdown in practice. The story is very different on chips with slower (or none) floating point hardware.
Of course, conversion from integer to floating point itself is not free in the first place, so sometimes it makes sense to stay in floating point for a longer time than what is critically needed.
|
I have a question regarding the for loop in the release list func. (The head is a dummy so we don't need to release it). I don't understand the:
```
next = next?
```
part in the loop. What does it actually do, and why simply
```
next?
```
won't suffice? here is the code:
```
typedef struct NODE {
int num;
struct NODE* next;
} Node;
void release_list(Node* head) {
Node* next = head->next ? head->next->next : NULL;
for( Node* curr = head->next;
curr != NULL;
curr = next, next = next? next->next : NULL) {
free(curr);
}
}
```
|
Ternary operator?:has higher precedence than assignment=.
Code is equivalent to:
```
next = (next? next->next : NULL)
```
Or:
```
if(next != NULL)
next = next->next;
else
next = NULL;
```
Point of the code is to avoid accidentally doingNULL->nexton last element.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.