question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Today I found strange syntax like
```
int _$[:>=<%-!.0,};
```
in some old code, but in fact the code is not commented. There seems to be no report of compile errors for this line. I tested it separately and it can compile too:
```
int main(){
int _$[:>=<%-!.0,};
return 0;
}
```
Why can it compile?
|
WithDigraph(see below), the line is converted to:
```
int _$[]={-!.0,};
```
On the right hand side,.0is thedoubleliteral,!is the logical negation operator,-is the arithmetic negation operator, and,is the trailing comma. Together{-!.0,}is an array initializer.
The left hand sideint _$[]defines anintarray. However, there's one last problem,_$is not a valid identifier in standard C. Some compilers (e.g,gcc) supports it as extension.
C11 Β§6.4.6 PunctuatorsIn all aspects of the language, the six tokens<: :> <% %> %: %:%:behave, respectively, the same as the six tokens[ ] { } # ##
|
This question already has answers here:Why do we need argc while there is always a null at the end of argv?(5 answers)Closed8 years ago.
I always thought thatargcwas required to mark the end ofargvbut I just learned thatargv[argc] == NULLby definition. Am I right in thinking thatargcis totally redundant? If so, I always thoughtCmade away with redundancy in the name of efficiency. Is my assumption wrong or there's a historic reason behind this? If the reason is historic, can you elaborate?
|
History.
Harbison & Steel (5th Edition, 9.9 "The main program") says the following:
Standard C requires thatargv[argc]be a null pointer, but it is not so in some older implementations.
|
I am trying to set a bit in a 8 bit variable.
Every time I print the variable after setting a particular bit , I always get the value as 1.
```
uint8 value;
value = (1<<1 || value)
printf(%x \n,value); //prints 1 instead of 2
value = (1<<2 || value)
printf(%x \n,value); //prints 1 instead of 4
```
|
You're using boolean 'or'||. Bitwise 'or' is|.
Also you haven't initializedvalueso you can't expect it to be anything.
|
I have a bunch of polygon data that I want to draw. I pulled out that drawing code so that it currently looks like this
```
for (int Index = 0; Index < Count; Index++) {
glDrawArrays(GL_TRIANGLE_FAN, Index * 4, 4);
}
```
I have a giant one dimensional array filled with multiple triangles, a new triangle every 4 vertices. Are there any OpenGL functions that I can replace this entire loop with so that I don't have the overhead of each glDrawArrays call? glMultiDrawArrays is sort of what I want, except I don't need a different first (well, I need a different first, but multiplied by a constant) and count each time.
I thought something like glVertexAttribDivisor would work, but nothing was drawing after I added it, I'm not completely sure if it works without instancing either.
EDIT: I am using a triangle fan, and I am buffering the vertices every frame.
|
glDrawElements()+GL_PRIMITIVE_RESTART&glPrimitiveRestartIndex().
|
Consider the following macro:
```
#define FOO(a,b) (--a)* 8 + (--b);
```
Now
```
int graph[8][8] = { 0 };
int *graph_p = &(graph[0][0]);
int *p = graph_p + FOO(2, 3);
```
Why do I get the error:
IntelliSense: expression must be a modifiable lvalue
|
It's because you are passing aninteger constantto function-like macroFOO(a, b), that applies pre-increment--operator to its arguments.
The result of this macro expansion looks as:
```
int *p = graph_p + (--2)* 8 + (--3);;
```
which is illegal in C, as operator requires amodifiable lvalueas its operand.
Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end:
```
#define FOO(a,b) ((--a)* 8 + (--b))
```
|
I've been tasked to build a Cocoa interface for a C terminal application.
There are no requirments other than the GUI.
My question is:
Would it be best and/or fastest to make the terminal calls or get source code (which I do have authorization to use) and call the functions directly from Cocoa?
Please state pros and cons for educational purposes.
|
It would be best (faster, easier) to call the functions directly from Cocoa.
Of course you realise that Cocoa apps must be Sandboxed if they are going on the Mac App Store and Sandboxing can make many, previously trivial, operations much more complicated?
|
I would like parse two numbers.
From a RTC IC I get 7 bits, where bit 6, 5, 4 are upper digits (first digit in number of seconds 0 - 5) and bits 3, 2, 1, 0 are unit digits (0 - 9). Now I would like to create a function that parses these two numbers and return the number of seconds.
Here is a table of the second number which I get from the RTC IC.
For the first number, I masked these bits and I get upper and lower numbers. I would like to parse these two numbers and return them from a function.
How?
|
It's pretty straightforward, just split the bits as documented :
```
uint8_t i = getBcd();
return (i >> 4 & 0x7) * 10 + (i & 0xf);
```
|
My sourcecode:
```
#include <stdio.h>
int main()
{
char myArray[150];
int n = sizeof(myArray);
for(int i = 0; i < n; i++)
{
myArray[i] = i + 1;
printf("%d\n", myArray[i]);
}
return 0;
}
```
I'm using Ubuntu 14 and gcc to compile it, what it prints out is:
```
1
2
3
...
125
126
127
-128
-127
-126
-125
...
```
Why doesn't it just count up to 150?
|
intvalue of acharcan range from 0 to 255 or -127 to 127, depending on implementation.
Therefore once the value reaches 127 in your case, it overflows and you get negative value as output.
|
I want to move a 64-bit unsigned integer to a register using inline asm. What happens is the constant gets sign-extended if it in fact fits in 32 bits.
Here is my code:
```
#include "stdint.h"
uint64_t foo() {
uint64_t x;
asm ("movq %1, %0"
: "=q" (x)
: "i" (0x00000000faceffff) );
return x;
}
```
Now,clang -S code.cproduces the following assembly:
```
#APP
movq $-87097345, %rax # imm = 0xFFFFFFFFFACEFFFF
#NO_APP
```
Same thing for gcc. Same thing formovabsqin place ofmovq. Same for"p"constraint instead of"i".
I get the result I expect if the constant is larger than 32 bits.
|
Is there a suffix for constants to declare them as unsigned long long with gcc? With Microsoft compilers it's "...ull" in this case 0x00000000faceffffull.
|
Ideally, I want to have a directory that is not visible in the filesystem and that will be automatically removed when it's last open file descriptor is closed. It's contents would only be accessible throughopenat(),fstatat(), etc.
For regular files, this behaviour is achieved by giving theO_TMPFILEflag toopen(). However,mkdir()doesnt have a flags parameter.
Assuming I have the latest linux kernel available, is this possible?
|
I'm not aware of any way to do this, and don't expect it to be possible. Unlike files, which can have zero or more pathnames (due to hard links and unlinked files), directories have exactly one pathname, and it would probably break some valid application usage if the OS did not meet this expectation.
|
My computer made a beep sound even though I did not add\ato my code. Why?
Program:
```
#include <stdio.h>
#include <limits.h>
#include <float.h>
#include <stdlib.h>
#define START_CHAR ' '
#define END_CHAR 'DEL'
int main(void)
{ /* This code prints characters on keyboard.*/
/* declaration */
int char_code;
for (char_code=(int)START_CHAR; char_code<=(int)END_CHAR; char_code=char_code+1)
printf("%c", (char)char_code);
printf("\n");
return(0);
}
```
|
'DEL'is not a valid character constant. It ends up being equal to 4474188. And since you havechar_codedefined as anint, the loop goes from 32 (the ASCII code for a space) to 4474188. So it loops through the full character set multiple times.
You should be using0x7Finstead.
|
I have defined macros as below.
```
#define FALSE 0
#define TRUE (!FALSE)
```
What will be the data-type ofTRUEandFALSE? What literal value doesTRUEtake after preprocessing? Is it compiler dependent? Why?
|
#definepreprocessor directive (macros) are meant to dotextual replacement. It will replace all occurrence ofFALSEto0andTRUEto!0that essentially gets evaluated to1. So, the resultant data type will be same as0and1. i.e., integer.
Regarding the usage of!operator, it always produces a result of typeint.
Quoting theC11standard, chapter Β§6.5.3.3 (emphasis mine)
The result of the logical negation operator!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0.The result has typeint. [...]
|
I am trying to detect which lines of my plaintext start with "linePrefix". Using the code above, even when there is a coincidence,strcmpnever returns 0. Does anyone know where am I failing?
```
const char PREFIX[] = {"linePrefix"};
FILE *fp;
char *line = NULL;
char *aux = NULL;
aux = (char *) malloc(16);
size_t len = 0;
ssize_t read;
char path[] = {/*path*/};
fp = fopen(path, "r");
while ((read = getline(&line, &len, fp)) != -1) {
strncpy(aux, line, 15);
printf("strcmp: %i\n, strcmp(aux, PREFIX));
}
```
|
You forgot to add the string terminator onaux:
```
strncpy(aux, line, 15);
aux[15] = `\0`;
```
Note that there is a simpler way to do the comparison where you don't need to copy the string. Just compare with the beginning oflinedirectly:
```
while ((read = getline(&line, &len, fp)) != -1) {
printf("strcmp: %i\n, strncmp(line, PREFIX, strlen(PREFIX)));
}
```
|
```
float number = 1.0;
float* number_pointer = &number;
int* int_pointer = (int*) number_pointer;
*int_pointer += 30;
printf("%f \n",number);
```
What does the line(*int_pointer)+= 30;do here?
|
I see two questions there.
What happens when you useint* int_pointer = (int*) number_pointer;That line takes the address of an object that holds afloatand stores that address inint_pointer. At this point, the compiler will be able to treat the address as though it holds an integer. That constitutes a violation of thestrict aliasing rule.What happens when you use*int_pointer += 30;It increments the value of the object thatint_pointerpoints to by30. In cases whereint_pointerpoints to a validintobject, that operation will be fine. In your case, this will cause undefined behavior sinceint_pointerreally points to an object of typefloat.
|
I'm trying to color at a specific point of the screen using ncurses lib.I have written this code:
```
#include<curses.h>
int main(void)
{
initscr();
start_color();
init_pair(1, COLOR_BLACK, COLOR_RED);
attron(COLOR_PAIR(1));
move(10, 10);
printw(" \n");
refresh();
getch();
endwin();
return 0;
}
```
There is a better way to do this? Or this is the only way?
|
Have a look atmvchgat()for changing the color (and other attributes) of an already-existing character.You can also usemvaddch(10, 10, ' ' | COLOR_PAIR(1))to move the cursor and output a space character with a custom color (or other attributes).
|
I really dislike asking about compilation errors here, but this one has been really bugging me.
I have the following code:
```
struct rtModel_capacitor {
....
};
extern rtModel_capacitor *const capacitor_rtM;
```
This gives the error (for the last line):
```
expected β=β, β,β, β;β, βasmβ or β__attribute__β before β*β token
```
Why won't this compile?
|
Different ways to resolve the problem:
```
struct rtModel_capacitor {
....
};
extern struct rtModel_capacitor *const capacitor_rtM;
```
or
```
struct rtModel_capacitor {
....
};
typedef struct rtModel_capacitor rtModel_capacitor;
extern rtModel_capacitor *const capacitor_rtM;
```
or
```
typedef struct {
....
}rtModel_capacitor;
extern rtModel_capacitor *const capacitor_rtM;
```
|
Supposetempis a pointer to structurenode.temp->nextisNULL. So what will be the value oftemp->next->next?
In short what is the value ofNULL->next? Is it compiler dependent because I have seen different result in ubuntu and code blocks(windows)?
What will be the output of the program below?
```
struct node
{
int data;
struct node *next;
};
main()
{
struct node *temp,*p;
int c=0;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=50;
temp->next=NULL;
p=temp;
if(p->next->next==NULL)//will it enter the if loop?
c++;
printf("%d",c);
}
```
|
NULL->next must give you a segfault.
You may want to have something like :
```
if(p->next != NULL && p->next->next==NULL)
```
or
```
if(p->next == NULL || p->next->next==NULL)
```
|
For a small project i am using libudev to get notification for USB devices plug-in/plug-out.
Is there any way of knowing which USB port was used to plug in the device via libudev.
Actually there are multiple ports available and it is necessary to know which one was used.
Any hints would be highly appreciated!
|
Using thelsusbcommand and doing agrepto find the line with the name of the device. This command will output all sorts of useful information about all connected USB devices. You can also uselsusb -vto get very detailed info.
Check out the manpage for lsusbhttp://manpages.ubuntu.com/manpages/hardy/man8/lsusb.8.html
|
I started learning C programming withC Programming LanguagebyDenis M RitchieI am trying to execute program from that book
```
#include <stdio.h>
/* count lines in input */
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
getchar();
}
```
However all I get is blank console and when I type text and press enter,no value is displayed.
I am using Visual Studio 2013 IDE.
|
The program you posted here is for counting number of lines.
Q. However all I get is blank console and when I type text and press
enter,no value is displayed
A. Yes it shows nothing becausewhile ((c = getchar()) != EOF)waits until you enter EOF (use ctrl + z then you will get number for lines).
|
I have tried to generate C code from C++ code compiled byllvm-g++, using the following commands:
```
llvm-g++ -emit-llvm -c ./example.cpp -o example.o
llc -march=c example.o
```
I tried these commands on a machine runningUbuntu (Linux 3.16.0-45-generic).
However instead of writing C code to standard output, the LLVM static linker reports that the compiled file is invalid:error: expected top-level entity.
How can I generate C code using the LLVM linker?
|
The original C backend (llvm-cbe) was removed in 3.1 (release notes), but there is this Julia project,resurrected LLVM "C Backend", with improvements, which resurrected it.
|
```
float number = 1.0;
float* number_pointer = &number;
int* int_pointer = (int*) number_pointer;
*int_pointer += 30;
printf("%f \n",number);
```
What does the line(*int_pointer)+= 30;do here?
|
I see two questions there.
What happens when you useint* int_pointer = (int*) number_pointer;That line takes the address of an object that holds afloatand stores that address inint_pointer. At this point, the compiler will be able to treat the address as though it holds an integer. That constitutes a violation of thestrict aliasing rule.What happens when you use*int_pointer += 30;It increments the value of the object thatint_pointerpoints to by30. In cases whereint_pointerpoints to a validintobject, that operation will be fine. In your case, this will cause undefined behavior sinceint_pointerreally points to an object of typefloat.
|
I'm trying to color at a specific point of the screen using ncurses lib.I have written this code:
```
#include<curses.h>
int main(void)
{
initscr();
start_color();
init_pair(1, COLOR_BLACK, COLOR_RED);
attron(COLOR_PAIR(1));
move(10, 10);
printw(" \n");
refresh();
getch();
endwin();
return 0;
}
```
There is a better way to do this? Or this is the only way?
|
Have a look atmvchgat()for changing the color (and other attributes) of an already-existing character.You can also usemvaddch(10, 10, ' ' | COLOR_PAIR(1))to move the cursor and output a space character with a custom color (or other attributes).
|
I really dislike asking about compilation errors here, but this one has been really bugging me.
I have the following code:
```
struct rtModel_capacitor {
....
};
extern rtModel_capacitor *const capacitor_rtM;
```
This gives the error (for the last line):
```
expected β=β, β,β, β;β, βasmβ or β__attribute__β before β*β token
```
Why won't this compile?
|
Different ways to resolve the problem:
```
struct rtModel_capacitor {
....
};
extern struct rtModel_capacitor *const capacitor_rtM;
```
or
```
struct rtModel_capacitor {
....
};
typedef struct rtModel_capacitor rtModel_capacitor;
extern rtModel_capacitor *const capacitor_rtM;
```
or
```
typedef struct {
....
}rtModel_capacitor;
extern rtModel_capacitor *const capacitor_rtM;
```
|
Supposetempis a pointer to structurenode.temp->nextisNULL. So what will be the value oftemp->next->next?
In short what is the value ofNULL->next? Is it compiler dependent because I have seen different result in ubuntu and code blocks(windows)?
What will be the output of the program below?
```
struct node
{
int data;
struct node *next;
};
main()
{
struct node *temp,*p;
int c=0;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=50;
temp->next=NULL;
p=temp;
if(p->next->next==NULL)//will it enter the if loop?
c++;
printf("%d",c);
}
```
|
NULL->next must give you a segfault.
You may want to have something like :
```
if(p->next != NULL && p->next->next==NULL)
```
or
```
if(p->next == NULL || p->next->next==NULL)
```
|
I was wondering around Internet for proper article regarding how to develop a good UI app for QNX . I was able to find things like -
We can use jamaicaVM to port our code developed on java to c .
Following are my questions :
On what platform should i develop the app for QNX .The app should have proper UI.
This might even help other beginner .
|
Now thatQt 5 has support on QNX 6.6, I would suggest using it. With Qt you can either develop your GUI in either in native C++ (Qt Widgets) or withQt Quick.
The biggest limiting factor will be the hardware you are running on (particularly the GPU or lack of) and the available QNX drivers for the hardware.
|
Is there any difference between the two? this take the program into two different point or what ,please provide all the detail of it. return is a statement, so why even usedreturn(1)(looking like a function call), please give the detail of 'how it actually works'?.
|
There should be no functional or performance difference at all at run time, since you're either returning the expression1or the expression(1), which is the same thing.
It's no different to the following situation, where the statements should have identical run time cost:
```
int a = 42;
int b = (42);
```
There's probably thesmallestdifference at compile time since the compiler has to evaluate more characters in the translation unit but I'd beverysurprised if it was noticeable.
|
I have no idea why my libssh program fails to connect to the localhost but it works fine for remote host.
```
ssh_session my_ssh_session = ssh_new();
ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "my_user_name");
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
int rc = ssh_connect(my_ssh_session);
if(rc != SSH_OK) {
printf("Error connecting to the localhost\n");
exit(-1);
}
// Authorized by the password.
rc = ssh_userauth_password(my_ssh_session, "my_user_name", "my_password");
```
The program can successfully create the session but it always failed in the last line when I tried to get authenticated. The error message I got fromssh_userauth_passwordis(Access denied. Authentication that can continue: publickey,keyboard-interactive).
|
you see the config/etc/ssh/sshd_config
changepasswordauthentication notopasswordauthentication yes
refer:Permission denied (publickey,keyboard-interactive)
|
I have a struct that I want to zero and then set the members. I tried this:
```
cmdRequest_t cmdRequest = {0};
cmdRequest = {3, "d t"};
```
but that doesn't work. I have also tried several variants, but I always get a syntax error on that second line. How can I do this?
|
Simply do:
```
cmdRequest_t cmdRequest = {3, "d t"};
```
There's no need to zero the structure if you're going to immediately fill in other values.
|
I'm interested in overriding compiler symbol names, generally automatically generated using mangled strings like this:
modules::ModuleAPI::ModuleAPI()becomes_ZN7modules9ModuleAPIC2Ev
I know there's an alias attribute:
void name1() __attribute__((alias ("name2")));
I'd prefer to do the same, except instead of aliasing, overriding it altogether.
Is this possible?
|
Yes, gcc supports this with the__asm__keyword:
```
void name1() __asm__("name2");
```
|
Given is the following code
```
char str[200];
str[0] = '\0';
double averrage[NUMBER_INPUTS];
for (int i = 0; i < NUMBER_INPUTS; i++) {
...
sprintf(str, "%s%.3f;", str, averrage[i]);
}
```
I am trying to understand sprintf, but I cant. Specialy because of the variablestr.
I hope anybody can helps me, to understand.
|
sprintf(str, "%s%.3f;", str, averrage[i]);isundefined behavior.
Withsprintf(), attempting to read and write to the same pointerstrmakes for bad code.
... If copying takes place between objects that overlap, the behavior is undefined.C11dr Β§7.21.6.6 2
Sample idea to concatenate follows.
```
char str[200];
str[0] = '\0';
char *p = str;
double averrage[NUMBER_INPUTS];
for (int i = 0; i < NUMBER_INPUTS; i++) {
int n = sprintf(p, "%.3f;", averrage[i]);
if (n < 0) break;
p += n;
}
puts(str);
```
Additional code is needed to preventstroverrun. Considersnprintf().
|
In Xcode I declared a string calledmyStringwith 5 spaces in memory.
```
int main() {
char myString[5];
printf("Insert a string: ");
scanf("%s", myString);
printf("Your string is %s.", myString);
return 0;
}
```
The problem is that whenever I type a word longer than 4 characters the console still prints out withprintf()my string instead of complaining about it.
What is this due to?
|
In your case, as you've definedmyStringto have 5chars, any input running longer than 4 chars (consider terminating null also as the 5th) will actually cause out of bound memory access, which producesundefined behavior. The result can be anything, inducing workingnormally, as if you had allocatedenoughmemory.
You should be limiting your input using
```
scanf("%4s", myString);
```
and likewise.
Also, as a note, the recommended signature formain()isint main(int argc, char *argv[])or at least,int main(void).
|
I am new to pointers.
For the below program , I get an answer of 255 and not 20. Please suggest how to correct.
Here is the code :
```
int sum(int *a , int *b);
int main()
{
int *p;
int *q;
*p =10;
*q =10;
int c = sum(p,q);
printf("%d",c);
}
int sum(int *a , int *b)
{
return((*a)+ (*b));
}
```
|
There is data, then there are pointers. For simplicity, once you have data, then you can point to it. This is accomplished by using the&operator. To go back to the data from a pointer, use the*operator as you have
Something more like
```
int sum(int *a , int *b);
int main()
{
int p_data=10;
int q_data=10;
int *p =&p_data;
int *q =&q_data;
int c = sum(p,q);
printf("%d",c);
}
int sum(int *a , int *b)
{
return((*a)+ (*b));
}
```
EDIT:Also note that pointers can be used to access memory allocated frommalloc, ormmap'd, or other means
|
I have not really a programming issue but more like an IDE issue. My Eiffel Studio 15.01 won't start up because of this error shown on the picture in the link.https://i.stack.imgur.com/mCzrO.jpg
Can anybody help please?
|
You can try to go to menu View > Tools Layout > Reset Tools Layout
Otherwise remove the files under
%LOCALAPPDATA%\Eiffel Software\.es\15.01\docking
(or ~/.es/15.01/docking in linux)
And restart EiffelStudio.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question
I am trying the below code in my program and getting the error.
```
abc rec; //abc is a struct which is having data member with void*.
rec.data = (price*)malloc(sizeof(price)); //rec.data is a void* and price is a structure
emp * e = (emp *)calloc(2, sizeof(emp)); // emp is a struct, which is member of struct price.
e[0].a = 1;
rec.data->emp = e; // error: 'void*' is not a pointer-to-object type
```
Can anyone please suggest on this.
|
datais of typevoid*, sodata->empwould be of typevoid, which you can't really have, much less assign to.
|
Given the following scenario:
2 Threads (no more, no less)A shared variable (let's say a void *)One thread writes to the variable ONLY once (this is guaranteed)And the other thread is responsible for reading the variable
Is it thread safe to have the reader thread check for null of the variable? Explicitly in a C program?
Example code:
Thread 1:
```
void initOnStartup()
{
ptr = malloc(10);
}
```
Thread 2:
```
void waitingForValue()
{
while(!ptr);
}
```
|
No, as the assignment=operation is not atomic.
|
I have not really a programming issue but more like an IDE issue. My Eiffel Studio 15.01 won't start up because of this error shown on the picture in the link.https://i.stack.imgur.com/mCzrO.jpg
Can anybody help please?
|
You can try to go to menu View > Tools Layout > Reset Tools Layout
Otherwise remove the files under
%LOCALAPPDATA%\Eiffel Software\.es\15.01\docking
(or ~/.es/15.01/docking in linux)
And restart EiffelStudio.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question
I am trying the below code in my program and getting the error.
```
abc rec; //abc is a struct which is having data member with void*.
rec.data = (price*)malloc(sizeof(price)); //rec.data is a void* and price is a structure
emp * e = (emp *)calloc(2, sizeof(emp)); // emp is a struct, which is member of struct price.
e[0].a = 1;
rec.data->emp = e; // error: 'void*' is not a pointer-to-object type
```
Can anyone please suggest on this.
|
datais of typevoid*, sodata->empwould be of typevoid, which you can't really have, much less assign to.
|
Given the following scenario:
2 Threads (no more, no less)A shared variable (let's say a void *)One thread writes to the variable ONLY once (this is guaranteed)And the other thread is responsible for reading the variable
Is it thread safe to have the reader thread check for null of the variable? Explicitly in a C program?
Example code:
Thread 1:
```
void initOnStartup()
{
ptr = malloc(10);
}
```
Thread 2:
```
void waitingForValue()
{
while(!ptr);
}
```
|
No, as the assignment=operation is not atomic.
|
Given the following scenario:
2 Threads (no more, no less)A shared variable (let's say a void *)One thread writes to the variable ONLY once (this is guaranteed)And the other thread is responsible for reading the variable
Is it thread safe to have the reader thread check for null of the variable? Explicitly in a C program?
Example code:
Thread 1:
```
void initOnStartup()
{
ptr = malloc(10);
}
```
Thread 2:
```
void waitingForValue()
{
while(!ptr);
}
```
|
No, as the assignment=operation is not atomic.
|
I need a regex that will match 24 time format.
Eg2300is valid2900is not valid
I was using this:
```
_[0-2][0-3][0-5][0-9]_
```
But this doesn't allow _1900_etc_
|
You need to decompose thehourspart in two cases: from00to19and from20to23. This is done by using a(pattern1|pattern2)expression.
Hours: 00-23.
```
([01][0-9]|2[0-3])
```
Minutes: 00-59.
```
[0-5][0-9]
```
All together:
```
([01][0-9]|2[0-3])[0-5][0-9]
```
|
What is the mathematical formula to calculate the range of signed, unsigned, short and long data types in ANSI C?
|
unsigned types have a range from0to2^(effective number of bits used by the type) - 1
signed types have a implementation defined minimum:
2's complement-(2^(effective number of bits used by the type - 1))all others-(2^(effective number of bits used by the type - 1) - 1)
the maximum for signed types is2^(effective number of bits used by the type - 1) - 1
^is the power function, not the xor.
|
I was just wondering howdata breakpoints(aka watchpoint) are created?
I know common breakpoints are made with some special INT3 instruction on x86.
I suppose you can createsoftwarewatchpoint by scanning the memory regularly.
But from the perspective of writing my own debugger with hardware breakpoints, I can't find anything in theWindows Referenceregarding this (only theses two topics on WinDbg12). I didn't look yet on Linux.
Any idea?
Thanks
|
On an x86 processor, you set up data breakpoints by using thedebug registerson the processor. Debug registers DR0-DR3 store the addresses to watch. That's the reason that Visual Studio is limited to four data breakpoints.
|
I have a jni function which calls an instance method. This function passes a byte array to the java side as below pseudocode. Do I need toDeleteLocalRefandReleaseByteArrayElementsinCside and what should I do in theJavaside?
```
// C side
func() {
while(something) {
jbyteArray array = NewByteArray();
// pass c side array as parameter to the java side
callInstanceMethod(array);
// delete and relase here?
}
}
// Java side
method(byte[] array) {
// delete array??
}
```
|
Do I need to DeleteLocalRef and ReleaseByteArrayElements in C side
Yes, otherwise you may exceed your local reference table in the JNI code, which I believe is only 20 large.
and what should I do in the Java side?
There isn't anything you can do in the Java side. The calling method still holds a reference while the Java callback is executing.
|
This question already has answers here:Macro expansion in context of arithmetic expression?(6 answers)Closed8 years ago.
```
#include <stdio.h>
#define sqr(a) a*a
int main()
{
int i;
printf("%d",64/sqr(4));
return 0;
}
```
Why am I getting the output as 64 .
Normally what should happen is it first checks the value forsqr(4)and then divide . In case of any other operator it works fine .
Please Explain .
|
After preprocessing the printf line will be:
```
printf("%d",64/4*4);
```
which should explain why it prints 64.
Always use parenthesis in macros definitions when they contain expressions:
```
#define sqr(a) ((a)*(a))
```
Even this is not safe against macro invocations like:sqr(x++). So don't use marcos unless you have to :)
|
This question already has answers here:Why does printf not flush after the call unless a newline is in the format string?(10 answers)Closed8 years ago.
I have a simple c program
```
#include <stdio.h>
int add(int, int);
int add (int a, int b) {
return a+b;
}
int main(void) {
int a, b, c;
printf("Enter the 1st number ");
scanf("%d",&a);
printf("Enter the 2nd number ");
scanf("%d",&b);
c = add(a, b);
printf("The value is %d ", c);
return (0);
}
```
I am compiling the program withcc main.cand when I am running the program with./a.outI am not getting any output in the console.
|
The output is buffered for performance reasons. Replace
```
printf("The value is %d ", c);
```
with
```
printf("The value is %d\n", c);
```
or usefflush(stdout);.
SeeWhy does printf not flush after the call unless a newline is in the format string?
|
In this code, the value ofrris working properly only when i am using theprintfstatement, otherwise the code is entering into the while loop even ifrris actually an integer value, for examplerr = 2.0.
My full code here
```
double rr = log(c)/log(2);
printf("Current value of rr is %lf\n",rr);
while(!(rr == (int)rr))
{
printf("hung in loop with c = %d\n",c);
if(c % 2 == 0)
c = c/2;
else
c = (c-1)/2;
rr = log(c)/log(2);
cc++;
}
```
This is the weirdest problem i have ever faced. The question is codechef august challenge problem 1.
|
As mentioned in lurker's comment, this is not doing what you expect:
```
while(!(rr == (int)rr))
```
A better method would be:
```
while((rr - floor(rr)) > .0001)
```
This avoids casting and accounts for the fact that floating point is not always an exact representation.
|
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.Closed8 years ago.Improve this question
I want a program for c language that takes text input using gets() function,...and then, prints the same text using print f statement.please answer! :)
|
Try this:
```
#include <stdio.h>
int main()
{
char str[50];
printf("Enter a string : ");
gets(str);
printf("You entered: %s", str);
return(0);
}
```
|
This question already has answers here:Comparison operation on unsigned and signed integers(7 answers)In a C expression where unsigned int and signed int are present, which type will be promoted to what type?(2 answers)Closed8 years ago.
This is the code,
```
#include <stdio.h>
int main()
{
unsigned int i = 0xFFFFFFFF;
if (i == -1)
printf("signed variable\n");
else
printf("unsigned variable\n");
return 0;
}
```
This is the output,
```
signed variable
```
Why isi's value-1even it is declared as unsigned?Is it something related to implicit type conversations?
This is the build environment,
```
Ubuntu 14.04, GCC 4.8.2
```
|
The==operator causes its operands to be promoted to a common type according to C's promotion rules. Converting -1 tounsignedyieldsUINT_MAX.
|
When using the following code to create a Window:
```
CreateWindowEx(0, "WinClass", "My Title", WS_OVERLAPPED | WS_SYSMENU, 261, 172, 594, 384, NULL, NULL, hInstance, NULL);
```
I get different Window sizes under Windows XP and Windows 7:
However, when I add theWS_THICKFRAMEstyle, the problem is solved:
```
CreateWindowEx(0, "WinClass", "My Title", WS_OVERLAPPED | WS_SYSMENU | WS_THICKFRAME, 261, 172, 594, 384, NULL, NULL, hInstance, NULL);
```
But unfortunatelyWS_THICKFRAMEmakes the Window resizable which I don't want.
Edit:
What I want it to remain the same size across different versions of Windows is the client area.
|
I think you are looking forAdjustWindowRect function:
Calculates the required size of the window rectangle, based on the
desired client-rectangle size. The window rectangle can then be passed
to the CreateWindow function to create a window whose client area is
the desired size.
|
This question already has answers here:How to return multiple values and store them in main() function?(2 answers)Closed8 years ago.
How can I return two integer type values at the same time in one function in the C programming language or should I write two different functions?
|
You can create astructin which you have two integers and return thisstructas the result of your function.
In a language such C, you can store your data instructlike this :
```
struct foo {
int x;
int y;
}
```
|
I'm using SWIG to make C data structures and functions available to my Python code. I have 2 structures as below -
```
struct A {
.....
};
struct B {
struct A a;
......
};
```
I call a C function from Python, which returns a(struct A *) b, where b is an instance ofstruct B.
Can I type cast the pointer fromstruct A *tostruct B *within my Python code?
|
Yes, but only because the two swig proxies are identical.
There's a layer in between the C objects and the python ones called the proxy layer.
|
Question speaks for itself. I have a program that used SHBrowseforfolder, but now they want me to upgrade it to IFileDialog which I made but is in C++, so is it even possible to get it to work with C since it's OOP?
|
IFileDialog is part of Microsoft's Component Object Model (COM). COM programming can be done in C. Quite tedious though.
Here's a tutorial (can't vouch for it's quality)
http://www.codeproject.com/Articles/13601/COM-in-plain-C
|
I'm using SWIG to make C data structures and functions available to my Python code. I have 2 structures as below -
```
struct A {
.....
};
struct B {
struct A a;
......
};
```
I call a C function from Python, which returns a(struct A *) b, where b is an instance ofstruct B.
Can I type cast the pointer fromstruct A *tostruct B *within my Python code?
|
Yes, but only because the two swig proxies are identical.
There's a layer in between the C objects and the python ones called the proxy layer.
|
Question speaks for itself. I have a program that used SHBrowseforfolder, but now they want me to upgrade it to IFileDialog which I made but is in C++, so is it even possible to get it to work with C since it's OOP?
|
IFileDialog is part of Microsoft's Component Object Model (COM). COM programming can be done in C. Quite tedious though.
Here's a tutorial (can't vouch for it's quality)
http://www.codeproject.com/Articles/13601/COM-in-plain-C
|
This question already has answers here:Why can't we initialize members inside a structure?(6 answers)Closed8 years ago.
Why this error is being thrown for below code.
```
Error: error: expected β:β, β,β, β;β, β}β or β__attribute__β before β=β token
struct node_s *next=NULL;
```
Code:
```
#include<stdio.h>
#include<stdlib.h>
typedef struct node_s {
int data;
struct node_s *next=NULL;
} node;
```
|
You have to remove theNULLinitialization of the pointer. An initialization is only allowed at the declaration.
```
typedef struct node_s {
int data;
struct node_s *next;
}node;
```
You can donode a = { .next = NULL };to initialize the pointer during the declaration.
|
I came across therewind()function in C. I went through its description and example fromhere.
The description mentioned the following about the function:
The C library functionvoid rewind(FILE *stream)sets the file position to the beginning of the file of the given stream.
I really didn't get the idea clear yet. Can we imagine it as a cursor moving in the file to be read, andrewind()simply sets that cursor to the beginning of the file?
|
From theman page:
The rewind() function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to:(void)fseek(stream, 0L, SEEK_SET)except that the error indicator for the stream is also cleared (seeclearerr(3)).
So the next time you read from a file after callingrewind, you start reading from the beginning. So your cursor analogy is a valid one.
|
Problem
I am trying to remove__attribute__from myCcode before I send it into a parser. Is there a way to define function-like macros using the-Dargument?
Solution using header file
```
#define __attribute__(x)
```
Attempted Solution
```
gcc -E -D__attribute__(x)= testfile.c
gcc -E -D__attribute__(x) testfile.c
```
|
from the man pages
```
If you wish to define a function-like macro on the command line,
write its argument list with surrounding parentheses before the
equals sign (if any). Parentheses are meaningful to most shells,
so you will need to quote the option. With sh and csh,
-D'name(args...)=definition' works.
```
So this works on a Unix/Linux shell
```
gcc -D'__attribute__(x)='
```
on Windows CMD the original expression works, since parentheses aren't special:
```
gcc -D__attribute__(x)=
```
|
I have directories named 0001_1000_solar, 0002_1000_solar, ... 1000_1000_solar. I want to go to each directory, compile a C program, pause for a second and move to another directory and do the same thing.
I wrote something like that in my terminal but it does not work:
for num in {0001..1000}; docd $num_1000_solar
gcc singl.c binary.c -lm
sleep 1
cd ..done
It takes me from the current directory to my user directory... Any ideas?
Cheers.
|
I think$num_1000_solaris the problem. Only $num has the assigned value.
It should becd {$num}_1000_solar
In the current case $num_1000_solar is an undefined variable, so it is empty. Hence the command becomes justcd, which takes you to your home directory.
Edit
Answer updated.
Thanks to the suggestions from redimp and Klas.
|
Since I've started doing serious things with C I need now to know if there's a way to make console (or terminal) not appear when the program starts.
Is there a code line for this?
I'm using SDL.
EDIT: I use Code::blocks
|
In your project settings you probably specified that your application is a console application. So the IDE makes sure that a console is opened for you when you launch the program. Change your project settings to fix this.
Edit:
This SO answer is what you're looking for:How to get ride of console box of a GUI program compile by MinGW + Code::Block
|
I've got a class that gets a 3-dimensional struct array in the constructor. For further calculations it also needs the length of each dimension.
a short example:
```
MyStruct*** mySt;
mySt = new MyStruct**[5]
mySt[0] = new MyStruct*[4]
mySt[0][0] = new MyStruct[3]
```
How can I get those values (5, 4, 3) back to save them in the new class without explicitely sending them to the constructor?
|
You cannot get sizes from plain C++ arrays allocated withnewand stored as pointers: there is no language construct that would let you retrieve an array size.
There are two options for how to deal with this situation:
In C++ use a container that supports sizing - for example,std::vectorof vectors of vectors, orIn C (or in C++, if you prefer to stay with arrays) construct a separate 3D array of sizes, and pass it along with themyStarray.
|
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.Closed8 years ago.Improve this question
I'd like to parse a medium to large XML file on 64-bit Linux with C/ C++. What is the easiest way to write such a code?
The details about the XML are contained in this questionWorking with a forest of binary trees stored in a large XML file (PHP)
|
libxml, the Gnome XML library, provides a fairly simple, but full-featured XML parser.
http://www.xmlsoft.org/
It's mostly a C library, and although there is a C++ facade for it, I often found it easier to write my own, light, wrapper around it's C interface. Since Gnome uses it, libxml is included in all Linux distributions.
|
Can anyone explain me the output.
```
#include<stdio.h>
int main() {
int a[]={10,20,30};
int *p=a;
++*p++;
printf("%d %d %d %d",*p,a[0],a[1],a[2]);
}
```
output is 20 11 20 30
Postfix incrementation has a higher precedence, so value of second index should have been incremented. Why is the value of first index incremented?
|
Due tooperator precedence,
++*p++is same as++(*(p++)).
That is equivalent to:
```
int* p1 = p++; // p1 points to a[0], p points to a[1]
++(*p1); // Increments a[0]. It is now 11.
```
That explains the output.
|
In c or a c-like language assuming I have arandom_hashwhat is the cheapest way to reduce it to a boolean value i.e.0or1?
An examplerandom_hashto normalise answers:0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa
Restrictions: no method/stdlib calls.
Whyc-like, I'm actually trying to do it in a language calledSolidity, which is modeled afterc/javascript, which has a very limited runtime/stdlib.
|
Take the largest or smallest bit from the hash and use this as the boolean. Actually, taking any bit should be fine, assuming a good hash function. Assuming the hash is an array of unsigned char, you can use the bitwise AND operator&
```
(hash[0] & 1) > 0
```
|
This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.
Taking the following example:
```
void foo(const int foobar);
```
Is the keywordconstmeaningful?
|
Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.
|
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.Closed8 years ago.Improve this question
I'd like to parse a medium to large XML file on 64-bit Linux with C/ C++. What is the easiest way to write such a code?
The details about the XML are contained in this questionWorking with a forest of binary trees stored in a large XML file (PHP)
|
libxml, the Gnome XML library, provides a fairly simple, but full-featured XML parser.
http://www.xmlsoft.org/
It's mostly a C library, and although there is a C++ facade for it, I often found it easier to write my own, light, wrapper around it's C interface. Since Gnome uses it, libxml is included in all Linux distributions.
|
Can anyone explain me the output.
```
#include<stdio.h>
int main() {
int a[]={10,20,30};
int *p=a;
++*p++;
printf("%d %d %d %d",*p,a[0],a[1],a[2]);
}
```
output is 20 11 20 30
Postfix incrementation has a higher precedence, so value of second index should have been incremented. Why is the value of first index incremented?
|
Due tooperator precedence,
++*p++is same as++(*(p++)).
That is equivalent to:
```
int* p1 = p++; // p1 points to a[0], p points to a[1]
++(*p1); // Increments a[0]. It is now 11.
```
That explains the output.
|
In c or a c-like language assuming I have arandom_hashwhat is the cheapest way to reduce it to a boolean value i.e.0or1?
An examplerandom_hashto normalise answers:0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa
Restrictions: no method/stdlib calls.
Whyc-like, I'm actually trying to do it in a language calledSolidity, which is modeled afterc/javascript, which has a very limited runtime/stdlib.
|
Take the largest or smallest bit from the hash and use this as the boolean. Actually, taking any bit should be fine, assuming a good hash function. Assuming the hash is an array of unsigned char, you can use the bitwise AND operator&
```
(hash[0] & 1) > 0
```
|
This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.
Taking the following example:
```
void foo(const int foobar);
```
Is the keywordconstmeaningful?
|
Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.
|
Can anyone explain me the output.
```
#include<stdio.h>
int main() {
int a[]={10,20,30};
int *p=a;
++*p++;
printf("%d %d %d %d",*p,a[0],a[1],a[2]);
}
```
output is 20 11 20 30
Postfix incrementation has a higher precedence, so value of second index should have been incremented. Why is the value of first index incremented?
|
Due tooperator precedence,
++*p++is same as++(*(p++)).
That is equivalent to:
```
int* p1 = p++; // p1 points to a[0], p points to a[1]
++(*p1); // Increments a[0]. It is now 11.
```
That explains the output.
|
In c or a c-like language assuming I have arandom_hashwhat is the cheapest way to reduce it to a boolean value i.e.0or1?
An examplerandom_hashto normalise answers:0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa
Restrictions: no method/stdlib calls.
Whyc-like, I'm actually trying to do it in a language calledSolidity, which is modeled afterc/javascript, which has a very limited runtime/stdlib.
|
Take the largest or smallest bit from the hash and use this as the boolean. Actually, taking any bit should be fine, assuming a good hash function. Assuming the hash is an array of unsigned char, you can use the bitwise AND operator&
```
(hash[0] & 1) > 0
```
|
This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.
Taking the following example:
```
void foo(const int foobar);
```
Is the keywordconstmeaningful?
|
Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.
|
I have a wriiten a C program that contains a char array 'long_string' that looks something like this.
```
long_string[16] = "AHDAHDAHDAHDAHDA";
```
I wish to replace the letters in the string as follows:
A-0, H-1, D-2.
Could somebody tell me how could I achieve this? I tried to look online but most of the cases show the conversion of letters to there ASCII values which is not what I need. THank you for your time in advance :)
|
The way you have defined your string, it won't be null terminated (16 is not enough to fit in also the null terminator). Other than that, what you want should be fairly easy:
```
int i = 0;
char long_string[] = "AHDAHDAHDAHDAHDA";
int len = strlen(long_string);
for(i = 0; i<len; i++)
{
if(long_string[i] == 'A')
long_string[i] = '0';
else if(long_string[i] == 'H')
long_string[i] = '1';
// etc.
}
```
|
Lets say I have achar[10]="1234567890. I want it to break it in two 5digits number. I want to ask two thing that do i need to convert it in int before spliting and how will i split it
|
ex
```
char num10[]="1234567890";
int n1, n2;
sscanf(num10, "%5d%5d", &n1, &n2);
printf("%d, %d\n", n1, n2);
```
|
Say we have the following array:
```
char *names[]={"Abc", "Def", "Ghi", "Klm", "Nop"};
```
If we want to create a pointer that points to the array above, why should we use a two-level pointer as follows?
```
char **p1 = names;
```
Thanks.
|
Yournamesis an array[], ofchar *, i.e., an array of pointers tochar.
Meanwhilep1is a pointer which points to a pointer tochar, i.e., a pointer tochar *. You can assignnamesto it because the array decays to a pointer to its first element, and the first element ofnamesis a pointer tochar, hencenamesdecays to a pointer tochar *. This is the same type βchar **β asp1, therefore they are compatible.
(On another note, the element type ofnamesis incorrect; the string literals are constant, and thus it should beconst char *names[], and similarlyp1should beconst char**β pointer to pointer toconst char.)
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed8 years ago.
Given the following code:
```
int a=0,b=2;
printf("(%d,a=%d,a+b=%d)",a=a+3,a,a+b);
```
why the result is(3,a=3,a+b=5)
|
You are printing the result of an assignment (a=a+3) which is the assigned value (3).
But the evaluation order of the parameters depends on the compiler (undefined behaviour). it could print:
```
(3,a=3,a+b=5)
```
or:
```
(3,a=0,a+b=2)
```
or even:
```
(3,a=0,a+b=5)
```
|
I'm reading a project , and I found this code, which I don't unterstand.
```
#define OUT_PINS {X2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Y2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Z2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}
```
the program is running on SAM3S a cortex M3 from Atmel .
X2_Pin , Y2_Pin and Z2_Pin are defined .
can anyone explain o me whatOUT_PINSnow is ?
|
OUT_PINSis a macro defined with some 2D array values. check the following example for better understanding.
eg:int *OP[] = {OUT_PINS }is similar to
```
int *OP[] = {{X2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Y2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Z2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}}
```
|
The definition of the c library functionmemmoveis like the following:
```
void* memmove(void *s1, const void *s2, size_t n)
{
char *sc1;
const char *sc2;
sc1 = s1;
sc2 = s2;
...
}
```
I'm wondering why do we need to usevoid*andconst void*as the parameters' type. Why not directlychar*andconst char*?
update
```
int test_case[] = {1, 2, 3, 4, 5, 6, 7, 8, 10};
memmove(test_case+4, test_case+2, sizeof(int)*4);
```
Output:
test_case = {1, 2, 3, 4, 3, 4, 5, 6, 10}
|
Ifchar*andconst char*are used, then we have to always cast tochar*when invokingmemmoveon other types.
By usingvoid*andconst void*, we are able to write shorter code, and the casting has no performance overhead.
|
How can I convert a string into a variable name? E.g. I have a list of strings:
```
"str1", "str2", "str3", etc.
```
And a structure:
```
struct my_struct {
int str1;
int str2;
int str3;
} m = {5, 10, 15, ... etc};
```
Given a string"str2", I want to print the variable associated with that
namem.str2. Does C have any way to do this?
Thank you!
|
This is simply not possible in C.Check out this question for more details.How to return a variable name and assign the value of the variable returned in c
To quote Wichert, 'I suggest that you reconsider the problem you are trying to solve and check if there might not be a better method to approach it. Perhaps using an array, map or hash table might be an alternative approach that works for you.'
|
I'm reading a project , and I found this code, which I don't unterstand.
```
#define OUT_PINS {X2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Y2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Z2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}
```
the program is running on SAM3S a cortex M3 from Atmel .
X2_Pin , Y2_Pin and Z2_Pin are defined .
can anyone explain o me whatOUT_PINSnow is ?
|
OUT_PINSis a macro defined with some 2D array values. check the following example for better understanding.
eg:int *OP[] = {OUT_PINS }is similar to
```
int *OP[] = {{X2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Y2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}, \
{Z2_PIN, PIOC, ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT}}
```
|
The definition of the c library functionmemmoveis like the following:
```
void* memmove(void *s1, const void *s2, size_t n)
{
char *sc1;
const char *sc2;
sc1 = s1;
sc2 = s2;
...
}
```
I'm wondering why do we need to usevoid*andconst void*as the parameters' type. Why not directlychar*andconst char*?
update
```
int test_case[] = {1, 2, 3, 4, 5, 6, 7, 8, 10};
memmove(test_case+4, test_case+2, sizeof(int)*4);
```
Output:
test_case = {1, 2, 3, 4, 3, 4, 5, 6, 10}
|
Ifchar*andconst char*are used, then we have to always cast tochar*when invokingmemmoveon other types.
By usingvoid*andconst void*, we are able to write shorter code, and the casting has no performance overhead.
|
How can I convert a string into a variable name? E.g. I have a list of strings:
```
"str1", "str2", "str3", etc.
```
And a structure:
```
struct my_struct {
int str1;
int str2;
int str3;
} m = {5, 10, 15, ... etc};
```
Given a string"str2", I want to print the variable associated with that
namem.str2. Does C have any way to do this?
Thank you!
|
This is simply not possible in C.Check out this question for more details.How to return a variable name and assign the value of the variable returned in c
To quote Wichert, 'I suggest that you reconsider the problem you are trying to solve and check if there might not be a better method to approach it. Perhaps using an array, map or hash table might be an alternative approach that works for you.'
|
The problem is with this for loop:
```
for (int i = 0; i < n; i++);
{
a = y & 1;
y = y >> 1;
b = a | b;
b = b << 1;
}
```
you see i have set n to 4 so the compiler should've went four times through the loop, but it only goes through once (I added a "printf" to print 'i' and it prints 4). Why is i being set to 4 instead of zero?
ps I'm using visual studio 2013
|
```
for (int i = 0; i < n; i++);
^
```
Extra semi-colon. Easy mistake to make.
|
I Want to get the username or SID from a session id value, how can I do that working from Window XP using the WinAPI?
|
You can use theWTSQuerySessionInformationfunctionto get the Username and Domain (WTSUserNameandWTSDomainNamefromWTS_INFO_CLASS).
This function is available as far back as Windows 2000.
|
Explain how sizeof determines the length of the string.
```
#include<stdio.h>
int main()
{
char str[] = "Sasindar\0Baby\0";
printf("%d\n", sizeof(str));
return 0;
}
```
|
sizeofdoes not determine the length of the string. It determines how many bytes a structure takes in memory.
In your case, the structure isstr, an array of bytes. The compiler knows how many bytes, including the two trailing'\0's, was placed into the array, so it produces the proper size at compile time.sizeofhas no idea thatstris a null-terminated C string, so it produces 15.
This is in contrast tostrlen, which interprets your string as a C string, and returns the count of characters before the first'\0'.
|
I have to run a loop for certain amount of time. I know the following way to do that.
```
get start time;
while(1)
{
getcurrenttime;
if(start time + time to run >= current time)
break;
else
do what ever you want.
}
```
Is it ok ? or any other better way to do this?
|
I suggest you introduce any "Thread.Sleep" inside the loop to prevent the use and energy comsuption of the processor, improving the performance of other processes and operating system. If you want to wait a fix time you can use the system threading sleep directly otherwise if you want to wait an undefined time you could have a loop with exit conditions like maximum time or another conditional expressions but you must adjusts the waiting time with small sleep values.
|
This question already has answers here:Why does the expression a = a + b - ( b = a ) give a sequence point warning in c++?(4 answers)Closed8 years ago.
To swap to integers, A and B, this seems to work in C,
```
A = A + B - ( B = A);
```
Why does this work?
And if this works in all conditions, can this be used to shorten any other commonly implemented algorithms?
|
Actually it invokes undefined behaviour according to standards-
C99 Β§6.5: β2. Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.β
|
I am using<stdio.h>and<string.h>.
fp's text file only contains 420.42
```
fgets(str[0].flo, 7, fp)
```
Has a 7 character string of "420.42" (4, 2, 0, ., 4, 2, \0)
When I try to convert it into a float viaatof()as
```
float flt = 0;
flt = atof(str[0].flo);
```
The value of flt is not 420.42; am I doing it wrong or is there a different way?
|
If you get a0.0000result is likely you have omittedstdlib.hin your include list.
Even so, you will get something like420.420013, as420.42cannot be represented exactly with a 23 bit mantissa.
|
I'm looking into why Warframe does not work on WINE in Linux, and I suspect that it is due to missing system or library calls. I'd like to determine what calls it makes, and compare them to calls supported directly or indirectly by WINE.
|
There is a tool calledEXE Import Viewerit doesn't continuously list the function calls but it does reveal the dependencies of the the exe.
From the site:
EXE Import Viewer shows the information about linked libraries and functions, the list of function that an executable file imports, and the DLL's from which the program imports these functions.
This might be a good place to start for your problem.
|
Is it safe to do this:
```
SDL_Window* window = NULL;
SDL_DestroyWindow(window);
```
Or do I have to do this:
```
if(window != NULL)
{
SDL_DestroyWindow(window);
}
```
I know that it is safe to free a null pointer using free(void*) in stdlib.h, but I want to know if the same goes for SDL functions
|
The documentation doesn't say either way, but I can see from the v2.0.3 source code thatSDL_DestroyWindowdoes have protection against a null pointer input.
That being said, it's undocumented and I can't even promise how reliable thisCHECK_WINDOW_MAGICmacro is across all build modes, so you should take theifstatement approach.
Besides, if you can have a NULL window then I question your design.
|
This question already has answers here:Why is the asterisk before the variable name, rather than after the type?(13 answers)Closed8 years ago.
I Just want to know what is the difference between the following way of assigning a pointer. i was watching a C tutorial online and couldn't understand why he used the second pointer like thischar * buffer;. Instead ofchar *buffer
Like the way I use the pointer in all my C learning. is it style?
e.g
```
FILE *pFile;
struct product *next;
```
does it matter where you put the asterix (pointer) or what is the meaning behind it?
|
Nope, there is no difference, it's a matter of preference.
I tend to put it asstruct product* nextbecause it makes it clearer that the type ofnextisproduct*, AKA a pointer to a product. But different people advocate different things.
|
```
void deleteat(int pos)
{
struct node *temp,*temp1;
//temp=(struct node*)malloc(sizeof(struct node));
temp1=temp=head;
int i;
if(pos==0)
{
temp=head->next;
free(head);
head=temp;
}
else
{
for(i=0;i<pos;i++)
{
temp1=temp;
temp=temp->next;
}
temp1->next=temp->next;
temp->next=NULL;
free(temp);
}
}
// Fucntion calls in the main
deleteat(4);
deleteat(1);
deleteat(6);
```
I submitted a similar code on an online judge, but it got accepted there, while running the same code on my linux machine gives the segmentation fault (core dumped). I know this question has been asked many times, but I couldn't find the error in my code.
|
While you iterating list you don't check if temp or temp1 are valid pointers. Some of them could be null
|
Explain how sizeof determines the length of the string.
```
#include<stdio.h>
int main()
{
char str[] = "Sasindar\0Baby\0";
printf("%d\n", sizeof(str));
return 0;
}
```
|
sizeofdoes not determine the length of the string. It determines how many bytes a structure takes in memory.
In your case, the structure isstr, an array of bytes. The compiler knows how many bytes, including the two trailing'\0's, was placed into the array, so it produces the proper size at compile time.sizeofhas no idea thatstris a null-terminated C string, so it produces 15.
This is in contrast tostrlen, which interprets your string as a C string, and returns the count of characters before the first'\0'.
|
I have to run a loop for certain amount of time. I know the following way to do that.
```
get start time;
while(1)
{
getcurrenttime;
if(start time + time to run >= current time)
break;
else
do what ever you want.
}
```
Is it ok ? or any other better way to do this?
|
I suggest you introduce any "Thread.Sleep" inside the loop to prevent the use and energy comsuption of the processor, improving the performance of other processes and operating system. If you want to wait a fix time you can use the system threading sleep directly otherwise if you want to wait an undefined time you could have a loop with exit conditions like maximum time or another conditional expressions but you must adjusts the waiting time with small sleep values.
|
This question already has answers here:Why does the expression a = a + b - ( b = a ) give a sequence point warning in c++?(4 answers)Closed8 years ago.
To swap to integers, A and B, this seems to work in C,
```
A = A + B - ( B = A);
```
Why does this work?
And if this works in all conditions, can this be used to shorten any other commonly implemented algorithms?
|
Actually it invokes undefined behaviour according to standards-
C99 Β§6.5: β2. Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.β
|
I am using<stdio.h>and<string.h>.
fp's text file only contains 420.42
```
fgets(str[0].flo, 7, fp)
```
Has a 7 character string of "420.42" (4, 2, 0, ., 4, 2, \0)
When I try to convert it into a float viaatof()as
```
float flt = 0;
flt = atof(str[0].flo);
```
The value of flt is not 420.42; am I doing it wrong or is there a different way?
|
If you get a0.0000result is likely you have omittedstdlib.hin your include list.
Even so, you will get something like420.420013, as420.42cannot be represented exactly with a 23 bit mantissa.
|
I'm currently trying to change the process name of a process so I can read the more easily with htop, top, .... I want toLD_PRELOADthis code into another process so it gets renamed by an environemt variable.
I found a lot of stuff in the internet, but nothing works:
```
prctl(PR_SET_NAME, "Test");
```
This does not work because htop is not honoring the name.
Nginxsetproctitle(Link) doesn't work as well, because it strips the parameters (which are needed by the process).
I tried everything I found and now I'm out of ideas.
Is this even possible in linux? And how?
|
Just run your program by shell script or your program throughexecand pass desired name asargv[0]:
```
#/bin/bash
exec -a fancy_name a.out ...
```
or C/C++:
```
execl( "./a.out", "fancy_name", ... );
```
|
So in c I have a data matrix that is n x m. How can I extract a single row to pass it to a new variable. My python code looks like this:
new_var = data[i, :]
Please help me translate into C.
My way is
```
int i = rand(num_rows);
double new_var[num_cols];
for (j = 0; j < num_cols; j++)
{
new_var[j] = data[i][j];
}
```
Please comment.
Many thanks
|
What you are doing is correct. But I don't get what you are trying to do with this -
```
int i = rand(num_rows); // using rand like this is incorrect syntax.
```
If you want a random number between0tonum_rows. Correct will be -
```
int i = rand()%num_rows;
```
See here how to userand.
|
I'm a bit confused because I wanted to initialize a variable of typeunsigned longwhose size is 8 bytes on my system (on every modern system I suppose). When I want to assign1 << 63to the variable, I get a compiler warning however and the number is in fact 0. When I do1 << 30I get the expected result of2 ^ 30 = 1073741824. Yet when I do1 << 31, I get the result of2 ^ 64(I think; actually this shouldn't be possible) which prints18446744071562067968.
Can anyone explain this behaviour to me?
|
1 << 63will be computed inintarithmetic, and yourintis probably 32 bit.
Remedy this by promoting the left argument:1ULL << 63will do it.
ULLmeans the expression will be at least 64 bits.
|
I used the PostgreSQL as my data base and I am coding a c++ project, so I have to use thelibpqto connect it.
I have already found the include file and lib file in the PostgreSQL file but there are too many files. I think I don't need to add them all.For the include file, I just addedlibpq-fe.h,pg_config_ext.handpostgres_ext.h, then I included thelibpq-fe.h, it seems that everything goes well, I can call some functions such asPQconnectdb,PQexecetc. But when I compile it, I get some LNK errors, meaning that I didn't add the right lib files.I've tried to addlibpq.libandlibpq.dll, but I still got the LNK errors.Does someone know which lib files should I add?
|
I got this error because of the wrong version.Hereis a same problem which has been solved.
|
```
int* intptr ()
{
int i;
i=rand();
printf("%d_____",i);
return(&i);
}
int main()
{
int* j,k,l;
j=intptr();
k=intptr();
l=intptr();
printf("%d/n",j);printf("%d/n",k);printf("%d/n",l);
}
```
Here theintptrfunction returns a pointer in the first call and after that all the subsequent calls return the int2752220
|
The other answers address undefined behavior, which is the poor coding practice your code sample exhibits. However, as shownhere, the real issue is that when you define
```
int* j,k,l;
```
only the first variablejis an int pointer. The others are regular integers. In order to make them all pointers, you have to define them like this:
```
int* j;
int* k;
int* l;
```
By running the code by chance each pointer may point to the samedeleted valuefrom your function, but at least they'll be pointers and not integers.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.