question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I have a little question:
```
struct point {int x ; int y;};
int main(){
struct point p = {10,20};
struct point *pp = &p;
(∗ pp).x = 10; // what is happening here
int y= (∗ pp).y; return 0} // what is happening here
```
and more general , why is the () required?
(its from a tutorial but they g... |
Because.has higher precedence than*. That is, without the parenthesis,
```
*pp.x = 10;
```
stands for
```
*(pp.x) = 10;
```
However,ppis a pointer. Thus, the.operator does not work on it.
You need to either use->operator to access the member of a pointer to struct, or use parenthesis to dereference the pointer bef... |
I need it because I have to modify the linker, specifically that part where it resolves the symbols in plt section and updates them in GOT.
|
As I've already posted in my previous answer to your question,this page is great.
Read it carefully — there is also a number of references and books in the beginning (Useful books and referencesheading).
You may also want to look atLinkers and Loadersby Levine for reference.
|
Is there a simple way to split one 64-bit (unsigned long long) variable into eightint8_tvalues?
For example:
```
//1001000100011001100100010001100110010001000110011001000110011111
unsigned long long bigNumber = 10455547548911899039;
int8_t parts[8] = splitULongLong(bigNumber);
```
partswould be something along the ... |
```
{
uint64_t v= _64bitVariable;
uint8_t i=0,parts[8]={0};
do parts[i++]=v&0xFF; while (v>>=8);
}
```
|
```
FILETIME Kernel_Time;
HANDLE Process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 0);
GetProcessTimes(Process, NULL, NULL, &Kernel_Time, NULL);
SYSTEMTIME Sys_Time;
FileTimeToSystemTime(&Kernel_Time, &Sys_Time);
printf("%d", Sys_Time.wYear); // WHY ?
```
WhySys_Time.wYearis not 2013?
Could anyone help me?
|
```
HANDLE Process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 0);
```
As per thedocumentation,
If the specified process is the System Process (0x00000000), the function fails and the last error code is ERROR_INVALID_PARAMETER.
So, yourOpenProcessfails withERROR_INVALID_PARAMETER, and theHANDLE ProcessisNULL. Always c... |
I'm using the following C code:
```
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
int main()
{
int file=0;
if((file=open("testfile.txt",O_RDONLY)) < -1)
return 1;
char buffer[19];
if(read(file,buffer,19) != 19) return 1;
printf("%s\n",buffer);
if(lseek(file,10,SE... |
You need to add#include <stdio.h>to the top of your file.
|
"Write a single program, called program.c, that will create a total of 9 processes which will identify themselves as process0, process1, process2, process3, process4, process5, process6, process7 and process8. The original process should be process0."
How can I have my process identify as "processX" when creating a p... |
```
for (int i = 1; i < 9; i++)
{
int pid = fork();
if (pid < 0)
exit(1);
else if (pid == 0)
{
printf("Process%d\n", i);
exit(0);
}
}
printf("Process%d\n", 0);
```
|
I want to insert characters into the middle of a char array in C, but first I want to shift it to the right each time prior to adding a char so that I don't lose what's already in the char array (called input) by overwriting.
|
I assume you are terminating the array with a null char since you are using strlen. In that case, I'm pretty sure the first iteration of your for loop will overwrite the null character with the preceding char, and you don't seem to replace it. Try running
```
for( k = strlen(input) + 1; k > place42; k--)...
```
This... |
I am using the scanf() function in my program to scan an integer. The way I am doing it is:
```
while (!feof (stdin))
if (scanf("%d", &height) != 1) { puts("Wrong input!"); return 1; }
```
The problem is, that after actually doing EOF, I get the wrong input and return 1, due to the scanf not returning 1. How should ... |
There are many problems with this approach. (EOF not active until after trying to read, text input like 'A' creates infinite loop, etc.) Instead :
```
char buf[100];
while (fgets(buf, sizeof buf, stdin) != NULL) {
if (sscanf(buf, "%d", &height) != 1) {
puts("Wrong input!");
return 1;
}
do_something(h... |
I want to change FileTime to SystemTime, but the program always collapsed, WHY?
Thanks in advance.
```
FILETIME *Kernel_Time;
HANDLE Process = OpenProcess ( PROCESS_ALL_ACCESS, FALSE, 0);
GetProcessTimes (Process, NULL, NULL, Kernel_Time, NULL);
SYSTEMTIME *Sys_Time;
FileTimeToSystemTime (Kernel_Time, Sys_Time);
``... |
You don't allocate memory for the result. It is probably easier to allocate it on the stack, and use the address in the function call like this:
```
FILETIME Kernel_Time;
HANDLE Process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 0);
GetProcessTimes(Process, NULL, NULL, &Kernel_Time, NULL);
SYSTEMTIME Sys_Time;
FileTime... |
I am currently working with some function like below:
```
void vadd(float * a, float * b, int n){
for(int i = 0; i < n; i++){
a[i] += b[i];
}
}
```
This loop essentially can be rewritten using SSE but my question is how to handle the few elements that are left out if n is not a multiple of 4?
Th... |
You can handle the lastn % 4elements with a separate loop:
```
void vadd(float *a, float *b, int n)
{
int i = 0;
for (; i < n - n % 4; i += 4) {
a[i + 0] += b[i + 0];
a[i + 1] += b[i + 1];
a[i + 2] += b[i + 2];
a[i + 3] += b[i + 3];
}
for (; i < n; i++) {
a[i] +... |
How to write a C Code in order to disable the 'Close Window' option in the taskbar?
Compiler: GCC-mingw32
Which API Function should I use?
Thanks.
|
Make the window's message dispatcher process the messageWM_SYSCOMMANDand filter it out if the message'swParamisSC_CLOSE.
LetWndProcbe the windows message handler then the code to do might look like this:
```
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
...
switch (message)
... |
How can I enumerate allenumnames and values in C to print it like
```
printf("Name: %s, value: %d\n", name, value);
```
?
|
Check outthe X macro:
```
#define COLORS \
X(Cred, "red") \
X(Cblue, "blue") \
X(Cgreen, "green")
#define X(a, b) a,
enum Color { COLORS };
#undef X
#define X(a, b) b,
static char *ColorStrings[] = { COLORS };
#undef X
printf("%s\n", ColorStrings[Cred]); // output: red
```
|
I'm learning c and I'm finding difficulties with the expression(int*)arrin the line 18. The whole program is
```
int main () {
char c, arr['z'-'a'], *pChar;
int i, *pInt, int matr = 74 ;
for ( c='a'; c<'z'; c++) {
arr[c-'a'] = c;
printf("%c ", arr[c-'a']);
}
printf("\n");
... |
You declaredarraschartype. Asthe name of an array can be used as a pointer to its first element;arris a pointer to firstcharof arrayarrand is of typechar *.pIntis of typeint *, for the expression
```
pInt = (int *)arr + matr%2;
```
a cast is needed to covertarrtoint *type in your program.
|
I have a certain set of available enumed options
```
typdef enum {
option1 = 1 << 0,
option2 = 1 << 1,
option3 = 1 << 2,
} availableOptions;
```
I want to toggle them off and on according to an input from the user before executing them.
For instance:
```
// iniatially set to all options
myOption = option1 | optio... |
Use bit-wise XOR:
```
void toggleOption1()
{
myOption ^= option1;
}
```
The caret symbol^is the bit-wise XOR operator. The statement:
```
a ^= b;
```
flips only the bits inawhere the corresponding bit inbis set. All other bits are left alone.
|
I am trying to find the absolute value in C++ by the following method:
```
#include <cmath>
unsigned value1=4;
unsigned value2=10;
unsigned absoluteValue=abs(value1-value2);
int absValue=abs(value1-value2);
Answer: absoluteValue=4294967294
absValue=-2147483648
Desired Answer=6
```
The value that I am gett... |
By subtractunsignedvalues like this, it might wrap.
If you want to get the absolute value of aunsigneddo something like this:
```
unsigned absoluteValue = (value1>value2)?(value1-value2):(value2-value1);undeflow
```
|
I want to replace all 'a' characters from a string in ANSI C. Here's my code:
```
#include <stdio.h>
#include <stdlib.h>
void sos(char *dst){
while(*dst){
if(*dst == 'a')
*dst = '\0';
dst++;
}
}
int main(void){
char str[20] = "pasternak";
sos(str);
printf("str2 = %s ... |
In C, strings arezero-terminated, it means that when there's a'\0'in the string it is theend of the string.
So what you're doing is spliting the string in 3 different ones:
```
p
stern
k
```
If you want to delete theayou must move all the characters after theaone position.
|
I found the following code in a program example:
```
const unsigned int n = /* something */
unsigned int i = 1;
for (unsigned int j = 1; j < n-1; ++j) {
i <<= 1;
}
```
Is there a direct formula to computeifromnwithout a loop ?
|
More accurately:
assuming unsigned int is 16 bits (minimum as specified by C++ standard)
```
i = ( n < 18 ) ? ( ( n >= 2 ) ? ( 1 << (n-2) ) : 1 ) : 0;
```
|
I'm looking for an scenario where using Union is a better option than Structure in C?
I'm not looking for the difference between the two. I'm aware of the Structure and Union concepts in C, and the difference.
And I looked the questionDifference between a Structure and a Union in C, which is no way the possible dupl... |
Well, consider the situation where you would like to be able to change each byte of an integer. You could use a union of the integer, and, for example, an array of 4 characters.
```
union Example
{
int x;
char array[4];
};
```
That way, by modifying one of the characters, you would also modify a corresponding ... |
Given a current directory with lots of files and let's say I compiled one file and generated executablea.out. Now, I want to find from which program this executable has been generated.
How, can I do it?
|
You can usereadelf:
```
readelf -a a.out | grep FILE
```
For instance:
```
$ gcc t.c
$ readelf -a a.out |grep FILE
28: 0000000000000000 0 FILE LOCAL DEFAULT ABS crtstuff.c
36: 0000000000000000 0 FILE LOCAL DEFAULT ABS crtstuff.c
41: 0000000000000000 0 FILE LOCAL DEFAULT ABS t.... |
All is in the title: does IEEE-754float,doubleandquadguarantee exact representation of-2,-1,-0,0,1,2?
|
It guarantees precise representations of all integers until the number of significant binary digits exceeds the range of the mantissa.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
Prototype with your OpenGL calls in python - it is much quicker to prototype than C/C++ and then see if it is quick enough - if it is then you are done - if not then find the bottlenecks and consult the documentation on C/C++ plug in to address those issues.
Note that there are python OpenGL bindings availableherewhi... |
I'm trying to create a 2d array 4x5. Each row takes in the number of the row so the first row will be all 0's, 2nd row all 1's etc..
```
int main (void)
{
int A[4][5],i,j;
// int B[10][8];
for (i=0;i<4;i++){
for (j=0;j<5;j++){
A[i][j]=0;
printf("%i\n", A[i][j]);
} return 0;
}
}
```
havin... |
Your loop needs modification:
```
for (i=0;i<4;i++)
{
for (j=0;j<5;j++)
{
A[i][j]=i; //---> Assign each element in i-th row the value of i
printf("%d", A[i][j]);
}
printf("\n");
}
```
Sampleoutput. Also use%dfor printingints.
|
```
char symbol[100][100];
for(i=0;i<n;i++)
{
printf("enter the symbol\n");
scanf("%s",&symbol[0][i]);
}
strncat(&symbol[0][0],"1",1);
```
outputfor ex:-
in symbol[0][0] i have entered 'a'
```
strncat(&symbol[0][0],"1",1);
```
should give the output asa1buti know the size of symbol[0][0] is... |
Try this
```
strncat(symbol[0],"1",1);
int main()
{
int i,n=1;
char symbol[100][100];
for(i=0;i<n;i++)
{
printf("enter the symbol\n");
strcpy(symbol[0],"a");
}
strncat(symbol[0],"1",1);
printf(symbol[0]);
return 0;
}
```
Make changes as required..:)..
|
I am currently reading The C Programming Language (1st ed). In section 1.5, under Character Counting, the book shows you how you can count the number of characters.
```
#define EOF -1
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
```
When I type
```
abcde... |
It's just your terminal showing you your EOF character^D(the5is just covering up^, and when it's double digits it's covering up all of^D). If you do:
```
echo qwer | ./myprogram
```
You'll see it's not there.
|
Here is the problem I'm having:
I'm able to echo the last variable that is set, but not previous variables.So if x=Welcome and I do echo $x... I get Welcome.
But if I do xx=Back... it erases the original x
|
You're storing the pointers in your table, but the pointers are to a local variable which is simply reused… you're overwriting your key and value that the table point to.
In your Node structure, make copies of what the pointers point to so that you keep a copy that won't get overwritten.
Since you're dealing with st... |
I use GCC--mingw32 to compile a program on Windows.
Are there some feasible ways to grey out the close button at the upper right corner of "Console Window"? (like adding some codes?)
I don't want to close my program incautiously XDD
I tried something like this, but never works, help me, thanks.
```
HWND StdHandle =... |
```
W := GetConsoleWindow; // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683175%28v=vs.85%29.aspx
M := GetSystemMenu(W, False);
//EnableMenuItem(M, SC_CLOSE, MF_BYCOMMAND or MF_DISABLED or MF_GRAYED);
DeleteMenu(M, SC_CLOSE, MF_BYCOMMAND);
```
|
I have a very basic query.
For the following code:
```
int i = -1;
unsigned int j = (unsigned int) i;
printf("%d",j); // I get 65535 the int limit in turbo C 16 bit compiler
```
Shouldn't it simply drop the negative sign or does it wrap around the limits ?
|
The scheme most commonly used to represent negative numbers is calledTwo's Complement. In this scheme-1has the bit pattern of all1bits:1111 1111 1111 1111. When interpreted as an unsigned integer, which is what your cast means, that's 65535.
In other words, it does "simply drop the negative sign", except that doing s... |
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.Closed9 years ago.Improve this question
I'm just getting started with c and objective c, and I made this simple script:
```
#import <Foundation/Fo... |
Try this
```
#import <Foundation/Foundation.h>
int main(void)
{
NSLog(@"Hello World");
return 0;
}
```
NSLog takes an objective-C string and prints it to the console.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
```
char *tmp=strdup(oldstr);
strcpy(oldstr, &tmp[4]); // copy from character # 5 back into old string
free(tmp);
```
Try that.
|
I found this C example on a website and are trying to get it work:
```
void simple(int n, float *a, float *b)
{
int i;
for (i=1; i<n; i++)
{
b[i] = (a[i] + a[i-1]) / 2.0;
}
}
```
This is what I added just for testing purposes:
```
int main()
{
float *p1, *p2, a, b;
a = 5;
b = 10;... |
No, your example is not ok, you are using 5 elements in an object that only contains 1. Use something like
```
float a[5] = { 2, 3 ,4, 5, 6 };
```
to obtain real arrays to operate on.
|
I'd like to print a float number with only 2 decimal places and align it to the right in a 6 characters space.
I tried to do this, but didn't work:
```
printf("%6.2f", value);
```
|
What you've posted will fit the whole float into a 6 char wide column with the .xx taking up the last 3. If you want the integer portion in a six char wide column with the '.' and the fractional portion after these 6 characters, its %9.2f. Quick example program to show the differences
```
#include <stdio.h>
int main... |
I have a very simple question and just want an answer to reassure whether or not my knowledge of the fork() function and fd table are correct. My question is: perhaps there is a parent process that forks a child. According to my understanding, this child process also has a fd table that is the same as its parent. Supp... |
No it will not. The fd table gets inherited from the parent process, but it is private to each process. - So the child process will start out with a copy of the parent fd table.
|
On the Arduino Nano V3, I am trying to get an LED driver (TLC5960) and two analog to digital (ADC) converters (MCP3208) to work together. The LED driver is on the same pins asthis guide. The ADCs are assigned to different pins than the LED driver. I found that the LED driver conflicts with the SPI communication int... |
If you look at the code, you'll see thattlc_config.hcontains options relating to the communication and connection with the TLC'. Simply edit the options within that file to suit your needs.
|
I need explanation for following code:
```
int a[2][3][2] = { 1,2,3,
4,5,6,
7,8,9,
10,11,12 };
std::cout << a[0][5][0];
```
As far asmulti dimensional arraysare concerned, first index indicates row count, second index indicates column count and third index ind... |
Think about it like this.
a[2][3][2] is really just a[12] grouped into groups of 2 then 3.
a[0][5][0] is really a[0][0][5*2] = a[0][0][10]
This is because an array is loaded into contiguous memory.
|
I've got an array of characters which could contain a NULL character.The array is not null-terminated, but I do know it's length.
QuestionHow do I output this exact array (including null characters) and nothing else (no trailing \n) to stdout? Unfortunately, I am not allowed to output one character at a time.
|
```
char buffer[SIZE];
if(fwrite(buffer, 1, SIZE, stdout) != SIZE) {
perror("fwrite");
}
```
|
```
pid_t fork(void);
```
I want to know what this command does in C. Process Control.
|
This creates a child process which has a copy of the parent’s heap, stack and data space.
You need to#include <unistd.h>. You could use this when you want a process to duplicate itself so that the parent and child can each execute different sections of code at the same time.
|
I have the followingsscanf:
```
int four;
sscanf("1234&awe$asdf@3222*gr45", format, four);
```
I want this sscanf to put the value3222in the variablefour.
What should be theformatstring?
&$@and*always stays the same. So other example of string inputs can be:
"6345&346dfh$aweg@5463*nvm"-> andfourwill be5463
"0hjgf... |
Your suggestion won't work, you need first to skip everything to the @, so"%*[^@]@%d"
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
The Dart SDK comes with a Dart VM that is written in C++. It can be used as a standalone program, or can be embedded in other programs (like, for instance, Chromium).
|
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.Closed9 years ago.Improve this question
I have my codes working where I got separate date and time columns. I would like to add one more column whi... |
Looks like you have not added format specifier for the added column.
|
I am trying to read a file using FILE *fp, fgets
```
while( (ch=getc(fp)) != '\n' ){
printf("%d\n",ch);
}
```
The peculiar thing is, this code prints also the newline. Isn't the while loop saying to print if its not "\n" being detected? How can I do it such that it doesn't print the "\n". thanks
|
If one is reading from a file to do string processing (a text file), insure the file is opened intextmode.
Files opened in text mode on systems that use something other than"\n"to indicate the end-of-line like"\r\n"or"\n\r"or"\rwill transform that into"\n". Other processing may happen too concerning Byte-order-marks... |
```
#include <stdio.h>
int singleFib(int x,int a,int b);
int multiFib(int x);
void main(){
int n,i;
printf("How much?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("%5d. number: %d - %d \n",i+1,multiFib(i),singleFib(i,1,1));
}
getch();
return 0;
}
int multiFib(int x){
if (x<2){
return 1;
}
else... |
You're missing a close bracket}at the end of yourmultiFibfunction.You have an extra close bracket}at the end of yoursingleFibfunction.The functionmainshould have return typeint.
|
I am having a problem with my code to convert from 'void *' to 'NODE *'
Can anyone help me get around this problem?
```
NODE *list_create(void *data)
{
NODE *node;
if(!(node = malloc(sizeof(NODE)))) return NULL;
node->data=data;
node->next=NULL;
return node;
}
```
I get the error right underneath the = sign.
Any h... |
You have not specified the error, but assuming from the looks of the code, most probable is the type conversion error, something like:
Cannot convert void* to NODE*
The question is tagged withCand the code written here is also validC, but invalidC++. So if there is an error, it can be safely assumed that a C++ compi... |
I would like to know how to detect if input got leading zeroes or not.
```
scanf("%d", &d);
```
This will just change 07 to 7 etc..
In the end i would like to return(1) if input got leading zeroes and return(0) if the input is ok.
Thank you.
|
If you want to know if a number have leading zeros you have to read it as a string, and make the verification yourself. The string07is just presentational, when stored as an integer it's stored as just7.
To verify that the string you've read is an integer with leading zeros, you can first usestrtolto check that it is... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
The Dart SDK comes with a Dart VM that is written in C++. It can be used as a standalone program, or can be embedded in other programs (like, for instance, Chromium).
|
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.Closed9 years ago.Improve this question
I have my codes working where I got separate date and time columns. I would like to add one more column whi... |
Looks like you have not added format specifier for the added column.
|
I am trying to read a file using FILE *fp, fgets
```
while( (ch=getc(fp)) != '\n' ){
printf("%d\n",ch);
}
```
The peculiar thing is, this code prints also the newline. Isn't the while loop saying to print if its not "\n" being detected? How can I do it such that it doesn't print the "\n". thanks
|
If one is reading from a file to do string processing (a text file), insure the file is opened intextmode.
Files opened in text mode on systems that use something other than"\n"to indicate the end-of-line like"\r\n"or"\n\r"or"\rwill transform that into"\n". Other processing may happen too concerning Byte-order-marks... |
```
#include <stdio.h>
int singleFib(int x,int a,int b);
int multiFib(int x);
void main(){
int n,i;
printf("How much?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("%5d. number: %d - %d \n",i+1,multiFib(i),singleFib(i,1,1));
}
getch();
return 0;
}
int multiFib(int x){
if (x<2){
return 1;
}
else... |
You're missing a close bracket}at the end of yourmultiFibfunction.You have an extra close bracket}at the end of yoursingleFibfunction.The functionmainshould have return typeint.
|
I am having a problem with my code to convert from 'void *' to 'NODE *'
Can anyone help me get around this problem?
```
NODE *list_create(void *data)
{
NODE *node;
if(!(node = malloc(sizeof(NODE)))) return NULL;
node->data=data;
node->next=NULL;
return node;
}
```
I get the error right underneath the = sign.
Any h... |
You have not specified the error, but assuming from the looks of the code, most probable is the type conversion error, something like:
Cannot convert void* to NODE*
The question is tagged withCand the code written here is also validC, but invalidC++. So if there is an error, it can be safely assumed that a C++ compi... |
I would like to know how to detect if input got leading zeroes or not.
```
scanf("%d", &d);
```
This will just change 07 to 7 etc..
In the end i would like to return(1) if input got leading zeroes and return(0) if the input is ok.
Thank you.
|
If you want to know if a number have leading zeros you have to read it as a string, and make the verification yourself. The string07is just presentational, when stored as an integer it's stored as just7.
To verify that the string you've read is an integer with leading zeros, you can first usestrtolto check that it is... |
Situation: I have a lot of algorithms in ANSI C and want to connect them dynamically
Idea: Creating a Simulink type of Canvas to dynamically drag/drop and connect the algorithms and check for correct inputs. So i have blocks to connect with a "line" which symbols the signal (i.e. the numerical data).
Question: Is th... |
The thing you want is called data flow programming. You can certainly develop a graphical application with Qt that will allow you chaining your computational blocks together.
Take a look on a similar idea discussionon qt forum.
|
When compiling this program in GCC-mingw32 and trying to run it, it always pops up a Console Window in a very short time and closes immediately.
```
int main (void)
{
system("shutdown -s -t 60"); // Shutdown the computer in 1 minute
return 0;
}
```
How could I modify this code in order to run it without any... |
Your executable is being marked as using the console subsystem, which makes Windows show a console window automatically. If you change it to use the GUI subsystem, Windows won't show a console window. To tell MinGW to use the GUI subsystem, pass the-mwindowsflag.
|
I am new in c programming and i need to scan variable if variable is EOF or non-number.
My code is this:
```
while (scanf("%d", &var) != EOF) {
code...
}
```
I need something like this:
```
while ((scanf("%d", &var) != EOF)||(scanf("%d", &var) != 1)) {
code...
}
```
Problem is that when i use scanf on... |
Put the result ofscanfin a variable so you can test it again.
```
while ((res = scanf("%d", &var)) != EOF && res != 1) {
code ...
}
```
|
I defined this structure
```
typedef struct UNIAO_NOME
{
int vert;
struct un *Pai;
} un;
```
but, then, when I try
```
int name (un *conj/*pointer to a subset*/)
{
un c;/*subset*/
c = *conj;
while (c.Pai != NULL)
c = *(c.Pai);
return c.vert;
}
```
the editor says that
```
c = ... |
You have two different types — inside thestruct, you havedeclared a new typeun. Write it like this:
```
typedef struct UNIAO_NOME
{
int vert;
struct UNIAO_NOME *Pai; // refers to this type
} un;
```
|
This is the code:
```
for(i = 1; i <= 4; i++)
{
scanf("%c", &input);
choice = ChooseGame(input);
}
// ChooseGame function (Definition)
int ChooseGame(char input)
{
switch (input) {
case '1': choice = 1;
printf("Game 1!");
break;
default:
choice = 0;
printf("W... |
The reason behind this is\nleft over by the previousscanf(on pressingEnter).Try this
```
scanf(" %c",&input);
// ^space
```
A space before the format specifier%ceat up all the newline characters and will help you to solve this problem.
|
I got
```
uint32_t bits = 0;
bits |= 1<< 31;
bits |= 1<< 15;
bits |= 1<< 14;
bits |= 1<< 13;
```
which gives me 10000000000000001110000000000000
and in another function I do*(bits) |= 0 << 15;but it doesn't do anything, it should change the 16th 1 to a 0, so the following should come: 10000000000000000110000000000... |
The correct way to change a bit to 0 is toandthe negation, e.g.
```
bits &= ~(1 << 15);
```
|
What does it mean for a function call to "spin?" Is it the same as blocking?
This is the context I'm referring to:
```
/*
* Obtain a free channel
* This call spins till a free channel is obtained
*/
chNum = _getFreeChannel(&tccNum);
```
Thanks.
|
To loop, basically. What a spinning function does is busy-waiting with a loop.
|
```
int main()
{
char str[1000],temp;
int i,j=0;
printf("String: ");
gets(str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("\n");
printf("%s",str);
return 0;
}
```
I want to change the rota
- In: 15 15 15 15 15 0 0- Out: 0 0 51 51 ... |
Call this function to reverse the string. It accepts the string, then pushes each word onto stack until the string is empty. Then it starts popping out the words from stack thereby reversing the string, but not the words.
```
void rev(char *str){
char s[20];
int i=0;
for(; str[i]!=' ' && str[i]!='\0'; i++... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
You can sort the character in a string usingcounting sortin linear time.
|
```
/* test1.c */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m = 11;
system("./test2 m");
return 0;
}
```
The above program prints 0, whereas I expect it to print 11.
```
/* test2.c */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int m = atoi(argv[1]);
... |
You are passing the charactermto the command line, not its value.
|
Problem:
I would like to pass all the content of a float32 variable to a int32 however doing the following:
```
float32 source;
int32 destination;
source = 23.59463; // Hex = 0x41BCC1CE
destination = 0; // Hex = 0x00000000
destination = source; // Destination = 0x00000017 = 23
```
This does... |
As an alternative answer, there's always fun with pointers:
```
destination = *(int32*)&source;
```
|
I have a variable in an header file:
myHeader.h
```
uint16 dummyVar = 0;
extern const uint16 myVar __attribute__((weak,alias("dummyVar")));
```
So when I don't link the parts wheremyVargets defined, the linker will just give it the value of the symboldummyVar.
My problem is, that I am working on a Project with a g... |
A simple solution would be to to just declare it as follows:
```
static uint16 dummyVar = 0;
```
|
Is there any function to check file(s) exist with specific extension or pattern in a directory(s) in Windows and Linux?
For example, to check for files with bbram extension in nvmdir directory.
```
file_exists(nvmdir .. "\\*.bbram")
```
|
A somewhat less elegant solution would be to usepopen()or even lesser elegantsystem()to issue an OS specific "shell" command.
|
I have:
```
unsigned char *programBinary = (unsigned char) malloc(binarySize);
```
But I'm getting the following errors:
```
test.c:127:34: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
test.c:127:33: error: invalid type argument of unary ‘*’ (have ‘int’)
```
This is fairly new to... |
You need to cast(unsigned char*)not(unsigned char)
|
Is it better to have two listening sockets one ipv4 and one ipv6 or to have one ipv6 socket that has had ipv6 only turned off. I would like to support both ipv4 and ipv6 from the start so I don't want to have to redo it later and have it hacked together. From what I can tell there isn't any problems with having ipv6 o... |
There are operating system out there which just don't support providing both protocols over the same socket. There you can switch offIPV6_V6ONLYas much as you want, it will have no effect.
If you want to stay compatible with these systems - Windows XP is an example - you'll have to work with two sockets.
|
I just want to print out a static array (2D array) in C using functions. I use gcc as my compiler. When I try to run my code it gives me a seg fault and I dont have any idea why:
```
#include <stdio.h>
void print_out_an_array(int n, int m, int tab[n][m])
{
int i,j;
for(i=0; i<n; i++)
for(j=0; j<m; j+... |
your function call and function definition doesnt match
your function callprint_out_an_array(tab, 2, 4);but in function definition your first argument isintvoid print_out_an_array(int n, int m, int tab[n][m])
make the arguments same, like:
change function call to``print_out_an_array(2, 4, tab);`
update:checkthis c... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
If you are using the shell syntax for input redirection — that is< filename— then you don't actually have to do anything special. You just read from stdin (e.g. plaingetsorscanfinstead offgetsorfscanf).
If you want to take the names of files as arguments, then, as the commenters have indicated, you can find those arg... |
I'm playing around with libav*. I wrote a simple program to open a file and output how many streams it has in it, just something to get my feet wet. I link with avformat, avcodec and avutil. However, I get undefined reference errors from ld. The undefined references are all libav* functions. I took a look at the verbo... |
Are you programming in C++? If that's the case, you need to add 'extern "C" {...};'.
Take a look here:Why do we need extern "C"{ #include <foo.h> } in C++?and note that libav* is written in C.
|
In C/C++, what is the difference between using#define[and#ifndef#endif] to create values, when you can easily do it with anintorstd::string[C++] too?
```
#ifndef MYVAL
#define MYVAL(500)
#endif
//C++
cout << MYVAL << endl;
//C
printf(MYVAL);
```
```
//C++
int MYVAL = 500;
cout << MYVAL << endl;
//C
int MYVAL... |
Your assumptions are wrong.#definedoesn't create "values", it createsreplacement textin your source code. It has basically nothing to do with C or C++ at all.
|
I have:
```
unsigned char *programBinary = (unsigned char) malloc(binarySize);
```
But I'm getting the following errors:
```
test.c:127:34: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
test.c:127:33: error: invalid type argument of unary ‘*’ (have ‘int’)
```
This is fairly new to... |
You need to cast(unsigned char*)not(unsigned char)
|
Is it better to have two listening sockets one ipv4 and one ipv6 or to have one ipv6 socket that has had ipv6 only turned off. I would like to support both ipv4 and ipv6 from the start so I don't want to have to redo it later and have it hacked together. From what I can tell there isn't any problems with having ipv6 o... |
There are operating system out there which just don't support providing both protocols over the same socket. There you can switch offIPV6_V6ONLYas much as you want, it will have no effect.
If you want to stay compatible with these systems - Windows XP is an example - you'll have to work with two sockets.
|
I just want to print out a static array (2D array) in C using functions. I use gcc as my compiler. When I try to run my code it gives me a seg fault and I dont have any idea why:
```
#include <stdio.h>
void print_out_an_array(int n, int m, int tab[n][m])
{
int i,j;
for(i=0; i<n; i++)
for(j=0; j<m; j+... |
your function call and function definition doesnt match
your function callprint_out_an_array(tab, 2, 4);but in function definition your first argument isintvoid print_out_an_array(int n, int m, int tab[n][m])
make the arguments same, like:
change function call to``print_out_an_array(2, 4, tab);`
update:checkthis c... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
If you are using the shell syntax for input redirection — that is< filename— then you don't actually have to do anything special. You just read from stdin (e.g. plaingetsorscanfinstead offgetsorfscanf).
If you want to take the names of files as arguments, then, as the commenters have indicated, you can find those arg... |
I'm playing around with libav*. I wrote a simple program to open a file and output how many streams it has in it, just something to get my feet wet. I link with avformat, avcodec and avutil. However, I get undefined reference errors from ld. The undefined references are all libav* functions. I took a look at the verbo... |
Are you programming in C++? If that's the case, you need to add 'extern "C" {...};'.
Take a look here:Why do we need extern "C"{ #include <foo.h> } in C++?and note that libav* is written in C.
|
In C/C++, what is the difference between using#define[and#ifndef#endif] to create values, when you can easily do it with anintorstd::string[C++] too?
```
#ifndef MYVAL
#define MYVAL(500)
#endif
//C++
cout << MYVAL << endl;
//C
printf(MYVAL);
```
```
//C++
int MYVAL = 500;
cout << MYVAL << endl;
//C
int MYVAL... |
Your assumptions are wrong.#definedoesn't create "values", it createsreplacement textin your source code. It has basically nothing to do with C or C++ at all.
|
Is it better to have two listening sockets one ipv4 and one ipv6 or to have one ipv6 socket that has had ipv6 only turned off. I would like to support both ipv4 and ipv6 from the start so I don't want to have to redo it later and have it hacked together. From what I can tell there isn't any problems with having ipv6 o... |
There are operating system out there which just don't support providing both protocols over the same socket. There you can switch offIPV6_V6ONLYas much as you want, it will have no effect.
If you want to stay compatible with these systems - Windows XP is an example - you'll have to work with two sockets.
|
I just want to print out a static array (2D array) in C using functions. I use gcc as my compiler. When I try to run my code it gives me a seg fault and I dont have any idea why:
```
#include <stdio.h>
void print_out_an_array(int n, int m, int tab[n][m])
{
int i,j;
for(i=0; i<n; i++)
for(j=0; j<m; j+... |
your function call and function definition doesnt match
your function callprint_out_an_array(tab, 2, 4);but in function definition your first argument isintvoid print_out_an_array(int n, int m, int tab[n][m])
make the arguments same, like:
change function call to``print_out_an_array(2, 4, tab);`
update:checkthis c... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
If you are using the shell syntax for input redirection — that is< filename— then you don't actually have to do anything special. You just read from stdin (e.g. plaingetsorscanfinstead offgetsorfscanf).
If you want to take the names of files as arguments, then, as the commenters have indicated, you can find those arg... |
I'm playing around with libav*. I wrote a simple program to open a file and output how many streams it has in it, just something to get my feet wet. I link with avformat, avcodec and avutil. However, I get undefined reference errors from ld. The undefined references are all libav* functions. I took a look at the verbo... |
Are you programming in C++? If that's the case, you need to add 'extern "C" {...};'.
Take a look here:Why do we need extern "C"{ #include <foo.h> } in C++?and note that libav* is written in C.
|
In C/C++, what is the difference between using#define[and#ifndef#endif] to create values, when you can easily do it with anintorstd::string[C++] too?
```
#ifndef MYVAL
#define MYVAL(500)
#endif
//C++
cout << MYVAL << endl;
//C
printf(MYVAL);
```
```
//C++
int MYVAL = 500;
cout << MYVAL << endl;
//C
int MYVAL... |
Your assumptions are wrong.#definedoesn't create "values", it createsreplacement textin your source code. It has basically nothing to do with C or C++ at all.
|
Below program works:
```
int main()
{
char *g[10];
char a[10] = "test";
g[0] = &a[0];
printf("string = %s\n",g[0]);
exit(0);
}
```
output : test
But this does not work:
```
int main()
{
char t[] = "test";
struct abc
{
char *a[255];
}*p;
p->a[0] = &t[0];
printf("v... |
In your second code you are using pointerpwithout initializing it. This lead toundefined behavior.Try this
```
struct abc q;
p = &q;
p->a[0] = t;
printf("value = %s\n", p->a[0]);
```
|
```
#include <stdio.h>
int main ()
{
int a = 0 ;
/*How can I write it on gcc*/
__asm {
mov a, 2 ;
add a, 4 ;
}
printf ("%d\n",a );
return 0 ;
}
```
This is some assembly code by VS2012, how can I write it on gcc?
|
You can write it in gcc as:
```
#include <stdio.h>
int main ()
{
int a = 0 ;
/*How can I write it on gcc*/
__asm__ __volatile__ (
"movl $2, %0\n\t"
"addl $4, %0\n\t"
:"=r"(a) /* =r(egister), =m(emory) both fine here */
);
printf ("%d\n",a );
return 0 ;
}
```
|
I'm having an issue with pointers. I've read through 30+ posts on this subject and none match my setup. Here's what I'm trying to do:
```
void doSomething(myStruct **myList)
{
resizeMyList(myList,5);
myList[0] = '42';
myList[1] = '43'; // ERRORS OUT OF MEMORY
}
void resizeMyList(myStruct **theArray,int ... |
You do
```
myList[0] = ...
```
butmyListis a double pointer so it should be
```
(*myList)[0] = ...
```
Also, you try to assign multi-character literals to a structure.
|
I see many different answers to this question and have looked at many of them yet I cannot find the answer to my problem.
The error im getting is
```
bitarray.c:27:19: error: lvalue required as left operand of assignment
(newArr << i) ^= 1;
```
Any ideas?
Thanks
|
You are trying to assign to a result from an operation another result. Try the following right way to do it:
```
newArr = (newArr << i) ^ 1;
```
The idea is that you have to have a valid lvvalue and the temporary result of the "<<" is not a valid one. You need a variable like newArr. The following answer on SO expla... |
I'm forking a process in my program, and this process calls aexec()function, then the child process calls thesleep()function.
I want to know if thesleep()function sends some kind of signal that the parent can detect, and if so, what type of signal does it send?
|
Typicallysleep()is implemented by callingalarm(2)which arranges for aSIGALRMsignal to be delivered to the calling process once timeout expires.
In other words, signal is sent aftersleepis finished sleeping, just not to the parent process - but to process which calledsleep. And parent process cannot intercept signals ... |
I read the tutorial here:http://www.techytalk.info/c-cplusplus-library-programming-on-linux-part-two-dynamic-libraries/
It looks to me there is no functionality likedllexportof DLL in Windows platform.
Is there some way to select certain functions within the library as export function and make the rest functions in ... |
You may want to use thevisibility function attributeof GCC.
SeeGCC visibility wikipageand readDrepper's paperHow To Write Shared Libraries
|
I am using C and the SDL library and am trying to express something like the following code:
```
Surface = SDL_LoadBMP("Resources/Images/ButtonPlay.bmp");
```
as something like this:
```
ButtonName = "ButtonPlay";
Surface = SDL_LoadBMP("Resources/Images/"+ButtonName+".bmp");
```
to introduce some type of templatin... |
if you don't have an issue including <stdio.h> then you can do the following
```
char ResourcePath[1024];
ButtonName = "ButtonPlay";
sprintf(ResourcePath, "Resources/Images/%s.bmp", ButtonName);
Surface = SDL_LoadBMP(ResourcePath);
```
|
In case I want to programatically clear the recycle bin under Windows, how to implement that?
DoesIFileOperationhelp?
|
You can useSHEmptyRecycleBin()function fromshell32.dlllibrary to achieve this.
|
The resulting code only prints out the first element of the array in my Xcode, even though I pass it three words. Any reason why?
```
char str[100] = {0};
NSLog(@"Please enter three words: ");
scanf("%s", str);
NSString *words = [NSString stringWithUTF8String: str];
NSMutableArray *m... |
```
fgets(str, sizeof(str), stdin);
```
This will read the entire line intostr.
The easiest way to get rid of the'\n'character left as the last index of your array is to simple change how you're splitting your array:
```
NSMutableArray *mutableWords = [[words componentsSeparatedByCharactersInSet:
[NSCharacter... |
I used to use GDB to debug my C/C++ program. But after the server crashed and reinstalled, the GDB is not working properly. After the program reports a 'core dumped', actually the core file is not found. My flags to compile is:
```
CFLAGS= -ggdb -g -pg -Wall -O2 $(shell pkg-config --libs glib-2.0 gthread-2.0 --cf... |
On my machine (Ubuntu 12.04), the file/proc/sys/kernel/core_patternpipes the core dumped result to/usr/share/apport/apport:
```
|/usr/share/apport/apport %p %s %c
```
So changed to pattern:
```
sudo bash -c 'echo core.%e.%p > /proc/sys/kernel/core_pattern'
```
It works.
Reference:Unable to create a core file for ... |
Is it possible to position a particular C library function at a specified memory location with GNU GCC compiler.?
I am using avr-gcc for compiling application. The exact purpose of this is I need to write a code snippet which contain a call to fscanf function, And I want all code for this application and dependent fu... |
Not a specific function, but if you have control of the source code for the library you can place the function in a specific segment, and then use alinker scriptto place that segment at a specific location.
|
So I have this code
```
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%d", balance[0]);
```
So I expect the first element of the array to print out, which would be 1000.0. However, it keeps on printing 0 for some odd reason. Anyone have an idea on why??
|
From C11 draft
§7.16.1.1/2
```
...if type is not compatible with the type of the actual next argument
(as promoted according to the default argument promotions), the behavior
is undefined, ....
```
You need to use correct format specifier to print the value of variable.
|
```
typedef union
{
unsigned i;
float x;
} f;
f array[12];
```
What do I need to do to address theunionmembers in an array like this? If not possible, how can I do this?
|
```
typedef union
{
unsigned i;
float x;
} f;
f array[12];
```
now you can use by this way :
```
array[index].member=value;
```
|
I encountered the following line as a C function declaration. I'm confused by the type of the first argument passed in. Can anyone explain how to understand the type of the first argument?
```
int clone(void (*fcn) (void *) , void *arg, void *stack)
```
|
```
void (*fcn) (void *)
```
Read the type from inside out:fcnis a pointer to a function, that function takes avoid *parameter and returns nothing (void).
|
I am trying to use theread()function for the first time inC:
```
int file2p = open(curFilePath, O_RDONLY, 0);
char* buffer = NULL;
while(read(file2p, buffer, sizeof(char*)) != 0){
write(filep, buffer, sizeof(char*));
}
close(file2p);
```
filepis a currently opened file I am writing t... |
Where on Earth do you think the data is going to be put?
Got buffer set to NULL
Got read the size of a character pointer.
Why not do
```
int file2p = open(curFilePath, O_RDONLY, 0);
char buffer[1024];
int len;
while((len = read(file2p, buffer, 1024)) != 0){
write(filep, buffer, len);... |
I used to use GDB to debug my C/C++ program. But after the server crashed and reinstalled, the GDB is not working properly. After the program reports a 'core dumped', actually the core file is not found. My flags to compile is:
```
CFLAGS= -ggdb -g -pg -Wall -O2 $(shell pkg-config --libs glib-2.0 gthread-2.0 --cf... |
On my machine (Ubuntu 12.04), the file/proc/sys/kernel/core_patternpipes the core dumped result to/usr/share/apport/apport:
```
|/usr/share/apport/apport %p %s %c
```
So changed to pattern:
```
sudo bash -c 'echo core.%e.%p > /proc/sys/kernel/core_pattern'
```
It works.
Reference:Unable to create a core file for ... |
Is it possible to position a particular C library function at a specified memory location with GNU GCC compiler.?
I am using avr-gcc for compiling application. The exact purpose of this is I need to write a code snippet which contain a call to fscanf function, And I want all code for this application and dependent fu... |
Not a specific function, but if you have control of the source code for the library you can place the function in a specific segment, and then use alinker scriptto place that segment at a specific location.
|
So I have this code
```
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%d", balance[0]);
```
So I expect the first element of the array to print out, which would be 1000.0. However, it keeps on printing 0 for some odd reason. Anyone have an idea on why??
|
From C11 draft
§7.16.1.1/2
```
...if type is not compatible with the type of the actual next argument
(as promoted according to the default argument promotions), the behavior
is undefined, ....
```
You need to use correct format specifier to print the value of variable.
|
```
typedef union
{
unsigned i;
float x;
} f;
f array[12];
```
What do I need to do to address theunionmembers in an array like this? If not possible, how can I do this?
|
```
typedef union
{
unsigned i;
float x;
} f;
f array[12];
```
now you can use by this way :
```
array[index].member=value;
```
|
I encountered the following line as a C function declaration. I'm confused by the type of the first argument passed in. Can anyone explain how to understand the type of the first argument?
```
int clone(void (*fcn) (void *) , void *arg, void *stack)
```
|
```
void (*fcn) (void *)
```
Read the type from inside out:fcnis a pointer to a function, that function takes avoid *parameter and returns nothing (void).
|
I am trying to use theread()function for the first time inC:
```
int file2p = open(curFilePath, O_RDONLY, 0);
char* buffer = NULL;
while(read(file2p, buffer, sizeof(char*)) != 0){
write(filep, buffer, sizeof(char*));
}
close(file2p);
```
filepis a currently opened file I am writing t... |
Where on Earth do you think the data is going to be put?
Got buffer set to NULL
Got read the size of a character pointer.
Why not do
```
int file2p = open(curFilePath, O_RDONLY, 0);
char buffer[1024];
int len;
while((len = read(file2p, buffer, 1024)) != 0){
write(filep, buffer, len);... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.