question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I'm having issues with a c program that I want to debug.
I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it.
Thanks :)
|
For GCC specify-gwhen compiling.
More here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
|
```
#include<stdio.h>
int main(void)
{
double c;
scanf("%f", &c);
printf("%f", c);
}
```
This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous ques... |
You need to use"%lf"for double.
This is the warning from clang compiler.
warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%f", &c);
Here is thescanf reference. It's format is%[*][width][length]specifier. The specifier for 'floating point number' isf. So we use%fto ... |
Making a simple program where the user inputs different classes, times and dates, and a timetable is generated (like a timetable with university classes). I've worked with Windows API for basic applications however I cannot find a way to display all the information in a timetable chart.
Something like this:
Is the... |
If you are programming in Win32 mode, to use ListView control is a better choice. You could get references from msdn:ListView ControlYou can also use the TextOut api to print information onto your Window form.
|
I have been trying to study the source code of clamav open source antivirus as a part of my project. Hence I downloaded the latest stable releaseclamav.0.99.2.tar.gzfrom the website.
I'm using eclipse neon.2 Release 4.6.2 on Windows 10 64-bit.
I created an existing make file project using the clamav folder extracted... |
from the terminal in the linux VM, type:
```
sudo apt-get install libssl-dev
```
to install the SSL then from the clamav-0.99.2 directory type:
```
./configure
```
when that completes then type:
```
make
```
This will take a while to complete, then (if you want to actually install the clamav application) type:
... |
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago.
like 52.7-->53, 5.5-->6, 3.2->3
|
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:
```
((int)(num + ((num > 0)? +0.5 : -0.5)))
```
|
This question already has answers here:What's the difference between passing by reference vs. passing by value?(18 answers)Closed6 years ago.
```
#include <stdio.h>
increment(char *c)
{
c++;
c++;
printf("works 'n' %c \n", *c);
}
int main()
{
char *p;
char mon[10] = "Monday";
p = mon;
in... |
Inincrement(char *c)you create a new pointercwhich is pointing to the same objectpdoes, but they arenotthe same, they are just pointing to the same thing. If you increment one, the other one stays the same.
If you want to increment the pointerpyou need a pointer to this pointer, pass it to your function and changepin... |
I have been trying to study the source code of clamav open source antivirus as a part of my project. Hence I downloaded the latest stable releaseclamav.0.99.2.tar.gzfrom the website.
I'm using eclipse neon.2 Release 4.6.2 on Windows 10 64-bit.
I created an existing make file project using the clamav folder extracted... |
from the terminal in the linux VM, type:
```
sudo apt-get install libssl-dev
```
to install the SSL then from the clamav-0.99.2 directory type:
```
./configure
```
when that completes then type:
```
make
```
This will take a while to complete, then (if you want to actually install the clamav application) type:
... |
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago.
like 52.7-->53, 5.5-->6, 3.2->3
|
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:
```
((int)(num + ((num > 0)? +0.5 : -0.5)))
```
|
Just learned that there is no pre-defined graphics library for C. I want to get the resolution of the current monitor screen.
|
That is simply not possible to answer as a "pure C" question; there is no "screen" in C, i.e. the language and its standard library never assumes that there is any kind of screen-like output device available.
You need to settle for a suitable library for a portable solution, or figure out how to talk directly to your... |
How can I check if my program is running as an administrator on a Windows 7 system, using C?
In batch I could do something along the lines of:
```
whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" | findstr /c:"Enabled group" > nul: && set IS_ELEVATED=1
if %IS_ELEVATED%==0 (
set /p _=... |
I suggest that if you set the executable's properties and permissions, so that it canonlybe run by administrator, that could solve the problem.
|
In the following code from core_cm4.h why is there a double cast((uint32_t)(int32_t)IRQn)?
For example in the following function:
```
__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
```
What is the pu... |
Since CM4 software implements negative interrupt sources for core, you have to cast value first to 32bit signed integer and later to unsigned 32bit to make proper right shift with padding zeros on the left side of number.
CM4 uses -15 to -1 as CM4-Core sources and from 0 to next as vendor specific sources.
|
I am using the ARMv8 instruction set with Aarch64 execution state. The problem I am having, is were supposed to translate C code into assembly, and I am stuck on the following:
```
while (c != '\n' && c != EOF)
c = getchar();
```
I know the basic setup for the while loop, as well as how to testc != '\n'but the i... |
It depends on what code you're using in assembly forgetchar()-
If you're just using a call to the assembly version of standard C librarygetchar(), then you can test with the C library's definition ofEOF- normally-1.If you're implementing your owngetchar()in assembly, then you need to match your test to the return val... |
If you fork() and create two processes for reading and writing to a pipe and the child process is reading from the pipe and the parent process is writing to the pipe, will writing in the parent process fail if the child process was to close the pipe that writes before the parent process has a chance to write to the pi... |
The child process closing its write end of the pipe only removes its reference to the pipe, it doesn't cause the pipe to "shut down" or any such thing, and thus won't affect the parent's reference to it in any way. This is true for theclose(2)call in general.
Further reading:
File descriptors
|
In C, I have a function that calculates the product of a and b. If a < b it returns false otherwise returns true. How can I return the product when the function is defined as boolean?
```
bool multiplication(int a, int b)
{
int c = a*b;
if (a < b)
return false;
else
return true;
}
```
|
How to return bool and double simultaneously?
A function can only have one return type. But you can use a workaround of using a struct containing a bool and an int members as stated in one of the comments.
You can achieve your goal of writing a multiplication function of positive integers with a recursion logic the ... |
Here's what I've coded:
```
#include <stdio.h>
void add(int *a, int i){
while(i != 0){
a++;
i--;
}
}
int main(){
int a = 6;
add(&a, 4);
printf("a = %d\n", a);
return 0;
}
```
And here's the result
```
a = 6
```
The result I'm expecting is10, of course, but I don't understa... |
In the function there is advanced the pointer itself instead of incrementing the value pointed to by the pointer. Change the function the following way
```
void add(int *a, int i){
while(i != 0){
( *a )++;
i--;
}
}
```
Or the expression statement( *a )++;can be substituted for++*a;
Also the ... |
I want to create a functionvoid vec2_from_vec3(vec2 res, vec3 from)in pure C, using operator##like so:
```
#define MAGIC_MACROS(n) \
void vec##(n-1)##_from_vec##n##(vec##(n-1) res, vec##n from);
```
but compiler woudn't let it. Is it possible?
Inspired byhttps://github.com/datenwolf/linmath.h/blob/master/linmath.h
|
The preprocessor won't evaluate/computen-1, it will just expand it. Ex:3-1, so string concatenation won't work
(a modern compiler does it but it's already too late)
You can always do that which isn't that bad already:
```
#define MAGIC_MACROS(n1,n2) \
void vec##n1##_from_vec##n2##(vec##n1 res, vec##n2 from)
```
an... |
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 answer... |
This is linking against themlibrary... Which is used for math functions.
The-l<library name>parameter togccmeans 'link with this library'.
Themis the library to link with (e.g:libm.soorlibm.a).
See theGCC man page(runman gcc), and functions likesin(),sqrt(),pow(), etc.
Note that in these man pages, it states:
Lin... |
Is there a way to use a delim more then once for strtok? I can only get the code to work for either load or init but not both. Example code in which strtok is used to token input from the user in the form of load # or init #,#,direction:
```
if ((tok = strtok(choice, " ")) && strcmp(tok, COMMAND_LOAD) == 0){
tok ... |
Thestrtokfunction is not reentrant, you can not use it for multiple simultaneously tokenizations.
Usestrtok_sinstead, if you have it. Orstrtok_ris you have it.
|
```
#define TERMMAX 100
typedef struct{
int coef;
int expon;
} poly;
poly term[TERMMAX];
int avail = 0;
#define TERMMAX 100
enter code here
int main()
{
int i;
FILE *fp = fopen("a.txt", "r");
while(fscanf(fp, "%d\t%d", &term[avail].coef, &term[avail].expon) != EOF)
avail++;
```
the fscan... |
IIRC, the order of evaluation of function parameters is unspecified by the Standard. Any side effects of function parameters are indeterminately sequenced.
|
Here's what I've coded:
```
#include <stdio.h>
void add(int *a, int i){
while(i != 0){
a++;
i--;
}
}
int main(){
int a = 6;
add(&a, 4);
printf("a = %d\n", a);
return 0;
}
```
And here's the result
```
a = 6
```
The result I'm expecting is10, of course, but I don't understa... |
In the function there is advanced the pointer itself instead of incrementing the value pointed to by the pointer. Change the function the following way
```
void add(int *a, int i){
while(i != 0){
( *a )++;
i--;
}
}
```
Or the expression statement( *a )++;can be substituted for++*a;
Also the ... |
I want to create a functionvoid vec2_from_vec3(vec2 res, vec3 from)in pure C, using operator##like so:
```
#define MAGIC_MACROS(n) \
void vec##(n-1)##_from_vec##n##(vec##(n-1) res, vec##n from);
```
but compiler woudn't let it. Is it possible?
Inspired byhttps://github.com/datenwolf/linmath.h/blob/master/linmath.h
|
The preprocessor won't evaluate/computen-1, it will just expand it. Ex:3-1, so string concatenation won't work
(a modern compiler does it but it's already too late)
You can always do that which isn't that bad already:
```
#define MAGIC_MACROS(n1,n2) \
void vec##n1##_from_vec##n2##(vec##n1 res, vec##n2 from)
```
an... |
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 answer... |
This is linking against themlibrary... Which is used for math functions.
The-l<library name>parameter togccmeans 'link with this library'.
Themis the library to link with (e.g:libm.soorlibm.a).
See theGCC man page(runman gcc), and functions likesin(),sqrt(),pow(), etc.
Note that in these man pages, it states:
Lin... |
I see the standard only said that FILE is a object type, but what's the object type in c? built-in type, struct, union and emun? Is fuction type a kind of object type? Can FILE * cast to void * always correctly?
|
what's the object type in c? built-in type, struct, union and emun?
yes, plus some other "intrinsic" types such asmtx_toratomic_flag
Is function type a kind of object type?
no, function types are different, they are those that are declared by designated function declarations.
Functions can be called by using af(so... |
I am trying to optimize following operation where I have a large number of unsigned short inputs which needs to be scaled down by a certain factor. Is there a way to optimize it to not use floating point operations
```
unsigned short val = 65523U;
val = val * 0.943;
```
Note
I will be running above operation on a D... |
The simplest way is to just use a 32 bit type that can hold the result:
```
uint16_t val = 65523U;
val = (uint_fast32_t)val * 943 / 1000;
```
Or if you want more type correctness and portability, while at the same time allowing the compiler to use the best possible integer type for the task:
```
#include <stdint.h>... |
So after looking on the massive interweb, I was unable to find an answer to this.
Say I have this piece of code:
```
if(P4IN & GPIO_PIN1?0:1){
if (state==1){
state = 0;
//Wait for this state to pass -- ends up saving the current state on button press.
while (counter < 1000... |
You can simplify the whole thing to this:
```
if (!(P4IN & GPIO_PIN1)) {
state = !state;
while (counter < 10000) {
counter++;
}
}
```
|
I am trying to allocate memory for an integer array
```
ptr=malloc(length*sizeof(int));
```
which will give me the pointer to the allocated memory. I understand that I can access the values with *(ptr+k), where k is the position in the integer array. However is there a way to define a new array
```
int allocarray[l... |
If you declare an array like you do above, it will be automatically allocated. However, if you say:
```
int *allocarray = (int *)malloc(length*sizeof(int));
```
you can still access elementkusing the syntaxallocarray[k].
|
I am in a similar situation :Eclipse CPP and GNU following these instructions. But i need to build GLUS with MinGW and sublime text.
I am learning C and OpenGL ,so i lack compilation/dependencies logic.
I would just like to undertsand in a simple way.
how to compile GLUS from those source:https://github.com/McNoppe... |
Well Norbert Nopper kindly answer my question directly. And like the answer mention above. The path to follow to compile GLUS without any ide is by using cmake.
in the GLUS folder, there is a CMake file (https://cmake.org/). With
CMake, you can create the GLUS library without any IDE and for a lot
of platforms – ... |
```
int *ptr = malloc~
while (fscanf(fp, "%d", ptr++) != EOF)
;
```
Assuming that there's sufficient memory allocated to ptr,
What does the value stored in *ptr when the function encouters EOF indicate?
I tried using debugging tools in Visual Studio and found out that the value of *ptr is -33686019
Is this garbag... |
When scanf hits EOF,no value is storedat the addressptrpoints to.
Likewise if it returns 0. This is why the canonical way to iterate over input must check the scanf return value, e.g. with
```
if (fscanf(fp, "%d", &ptr_to_int) == 1) {
/* successful conversion */
}
else {
/* Unsuccesful conversion or EOF; use feof... |
I have a sorted linked list, one function takes the root pointer and an Id and searches through the list to delete the item, however this takes linear time.
Is there any way to efficiently search through the linked list without doing it linearly using the fact that its sorted? The assignment hints heavily that their ... |
Each node in a linked list only contains a pointer to the next node (and optionally the previous node), so without any other constructs the only way to search the list is linearly.
However, since you sort the list, you could build a binary tree in the process. Then you can use that tree to search the list with a tim... |
I have currently got it as :
```
scanf("%d%d%d",&day1,&mon1,&year1);
```
This works fine when I pass in a date which is to be like :
```
02-02-2016
```
However I want it to also be fine if I pass it with slash instead of the dash :
```
02/02/2016
```
I have tried this way:
```
scanf("%d/%d/%d",&day1,&mon1,&year... |
You can use a format string like:"%d%*[-/]%d%*[-/]%d"to accept only dash or slash between the numbers, but throw away whatever character is there. (This is getting to the outer limits of myscanfknowledge; I don't think I've ever actually used this feature.)
|
When I run this code it gave a segmentation fault.
```
main ()
{
char *line ="2,3,22";
int size=3,i,j;
double value;
char *val;
for (i = 0; i<size ; i++) {
if (line == NULL) break;
printf("%s\n",strtok (line ,","));
}
}
```
and gave a
"warning: format ‘%s’ expects argument... |
It's using an implicit prototype forstrtok. You need to#include <string.h>(You might also need to includestddef.hforNULLand should also includestdio.hforprintf).
|
I have a sorted linked list, one function takes the root pointer and an Id and searches through the list to delete the item, however this takes linear time.
Is there any way to efficiently search through the linked list without doing it linearly using the fact that its sorted? The assignment hints heavily that their ... |
Each node in a linked list only contains a pointer to the next node (and optionally the previous node), so without any other constructs the only way to search the list is linearly.
However, since you sort the list, you could build a binary tree in the process. Then you can use that tree to search the list with a tim... |
I have currently got it as :
```
scanf("%d%d%d",&day1,&mon1,&year1);
```
This works fine when I pass in a date which is to be like :
```
02-02-2016
```
However I want it to also be fine if I pass it with slash instead of the dash :
```
02/02/2016
```
I have tried this way:
```
scanf("%d/%d/%d",&day1,&mon1,&year... |
You can use a format string like:"%d%*[-/]%d%*[-/]%d"to accept only dash or slash between the numbers, but throw away whatever character is there. (This is getting to the outer limits of myscanfknowledge; I don't think I've ever actually used this feature.)
|
When I run this code it gave a segmentation fault.
```
main ()
{
char *line ="2,3,22";
int size=3,i,j;
double value;
char *val;
for (i = 0; i<size ; i++) {
if (line == NULL) break;
printf("%s\n",strtok (line ,","));
}
}
```
and gave a
"warning: format ‘%s’ expects argument... |
It's using an implicit prototype forstrtok. You need to#include <string.h>(You might also need to includestddef.hforNULLand should also includestdio.hforprintf).
|
I have currently got it as :
```
scanf("%d%d%d",&day1,&mon1,&year1);
```
This works fine when I pass in a date which is to be like :
```
02-02-2016
```
However I want it to also be fine if I pass it with slash instead of the dash :
```
02/02/2016
```
I have tried this way:
```
scanf("%d/%d/%d",&day1,&mon1,&year... |
You can use a format string like:"%d%*[-/]%d%*[-/]%d"to accept only dash or slash between the numbers, but throw away whatever character is there. (This is getting to the outer limits of myscanfknowledge; I don't think I've ever actually used this feature.)
|
When I run this code it gave a segmentation fault.
```
main ()
{
char *line ="2,3,22";
int size=3,i,j;
double value;
char *val;
for (i = 0; i<size ; i++) {
if (line == NULL) break;
printf("%s\n",strtok (line ,","));
}
}
```
and gave a
"warning: format ‘%s’ expects argument... |
It's using an implicit prototype forstrtok. You need to#include <string.h>(You might also need to includestddef.hforNULLand should also includestdio.hforprintf).
|
I need help with how to generate random numbers between -1 and 1 using rand_r(). I didn't have much luck online looking for examples on how to do this. Any help would be greatly appreciated.
|
Each time you callrand_r, you pass it the address of a state variable. Before callingrand_rthe first time, this state variable should be assigned a seed value. You'll also need to keep a separate state variable for each thread so they each have their own state.
```
unsigned int myseed = time(NULL) ^ getpid() ^ pthr... |
This question already has answers here:Detecting and skipping line comments with Flex(3 answers)Closed6 years ago.
I need a regular expression for inline comment in C for a compiler's lexical analyser.
I tried thisScreenShotbut it is of no use as it comments out the regular expression.
Here is simplest code
|
For catching C style comments better use start conditions. Example for flex you can findin documentation.
There is simple example for ignoring C stype comments by using exclusive start condition:
```
%x comment
"/*" BEGIN(comment);
<comment>[^*\n]* /* eat anything that's not a '*' */
<comment>"*"+[^*/... |
I'm trying to do analysis on some data and I am building a few tools that I was hoping to chain together with pipes.
cat file.dat | ./tool | ./tool2 ...
But I'm not sure how to read the piped in data. I know it's coming in through stdin, but I can exactly wait for the file end. So I guess I'm looking for something l... |
The functionscanfreturnsEOFwhen it reaches the end of file. You can use a code like this to check for that:
```
while (1) {
long value;
int ret = scanf("%ld\n", &value);
if (ret == EOF) {
break;
}
printf("%ld\n", value);
}
```
See thedocsfor more details.
|
Does this mean anything:
```
typedef struct spBone spBone;
struct spBone {
...
}
```
I found the above in a header of a .c file. What could be the side-purpose of assigning anon-alternativename to a struct?
|
First, remember that C and C++ are different languages. C++ is rooted in C, but went in some very different directions. This is one of them.
When declaring or defining a variable of typestructin C, one must always use the keywordstruct. For example
```
struct spBone myspBone;
```
is required. Why this is required l... |
Say we have a char array of size 40,
```
char buffer[40];
```
Secondly, let's say that this array is completely full, that someone has written 40 characters to it.
Thus, we could say that the elements of this array take up 40 bytes, as each char is 1 byte.
My question is this:
How much space does our arrayactually... |
Unlike languages like Java or C#, C does not store any type meta information at runtime. Therefore,char[40]requires exactly 40 bytes.
|
I'm working on 8051 micro-controller platform with KEIL as IDE and C as the programming language.
I'm trying to create array of bits for use in switch function.
```
sbit P1;
sbit P2;
sbit P3;
buttons [2:0] = P1 | P2 | P3
switch (buttons[2:0])
{
case 0x1: //First button is pressed
case 0x2: //Second ... |
Finally i have found a way around to solve my problem.
```
int buttons=0x00;
buttons = ((0xFF & !P1) << 2) | ((0xFF & !P2) << 1) | ((0xFF & !P3) << 0);
```
|
I have a random number generator feeding numbers into an array, but when I print out the table, the last line is always a set of values out of the boundaries that I defined in the following function:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int temp[22];
int n;
for(n=0; n<23; n++){
... |
You are accessing the array outside the bounds which isundefined behaviour.
Instead make use ofsizeofoperator to avoid such problems:
```
for(n = 0; n < sizeof temp/sizeof temp[0]; n++)
```
But note that iftempwere to be an malloc'ed pointer (int *temp = malloc(23 * sizeof *temp);) thensizeofwouldn't work.
|
The python script contains lots of libraries imported
My C code so far:
```
#include <stdio.h>
#include <python2.7/Python.h>
void main(int argc, char *argv[])
{
FILE* file;
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
file = fopen("analyze.py","r");
PyRu... |
One useful way is calling a python function within c, which is that you need instead of execute whole script.
As described in>> here
|
The python script contains lots of libraries imported
My C code so far:
```
#include <stdio.h>
#include <python2.7/Python.h>
void main(int argc, char *argv[])
{
FILE* file;
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
file = fopen("analyze.py","r");
PyRu... |
One useful way is calling a python function within c, which is that you need instead of execute whole script.
As described in>> here
|
I have a c executable which gets data from a iot hardware and print information on console using printf. I want to run this executable from python which I am able to do so using subprocess.call in following way
```
subprocess.call(["demoProgram", "poll"])
```
and print the output to console. But I need to capture th... |
The following opens a subprocess and creates an iterator from the output.
```
import subprocess
import sys
proc = subprocess.Popen(['ping','google.com'], stdout=subprocess.PIPE)
for line in iter(proc.stdout.readline, ''):
print(line) # process line-by-line
```
This solution was modified from the answer to asi... |
When summarized the chapter 2, the author mentioned that
"Specifically, a 200-digit number is raised to a large power (usually another 200-digit number), with only the low 200 or so digits retained after each multiplication."
Q:What is this mean? P.S:My English is a little bad.
|
If we replace 200 with 3, it would mean something like computing 123^456, but only retaining the low 3 digits (the ones, tens and hundreds places), mathematically equivalent to (123^456)%1000.
|
Insched.h, task_struct has following 2 fields: thread_group & thread_node. They keep the first element of their list but I could not find which type of variables they contain.
```
1511 struct task_struct {
....
1657 /* PID/PID hash table linkage. */
1658 struct pid_link pids[PIDTYPE_MAX];
1659 ... |
thread_groupandthread_nodeare both intrusive linked-lists of all the threads in a thread group - they are use to link togethertask_structs, they don't "contain" anything.
The difference between the two is thatthread_grouphas its head in thetask_structof the thread group leader, whereasthread_nodehas its head in thesi... |
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'm programming an OS.
So I want to know how can an expression like (2*(7+8)-9)+2 can be ... |
StackOverflow has already covered the topic of Infix expression parsing and Recursive Decent parsing using C++here. Read it over to understand the algorithm, then see if you can convert it to C. That will definitely be "fun" and teach you a little bit about C along the way.
|
```
#include<stdio.h>
int main(){
int a = 320;
char *ptr;
ptr =( char*)&a;
printf("%d",*ptr);
return 0;
}
```
I just wanted to know what is the use(char*)? What if I used(int*)instead of that?
|
Your variable is of type integer i.e.int a = 320;Your pointer is of type character i.e.char *ptr;
character pointer can only points to character type variable, but you in your code want to point a integer variable so how would that be possible? By this line of code:ptr =( char*)&a;what it doing is type casting your p... |
My GNU-Linux platform (debian stretch) has the C typesu_int8_t,u_int16_t,u_int32_tandu_int64_tdefined in the filesys/types.hwhileuint8_t,uint16_t,uint32_tanduint64_tare defined instdint.h. I have found these types useful in the course of practicing X86-64 assembly language and interacting with C. Is there any reason w... |
stdint.his standard C, which maps tocstdintin standard C++.
sys/types.his not portable C.
|
I know thatint *(*func)()means a function pointer which takes no arguments and returns an integer pointer but what does the following syntax means in C:
```
int *(*func())[]
```
Any explanations on how do we read such syntax in C would be very helpful.
|
funcis a function and returning a pointer to an array of pointers to int.
reference link :http://gateoverflow.in/35193/regarding-pointers
|
Trying to figure out where I am going wrong in this code, I realize I keep getting 1 because that's what am I passing in the function but how else can I do this?
```
#include <stdio.h>
#include <stdlib.h>
int totalOdd();
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int n){
int odd = n;
if(odd >= 1... |
try this one
one :
```
#include <stdio.h>
#include <stdlib.h>
int totalOdd(int);
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int n)
{
int odd = n;
if(odd > 100){
return 0;
}
else{
return (n+totalOdd(odd+2));
}
}
```
in your code , additi... |
```
unsigned short octet2, octet3, octet4;
sscanf(ipAddr.c_str(), "%hu.%hu.%hu.%hu", &octet2, &octet2, &octet3, &octet4);
```
ipAddr is a string.
From the above code, it is successfully breaking the octets up. However, I'd like to just avoid touching the first octet of the IP address. I want to avoid extra operation... |
you could scan but not store the first argument by prefixing first format specifier by*to tellsscanfto parse but not store the field (and you only need 3 parameters in that case):
```
sscanf(ipAddr.c_str(), "%*hu.%hu.%hu.%hu", &octet2, &octet3, &octet4);
```
|
Simple question. I've been trying to find the answer before asking but i dont know if im wording the question right.
I want to write in C usingwrite(int fd, char* buffer, size).
```
char buffer[40];
//just assume the buffer has been read into.
write(fdout,buffer,40);
```
I want to write say starting at index 2 of t... |
You just need a pointer into the proper place in the buffer:
```
write(fdout, &buffer[2], 40-2);
```
|
I am programming in C using Atmel Studio (for those unfamiliar with this it is used to program to micro controllers such as arduino. You can not simply print, you have to send the data Serially to an application such as Terminal.)
I have so far:
```
uint8_t * stackHolder;
char buffer[128];
stackHolder = &buffer[127]... |
How can I convert theuint8_t * stackHolderinto achar *?
Bycasting:
```
print((char*) stackHolder);
```
|
I need the result of this variable in a program, but I don't understand why I can't get the right result.
```
double r = pow((3/2), 2) * 0.0001;
printf("%f", r);
```
|
The problem is integer division, where the fractional part (remainder) is discardedTry:
```
double r = pow((3.0/2.0), 2) * 0.0001;
```
The first argument of thepow()expects a double. Because the ratio:3/2uses integer values, the result passed to the argument is 1. By changing to float values, the result of the div... |
In the following code,BITS_IN_INTis anlong unsigned intwith value32. Why does the modulo operation return the value0instead of the expected20?
```
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define BITS_IN_INT sizeof(int) * CHAR_BIT
int main()
{
size_t i = 20;
printf("%zu\n", i);
printf(... |
After macro expansion, the last printf looks like:
```
printf("%lu\n", i % sizeof(int) * 8);
```
So, the expression (in printf) is evaluated as if:
```
(i % sizeof(int)) * 8
```
Ifsizeof(int)is 4 (which seems to the case on your platform) theni % sizeof(int)yields 0;0 * 8is0.
Avoid macros if you can. If not, alwa... |
I'm trying to pass a struct to a callback set with curl_easy_setopt. Here's the struct:
```
typedef struct gfcontext_t {
int sockfd;
char requested_path[1024];
char path[1024];
} gfcontext_t;
struct gfcontext_t ctx;
```
I've got these two lines setting up the callback:
```
curl_easy_setopt(curl, CURLOPT_WRIT... |
userp is a pointer. You should type cast it togfcontext_t *.
```
printf("userp: %s\n", ((gfcontext_t *)userp)->requested_path);
```
|
I need to create a program that get's the sum of numbers from 100 to 500.
```
int sum = 0;
for (int i = 1; i <10; i++)
{
sum = sum + i;
printf("%d", sum);
}
```
It should print 55 (the sum of numbers between 1 and 10), but it prints out 136101521283645.
After this I need a program that gets the sum of numbe... |
Here you are only doing the sum for i from 1 to 9, and you print that sum every loop.
Instead, you should do this:
```
int sum = 0;
for (int i = 1; i <= 10; i++)
{
sum += i;
}
printf("%d", sum);
```
For 100 to 500, do that:
```
int sum = 0;
for (int i = 100; i <= 500; i++)
{
sum += i;
}
printf("%d", sum);
... |
I have a dynamic array of c-strings
char **my_strings = (char**)malloc(50 * sizeof(char*));
and I want to find it's actual length (how many strings it actually contains). How can I do this?
|
You can't tell: it's your job to keep track of the size, or to use a magic value (NULL, say) to mark the final element.
Note that the c runtime probably keeps track of the amount of memory allocated, but this is not exposed to you in any portable way.
|
When attempting to compile
```
#include<stdio.h>
int main(){
printf("Hello World");
return 0;
}
```
I get the following errors with Solaris11 gcc:
hello.c:4:23: error: expected expression before ';' tokenhello.c:6:1: error: expected ';' before '}' token
Visual C++ can compile this code.
|
the ';' in line four (thereturnstatement) is not a standard ';'.
|
I've already installed kernel-devel on centos, still cannot find kernel header
```
# yum install kernel-devel
Loaded plugins: fastestmirror, ovl
Setting up Install Process
Loading mirror speeds from cached hostfile
* base: mirrors....net
* extras: ...
* updates: mirrors.....net
Package kernel-devel-2.6.32-642.15.1... |
Do you know locate command?
```
$ locate kmem.h
/usr/src/kernels/3.10.0-514.10.2.el7.x86_64/include/config/memcg/kmem.h
/usr/src/kernels/3.10.0-514.10.2.el7.x86_64/include/trace/events/kmem.h
```
:-), I think yourPATHhas error.
|
This is a homework assignment. I have a makefile that by default compiles an executable usinggcc -o myprogram myprogram.c
In the assignment we are supposed to make 3 extra make cases: "The makefile should also support inserting a sleep of 10 seconds into 3 different specified places of the program using these 3 cases... |
A simple solution would be a macro that you can define at compile time, like
```
int main(void)
{
SLEEP_HERE;
return 0;
}
```
and at compile time
```
gcc -Wall -Werror -DSLEEP_HERE='sleep(10)' -o myprogram myprogram.c
```
|
```
#include <stdio.h>
struct bar
{
int data[10];
};
int main(void) {
printf("%d", ((struct bar*)0)+5);
return 0;
}
```
Output is 200.
I came across this on some c programming website. Can someone explain me this?
|
Edit:I am updating based on the comment section.
We understand that arithmetic onnull pointeris undefined behavior. You can read morehere.
The current code does not specifically useNULL. Instead it uses literal0which is then casted intonull pointerwith((struct bar*)0). As a result, in this code we have an undefined ... |
```
#include<stdio.h>
int main()
{ int n=3;
while(n>0)
{ printf("P");
n--;
sleep(1);
}
return 0;
}
```
With this code 3 P's are appearing at the same time after 3 seconds. But I want it to appear one by one with 1 second time interval. How should I modify it?
|
The problem is the buffer is not flushed byprintf. To do so, you can either print '\n' after your P :printf("P\n");
Either call fflush on stdout :
```
printf("P");
fflush(stdout);
```
|
I have this code: (assuming short ints are 16 bits wide, and ints are 32 bits wide)
```
short int x = -5;
int y;
y = x;
```
Does padding on the left with the sign bit to increase precision change the value of a negative number?
|
Does padding (sign-extension) on the left with the sign bit to increase precision change the value of a negative number?
Taking into acount@Amin Negm-Awad, when a variable is assigned from one type to another,andthevalueis representable in both types, like -5 as inintorshort, there is novaluenor precision change.
Th... |
I was wondering about the "? :" operators in C. Can one use the conditional operator inside another conditional operator like this?
```
int a = 0;
a == 1?a += 1:a == 0?a += 2:a = 3;
```
This is a very bad example, but I hope you understand what I'm trying to ask.
|
Of course you can, like this :
```
int a = 0;
a == 1?(a += 1):((a == 0)?(a += 2):(a = 3));
```
It is the same as writing :
```
int a = 0;
if (a == 1)
a += 1;
else
if (a == 0)
a += 2;
else
a = 3;
```
which is much more clear to read and understand.
|
I'm implementing some form of internal profiler. Is there a way to know when and for how long a thread is context switched out? I know windows has it w the event tracing api and I know perf logs how many context switches happens. Is there a way to do it on linux? Needing root privileges is not an issue since it will b... |
Sort of.
Seehttp://man7.org/linux/man-pages/man2/getrusage.2.htmlabout thegetrusage()function.
Notice that the structure it returns has voluntary and involuntary context switch numbers. Also, you have user and system time. Other APIs return wall-clock time.
Any wall-clock time greater than your user and system time... |
I'm starting coding in C and I was doing an exercise, but saw a miscalculation testing this code:
```
int main(){
int number;
int square;
printf("Pick a number: ");
scanf("%d",&number);
while(number<=0)
{
printf("ERROR: The number MUST be greater than zero\nPick a number greater than zero: ");
scanf("%d",&... |
powtakesdoublearguments and returns adouble. So you're getting a rounding error.
|
This question already has answers here:Number at f(93) in fibonacci series has negative value, how?(3 answers)Closed6 years ago.
I don't know why am I getting the last number as negative.
I want to get the output as 0 1 1 ... 'n' numbers (fibonacci series)
```
#include<stdio.h>
int main()
{
int n;
scanf("... |
Yes, it is definitely out of int range
```
1836311903 //before last
-1323752223 //last
```
the max int is 2,147,483,647
If you want more than n=48, you must declare a,b,c as long type
```
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
long a=-1,b=1,c=0;
for(int i=0;i<n;i++)
{
c=a+b... |
I am going through my revision material and can't understand the following:
I have a compiled CmyCProgramprogram which prints out its input in the form of text. So if it were called in bash by./myCProgram input.txtandinput.txtcontained"this is a test"the program would output on stdout"this is a test". I have a range ... |
This redirects the content of input.txt to your program via stdin. This does the same as:
```
./myCProgram file.txt
```
and then typing in the contents of input.txt
|
I was wondering about the "? :" operators in C. Can one use the conditional operator inside another conditional operator like this?
```
int a = 0;
a == 1?a += 1:a == 0?a += 2:a = 3;
```
This is a very bad example, but I hope you understand what I'm trying to ask.
|
Of course you can, like this :
```
int a = 0;
a == 1?(a += 1):((a == 0)?(a += 2):(a = 3));
```
It is the same as writing :
```
int a = 0;
if (a == 1)
a += 1;
else
if (a == 0)
a += 2;
else
a = 3;
```
which is much more clear to read and understand.
|
I'm implementing some form of internal profiler. Is there a way to know when and for how long a thread is context switched out? I know windows has it w the event tracing api and I know perf logs how many context switches happens. Is there a way to do it on linux? Needing root privileges is not an issue since it will b... |
Sort of.
Seehttp://man7.org/linux/man-pages/man2/getrusage.2.htmlabout thegetrusage()function.
Notice that the structure it returns has voluntary and involuntary context switch numbers. Also, you have user and system time. Other APIs return wall-clock time.
Any wall-clock time greater than your user and system time... |
I'm starting coding in C and I was doing an exercise, but saw a miscalculation testing this code:
```
int main(){
int number;
int square;
printf("Pick a number: ");
scanf("%d",&number);
while(number<=0)
{
printf("ERROR: The number MUST be greater than zero\nPick a number greater than zero: ");
scanf("%d",&... |
powtakesdoublearguments and returns adouble. So you're getting a rounding error.
|
This question already has answers here:Number at f(93) in fibonacci series has negative value, how?(3 answers)Closed6 years ago.
I don't know why am I getting the last number as negative.
I want to get the output as 0 1 1 ... 'n' numbers (fibonacci series)
```
#include<stdio.h>
int main()
{
int n;
scanf("... |
Yes, it is definitely out of int range
```
1836311903 //before last
-1323752223 //last
```
the max int is 2,147,483,647
If you want more than n=48, you must declare a,b,c as long type
```
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
long a=-1,b=1,c=0;
for(int i=0;i<n;i++)
{
c=a+b... |
I am going through my revision material and can't understand the following:
I have a compiled CmyCProgramprogram which prints out its input in the form of text. So if it were called in bash by./myCProgram input.txtandinput.txtcontained"this is a test"the program would output on stdout"this is a test". I have a range ... |
This redirects the content of input.txt to your program via stdin. This does the same as:
```
./myCProgram file.txt
```
and then typing in the contents of input.txt
|
I have a string input that goes like this
string@floatValue
A set of values in this format is being passed as an input to the program. I am trying to read them usingscanf()but to no avail.
Some of the formats that I have tried are
scanf("%[^@]s%f",&s,&f);
scanf("%s@%f",&s,&f);
scanf("%s[@]%f",&s,&f);
No matter ... |
Remove an&befores, this should work:
```
scanf("%[^@]@%f",s,&f);
```
|
I did some experiment, pulling my hair out to figure the solution, please help!
```
#include <stdio.h>
int main() {
int USD , JPY;
int lower,upper,skip;
lower = 1;
upper = 1000;
skip = 50;
USD = lower;
while (USD <= upper) {
JPY = USD * 114;
printf("%d\t\%d\n", USD, JPY)... |
Try
```
USD = USD + skip - (USD == 1);
```
This works whenloweris 1.
If you want to make it general for everyloweryou need, as pointed by @EOF
```
USD = USD + skip - (USD == lower ? lower : 0);
```
|
Statement:
"array of N pointers to functions, returning pointers to functions and returning pointer to integer"
Can anyone help me with understanding the function prototype for above statement ?
Given answer-int *(*(*a[N])()) ();
Please can anyone explain me how we arrive at the above answer ?
|
```
*a[N]
```
is the array of N pointers, calling it x
```
*(x)()
```
returning function pointer, calling it y
```
int *(y) ()
```
is function pointer returning integer
|
I am writing a C code, this code consist with many sub functions and also within a sub function there is another sub function after execution of this sub sub function I need to go back in the beginning of main function.
My question is how can I exit from this function and come back main function?
As this code is too... |
THIS ANSWER NEEDS A HEALTH HAZARD - THIS IS THE WRONG WAY TO PROGRAM
You can usesetjmpandlongjmpto do this.
ButPLEASEdo everything in your power to avoid this - by thinking about the design of the code beforehand
|
I did some experiment, pulling my hair out to figure the solution, please help!
```
#include <stdio.h>
int main() {
int USD , JPY;
int lower,upper,skip;
lower = 1;
upper = 1000;
skip = 50;
USD = lower;
while (USD <= upper) {
JPY = USD * 114;
printf("%d\t\%d\n", USD, JPY)... |
Try
```
USD = USD + skip - (USD == 1);
```
This works whenloweris 1.
If you want to make it general for everyloweryou need, as pointed by @EOF
```
USD = USD + skip - (USD == lower ? lower : 0);
```
|
Statement:
"array of N pointers to functions, returning pointers to functions and returning pointer to integer"
Can anyone help me with understanding the function prototype for above statement ?
Given answer-int *(*(*a[N])()) ();
Please can anyone explain me how we arrive at the above answer ?
|
```
*a[N]
```
is the array of N pointers, calling it x
```
*(x)()
```
returning function pointer, calling it y
```
int *(y) ()
```
is function pointer returning integer
|
I am writing a C code, this code consist with many sub functions and also within a sub function there is another sub function after execution of this sub sub function I need to go back in the beginning of main function.
My question is how can I exit from this function and come back main function?
As this code is too... |
THIS ANSWER NEEDS A HEALTH HAZARD - THIS IS THE WRONG WAY TO PROGRAM
You can usesetjmpandlongjmpto do this.
ButPLEASEdo everything in your power to avoid this - by thinking about the design of the code beforehand
|
```
#include<stdio.h>
int main( )
{
char ch = '1' ;
printf ( "\n%d %c\n", ch, ch ) ;
return 0;
}
#include<stdio.h>
int main( )
{
char ch = 1 ;
printf ( "\n%d %c\n", ch, ch ) ;
return 0;
}
```
What is the difference between these two declarations of char?? Which one is correct??
|
The first piece of code assigns the character'1', which has an ASCII value of 49. Printing this as a character will yield1, while printing as a number will yield49.
The second piece of code assigns the value 1. Printing it as a character yields an unprintable character with an implementation defined representation,... |
Is a 'for loop' a function? If not, what is it? How it works?
Example in C:
```
for(int i=0; i<32; i++)
{
...
}
```
Example in Python:
```
for i in range(0, 32):
print "..."
```
|
No, the wholethingis called "iteration statement". The one which includes theforkeyword is calledforstatement.
QuotingC11, chapter 6.8,
Astatementspecifies an action to be performed. [...]
and from §6.8.5
iteration-statement:while ( expression ) statement
do statement while ( expression ) ;
for ( expressionopt ;... |
I am using GDB Machine interface to debug binary file which read from stdin and write to sdtout. I would like redirect both stdin and stdout to files. With plain GDB i can use run command like this:
```
run < input.txt > output.txt
```
Is there any way to maybe use GDB/MI command -exec-run similarly to this?
Here i... |
You should be able to use the mi command-inferior-tty-setalong with the mkfifo utility.
|
My function isvoid x(int *y);
I want to call it likex(&6);orx({6});, I do not want to define an integer and assign 6 to it, I want single line.
|
What you need iscompound literals
```
#include <stdio.h>
void x(const int *y)
{
printf("%d\n", *y);
}
int main(void)
{
x(&(int){6});
return 0;
}
```
|
What does the standard (are there differences in the standards?) say about assigning a float number out of the range of an integer to this integer?
So what should happen here,
assuming 16 bit short, to keep the number small(USHRT_MAX == 65535)
```
float f = 100000.0f;
short s = f;
s = (short) f;
unsigned short us = ... |
This is undefined behaviour (with no diagnostic required). See C11 6.3.1.4 (earlier standards had similar text):
When a finite value of real floating type is converted to an integer type other than_Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part can... |
Let's say we have a c program as follow:
```
int fun(char *path) {
FILE *f = fopen(path, "r");
int result;
// Do something here without closing the file
return result;
}
int main(int argc, char *argv[])
{
int i = fun(argv[1]);
printf("%d\n", i);
return 0;
}
```
I know that it is not a go... |
It'smain. File handles are allocated to the process, not any given function. Think of what would happen if you declaredfas a global variable. Any process termination will close files and free any other system resources associated to the process.
|
In this code oncefis assigned some value ofi, for example from inside the loop after 3 iterationsf=i=2, then next timefcannot be assigned the value again: the value offhas to be rock solid to first assignment only.
```
for(i=0;i<N-1;i++)
{
if(array[i+1]>array[i]);
else if(array[i+1]<array[i])
... |
You could setfequal to some placeholder value initially. Then, check for this placeholder and only make an assignment once:
```
int f = -1;
for (i=0; i < N-1; i++)
{
if (array[i+1] > array[i]);
else if (array[i+1] < array[i])
{
if (f == -1) f = i;
s = i+1;
}
else
{
if ... |
How do I check if the system on which my program is running on is an arm based or not using c/c++?
|
Here's what you are looking for,
```
#include <stdio.h>
#include <windows.h>
int main(void)
{
SYSTEM_INFO SystemInfo;
GetSystemInfo(&SystemInfo);
if(SystemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM)
{
// System's processor is ARM based
}
return 0;
}
```
Edit: As And... |
What is the correct order for the following structures? It's throwing field has an incomplete type error.
```
#include <stdlib.h>
struct nl_msg
{
int nm_protocol;
int nm_flags;
struct ucred nm_creds;
struct nlmsghdr * nm_nlh;
size_t nm_size;
int nm_... |
In your code (rather, translation unit.), there's nowherestruct ucredis defined.
You need to define_GNU_SOURCEMACRO and includesys/socket.hheader which defines this structure.
See this online.
|
I always hear that you should never usesystem()and insteadfork/execbecause system() blocks the parent process.
If so, am I doing something wrong by callingwaitpid(), which also blocks the parent process when I do afork/exec? Is there a way around callingwaitpid...I always thought it was necessary when doing afork/ex... |
TheWNOHANGflag (set in the options argument) will make the call towaitpid()non-blocking.
You'll have to call it periodically to check if the child is finished yet.
Or you could setupSIGCHLDto take care of the children.
|
I'm using posix threads and have a workerRoutine that in some cases has to wait for I/O.
```
//WorkerRoutine
while(true){
if(NO CURRENT WORK){
//sleep for I/O
continue;
}
//Other cases....
}
```
My I/O function updates a statically-sized list. My problem is, when there's no current work for a... |
The closest pthreads equivalent of Java'swaitandnotifymethods are available as functions acceptingcondition variables. Set up a condition variable, callpthread_cond_waitto wait for work, andpthread_cond_signalto announce that work is available.
Usage examples can be easily foundon StackOverflow.andelsewhere.
If you ... |
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 rotate an image by 90 degrees (right and left) a one-dimensional array n-elemen... |
You can use therotation matrix.
The rotation matrix for 90 degrees is simply
```
[0 -1
1 0]
```
hereyou can see how to do matrix multiplication in c if you need.
|
I'm developping an easy game written in C (Visual C++)
and I want to know if there is a way to play sounds,
thanks
(I'm using Visual Studio)
|
Take a look at thePlaySound()function.
If you callPlaySound()with theSND_ASYNCflag, the function returns immediately after beginning the sound.
For example:
```
#include <windows.h>
#include <mmsystem.h>
PlaySound(L"test.wav", NULL, SND_ASYNC | SND_FILENAME);
```
You'll also have to addWinmm.libin your project se... |
I'm new to OpenGL programming. I installed Ubuntu 64bit OS and installed all required libraries. But today when compiling I got stuck with an error for which I'm unable to find a solution
When I compiled my program with this command:
```
cc aa.c -lglut -lGLU -lGL
```
the following error appeared
```
/urs/bin/ld: ... |
Looks like you need to link to the math library explicitly with-lm.
|
This question already has an answer here:Pointer to a specific fixed address(1 answer)Closed6 years ago.
A bit of a silly question but here it is - how do I get a value based on its address?
Usually to get the address for a certain value I just print it out like this:
```
printf("%p", &loc);
```
But now I need to ... |
The standard way of accessing a particular address 0x12345678 (such as a hardware register) is:
```
(volatile uint32_t*)0x12345678
```
If you want to use the contents of that address as if it was a variable, you could either have a pointer point there, or make a macro:
```
#define REGISTER ( *(volatile uint32_t*)0x... |
I want to remove warning without change data-type to char.
```
#include<stdio.h>
#include<stdlib.h>
main()
{
unsigned char ch;
printf("Hello This is Problematic\n");
scanf("%d",&ch);
printf("1\n");
}
```
This generates the warning
test.c:7:2: warning: format ‘%d’ expects argument of type ‘int *’, bu... |
Actually,
```
scanf("%d",&ch);
```
leaves your program withundefined behavioras the supplied argument is not the correct type for the conversion specifier. You need to write
```
scanf("%hhu",&ch);
```
QuotingC11, chapter §7.21.6.2
hhSpecifies that a followingd,i,o,u,x,X, ornconversion specifier applies
to an ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.