question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I've started writing a boot loader for my z80 system.
So far the program can accept hex via serial and load it to a location in the memory.
The problem I have though is the boot loader is at the start of memory and uses the interrupts,
How can I load a new program with out overwriting the boot loader?
(Also a loade... |
The best and most widely used approach is to split your app into a stable boot loader that is never updated, and the application that you can replace from time to time.
AFAIK, in Z80 there are just interrupt vectors and there no support for replacing them in the CPU itself. You need to have something in your hardware... |
I was searching for how to add two numbers without using ('+'/'++') and went throughlink. But, I also found this solution:
```
#include<stdio.h>
int add(int x, int y);
int add(int x, int y)
{
return printf("%*c%*c", x, ' ', y, ' ');
}
int main()
{
printf("Sum = %d", add(3, 4));
return 0;
}
```
Can so... |
```
return printf("%*c%*c", x, ' ', y, ' ');
```
The*in theprintfformat means that the field width used to print the character is taken from an argument ofprintf, in this case,xandy. The return value ofprintfis the number of characters printed. So it's printing one' 'with a field-width ofx, and one with a field-wid... |
I have a string being moved and i want to print it based on the register.
I did the following:
```
gdb x $esp
0xbffff110: "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267"
{then I copied the address}
>> x *0xbffff110
0x80485bc <__dso_handle+12>: "test1"
```
Is there any way to do thi... |
Is there any way to do this in one step?
```
(gdb) print *(char**)$esp
```
|
I compiled Connector/C from scratch, and when I try to connect using it, my_connect returns -1 and WSAGetLastError() == 2003
I have no clue what's wrong, any ideas? I've tried googling but I can't even find anything on what that error means.
```
MYSQL *my = mysql_init(NULL);
if(my)
{
MYSQL *result =... |
I've tracked the problem down to the MySQL C connector using the ipv6 getaddrinfo which returns ::1, I'm using an old mysql server version which doesn't support ipv6.
|
I have a simple C program and when I compile and run it with./output, does it get a PID on Linux? (I think, every running program is a process and it should have a PID.)
I used theps auxcommand but I couldn't find the process name there.
I remember, when my console application (a C program) was running on Windows 7,... |
Yes, every running program on Linux gets a PID.
Your program just prints"Hello, World!", and will complete so quickly that by the time you runps auxit will have finished.
Also,void main()should beint main(void), and you should add\nto the end of your output string.
|
Current way is like this, which looks quite clumsy..
```
ex1_test : ex1.o ex1_test.o
cc -o ex1_test ex1.o ex1_test.o
ex2_test : ex2.o ex2_test.o
cc -o ex2_test ex2.o ex2_test.o
ex3_test : ex3.o ex3_test.o
cc -o ex3_test ex3.o ex3_test.o
```
Is there a variable that I can use to represent the current targ... |
Step 1, introduce automatic variables:
```
ex1_test : ex1.o ex1_test.o
cc -o $@ $^
ex2_test : ex2.o ex2_test.o
cc -o $@ $^
ex3_test : ex3.o ex3_test.o
cc -o $@ $^
```
Step 2, realize that these rules all look the same, and replace them with a pattern rule:
```
ex%_test: ex%.o ex%_test.o
cc -o $@ $^
... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:trying to create a simple shell in c for win32 api
I'm doing some C programming in Windows for a low level coding assignment and I'm trying to get this create process to work however. I am try to trying to execute a command as a process... |
Since dir is a cmd.exe built in you need to run cmd , ie setlpApplicationNametocmd.exeandlpCommandLineto dir
|
I've started writing a boot loader for my z80 system.
So far the program can accept hex via serial and load it to a location in the memory.
The problem I have though is the boot loader is at the start of memory and uses the interrupts,
How can I load a new program with out overwriting the boot loader?
(Also a loade... |
The best and most widely used approach is to split your app into a stable boot loader that is never updated, and the application that you can replace from time to time.
AFAIK, in Z80 there are just interrupt vectors and there no support for replacing them in the CPU itself. You need to have something in your hardware... |
When I pass a file to bison (the usual way) it works fine, it parses the file and checks the grammar. However when I pass the same string with:
```
yy_scan_string(string);
yylex();
yyparse();
```
It crashes after the first token, it says it is expecting$end. Should I somehow reset something? The examples on here don... |
You're using Bison incorrectly. When using Bison, you only call yyparse(). You don't call yylex()--that function will be called by yyparse() whenever it needs a token.
What you're doing is setting string as the input, calling yylex which finds a token and advances the input stream. Then you call yyparse(). This yypar... |
We found that C will compile the log function when used with magic numbers, but not with a variable. Any ideas?
|
Because you didn't link your program to the math library and with a literal your compiler is probably using a builtin function.
Withgccyou will get the same error with-fno-builtinwith a literal.
Link with lib math this way:gcc bla.c -o bla -lm
|
I'm working on a testing framework which prints to the command-line and instead of 'Pass'/'Fail', I would like to print ticks (check mark) for pass and crosses for fail. I found the symbols at the bottom ofthis wingdings character set, and I've seen these exact ones used before inMocha(a javascript unit test framework... |
This depends on your platform, and whether the terminal (the program that receives theprintf()output and renders it as readable text) is Unicode-aware.
If it's running e.g. UTF-8, you can printthe character'sUTF-8 sequence:
```
/* This prints a ✓. */
printf("\xE2\x9C\x93\n");
```
|
In C/C++, what's the difference between the following two line code:
```
char *str1="hello";
char *str2={"hello"};
```
|
Per the 2011 C standard, clause 6.7.9 Initialization, paragraph 11: “The initializer for a scalar shall be a single expression, optionally enclosed in braces…”
That is it. There is no semantic difference; the braces simply may be present or may be absent, with no change to the meaning.
|
I have atoolthat takesinputand makesoutput:
```
$ tool input > output
```
I'd like to add an option that is a long string — say, a "comment" option. This comment text is an argument to the option and is a sentence enclosed in forward tick marks:
```
$ tool --comment='I am commenting on the use of comments' input > ... |
Tokenizing the command line into arguments for your program is the responsibility of your shell, not yours. So there's nothing for you to do.
Just put quotation marks around strings that contain spaces, or escape spaces with backslashes on your command line, and your--foovalue can contain as many spaces as you like.
|
I run into a code:printf("\tout:\t%-14.14s\n", (sprintf(tmpbuf[0], "[%s]", mystring), tmpbuf[0]));What does those sentence in () with sprintf mean?
|
It is an expression involving the comma operator, to put the following into a single line:
```
sprintf(tmpbuf[0], "[%s]", mystring);
printf("\tout:\t%-14.14s\n", tmpbuf[0]);
```
The comma operator evaluates both arguments and returns its right argument, i.e.tmpbuf[0].
|
Here simple code I am not getting the expected output.
```
#include<stdio.h>
int main()
{
char buf[1024];
while(1)
{
fgets(buf,strlen(buf),stdin);
printf("%s",buf);
printf("hello");
}
}
```
In the above code I am want whatever the string I enter from keyboard to be printed out to me th... |
The problem isstrlen(buf)is return 0 because buf[0] just happened to be 0 (not guaranteed). You should usesizeof(buf)instead:
```
fgets(buf,sizeof(buf),stdin);
```
|
I have seen a number of libs for parsing JSON in C but none of them can read and parse directly from file streams. The problem with all such libs e.g Yajl, cjson is that if the json document in the file is huge then you have to first read all of that into a memory buffer and then run the APIs provided by these libs to... |
http://lloyd.github.com/yajl/is probably what you are looking for
|
So I have a for loop which goes like this:
```
for(span=N>>1;span;span>>=1)
```
I am assuming the start and end conditions are equivalent to as follows:
```
span = N>>1; //right shift N by 1 and initialize to span
while(span!=0)
{
span = span >> 1;
}
```
However it seems a little bizarre in the context of my code... |
In every iteration you are dividing the variable span by 2 until it reaches 0.
so if initially N = 8, then values for span will be 4, 2, 1, 0 -> exit loop
|
```
#define START ((void (**)(int)) 0x0fff)
*START = &fun_foo();
```
I haven't seen this before. What is happening here? Is void (**)(int) a function pointer?
|
void (**)(int)is a pointer to a pointer to a function that takes anintand returns nothing.
SoSTARTis apointer to a function pointer, and*STARTis the actual function pointer which is set to point tofun_foo.
|
I'm trying to print the number684.545007with 2 points precisionin the sense that the number be truncated (not rounded)after684.54.
When I use
```
var = 684.545007;
printf("%.2f\n",var);
```
it outputs684.55, but what I'd like to get is684.54.
Does anyone knows how can I correct this?
|
What you're looking for istruncation. This should work (at least for numbers that aren't terribly large):
```
printf(".2f", ((int)(100 * var)) / 100.0);
```
The conversion to integer truncates the fractional part.
In C++11 or C99, you can use the dedicated functiontruncfor this purpose (from the header<cmath>or<mat... |
I have three pointers,*player1,*player2and*currentPlayer.
The pointer*currentPlayerwill always be pointing to either*player1or*player2. To switch between the two, I've been doing the following:
```
if (currentPlayer == player1) {
currentPlayer = player2;
}
else {
currentPlayer = player1;
}
```
My quest... |
No, conceptually there's no simpler way.
Syntactically the ternary operator is a little shorter:
```
currentPlayer = currentPlayer == player1 ? player2 : player1;
```
|
In C, on a 32-bit machine, I was just wondering if1>>31returns-1given1is a signed integer, since for 2's-complement, while doing right shift (arithmetic), sign bit is copied giving the result
1111 1111 1111 1111 1111 1111 1111 1111
|
No, the result will be zero in any conforming implementation.
C99, 6.5.7/5 ("Bitwise shift operators") states:
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has
an unsigned type or if E1 has a signed type and a nonnegative value,
the value of the result is the integral part of the quotient o... |
Here simple code I am not getting the expected output.
```
#include<stdio.h>
int main()
{
char buf[1024];
while(1)
{
fgets(buf,strlen(buf),stdin);
printf("%s",buf);
printf("hello");
}
}
```
In the above code I am want whatever the string I enter from keyboard to be printed out to me th... |
The problem isstrlen(buf)is return 0 because buf[0] just happened to be 0 (not guaranteed). You should usesizeof(buf)instead:
```
fgets(buf,sizeof(buf),stdin);
```
|
I have seen a number of libs for parsing JSON in C but none of them can read and parse directly from file streams. The problem with all such libs e.g Yajl, cjson is that if the json document in the file is huge then you have to first read all of that into a memory buffer and then run the APIs provided by these libs to... |
http://lloyd.github.com/yajl/is probably what you are looking for
|
So I have a for loop which goes like this:
```
for(span=N>>1;span;span>>=1)
```
I am assuming the start and end conditions are equivalent to as follows:
```
span = N>>1; //right shift N by 1 and initialize to span
while(span!=0)
{
span = span >> 1;
}
```
However it seems a little bizarre in the context of my code... |
In every iteration you are dividing the variable span by 2 until it reaches 0.
so if initially N = 8, then values for span will be 4, 2, 1, 0 -> exit loop
|
```
#define START ((void (**)(int)) 0x0fff)
*START = &fun_foo();
```
I haven't seen this before. What is happening here? Is void (**)(int) a function pointer?
|
void (**)(int)is a pointer to a pointer to a function that takes anintand returns nothing.
SoSTARTis apointer to a function pointer, and*STARTis the actual function pointer which is set to point tofun_foo.
|
I'm trying to print the number684.545007with 2 points precisionin the sense that the number be truncated (not rounded)after684.54.
When I use
```
var = 684.545007;
printf("%.2f\n",var);
```
it outputs684.55, but what I'd like to get is684.54.
Does anyone knows how can I correct this?
|
What you're looking for istruncation. This should work (at least for numbers that aren't terribly large):
```
printf(".2f", ((int)(100 * var)) / 100.0);
```
The conversion to integer truncates the fractional part.
In C++11 or C99, you can use the dedicated functiontruncfor this purpose (from the header<cmath>or<mat... |
I have three pointers,*player1,*player2and*currentPlayer.
The pointer*currentPlayerwill always be pointing to either*player1or*player2. To switch between the two, I've been doing the following:
```
if (currentPlayer == player1) {
currentPlayer = player2;
}
else {
currentPlayer = player1;
}
```
My quest... |
No, conceptually there's no simpler way.
Syntactically the ternary operator is a little shorter:
```
currentPlayer = currentPlayer == player1 ? player2 : player1;
```
|
In C, on a 32-bit machine, I was just wondering if1>>31returns-1given1is a signed integer, since for 2's-complement, while doing right shift (arithmetic), sign bit is copied giving the result
1111 1111 1111 1111 1111 1111 1111 1111
|
No, the result will be zero in any conforming implementation.
C99, 6.5.7/5 ("Bitwise shift operators") states:
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has
an unsigned type or if E1 has a signed type and a nonnegative value,
the value of the result is the integral part of the quotient o... |
If I have pointers of typeT (T*)and I have an array of themT* array[N]will these two methods allow me to later check which entries are null pointers to lazily initialize stuff in each bucket?
memset(array, 0, sizeof(T*)*N);
or
```
for (int i = 0; i < N; ++i)
array[i] = NULL;
```
i.e. will thememsetcall also le... |
Although a null pointer value isn't technically required be all zero bits I'm not aware of any system where it's not all zero bits. So either method should work.
However there's an easier way to initialize an array which will set the correct null pointer values even on some evil implementation:
```
T *array[N] = {};... |
If i create a
char a[100][100];
and send to a function void func(char** a);
It says that a char ()[100] cannot be converted to char *.
I imagined that a char [100][100] is like a pointer to pointer.
Was i wrong?
Thanks
|
Yes, you were wrong indeed. achar[100][100]is an array of (array of 100char), and when passing it to a function, it is converted to a pointer to (array of 100char), achar (*)[100]. The conversion of arrays to pointers when passed as function arguments only affects the outermost level of arrays.
You could either decla... |
First of all, there is a question title that almost exactly matches my question (strstr() equivalent in C#), but he's referring to a method to do a byte[] comparison version.
I'm looking for a string comparison that outputs the index of the first occurance of str2 in str1, and just cannot find it!
```
string s1 = ("... |
I think you're looking forIndexOf:
```
int idx = s1.IndexOf(s2);
```
|
In JavaScript i would usually do..
```
var myObject = { "Name" : "Liam", "Address" : "UK"};
```
How do i make something similar in C?
Preferably something of the structure
```
myObject { CHAR : INT}
```
|
```
struct myObj
{
char* string;
int num;
};
```
that's the most basic. you should learn c if you want to use this.
|
I have two C files 1.c and 2.c
2.c
```
#include<stdio.h>
static int i;
int func1(){
i = 5;
printf("\nfile2 : %d\n",i);
return 0;
}
```
1.c
```
#include<stdio.h>
int i;
int main()
{
func1();
printf("\nFile1: %d\n",i);
return 0;
}
```
I compiled both the files with "gcc 1.c 2.c -o st"
The outp... |
Choose one file which will store the variable. Do not usestatic. The whole point ofstaticis to keep the variable private and untouchable by other modules.
In all other files, use theexternkeyword to reference the variable:
```
extern int i;
```
|
my problem is that i would like to organize my code so i can have adebugandreleaseversion of the same methods, and i can have multiple definitions of the same methods for different targeted platforms.
Basically the core of the problem is the same for both, i need to have the same signature but with different definiti... |
```
// #define DEBUG - we're making a non debug version
#ifdef DEBUG
// function definition for debug
#else
// function definition for release
#endif
```
The same can be done for different operating systems. There's of course the problem of recompilating all of it, which can be a pain in the ass in C++.
|
How to print name of file open by some process (PID) in window? Or All Processes (PID) currently open a file.Process Exploreris a utility works for same.But how does it work not mentioned?Any/proc filesystemkind of thing present in windows?
```
Can we read any Window's Registry?
I wants to write a programming code ... |
Here is the platform independent solution in python.
```
import psutil
p = psutil.Process(os.getpid()) # or PID of process
p.open_files()
```
So i refer youpsutilpackage it has too good functions for getting information on running processes
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
Is this short way for printing the ... |
No "oneliner", no. Besides, your code looks broken.
You can't usesizeoflike that, you probably meanstrlen().
And you need to cast the character to an unsigned type to be safe.
So, something like this, perhaps:
```
void print_hex(const char *s)
{
while(*s)
printf("%02x", (unsigned int) *s++);
printf("\n");
... |
```
int age;
char name[10];
scanf("%d", &age);
scanf("%s", name);
```
In firstscanffunction we use'&'symbol before age, but in secondscanfwe don't use'&'as it is a char array. Can anybody tell me why is so?
|
Because the array is already passed as an address, whereas the integer variable is not (and thus explicitly needs its address passed via the&address-of operator).
|
I heardprintf()in C is not supposed to be used in ISR. Is it because it's a blocking call, or is it because it's not re-entrant?
Ifprintf()is not re-entrant, then wouldn't it means that it can not be used for multi-thread program as well, unless it's 'synchronized' in some way?
|
I think it might be all of those, and more. Typicalprintf()implementations can do dynamic (heap) memory allocation, which is generally not the fastest thing to be doing, and might also have issues with being non-re-entrant. The fastness thing can matter since you're typically not supposed to spend too much time in an ... |
I want to add an IP to a table in IPFW from within a C program. I don't want to call system() as this code has to be as efficient as possible. So basically my question is, can somebody explain how does this work? As there is no API that can be used, I'm reviewing the source (to see how the adding is being done), but t... |
It is not a real answer just an obvious suggestion. Check out the source code of the system with cvsup. Then look for ipfw.c and there you will see what system calls it is using to modify the rules. The ipfw program is a command line tool, so it must be in the userland. It means that you must be able to do what it doe... |
If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?
|
Initialisers can be nested for nested structs, e.g.
```
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
```
|
Say I have two variables x and y, and I want to align the most significant 1s, how would I write this in C? For example, I have x=11 and y = 1011, and I want to align x with y by making it 1100. How could I do this?
|
Run aBitScanReverse(or appropriate intrinsic for you compiler, like__builtin_clzfor GCC), subtract the smaller from the larger and shift the smaller to the left by the difference.
|
```
#include<stdio.h>
int main() {
int cases,no,**event,i,j;
scanf("%d",&cases);
for(;cases>0;cases--) {
scanf("%d",&no);
event=(int **)malloc(no*sizeof(int *));
for(i=0;i<no;i++) {
event[i]=(int *) malloc(3*sizeof(int));
for(j=0;j<3;j++) {
scanf("%d",event[i][j]);... |
Pass the address ofevent[i][j]to scanf
```
scanf("%d", &event[i][j]);
```
|
I have this simple test file:
```
#include "stack.h"
int main()
{
Stack* stck = init_stack();
return 0;
}
```
andstack.his defined as follows:
```
#ifndef STACK_H
#define STACK_H
#define EMPTY_STACK -1
typedef struct stack
{
char ch;
struct stack* prev;
} Stack;
extern Stack* init_stack();
extern char ... |
```
gcc -o testit teststack.c stack.c
```
You need to compile both C source files and link the object files; this does it all in one command.
|
```
int main(int argc, char *argv[])
{
printf("Temp is");
msgrcv(externalQid, &incomingMsg, sizeof(incomingMsg)-sizeof(long), 0, 0);
}
```
printf never actually prints in this case...it does however get printed if I don't have the msgrv call.. It is making it very hard to debug my program. Any ideas?
|
Try putting a newline character at the end of your printf. I'm not intimately familiar with the 'why', but it solved a similar problem I had a while ago.
|
Stack Overflow has this question answered in many other languages, but not C. So I thought I'd ask, since I have the same issue.
How does one concatenate two integers in C?
Example:
```
x = 11;
y = 11;
```
I would like z as follows:
```
z = 1111;
```
Other examples attempt to do this with strings. What is a wa... |
```
unsigned concatenate(unsigned x, unsigned y) {
unsigned pow = 10;
while(y >= pow)
pow *= 10;
return x * pow + y;
}
```
Proof ofcompilation/correctness/speed
I avoid thelog10andpowfunctions, because I'm pretty sure they use floating point and are slowish, so thismightbe faster on your ... |
I heardprintf()in C is not supposed to be used in ISR. Is it because it's a blocking call, or is it because it's not re-entrant?
Ifprintf()is not re-entrant, then wouldn't it means that it can not be used for multi-thread program as well, unless it's 'synchronized' in some way?
|
I think it might be all of those, and more. Typicalprintf()implementations can do dynamic (heap) memory allocation, which is generally not the fastest thing to be doing, and might also have issues with being non-re-entrant. The fastness thing can matter since you're typically not supposed to spend too much time in an ... |
I want to add an IP to a table in IPFW from within a C program. I don't want to call system() as this code has to be as efficient as possible. So basically my question is, can somebody explain how does this work? As there is no API that can be used, I'm reviewing the source (to see how the adding is being done), but t... |
It is not a real answer just an obvious suggestion. Check out the source code of the system with cvsup. Then look for ipfw.c and there you will see what system calls it is using to modify the rules. The ipfw program is a command line tool, so it must be in the userland. It means that you must be able to do what it doe... |
If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?
|
Initialisers can be nested for nested structs, e.g.
```
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
```
|
Say I have two variables x and y, and I want to align the most significant 1s, how would I write this in C? For example, I have x=11 and y = 1011, and I want to align x with y by making it 1100. How could I do this?
|
Run aBitScanReverse(or appropriate intrinsic for you compiler, like__builtin_clzfor GCC), subtract the smaller from the larger and shift the smaller to the left by the difference.
|
```
#include<stdio.h>
int main() {
int cases,no,**event,i,j;
scanf("%d",&cases);
for(;cases>0;cases--) {
scanf("%d",&no);
event=(int **)malloc(no*sizeof(int *));
for(i=0;i<no;i++) {
event[i]=(int *) malloc(3*sizeof(int));
for(j=0;j<3;j++) {
scanf("%d",event[i][j]);... |
Pass the address ofevent[i][j]to scanf
```
scanf("%d", &event[i][j]);
```
|
I have this simple test file:
```
#include "stack.h"
int main()
{
Stack* stck = init_stack();
return 0;
}
```
andstack.his defined as follows:
```
#ifndef STACK_H
#define STACK_H
#define EMPTY_STACK -1
typedef struct stack
{
char ch;
struct stack* prev;
} Stack;
extern Stack* init_stack();
extern char ... |
```
gcc -o testit teststack.c stack.c
```
You need to compile both C source files and link the object files; this does it all in one command.
|
```
int main(int argc, char *argv[])
{
printf("Temp is");
msgrcv(externalQid, &incomingMsg, sizeof(incomingMsg)-sizeof(long), 0, 0);
}
```
printf never actually prints in this case...it does however get printed if I don't have the msgrv call.. It is making it very hard to debug my program. Any ideas?
|
Try putting a newline character at the end of your printf. I'm not intimately familiar with the 'why', but it solved a similar problem I had a while ago.
|
Stack Overflow has this question answered in many other languages, but not C. So I thought I'd ask, since I have the same issue.
How does one concatenate two integers in C?
Example:
```
x = 11;
y = 11;
```
I would like z as follows:
```
z = 1111;
```
Other examples attempt to do this with strings. What is a wa... |
```
unsigned concatenate(unsigned x, unsigned y) {
unsigned pow = 10;
while(y >= pow)
pow *= 10;
return x * pow + y;
}
```
Proof ofcompilation/correctness/speed
I avoid thelog10andpowfunctions, because I'm pretty sure they use floating point and are slowish, so thismightbe faster on your ... |
On an Avl tree, when you delete a node with 2 children.. I know that you can replace it either with its successor (min value on right subtree) or its predecessor (max value on left subtree).
My question is that: In standards, to what sub tree do I swap with the node?
The successor or the predecessor?
Thanks! :)
|
So long as you do all the necessary rebalancing afterwards, you can use either one -- the algorithm works out either way.
If you wanted to be really clever, you could pick either one based on which one would require the least rebalancing afterwards. That'd be considerably more complicated than just always picking the... |
I'm trying to read in a string of text from a FILE*, but every time I try I get a segmentation fault. This is the only thing I'm doing in the program, so I'm not really sure why this is happening.
```
#include <stdio.h>
int main(){
FILE* file;
char* string;
file = fopen("practice.txt", "r");
fgets(string, 10... |
You haven't allocated any memory for your string. You can usemallocto allocate memory for your string, or use an arraychar string[100];
|
I have a c file that starts with a struct I am calling stringtable, looks like this
```
struct stringtable {
int table[];
int numElements = 15;
};
```
And I have a header for it that has this typedef
```
typedef stringtable *stringtable_ref;
```
When I compile with gcc I get the errors:
expected identifier o... |
```
struct stringtable {
int table[];
int numElements = 15;
};
```
A flexible array member likeint table[];can only be thelastmember of astruct(with at least one more member).
And you can't assign a default value to a member in astructdeclaration, C doesn't support that.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:C String literals: Where do they go?
If I have the following code
```
char *str = "Tryout" ;
```
where is the string going to be stored? Stack? If stack, does the pointer point to a stack location then?
|
The string has a static storage class, (likely in read only data) andstris a local variable with automatic storage. This is why it is better declared asconst char *.
|
Recent versions of gcc and clang on Fedora Linux compile the following program without error:
```
#include <ctype.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
char c = 'a';
if islower(c)
printf("%d", c);
else
printf("%c", c);
return 0;
}
```
This is with gcc 4.7.2 and cla... |
It's likely thatislower()is a macro, and that the expansion adds the parenthesis.
Post the pre-processed output from GCC, which you can get by compiling with the-Eoption.
|
Is it possible to convert a single dimensional array into a two dimensional array?
i first tought that will be very easy, just set the pointer of the 2D array to the beginning of the 1D array like this:
```
int foo[] = {1,2,3,4,5,6};
int bla[2][3] = foo;
```
because i can easily create an two dimensional array like... |
You can't initialise anint bla[2][3]with anint*(whatfoobecomes in that context).
You can achieve that effect by declaring a pointer to arrays ofint,
```
int (*bla)[3] = (int (*)[3])&foo[0];
```
but be sure that the dimensions actually match, or havoc will ensue.
|
I have this function
```
TOKENP scan_line() {
TOKENP cur, last = 0;
while(cur = scan_opd())
last = cur;
if (cur = scan_comm())
#if ENABLE_COMMENT_AS_TOKEN
add_token(cur);
#endif
return last;
}
```
If the#ifdirective is false, will it be compiled as
```
if (cur = scan_comm()... |
It will be compiled just as if the disabled line didn't exist, so:
```
if (cur = scan_comm())
return last;
```
You should use braces to make it clear what you mean.
```
if (cur = scan_comm())
{
#if ENABLE_COMMENT_AS_TOKEN
add_token(cur);
#endif
}
return last;
```
|
I have a linux based OS with a lot of system libraries compiled as static libraries.
How can I use such libraries in my application, andlinkthem to my final binary?
|
You use them as you do use shared libraries, except that you link against statically.An introduction to GCC - shared libraries and static librariesarticle will get you started.
|
Is there an existing library or codebase that is cross platform (Windows/Linux/OSX or a segment thereof) that would allow me to quickly compare the differences between two files over a network?
Basically, trying to recreate a basic version of rsync's "inplace" for a project I'm working on which would take the differe... |
There is alibrsync(with some more information available atthe author's site) that you could take a look at. It appears to have been abandoned for quite a while, the last release was in 2004, but it may work well enough as-is.
|
current->pid gets the process id accessing the module...but I want the threadid from the process in a multithreaded program accessing my module. What is the call to do this? I can't find it anywhere!
|
The linux kernel does not see multithreaded processes in the same way as the POSIX thread library (which I assume is what you mean by thread id). The kernel has tasks which are somewhat separate processes looped together by the thread library. Thispaperfrom IBM gives a more detailed explanation.
|
Isatoi()part of C standard?
What should I use to convertchar*tointifatoi()isn't standardised?
|
Yes,atoi()is part of standard C -- unfortunately.
I say "unfortunately" because it does no error checking; if it returns 0, you can't tell whether it's because you passed it"0"or because you passed it"hello, world\n"(whichhasmay have undefined behavior, but typically returns 0).
Thestrtol()function is more complicat... |
I have been writing an c s-function block for simulink.I want my output as an array
```
//
FILE *datafile;
datafile = fopen("datafile.dat","r");
pwork[0] = datafile;
//
//
static void mdlOutputs(SimStruct *S, int_T tid)
{
real_T *y = ssGetOutputPortSignal(S,0);
real_T *a;
real_T *b;
r... |
I don't know about Matlab, but I do know that the arguments to ascanfcall should bepointers, and unlessreal_Tis typedefed as a pointer already it will not work.
Besides, you are usingfscanfwhich is for reading from aFILEpointer.
I don't know if this will work or not, by try this instead:
```
sscanf(pwork[0], "%f %f... |
This question already has an answer here:Closed10 years ago.
Possible Duplicate:C++11: intptr_t/int_ptr_t, intmax_t/int_max_t?
I am using C platform on Visual Studio. I want to know that intmax_t datatype is only used for Linux based programming or It is supported by C language(ANSI Language) as well.
|
Well, bothintmax_tanduintmax_tare parts of C99, butsomecompilers actually need to be shimmed with something likethis(orthis) to use them. Quoting themain pageof the first link here:
This project fills the absence ofstdint.handinttypes.hin Microsoft
Visual Studio. This files were standartized by ISO/IEC as a part of... |
```
#include <stdio.h>
main()
{
float x;
x = (float)3.3==3.3;
printf("%f",x);
x=(float)3.5==3.5;
printf("\n%f",x);
}
```
i'm confused with
in the first case answer is 0.000
and in the second case answer is 1.00
can anyone explain ?
|
The expression
```
(float)3.3==3.3
```
first casts thedoublevalue 3.3 tofloatprecision, thereby changing its value, since it's not exactly representable in the target type. Then thatfloatvalue is converted back todouble, without changing the value` for the comparison, resulting in the comparison returning 0 (false).... |
Usingatoi()while reading from a file and it is dropping the first 0 in some of the zip codes, for example:
```
int x = atoi("06461");
```
seems to be savingx = 6461. Is dropping non significant 0's part of theatoifunction?
|
It doesn't drop zero. It stores the number. And as a number (decimal) 06461 and 6461 is exactly the same value. It's up to you how topresentthe number — with (printf("%05d",zip)) or without (%din case ofprintf) leading zero.
P.S. Note, that c folks are mightily confused by leading zeros, they tend to see numbers as o... |
Is it possible to know the CPU usage of a running/idle process programatically (in any language) in Windows?
|
If you don't care on support old Windows versions (earlier than Windows XP SP1) you could useGetSystemTimes Win32 API function.
Otherwise you have to usePerformance Counters.
|
How can I get the number of channels used by my video before initiating a capture?
I thought I could usecvGetCapturePropertybut there is no property_id I could set to get the number of channels.
|
Yes, you're right - there are noproperty_idfor number of channels. You can get number of channels only from single frame of capture.
|
```
int (*foo)(epoll_event e, void *data);
```
If I name the file with cc extension, this gets accepted. With .c extension this
```
error: expected ‘)’ before ‘e’
```
I have googled and declaration seems to be valid for C. Can anyone please provide input on how to fix this?
Thanks
|
I'm guessingepoll_eventis not a type name, it's a structure tag name.
In this case you need to addstruct:
```
int (*foo)(struct epoll_event e, void *data);
```
Thispagesuggests so:
```
struct epoll_event {
uint32_t events; /* Epoll events */
epoll_data_t data; /* User data variable */
};
``... |
I need to implement a Heap data structure in C.
While I was doing some research, I see people using buildHeap(), constructHeap() to convert an array into a heap. My question is, instead of implementing those functions, can I just call percolateDown() on the newly added item every time I need to add to the heap?
Than... |
A heap can be constructed in linear time, while the approach you propose will require O(N log(N)) time. Better construct heap in a separate function for better performance.
|
with MPI, in C, how can I execute a function if and only if I received all data from N processors, in my master process ID 0?
edit: Is there a way of receiving also all data in the same order than they have been sent?
|
If I get your question correctlyMPI_Reduceis what you need.
EDIT: so I did not get your question correctly. What you do need isMPI_Gather. And in this document you see that:Each process (root process included) sends the contents of its send buffer to the root process. The root process receives the messages and stores... |
I am currently building 3.1 kernel for android (tegra/goldfish branch). I would like to write a program in C that gets the sensor values. I do have inc/hardware/sensors.h and some relevant files but I keep getting an error when trying to open the sensor device.
Thanks
|
Take a look at the samples that are packed with the NDK,native-activityin particular.
|
What I am trying to do is open several images in C, then create a table comprised of GtkImages who's actual images can be set or reset to one of the initial images(I'm trying to create a chess board). I tried doing this with GTK but I can't use an image more than once because it is a widget. I tried using GDK, but acc... |
Store the images asGdkPixbufs. It's not deprecated. Swap them into theGtkImagewidgets usinggtk_image_set_from_pixbuf().
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
replace
```
printf("d\n",num1);
printf("d\n",num2);
```
with
```
printf("%d\n",num1);
printf("%d\n",num2);
```
|
I'm looking to implement a word count algorithm. However, anything that appears within~two tildes~is regarded as 1 word. For this reason I think regex is probably the best way to go?
The count must be calculated on every keypress on sample sets of about 10000 characters so it's good to get it right.
|
Do you really need to recalculate the whole thing on every keypress? It seems that unless you're in between two spaces, no key but~or space can change the number of words. And for those special keys, you should usually be able to determine the changes to the number of words locally without re-processing the whole buff... |
Usingatoi()while reading from a file and it is dropping the first 0 in some of the zip codes, for example:
```
int x = atoi("06461");
```
seems to be savingx = 6461. Is dropping non significant 0's part of theatoifunction?
|
It doesn't drop zero. It stores the number. And as a number (decimal) 06461 and 6461 is exactly the same value. It's up to you how topresentthe number — with (printf("%05d",zip)) or without (%din case ofprintf) leading zero.
P.S. Note, that c folks are mightily confused by leading zeros, they tend to see numbers as o... |
Is it possible to know the CPU usage of a running/idle process programatically (in any language) in Windows?
|
If you don't care on support old Windows versions (earlier than Windows XP SP1) you could useGetSystemTimes Win32 API function.
Otherwise you have to usePerformance Counters.
|
How can I get the number of channels used by my video before initiating a capture?
I thought I could usecvGetCapturePropertybut there is no property_id I could set to get the number of channels.
|
Yes, you're right - there are noproperty_idfor number of channels. You can get number of channels only from single frame of capture.
|
```
int (*foo)(epoll_event e, void *data);
```
If I name the file with cc extension, this gets accepted. With .c extension this
```
error: expected ‘)’ before ‘e’
```
I have googled and declaration seems to be valid for C. Can anyone please provide input on how to fix this?
Thanks
|
I'm guessingepoll_eventis not a type name, it's a structure tag name.
In this case you need to addstruct:
```
int (*foo)(struct epoll_event e, void *data);
```
Thispagesuggests so:
```
struct epoll_event {
uint32_t events; /* Epoll events */
epoll_data_t data; /* User data variable */
};
``... |
I need to implement a Heap data structure in C.
While I was doing some research, I see people using buildHeap(), constructHeap() to convert an array into a heap. My question is, instead of implementing those functions, can I just call percolateDown() on the newly added item every time I need to add to the heap?
Than... |
A heap can be constructed in linear time, while the approach you propose will require O(N log(N)) time. Better construct heap in a separate function for better performance.
|
with MPI, in C, how can I execute a function if and only if I received all data from N processors, in my master process ID 0?
edit: Is there a way of receiving also all data in the same order than they have been sent?
|
If I get your question correctlyMPI_Reduceis what you need.
EDIT: so I did not get your question correctly. What you do need isMPI_Gather. And in this document you see that:Each process (root process included) sends the contents of its send buffer to the root process. The root process receives the messages and stores... |
I am currently building 3.1 kernel for android (tegra/goldfish branch). I would like to write a program in C that gets the sensor values. I do have inc/hardware/sensors.h and some relevant files but I keep getting an error when trying to open the sensor device.
Thanks
|
Take a look at the samples that are packed with the NDK,native-activityin particular.
|
What I am trying to do is open several images in C, then create a table comprised of GtkImages who's actual images can be set or reset to one of the initial images(I'm trying to create a chess board). I tried doing this with GTK but I can't use an image more than once because it is a widget. I tried using GDK, but acc... |
Store the images asGdkPixbufs. It's not deprecated. Swap them into theGtkImagewidgets usinggtk_image_set_from_pixbuf().
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
replace
```
printf("d\n",num1);
printf("d\n",num2);
```
with
```
printf("%d\n",num1);
printf("%d\n",num2);
```
|
I'm looking to implement a word count algorithm. However, anything that appears within~two tildes~is regarded as 1 word. For this reason I think regex is probably the best way to go?
The count must be calculated on every keypress on sample sets of about 10000 characters so it's good to get it right.
|
Do you really need to recalculate the whole thing on every keypress? It seems that unless you're in between two spaces, no key but~or space can change the number of words. And for those special keys, you should usually be able to determine the changes to the number of words locally without re-processing the whole buff... |
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
(Shameless self advertisement) You may be interested in mylinmath.h. Be warned though that I update it only occassionally and some parts may still contain weird bugs. Please report anything you may find.
|
What will be the output of program
```
#include <stdio.h>
int fun(char *a){
printf("%d\n",sizeof(a));
return 1;
}
int main(){
char a[20];
printf("%d\n",sizeof (fun(a)));
return 0;
}
```
|
Except with variable length arrays,sizeofdoes not evaluate its operand. So it will just yield the size offun(a)type,i.e.sizeof(int)(without calling the function).
C11 (n1570) §6.5.3.4 Thesizeofand_Alignofoperators2 [...] If the type of the operand is a variable length array type, the operand is evaluated; otherwise, ... |
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
Otherwise,<dirent.h>header file is now pseudo-standard: both MinGW and GCC have it. So, you can handle directories on a conventional personnal computer, without too much trouble.
|
i have a STR16 (psString) that i want to add too.
something like this:
```
sprintf(psString,"%s 500 Left",psString);
```
but VS says STR16 is incompatible with sprintf
what's a way i can modify this STR16 and end up a STR16 ?
thanks.
|
Useswprintfinstead, since it deals with 16-bit wide characters rather than 8-bit characters. Windows provides a similar version calledwsprintf. You can also use _stprintf and the preprocessor will convert it either 8 or 16 bit-wide characters based on the TCHAR definition.
Note that this function is considered unsaf... |
In my computer science program we've been taught to work with child processes and forks and pipes and file descriptors etc etc in C, but we've never done comparable stuff in C++.
Do you use the same libraries, or does C++ have some (hopefully simplified) systems libraries of its own?
|
The types of things you have described are actually system specific rather then C specific. If you look around you might be able to find some wrappers for them, but they are not part of the C++ standard (nor the C standard).
As an example, there's no reason to use file descriptors in standard C. That's what the file ... |
I am looking for a way to know how much time will my C program use, preferably before I run it, but if this cannot be known before, then after it has ended.
Is there a way?
|
After, yes. On most (all?) UNIX-y systems, you can use this:
```
time ./myprog
```
Before, no, because the program could depend on external input.The halting problemmight also be an obstacle to finding the amount of time a program would take to execute beforehand.
|
I need to write a program in pureC. I wish to fill an array with user inputted floats and my function at the moment looks like this:
```
int fillWithCustom(float *array, int size) {
float customNumber;
for (i = 0; i < size; i++)
for (j = 0; j < size; j++) {
printf("\n Enter [%d... |
Don;t usescanf()for user input. It was written to be used with formatted data. User input and formatted data are as different as night from day.
Usefgets()andstrtod().
|
i'm reading the source code ofhttp-parserand came across some if statements with empty blocks. here's an example (source)
```
int
dontcall_message_begin_cb (http_parser *p)
{
if (p) { } // gcc
fprintf(stderr, "\n\n*** on_message_begin() called on paused parser ***\n\n");
abort();
}
```
the comment merely menti... |
My guess is someone trying to suppress the "unused parameter" warning.
The canonical way to do this is(void)p;, but I'm guessing the author of the code didn't know about that.
|
I have an input string of the form
```
char *s = "one.two three"
```
and I want to separate it into 3 string variables.
I'm doing
```
sscanf(s, "%s.%s %s", one, two, three);
```
but it's reading in "one.two" as the string for variable one. How do I handle the "." and the whitespace with sscanf?
|
The%sspecifier only stops for a space. Try something like:
```
sscanf(s, "%[^.].%s %s", one, two, three);
```
Interestingly, it's likely impossible to produce an acceptable input for"%s.%s %s"since%sonly stops for a space yet a.must immediately follow it.
|
I compiled the same program (not library) with different compilation flags, in CMake with Clang
with CMAKE_C_FLAGS = -Wl,-export-dynamicwith CMAKE_EXE_LINKER_FLAGS = -export-dynamic
But I noticed that the second way doesn't seem to work. I can't find the exported symbols. I'm so surprised that only the 1st way works... |
Provide same options for second variant.
set(CMAKE_EXE_LINKER_FLAGS "-Wl,-export-dynamic")
Because compiler and linker the same in your case.
|
I am using the above code to increment a counter using 2 threads, which independently take the mut lock and increment counter. I am facing a deadlock after the threads enter this function.
```
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
void *increment_counter(void *counter_addr)
{
int max = MAX_COUNTER_VA... |
You're trying to lock the mutexmaxtimes, then incrementcounterand release it once.
Try:
```
for(iter=0;iter< max ;iter++)
{
// LOCK
pthread_mutex_lock(&mut);
counter++;
// UNLOCK
pthread_mutex_unlock(&mut);
}
return NULL;
```
|
I have a constant defined:
```
#define MAX_STR_LEN 100
```
I am trying to do this:
```
scanf("%" MAX_STR_LEN "s", p_buf);
```
But of course that doesn't work.
What preprocessor trick can be use to convert the MAX_STR_LEN numerica into a string so I can use it in the above scanf call ? Basically:
```
scanf("%" XY... |
Use the#preprocessing operator. This operator only works during macro expansion, so you'll need some macros to help. Further, due to peculiarities inherent in the macro replacement algorithm, you need a layer of indirection. The result looks like this:
```
#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x... |
I have a socket that is set up to listen()
Normally I would accept() these connections based on a file descriptor being ready via select(). Can I change this to be a recv() instead of accept(), with that same file descriptor?
|
No, they're not interchangeable.
You're only listening on a single file descriptor usingselect, but you want have a file descriptorper connectiononce you have connected clients.
acceptextracts the first connection request on the queue of pending connections for the listening socket, creates a new connected socket, a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.