question
stringlengths 25
894
| answer
stringlengths 4
863
|
|---|---|
I need to parse the source code of different files, each written in a different language, and I would like to do this using C.
To do that, I was thinking of usingyacc/lex, but I find them very hard to understand, maybe due to the complete lack of decent documentation (either that, or they really are cryptic).
So my questions are: where can I find some good documentation foryacc/lex, preferably a tutorial style introduction? Or, is there any better way to do this in C? Maybe there's something else I could use instead ofyacc/lex, perhaps even written in a different language?
|
yaccandlexare very powerful tools, built around the theories for compiler construction. To be able to fully understand them you probably need some basics in formal languages, automata theory and compiler construction.
Thedragon bookis a classic on the subject.
|
Why does neither gcc or clang generate an error when I try to compile code containing the following two lines?
```
int palindrome(char s[]){
char s2[strlen(s)];
```
I thought in such an instance you would have to dynamically allocate memory to s2.
|
GCC has an extension for this behavior, and it's also standard in C99, known as variable length arrays.
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
Clang supports it due to GCC C and C99:http://clang.llvm.org/compatibility.html#vla
|
I have the following text file:
```
ax: 0
ay: -9.8
x: 0
y: 50
vx: 8.66
vy: 6
```
I want to read only the numerical values to be used for computations. Is there a way to ignore the strings and just read the values as floats?
Here is what I have so far:
```
FILE *fp;
FILE *fr;
fr = fopen("input_data", "rt");
fp = fopen("out_file.txt", "w");
if(fr == NULL) {
printf("File not found");
}
if(fp == NULL) {
printf("File not found");
}
float ax = 0, ay = 0,
x = 0, y = 0,
vx = 0, vy = 0,
time = 0, deltaTime = 0;
fscanf(fr, "%f %f %f %f %f %f %f %f\n",
&ax, &ay, &x, &y, &vx, &vy, &time, &deltaTime);
printf("%f %f %f %f %f %f %f %f\n",
ax, ay, x, y, vx, vy, time, deltaTime);
```
|
Use this instead:
```
fscanf(fr, "ax: %f ay: %f x: %f y: %f vx: %f vy: %f", &ax, &ay, &x, &y, &vx, &vy);
```
|
Can i have my javascript which is getting executed via Flash gui button to trigger backend application layer written with either C, C++ or Java?
Example: My operating system is Flash full screen. Button on press it use javascript and execute local system built in functions and give interactive response.
Thank you
|
One option is to have your back-end Java code exposed through a Java Web application. The JavaScript can invoke the Web application (ex. through Ajax) which in-turn will delegate the call to your Java code.
|
are there any specifics when developing a device driver (kernel-mode) on Windows 7 32 bit or Windows 7 64 bit? Can I develop on some platform and prepare builds to run on the other one?
Thank you.
|
You need theWindows Driver Kit. Yes, you should be able to cross-compile.
|
i have helper C functions in some Objective C classes.
Just found out that the values of global, static C variables which i use in these functions are shared between instances of the class (duh), which is not what i want.
Is there a way to declare these variables local to instances of the class, so that they are visible by the helper functions without passing them explicitly?
|
Is there a way to declare these variables local to instances of the class
Sure, make them instance variables.
But:
so that they are visible by the helper functions without passing them explicitly?
You can pass theobjectinto the function. If you have appropriate accessors, the function can get them. And if you have mutators, it can modify them, too.
But if you're doing that, you might as well just create a method, and automatically have access to the instance variables.
|
I came across this in the Python interpreter source code.
```
void
PyThread_delete_key_value(int key)
{
long id = PyThread_get_thread_ident();
struct key *p, **q;
```
The interesting part being thestruct key *p, **q;call. What exactly is this structure doing? I'm confused as to what exactly this is a struct of. Is this not the same as say, this?
```
struct 1 *p;
```
I are confused.
Edit:
Even though this has been answered, I should clear up my question. It was specifically the fact that the wordkeywas reused and that I didn't know that the compiler considers them in different namespaces.
|
key exists in two different namespaces here. Once as a variable, once as a structure. The compiler knows that 'struct key' and int key are different things.
|
I'm confused with range of values of Int variable in C.
I know that a 32bits unsigned int have a range of: 0 to 65,535.
So long has 0 to 4,294,967,295
This is fine in 32bits machine. But now in 64bits machines all thing keep the same?
Or maybe my int capacity is different?
I understand this questions as newbie, but I'm really confused.
This method signature is not helping too. :)
```
unsigned long long int atomicAdd(unsigned long long int* address, unsigned long long int val);
```
|
In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)
```
signed char: -2^07+1 to +2^07-1
short: -2^15+1 to +2^15-1
int: -2^15+1 to +2^15-1
long: -2^31+1 to +2^31-1
long long: -2^63+1 to +2^63-1
```
Now, on particular implementations, you have a variety of bit ranges. Thewikipedia articledescribes this nicely.
|
I am quite new to C (I am more used to C++) and I am trying to create an IRC Bot. I am currently struggling to find the correct string parsing functions to parse this line:
```
:nick!~username@server PRIVMSG #channel :message (could contain the word PRIVMSG)
```
So, I am asking if anyone could show me what functions I would use to split up this line into:
nickusernameserverchannelmessage
Thanks for any help!
|
I'd probably use sscanf. Something on this general order seems to be a reasonable starting point:
```
char nick[32], user[32], server[32], channel[32], body[256];
sscanf(buffer, ":%31[^!]!~%31[^@]@%31s PRIVMSG #%31s :%255[^\n]",
nick, user, server, channel, body);
```
|
The following code returns -1, how can I know what's wrong?
get a detailed error or something?
```
if (read(programFile, value, sizeof(FRAME)) == -1) {
return SYSTEM_CALL;
}
```
|
You need to look intoerrno, which is a variable set by system calls to indicate an error. You can use the convenience functionperrorto get a human-readable printout.
```
if (read(prog, value, sizeo(FRAME) == -1) {
perror("read");
// handle error
}
```
It can return something likeNo such file or directory. Either way its a good practice to use it.
Check outman errnoandman perrorfor more information.
|
As we know queue isFIFO,does it support such kind of operation?
|
No. If you want to be be able to put objects at specific positions, a queue is not the right data structure.
A deque lets you insert new items at either the back or the front. Once inserted, however, you can't normally rearrange them.
A priority queue maintains some specified ordering among the items, so the "next" is always the highest priority (based on some criteria you need to establish).
If you want to rearrange items after insertion, then you're normally looking at something that isn't very queue-like at all (much more like a normal array).
|
given an integer array of which first and second half are sorted. write a function to merge the two parts to create one single sorted array in place(do not use extra space).
one approach is
eg:
// 1,3,6,8,-5,-2,3,8
```
int l = 0;
int u = size;
int mid = (l+u)/2;
int i;
for (i = 0; i < mid; i++) {
for (j = mid; j < size; j++) {
if (a[i] >= a[j]) {
temp = a[j];
for (i = mid-1; i >= 0; i--)
a[i+1] = a[i];
a[0] = temp;
}
}
}
```
but i think there must be some O(n) algo for this..
|
Indeed there are O(n) algorithms for merging in-place. They're usually quite complex though. For few ideas, please see the papers such asHuang, Langston (PDF)orKatajainen, Pasanen, Teuhola (PostScript). These are actually defined based on precise terms of what kind of extra memory is allowed, without cheating by using recursion stack and so on.
|
What is the cleanest way to pass data from device driver to windows service and back?
|
This is normally achieved usingDevice Input and Output Control (IOCTL).
You can define your own private control code and then send information in both directions. The function is called from user mode, i.e. the service in your case.
|
By (5, 5) I mean exactly the fifth row and fifth column.
I found it very hard to draw things using screen coordinates, all the coordinates in OpenGL is relative, and usually ranging from -1.0 to 1.0. Why it is so serious to prevent programmers from using screen coordinates / window coordinates?
|
The simplest way is probably to set the projection to match the pixel dimensions of the rendering space viaglOrtho. Then vertices can be in pixel coordinates. The downside is that resizing the window could cause problems and you're mostly wasting the accelerated transforms.
Assuming a window that is 640x480:
```
// You can reverse the 0,480 arguments depending on you Y-axis
// direction preference
glOrtho(0, 640, 0, 480, -1, 1);
```
Frame buffer objects and textures are another avenue but you'll have to create your own rasterization routines (draw line, circle, bitmap, etc). There are problaby libs for this.
|
In the code below, what do the first and secondconstmean?
I guess first or second meansfoois constant; the other one means elements offooare also constants. Is it true?
```
static const char * const foo[] = {"bar", "baz"};
```
|
It means its an array of const pointers (so you can't change the pointers) to const chars (so you can't change the chars via the pointers). This is a common way of defining fixed strings, such as command names, in an application.
|
C++ can use c functions byextern "C",
can c use c++ functions somehow?
|
Not really. You can write a "C-compatible" function in C++, that is to say outside of any class or namespace and whose prototype does not use classes or references. If declaredextern "C"then you could call such a function from C. The function could then go on to make use of whatever C++ features were useful for it.
|
So I am writing a C file which includes /extfs/ext2fs.h. I am trying to call the function ext2fs_open(). I can clearly see that the header file ext2fs.h has that particular function. In fact, if I pass in the incorrect number of arguments, it even corrects me. However it does not compile, always giving me a "undefined reference" error. This problem lies with all the methods defined in the header file. How am I supposed to compile this file? Is there some library I need to link to?
Thank you.
|
You do need to link tolibext2fs, yes...
```
gcc -I/dir/containing/ext2fs.h -lext2fs your_source.c -o app
```
|
```
typedef struct {
float *numbers;
float val1;
float val2;
} Values;
Values val[16];
```
How can one allocate memory for numbers in the struct?
|
If you want to allocate the space for one float in the first element of your struct, you would do it like this:
```
#include <stdlib.h>
/* ... */
val[0].numbers = malloc(1 * sizeof(float)); /* "1 * " for clarity... */
```
If that's what you meant.
|
I need to parse the source code of different files, each written in a different language, and I would like to do this using C.
To do that, I was thinking of usingyacc/lex, but I find them very hard to understand, maybe due to the complete lack of decent documentation (either that, or they really are cryptic).
So my questions are: where can I find some good documentation foryacc/lex, preferably a tutorial style introduction? Or, is there any better way to do this in C? Maybe there's something else I could use instead ofyacc/lex, perhaps even written in a different language?
|
yaccandlexare very powerful tools, built around the theories for compiler construction. To be able to fully understand them you probably need some basics in formal languages, automata theory and compiler construction.
Thedragon bookis a classic on the subject.
|
Why does neither gcc or clang generate an error when I try to compile code containing the following two lines?
```
int palindrome(char s[]){
char s2[strlen(s)];
```
I thought in such an instance you would have to dynamically allocate memory to s2.
|
GCC has an extension for this behavior, and it's also standard in C99, known as variable length arrays.
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
Clang supports it due to GCC C and C99:http://clang.llvm.org/compatibility.html#vla
|
I have the following text file:
```
ax: 0
ay: -9.8
x: 0
y: 50
vx: 8.66
vy: 6
```
I want to read only the numerical values to be used for computations. Is there a way to ignore the strings and just read the values as floats?
Here is what I have so far:
```
FILE *fp;
FILE *fr;
fr = fopen("input_data", "rt");
fp = fopen("out_file.txt", "w");
if(fr == NULL) {
printf("File not found");
}
if(fp == NULL) {
printf("File not found");
}
float ax = 0, ay = 0,
x = 0, y = 0,
vx = 0, vy = 0,
time = 0, deltaTime = 0;
fscanf(fr, "%f %f %f %f %f %f %f %f\n",
&ax, &ay, &x, &y, &vx, &vy, &time, &deltaTime);
printf("%f %f %f %f %f %f %f %f\n",
ax, ay, x, y, vx, vy, time, deltaTime);
```
|
Use this instead:
```
fscanf(fr, "ax: %f ay: %f x: %f y: %f vx: %f vy: %f", &ax, &ay, &x, &y, &vx, &vy);
```
|
Can i have my javascript which is getting executed via Flash gui button to trigger backend application layer written with either C, C++ or Java?
Example: My operating system is Flash full screen. Button on press it use javascript and execute local system built in functions and give interactive response.
Thank you
|
One option is to have your back-end Java code exposed through a Java Web application. The JavaScript can invoke the Web application (ex. through Ajax) which in-turn will delegate the call to your Java code.
|
are there any specifics when developing a device driver (kernel-mode) on Windows 7 32 bit or Windows 7 64 bit? Can I develop on some platform and prepare builds to run on the other one?
Thank you.
|
You need theWindows Driver Kit. Yes, you should be able to cross-compile.
|
i have helper C functions in some Objective C classes.
Just found out that the values of global, static C variables which i use in these functions are shared between instances of the class (duh), which is not what i want.
Is there a way to declare these variables local to instances of the class, so that they are visible by the helper functions without passing them explicitly?
|
Is there a way to declare these variables local to instances of the class
Sure, make them instance variables.
But:
so that they are visible by the helper functions without passing them explicitly?
You can pass theobjectinto the function. If you have appropriate accessors, the function can get them. And if you have mutators, it can modify them, too.
But if you're doing that, you might as well just create a method, and automatically have access to the instance variables.
|
I came across this in the Python interpreter source code.
```
void
PyThread_delete_key_value(int key)
{
long id = PyThread_get_thread_ident();
struct key *p, **q;
```
The interesting part being thestruct key *p, **q;call. What exactly is this structure doing? I'm confused as to what exactly this is a struct of. Is this not the same as say, this?
```
struct 1 *p;
```
I are confused.
Edit:
Even though this has been answered, I should clear up my question. It was specifically the fact that the wordkeywas reused and that I didn't know that the compiler considers them in different namespaces.
|
key exists in two different namespaces here. Once as a variable, once as a structure. The compiler knows that 'struct key' and int key are different things.
|
I'm confused with range of values of Int variable in C.
I know that a 32bits unsigned int have a range of: 0 to 65,535.
So long has 0 to 4,294,967,295
This is fine in 32bits machine. But now in 64bits machines all thing keep the same?
Or maybe my int capacity is different?
I understand this questions as newbie, but I'm really confused.
This method signature is not helping too. :)
```
unsigned long long int atomicAdd(unsigned long long int* address, unsigned long long int val);
```
|
In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)
```
signed char: -2^07+1 to +2^07-1
short: -2^15+1 to +2^15-1
int: -2^15+1 to +2^15-1
long: -2^31+1 to +2^31-1
long long: -2^63+1 to +2^63-1
```
Now, on particular implementations, you have a variety of bit ranges. Thewikipedia articledescribes this nicely.
|
I am quite new to C (I am more used to C++) and I am trying to create an IRC Bot. I am currently struggling to find the correct string parsing functions to parse this line:
```
:nick!~username@server PRIVMSG #channel :message (could contain the word PRIVMSG)
```
So, I am asking if anyone could show me what functions I would use to split up this line into:
nickusernameserverchannelmessage
Thanks for any help!
|
I'd probably use sscanf. Something on this general order seems to be a reasonable starting point:
```
char nick[32], user[32], server[32], channel[32], body[256];
sscanf(buffer, ":%31[^!]!~%31[^@]@%31s PRIVMSG #%31s :%255[^\n]",
nick, user, server, channel, body);
```
|
The following code returns -1, how can I know what's wrong?
get a detailed error or something?
```
if (read(programFile, value, sizeof(FRAME)) == -1) {
return SYSTEM_CALL;
}
```
|
You need to look intoerrno, which is a variable set by system calls to indicate an error. You can use the convenience functionperrorto get a human-readable printout.
```
if (read(prog, value, sizeo(FRAME) == -1) {
perror("read");
// handle error
}
```
It can return something likeNo such file or directory. Either way its a good practice to use it.
Check outman errnoandman perrorfor more information.
|
As we know queue isFIFO,does it support such kind of operation?
|
No. If you want to be be able to put objects at specific positions, a queue is not the right data structure.
A deque lets you insert new items at either the back or the front. Once inserted, however, you can't normally rearrange them.
A priority queue maintains some specified ordering among the items, so the "next" is always the highest priority (based on some criteria you need to establish).
If you want to rearrange items after insertion, then you're normally looking at something that isn't very queue-like at all (much more like a normal array).
|
given an integer array of which first and second half are sorted. write a function to merge the two parts to create one single sorted array in place(do not use extra space).
one approach is
eg:
// 1,3,6,8,-5,-2,3,8
```
int l = 0;
int u = size;
int mid = (l+u)/2;
int i;
for (i = 0; i < mid; i++) {
for (j = mid; j < size; j++) {
if (a[i] >= a[j]) {
temp = a[j];
for (i = mid-1; i >= 0; i--)
a[i+1] = a[i];
a[0] = temp;
}
}
}
```
but i think there must be some O(n) algo for this..
|
Indeed there are O(n) algorithms for merging in-place. They're usually quite complex though. For few ideas, please see the papers such asHuang, Langston (PDF)orKatajainen, Pasanen, Teuhola (PostScript). These are actually defined based on precise terms of what kind of extra memory is allowed, without cheating by using recursion stack and so on.
|
What is the cleanest way to pass data from device driver to windows service and back?
|
This is normally achieved usingDevice Input and Output Control (IOCTL).
You can define your own private control code and then send information in both directions. The function is called from user mode, i.e. the service in your case.
|
By (5, 5) I mean exactly the fifth row and fifth column.
I found it very hard to draw things using screen coordinates, all the coordinates in OpenGL is relative, and usually ranging from -1.0 to 1.0. Why it is so serious to prevent programmers from using screen coordinates / window coordinates?
|
The simplest way is probably to set the projection to match the pixel dimensions of the rendering space viaglOrtho. Then vertices can be in pixel coordinates. The downside is that resizing the window could cause problems and you're mostly wasting the accelerated transforms.
Assuming a window that is 640x480:
```
// You can reverse the 0,480 arguments depending on you Y-axis
// direction preference
glOrtho(0, 640, 0, 480, -1, 1);
```
Frame buffer objects and textures are another avenue but you'll have to create your own rasterization routines (draw line, circle, bitmap, etc). There are problaby libs for this.
|
In the code below, what do the first and secondconstmean?
I guess first or second meansfoois constant; the other one means elements offooare also constants. Is it true?
```
static const char * const foo[] = {"bar", "baz"};
```
|
It means its an array of const pointers (so you can't change the pointers) to const chars (so you can't change the chars via the pointers). This is a common way of defining fixed strings, such as command names, in an application.
|
what's the meaning ofVOID()
There are the following C code, but what's it's meaning?
```
VOID(pthread_mutex_init(&tina_mutex,MY_MUTEX_INIT_FAST));
```
|
Looks like a preprocessor macro. Your editor should be able to find what it is. Or try
```
gcc -E source.c > source2.c
```
It runs the preprocessor only and replaces macros with what they really evaluate to.
|
Can someone explain what specifically needs to be done in exercise 5.17, what does it mean to sort within line, its field?
|
I don't have my copy of K&R here. I think it means this
Suppose the original file has
```
0000087423 Volkswagen 2001-01-01
0000642396 Fiat 2002-02-02
3900063521 Renault 2003-03-03
```
It is already sorted by the 1st field; if you want to sort it by the 2nd field (the name) the result would be
```
0000642396 Fiat 2002-02-02
3900063521 Renault 2003-03-03
0000087423 Volkswagen 2001-01-01
```
Or you can sort by date (the 3rd field)
|
I am working with optimizing a single C object file with regards on the footprint. I'm using the compiler arm-elf-gcc, as the target platform is for a ARM-926EJ processor.
I want to document the current size and then compare after the optimization and I'm wondering, why does arm-elf-size return a size that is smaller then the actual size of the object file?
This is what I get with arm-elf-size
text data bss dec hex filename15656 29188 0 44844 af2c hyper.o
And the actual size of the hyper.o file is 54 168 bytes.
Which one should i look at?
Best Regards
Mr Gigu
|
The object file has headers which aren't part of the segments sizes reported by elf-size.
|
Extracted from nginx:
```
static ngx_inline ngx_atomic_uint_t
ngx_atomic_cmp_set(ngx_atomic_t *lock, ngx_atomic_uint_t old,
ngx_atomic_uint_t set)
{
u_char res;
__asm__ volatile (
NGX_SMP_LOCK
" cmpxchgl %3, %1; "
" sete %0; "
: "=a" (res) : "m" (*lock), "a" (old), "r" (set) : "cc", "memory");
return res;
}
```
I don't understand the syntax the assembly instruction are combined(it's using a different syntax thanprintfuses),what is it doing at all?
|
Giventhisand ignoring operations atomicity, function is equivalent to:
```
static ngx_inline ngx_atomic_uint_t
ngx_atomic_cmp_set(ngx_atomic_t *lock, ngx_atomic_uint_t old,
ngx_atomic_uint_t set)
{
u_char res;
if (*lock == old){
*lock = set;
res = 1;
} else{
res = *lock
}
return res;
}
```
|
This code:
```
#include <stdio.h>
int main(void)
{
void *ptr;
int arr[] = {1,2,3,4,5};
ptr = arr;
ptr++;
printf("%d",*(int*)ptr);
}
```
Prints some garbage value but I was expecting it to print2. Why doesn't it print2?
|
You can't perform pointer arithmetic on a void pointer because the compiler doesn't have any idea about the size of the pointed to objects.
Your code doesn't get compiled on comeau online. Its another evil gcc extension I guess.
|
What is the meaning of<<=and|=in C?
I recognise<<is bitshift etc. but I don't know what these are in combination.
|
Just asx += 5meansx = x + 5, so doesx <<= 5meanx = x << 5.
Same goes for|. This is a bitwiseor, sox |= 8would meanx = x | 8.
Here is an example to clarify:
```
int x = 1;
x <<= 2; // x = x << 2;
printf("%d", x); // prints 4 (0b001 becomes 0b100)
int y = 15;
y |= 8; // y = y | 8;
printf("%d", y); // prints 15, since (0b1111 | 0b1000 is 0b1111)
```
|
here is a code that I wanna change LD_LIBRARY_PATH to exec a code:
```
#!/usr/bin/python
import os
code='''
import os
print os.getenv("LD_LIBRARY_PATH");
import wrap
'''
os.environ['LD_LIBRARY_PATH'] = '/home/dma/python'
os.environ["PYTHONPATH"] = '/home/dma/python'
exec code
```
The output is:
```
/home/dma/python
Traceback (most recent call last):
File "./test.py", line 13, in ?
exec code
File "<string>", line 4, in ?
ImportError: example.so: cannot open shared object file: No such file or directory
```
NOTE: test.py depend on wrap.so, wrap.so depend on example.so
Is there any way to execute the code object in the special environment?
Thanks
Dma
|
It appears as thoughexample.soisn't in/home/dma/python.
|
When I want to pass a "char (*c)[10];" as a parameter,
what argument should I define in my function definition?
I mean, if I have a function:
```
void foo(*****) { ... }
```
I want to passchar (*c)[10];to it, so what do I write in place of*****?
|
This should work fine:
```
void foo(char (*c)[10]);
```
|
How does gdb know the pointer points to aintorstructor any other data types?
|
from:Examining the Symbol Table
whatis exprPrint the data type of expression expr. expr is not actually evaluated, and any side-effecting operations (such as assignments or function calls) inside it do not take place. See section Expressions.
ptype exprptypePrint a description of the type of expression expr. ptype differs from whatis by printing a detailed description, instead of just the name of the type. For example, for this variable declaration:
```
struct complex {double real; double imag;} v;
```
the two commands give this output:
```
(gdb) whatis v
type = struct complex
(gdb) ptype v
type = struct complex {
double real;
double imag;
}
```
|
Hi there i have a method called
int compare(char op1, char op2)
the method willreturn 1, -1 or 0depending on the result of the comparison. (1 if op1 < op2).
I need to compare the following operations:
```
- subtraction
* multiplication
/ division
^ exponentiation
% remainder
```
I have considered using an enum such as:
```
enum ops{
'+'=1, '-'=1, '*'=2, '/'=2, '^', '%'
}var;
```
but this doesn't compile. Can anyone lend a hand?
|
You can't use characters as keys for the enum, you should do something like:
```
enum ops {
OP_PLUS = 1,
OP_MINUS = 1,
OP_MULT = 2,
OP_DIV = 2,
OP_POWER,
OP_MOD
} var;
```
|
This is an interview question. I have no idea how to solve it.
could anybody help me:?
Given a pointer to member a within a
structure, write a routine that
returns a pointer to the structure.
Thank you!
|
Firstly, in order to pull that off you need to know the type of the enclosing structStructTypeand the name of the membermember. That must be a given. Without it, the problem has no solution.
Secondly, I don't know why other answers insist on reinventing the wheel (and engage into undefined and non-portable hacks on top of that) instead of using the standardoffsetofmacro. Withoffsetofthe answer is
```
StructType *pstruct =
(StructType *) ((char *) pmember - offsetof(StructType, member));
```
|
I'm writing an emulator in C. Its memory is byte-addressible so I'm using a char array, but I need to read/write unaligned 32-bit integers.
Currently I'm using*((unsigned int*) &memory[address]), but it seems pretty horrible. What's the best way to do it?
|
You can usememcpy()directly. For example:
```
unsigned int x = 10;
unsigned char* memory = malloc(sizeof(unsigned char) * 512);
address = sizeof(unsigned char) * 256;
memcpy(memory + address, &x, sizeof(unsigned int));
```
|
are you aware of a trusted (i.e. efficient and accurate) implementation of special math functions (like gamma, beta, error and inverse error functions) for the C language available with a non-gpl license? BSD or MIT licenses are fine.
So something like:http://www.gnu.org/software/gsl/manual/html_node/Special-Functions.html
but with a more permissive license. I am aware boost have something similar but it's a bit overkill to add dependency on boost just for this...
Moreover C would be preferable in this context...
Thanks!
|
The answers to the questions below contain links to some excellent libraries, includingfdlibmandcephes:
C library of single-precision transcendental functionslong double math library implementations?Platform independent math library
|
I have an array of int pointersint* arr[MAX];and I want to store its address in another variable. How do I define a pointer to an array of pointers? i.e.:
```
int* arr[MAX];
int (what here?) val = &arr;
```
|
The correct answer is:
```
int* arr[MAX];
int* (*pArr)[MAX] = &arr;
```
Or just:
```
int* arr [MAX];
typedef int* arr_t[MAX];
arr_t* pArr = &arr;
```
The last part reads as "pArr is a pointer to array of MAX elements of type pointer to int".
In C the size of array is stored in the type, not in the value. If you want this pointer to correctly handle pointer arithmetic on the arrays(in case you'd want to make a 2-D array out of those and use this pointer to iterate over it),you - often unfortunately - need to have the array size embedded in the pointer type.
Luckily, since C99 and VLAs (maybe even earlier than C99?) MAX can be specified in run-time, not compile time.
|
I'm developing a C program and oddly as I update the source files I don't see any change in the resulting executable. Is it possible gcc stores a cached copy of the files and even if I compile I don't get the newer version of my executable? In this case how can I force the compiler to use the newly edited files?
I am compiling my code with the following:
```
# gcc -o myExecFileName source_file_1.c source_file2.c
```
|
To answer your question, no gcc will not cache your files. Something else is going on. You are either changing files in a different directory as @Lee D suggests, or you are not saving the files before compiling, or perhaps the changes you are making are ifdef'd out.
|
Is it possible to cross-compile for OpenVMS(i64) on Unix host and just transfer the executable to OpenVMS server? If it is possible, how do you do it?
|
No it is not possible.
It is however possible, providing the compiler is available on both Unix and OpenVMS (and many are), to develop the software on HP Unix and then copy the source to VMS and compile. Can't say I have ever done it and when I looked into it, I think the Unix was Digital Unix rather than HP Unix, so you may have to do some research there.
There is also a couple of web sites where you can compile source code for VMS...I think HP has one, and there is also the Deathrow Cluster which provides such a facility I believe.
|
So I am writing a little utility to format my inventory file is such a manner that I can import it to a preexisting db. I am having a large issue trying to just do fscanf. I have read tons of file in c in the past. What am I doing wrong here.
Edit based on Christopher's suggestion still getting NULL.
```
#include <stdio.h>
#include <string.h>
int main ()
{
FILE* stream;
FILE* output;
char sellercode[200];
char asin[15];
string sku[15];
string fnsku[15];
int quality;
stream = fopen("c:\out\dataextract.txt", "r");
output = fopen("c:\out\output.txt", "w");
if (stream == NULL)
{
return 0;
}
for(;;)
{
//if (EOF) break;
fscanf(stream, "%s", sku);
fprintf(output, "%s %s %s %s %i\n", sku, fnsku, asin, quality);
}
return 0;
}
```
|
```
if (stream = NULL)
{
return 0;
}
```
should be
```
if (stream == NULL)
{
return 0;
}
```
|
for example,
```
int a;
```
Here there is aspacebetween 'int' and 'a'but what can be the separators other than whitespace?
|
You can use a paren:
```
int main() {
int(a);
a = 42;
}
```
but please don't.
|
I need to deal with some data in the following form:
```
typedef struct{
unsigned n1 : 12;
unsigned n2 : 12;
unsigned n3 : 12;
unsigned n4 : 1;
unsigned n5 : 35;
} data;
```
I made sure that in total they count up to 9 bytes.But they don't.. Writing 9 bytes of that struct to a file and reading it back doesn't restore all the data, andsizeof(data)returns 16.What's the problem here ?
|
The problem is some padding is being added by the compiler for efficiency reasons.
This behavior can be overridden.
For how to do this with gcc seeforcing alignment in GCC
For how to do this with visual c++ see:forcing alignment in Visual C++
|
We know eventually everything is transistors which have state0and1.
And the transistor may be damaged sometimes.
Can we test if there's any bit of defect transistors in the memory?
I think it's similar for hardware or anything else.
|
You can't make a definite decision from a process whether a memory cell is bad or not. The way this is usually done by writing known values to memory addresses and checking if they're identical when read back in. Tools likememtest86work on that principle.
|
My daemon initializes itself in four different threads before it starts doing its things. Right now I use a counter which is incremented when a thread is started and decremented when it is finished. When the counter hits 0 I call the initialization finished callback.
Is this the preferred way to do it, or are there better ways?I'm using POSIX threads (pthread) and I just run awhilecycle to wait for the counter to hit 0.
Edit:pthread_barrier_*functions are not available on my platform although they do seem to be the best choice.
Edit 2:Not all threads exit. Some initialize and then listen to events. Basically the thread needs to say, "I'm done initializing".
|
A barrier is what you need. They were created for that, when you need to "meet up" at certain points before continuing. See pthread_barrier_*
|
```
#include<stdio.h>
int main()
{
int i = 10;
int *p = &i;
printf("\n address of initialized pointer p: %u \n", p);
p = &(*p);
printf("\n modified address of initialized pointer p:%u value:%d valuez address: %d \n", p, *p, &(*p));
return 0;
}
```
the code outputs:-
address of initialized pointer p: 3221221820
modified address of initialized pointer p:3221221820 value:10 valuez address: -1073745476
Why is "&(*p)", behaving differently when used in a assignment statement and in a printf statement ?
UpdateSorry, just format specifier mistake in printf ;).Thanks for the replies and pointing out.
|
You are using incorrect format specifier in printf. Using%dfor printing addresses won't work. Use%prather. [%ufor printing address isn't correct either.]
Thisworks as per expectation.
|
I used to usefflush(stdin). I read that this is not a good way to get rid of the extra characters and that it is better to use fgets like this:
```
fgets(buffer,maxsize,stdin);
```
In cases that I want to dispose of those extra chars...what kind of buffer should I use? Could I redirect in some kind of "buffer of no return"? Or do I have to use a finite size array?
Thanks in advance.
|
http://c-faq.com/stdio/stdinflush2.html
|
what's the meaning ofVOID()
There are the following C code, but what's it's meaning?
```
VOID(pthread_mutex_init(&tina_mutex,MY_MUTEX_INIT_FAST));
```
|
Looks like a preprocessor macro. Your editor should be able to find what it is. Or try
```
gcc -E source.c > source2.c
```
It runs the preprocessor only and replaces macros with what they really evaluate to.
|
Can someone explain what specifically needs to be done in exercise 5.17, what does it mean to sort within line, its field?
|
I don't have my copy of K&R here. I think it means this
Suppose the original file has
```
0000087423 Volkswagen 2001-01-01
0000642396 Fiat 2002-02-02
3900063521 Renault 2003-03-03
```
It is already sorted by the 1st field; if you want to sort it by the 2nd field (the name) the result would be
```
0000642396 Fiat 2002-02-02
3900063521 Renault 2003-03-03
0000087423 Volkswagen 2001-01-01
```
Or you can sort by date (the 3rd field)
|
I am working with optimizing a single C object file with regards on the footprint. I'm using the compiler arm-elf-gcc, as the target platform is for a ARM-926EJ processor.
I want to document the current size and then compare after the optimization and I'm wondering, why does arm-elf-size return a size that is smaller then the actual size of the object file?
This is what I get with arm-elf-size
text data bss dec hex filename15656 29188 0 44844 af2c hyper.o
And the actual size of the hyper.o file is 54 168 bytes.
Which one should i look at?
Best Regards
Mr Gigu
|
The object file has headers which aren't part of the segments sizes reported by elf-size.
|
I'm developing a C program and oddly as I update the source files I don't see any change in the resulting executable. Is it possible gcc stores a cached copy of the files and even if I compile I don't get the newer version of my executable? In this case how can I force the compiler to use the newly edited files?
I am compiling my code with the following:
```
# gcc -o myExecFileName source_file_1.c source_file2.c
```
|
To answer your question, no gcc will not cache your files. Something else is going on. You are either changing files in a different directory as @Lee D suggests, or you are not saving the files before compiling, or perhaps the changes you are making are ifdef'd out.
|
Is it possible to cross-compile for OpenVMS(i64) on Unix host and just transfer the executable to OpenVMS server? If it is possible, how do you do it?
|
No it is not possible.
It is however possible, providing the compiler is available on both Unix and OpenVMS (and many are), to develop the software on HP Unix and then copy the source to VMS and compile. Can't say I have ever done it and when I looked into it, I think the Unix was Digital Unix rather than HP Unix, so you may have to do some research there.
There is also a couple of web sites where you can compile source code for VMS...I think HP has one, and there is also the Deathrow Cluster which provides such a facility I believe.
|
Inthe documentationfor OCIAQDeq() it states:
The application may choose to pass
NULL for payload the first time
OCIAQDeq() is called, and let the OCI
allocate the memory for the payload.
It can then use a pointer to that
previously allocated memory in
subsequent calls to OCIAQDeq().
Does anyone have an example of how to use this feature? If I pass inNULL, where do I subsequently get the pointer from? Thanks!
|
This piece of the documentation refers to thepayloadparameter of the function which is a double pointer:dvoid **according to the following
http://files.edin.dk/php/win32/dev/php_build/include/oci805/OCIAP.H
Since it's a double pointer the allocated buffer will be passed back to the caller via the parameter passed in. For example
```
dvoid* pBuffer = NULL;
OCIAQDec(..., &pBuffer, ...);
```
BecauseNULLis passed the function will allocate a buffer and store it into thepBuffervalue which can be later re-used
|
I'm starting out with Linux programming, and I don't want to learn the gcc.
What buildtools can I use to compile large nested source directories with ease with clang? And cross platform? Cmake looks nice, but there is no mention of how to specify a different compiler.
edit: I'd like to use it with vim.
|
To use clang with cmake, you simply set the CC variable:
CC=clang cmake ...
There's also CXX for the C++ compiler, ie CXX=clang++.
CC/CXX are standard variables and should work with any build system.
|
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.Closed12 years ago.
I was asked this interview question:
what is the quickest way to multiply a number by 7.
she told me not to use any of the+ , - , * , /operators.
In tense,i could not answer the question.
I know the quickest way to multiply a number by 8 isn<<3but cann*7be acheived?
|
Assuming your compiler isn't terrible,n*7.
|
Quoted fromhere:
```
msg.msg_accrights = (caddr_t) &ch->fd;
msg.msg_accrightslen = sizeof(int);
...
n = sendmsg(s, &msg, 0);
```
IMHO&ch->fdcan't be shared between processes(the address offdwon't be available in another process),should transferch->fddirectly,
am I right?
|
You are not sending the address of the fd. You are sending an array (with 1 element in this case). Since only one fd is sent, the address of the filedescriptor itself is used, as there is really no difference between doing that and doing:
```
int fds[1];
fds[1] = ch->fd;
msg.msg_accrights = (caddr_t) fds;
msg.msg_accrightslen = sizeof fds;
```
sendmsg will send the value of that array, so the other end will receive the file descriptor value, not the address of the file descriptor.
|
I've been trying to use the system call "ptrace" (using the PTRACE_SINGLESTEP macro) to trace the execution of a simple application.
While recording the execution of the program I would like to skip the useless part of the reading to only follow from the 'main' of my application. Because whenever I launch my tracer I get around 100k execution steps.
Cordialy
|
You may want to insert a breakpoint atmainentry, wait for aSIGTRAPto arrive, restore the instruction under the breakpoint, and single-step from there.
|
Like so:
```
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
...
```
Though I've readman fcntl, I can't figure out what it does.
|
It sets theclose-on-execflag for the file descriptor, which causes the file descriptor to be automatically (and atomically) closed when any of theexec-family functions succeed.
It also tests the return value to see if the operation failed, which is rather useless if the file descriptor is valid, since there is no condition under which this operation should fail on a valid file descriptor.
|
I have a piece of code in C with the following:
```
a = b & ((1<<24) - 1);
```
If I am not mistaking, this is equivalent to:
```
a = b & 0xFFFFFF;
```
What is the benefit in terms of performance to write the first one? For me it is more complicated to read, but I suppose the guy who wrote that had a better C background than I have.
Thanks
|
There is no difference in performance since the compiler will perform the calculation for you.
The first option may be used to explicitly clarify that you are using 24 set bits. This is harder to count in the second option.
|
I know how to sort an array but I haven't sorted a stack before.
So please help. How can I sort a stack using the quicksort algorithm?
Thank you.
|
What do you mean by "sorting a stack"? The whole idea of a stack is that it is in last-in, first-out (LIFO) order. Things that use stacks expect the most recent thing they put on the stack will be at the top of the stack with older things below it, ordered in reverse by when they were inserted because that's what stacksare. If you sort the stack you're going to break that.
|
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.Closed12 years ago.
I need to post one attribute value present in a form to server using curl.
```
<form action="process.php" method="post">
<input tupe="text" name="userName" />
</form>.
```
Now I want to post this form to the server. How can I achive it using curl.
|
you can use the option "-d" for posting data.
```
curl -d "userName=narendra" http://example.com/process.php
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:what does this mean in c int a:16; ?
What does the:1mean here:
```
...
unsigned respawn:1;
unsigned just_respawn:1;
unsigned detached:1;
unsigned exiting:1;
unsigned exited:1;
} ngx_process_t;
```
|
This looks like abit fieldin astruct(the header you omitted). The:1means "1 bit wide", so in your case, they're all booleans. The compiler is supposed to optimize their space usage by packing many of them per byte.
|
```
i=n;
while (i>=1) {
--x=x+1;
--i=i/2;
}
```
What is the running time of this code?
A O(N^2)B O(N^3)C O(N^4)D O (LOG N)E O(2^N)
I believe it is the option D
This is for revision. Not homework
|
This will never terminate as the while condition is
```
i>=i
```
However, assuming you wanted to type
```
i>=1
```
The answer will be log(n).
|
I have seen it used twice already in different libraries as an abbreviation, but I can't wrap my head around what it should mean.
For example here:
```
static int reformat_string(void * ctx, const unsigned char * stringVal,
size_t stringLen)
{
yajl_gen g = (yajl_gen) ctx;
return yajl_gen_status_ok == yajl_gen_string(g, stringVal, stringLen);
}
```
As far as I can tell, it is usually used for structs.
|
It typically stands for "context". Usually this is some structure that gets passed around to functions in a library, used to maintain state (i.e., thecontextof the function call).
It's a preferable alternative to using global variables.
|
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.Closed12 years ago.
I want some ideas on parsing a string into character so that I can do manipulation as needed on the characters of the string.I want ideas,pseudocodes are appreciated.Please dont post any code here.
|
You could loop over all chars in your string, and check for some characters you need to manipulate. A simple draft could look like:
```
char *str = "some-text";
char *p = str;
while ( *p ) {
char ch = *p++;
switch( ch ) {
case '-': manip1(ch);
...
}
}
```
|
Does zlib allow decompressing from the middle of a file?What I mean is, if I callinflatewith a stream that points to the middle of compressed data without callinginflateto the data preceding the middle, would it work?
|
Copy from thezlib FAQ(the emphasis is mine):
28.Can I access data randomly in a compressed stream?No, not without some preparation.If when compressing you periodically useZ_FULL_FLUSH, carefully write all the pending data at those points, and keep an index of those locations, then you can start decompression at those points. You have to be careful to not useZ_FULL_FLUSHtoo often, since it can significantly degrade compression. Alternatively, you can scan a deflate stream once to generate an index, and then use that index for random access. See examples/zran.c.
|
I am sorry I am repeating a questionhttps://stackoverflow.com/questions/5687837/monitor-implementation-in-cbut not getting a solution as yet. I have probably asked the question incorrectly.
Say I have a code portion B. A parent process spawns a number of child processes to execute code B but I would like only one process to be inside code portion B at a time. How can I do it in C on Linux platform?
Thanks for your help
An edit. Not threads but process.
|
You want a mutex.
```
pthread_mutex_t mutexsum;
pthread_mutex_init(&mutexsum, NULL);
pthread_mutex_lock (&mutexsum);
// Critical code
pthread_mutex_unlock (&mutexsum);
```
If you are serious about it being multiple processes instead of multiple threads, the mutex needs to be stored in a shared memory segment.
|
gcc version 4.3.3 under Ubuntu Linux 9.04 in case that is relevant.
This is the offending code:
```
pthread_cleanup_push(ctl_cleanup, NULL);
```
with ctl_cleanup() defined as
```
void* ctl_cleanup(void *arg);
```
There are other instances where this warning pops up, in similar circumstances. The warning also appears if I call something like
```
pthread_cleanup_push(pthread_mutex_unlock, (void *)&m);
```
where m is of type pthread_mutex_t. The warning reads:
warning: initialization from incompatible pointer type
I don't understand. I've passed other things around using void pointers (e.g. when passing arguments to a pthread) without that warning. Can someone help me out?
|
```
void ctl_cleanup(void *arg);
```
The above is the prototype you are looking for. It returns void, not a pointer to void.
The extra * in the function is because it takes a pointer to a function taking one void* argument returning void.
|
Here's all .h files I've included so far,but non have the definition ofbool:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
#include <event.h>
```
Which file does definebool?
|
It's part ofC99and defined inPOSIX definition stdbool.h.
|
How do you map a single UTF-8 character to its unicode point in C?
[For example,Èwould be mapped to00c8].
|
If your platform'swchar_tstores unicode (if it's a 32-bit type, it probably does) and you have an UTF-8 locale, you can callmbrtowc(from C90.1).
```
mbstate_t state = {0};
wchar_t wch;
char s[] = "\303\210";
size_t n;
memset(&state, 0, sizeof(state));
setlocale(LC_CTYPE, "en_US.utf8"); /*error checking omitted*/
n = mbrtowc(&wch, s, strlen(s), &state);
if (n <= (size_t)-2) printf("%lx\n", (unsigned long)wch);
```
For more flexibility, you can call theiconvinterface.
```
char s[] = "\303\210";
iconv_t cd = iconv_open("UTF-8", "UCS-4");
if (cd != -1) {
char *inp = s;
size_t ins = strlen(s);
uint32_t c;
uint32_t *outp = &c;
size_t outs = 0;
if (iconv(cd, &inp, &ins, &outp, &outs) + 1 >= 2) printf("%lx\n", c);
iconv_close(cd);
}
```
|
I have to replacexmlnswithnsin my incomming xml in order to fix SimpleXMLElements xpath() function. Most functions do not have a performance problem. But there allways seems to be an overhead as the string grows.
E.g.preg_replaceon a 2 MB string takes50msto process, even if I limit the replaces to1and the replace is done at the very beginning.
If Isubstrthe first few characters and just replace that part it is slightly faster. But not really that what I want.
Is there any PHP method that would perform better in my problem? And if there is no option, could a simple php extension help, that just does Replace => SimpleXMLElement in C?
|
If you know exactly where the offending "x", "m" and "l" are, you can just use something like$xml[$x_pos] = ' '; $xml[$m_pos] = ' '; $xml[$l_pos] = ' 'to transform them into spaces. Or transform them intons___(where_= space).
|
I came across a piece of codevoid *p = &&abc;. What is the significance of&&here?
I know about rvalue references but I think&&used in this context is different. What does&&indicate invoid *p = &&abc;?
|
&&is gcc's extensionto get the address of the label defined in the current function.
void *p = &&abcis illegal in standard C99 and C++.
Thiscompiles with g++.
|
How can I create my own virus signature of a .exe or .lib file? I started my reading certain bytes to the file and then just storing them in another file and manually adding this to a virus scanner. Will this work? thanks
|
There are many different ways to create a signature of a file, one of the simplest, and easiest, is to take a hashing function, like SHA1, and run it against the whole file.
|
I want to call a pure C style function from a dll in my C++ program. I tried casting my function pointer usingreinterpret_castto__cdecland still the calling convention of_stdcallseems to be preserved. I am new to Windows C++ programming.
EditCode from comment
```
reinterpret_cast< Error ( __cdecl*)(int,int)> (GetProcAddress(Mydll::GetInstance()->ReturnDLLInstance(), "add"))(1,10)
```
is my call. The actual function syntax seems to have been declared as
```
Error __cdecl add(int,int);
```
Debugger throws me the errorrun time check failure #0. I am working in Windows-C++
|
I believe the solution to your question is 'extern "C" { ...'
Seehttp://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.3
|
I've heard that you shouldn't define anything in header files, because of the possibility of multiple defines, but if you have include guards, this shouldn't happen, right? What other reasons are there for adding extern to variables?
|
Include guards merely prevent multiple inclusion of a header within a singletranslation unit(akacompilation unit). This does not address the problem of multiple definitions from separate translation units at link time. Hence you should only ever putdeclarationsin header (.h) files, anddefinitionsin source (.c) files.
|
With my compiler (Apple llvm-gg-4.2) this code:
```
void fun1(const char *s)
{
char* t = s+1;
}
void fun2(char *s)
{
char* t = s+1;
}
int main(void)
{
char* a;
fun1(a);
fun2(a);
}
```
gives this warning:
junk.c:3: warning: initialization discards qualifiers from pointer target type
on fun1 but not on fun2. Why?
|
fun1 is taking const char* and is being assigned to char*Whereas fun2 is taking a char* and being assigned to char* which is fine.
If you are assigning a constant pointer to a non-const pointer, this means you can modify the const pointer by using the const pointer
In this case, inside fun1 if you dot[0] = 'a'its not legal because you are modifying const memory, which is why compiler warns you
|
I have to convert word datatype into char* to pass in a function.
Could anyone show me how to do it. IT should be in C and not C++.
Also I need to pass into function something like
2000-3000-2
where 2000 = word datatype
3000 = word datatype
2 = word
and "-"
while function takes char* as an argument.
so basically i need to convert above combination of word datatype into char*.
Any help or criticism will be helpful
|
You are looking forsprintf(), perhaps something like this:
```
sprintf(buffer, "%.4d-%.4d-%d", w1, w2, w3);
```
wherew1,w2andw3are integer variables holding values 2000, 3000 and 2 in your example.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed2 years ago.Improve this question
I recently bought a macbook and was wondering if I can write C and C++ programs on mac without having to install anything more. Say for Java, mac came with a preinstalled version.
Is it the same for C/C++. if yes, can you pls let me know hoe to compile and run a sample program or if not, can you please let me know what stuff to download?
|
You need to install the Mac Developer Tools either from your original Mac OS X disk or bydownloading the latest version. This package includes the GCC compiler collection (supporting the C and C++ languages, amongst others).
|
Writing/reading code seems less stress then preparing a deploy scripts such as ./configure then make and make install for my C application's. How can i make a ./configure file and make files for this following C code? Thank you for your valuable support.
```
@file: main.c:
#include <ptlib.h>
#include <ptlib/video.h>
#ifndef _WIN32
#ifdef H323_H46018
#include "h460/h460_std18.h"
H460_FEATURE(Std18);
H460_FEATURE(Std19);
#endif
#ifdef H323_H46023
#include "h460/h460_std23.h"
#endif
#endif // _WIN32
#define new PNEW
int main()
{
// just assume the above works first
return 0;
}
```
|
Runningautoscanis a good start. It scans your source files and creates an initial configure.ac file (named configure.scan). Also look atifnamesto scan for your #if's.
|
I've seen questions like thisstackoverflowquestion. However, in this and many other discussion like it the end result tends to be spamming keyboard events instead of operating, and being recognized as, a game controller.
I'm pretty certain drivers would be necessary to create that additional functionality. With that in mind, is it possible for a software application to masquerade as an input device like a analog game controller? I'm very new to developing drivers and this is beyond my scope of knwoledge.
|
Take a look athttp://code.google.com/p/vmulti/it implements a virtual joystick (along with some other devices) and also has a basic client api for synthesizing your own input events
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question
How does (exactly) utility like UNIXfilecommand guess the file type?
Are there any source-codes?
|
It uses various heuristics, mainly signatures which are described in a configuration file.
```
man -s 5 magic
```
will gives the file format.
|
Just a quick question: Is there a way to duplicate a file pointer (those returned byfopen()), similar to howdup()duplicates a file handlers returned by functions likeopen()?
Basically, I want to be able to do something like this:
```
FILE *fp = fopen("some_file", "r");
FILE *fp2 = /* do something to duplicate the file pointer */;
fclose(fp); // fp2 is still open
/* do something with fp2 */
fclose(fp2);
```
|
```
FILE *fp2 = fdopen (dup (fileno (fp)), "r");
```
|
Let me explain what the 'which' function does:
From GNU-R help:
which indices are TRUE?Give the ‘TRUE’ indices of a logical object, allowing for array indices.
or showing some code: (GNU-R starts counting indices with 1)
```
> x <- c(1,2,3,1,3,5);
> which(x == 1);
[1] 1 4
> which(x == 3);
[1] 3 5
> ll <- c(TRUE,FALSE,TRUE,NA,FALSE,FALSE,TRUE);
> which(ll);
[1] 1 3 7
```
Does anyone know a similar function in C/C++?
Thanks for your help
rinni
|
You have to understand thatRis vectorised, whereas C first and foremost works on individual atomistic data pieces: a singleint,double, ...
With C++, you can look into STL algorithms with which you approach this.
Lastly, at the R and C++ intersection, ourRcpppackage has some vectorized operations in C++ which mimic some operations; see theRcpp-sugarpdf vignette for more (and/or some of our talks on Rcpp).
|
I have an application which starts 5 threads.
After starting those threads nothing happens in main().
```
main(){
`start thread 1..5
}
```
How do I loop infinitely in main() so my program will run continuously until it gets a signal.
I don't want to use
```
while(true)
```
because it will eat CPU cycle. (As I think )
Edit:
I am using gcc 4
Thread Api :pthread
OS : Linux
|
the simplest would be:
```
while (true) sleep(1000);
```
and the best would be tojoin()all the five threads.
|
suppose I have a Unicode codepoint c (auint32). Is there a way to print this integer to console (as a wide character) without usinglocale.horwchar.h? Thanks.
|
You can try to use
```
printf("%lc", c);
```
though you really need to make sure thatcis awint_t(which requireswchar.h) rather than auint32_t, even though the two are most likely the same type...
|
Assuming I have C function with variable length argument list:
```
int some_func(int arg1 , ... );
```
Is it possible (easy?) to call this function from python using ctypes?
Update:
Implemented suggestion from cedric and that worked like charm:
```
libc = ctypes.CDLL( "/lib64/libc.so.6" , ctypes.RTLD_GLOBAL )
printf = getattr( libc , "printf")
printf("String1:%s int:%d String2:%s double:%lg\n" , "Hello" , 10 , "World" , ctypes.c_double( 3.1415 ))
```
With the ctypes.c_double( ) function as the only minor nuisance. So - all in all this was easier than I though; however I guess the possiblity to fxxx up with va_args remains the same.
|
Assuming you can bind thelibc printf function, that is a really good example of va_args using, I think you'll be able to create a binding with any function.
|
When i use GnuGK/Openh323gk from its telnet session how can i do makecall?
```
$ telnet localhost 7000
;
makecall alias1 alias2
$ ./gnugk -c config.ini -ttt
2011/05/23 11:10:48.957 1 MakeCall.cxx(55) MakeCallEndpoint: Error registering with gatekeeper at "<my public ip>"
2011/05/23 11:10:49.458 1 SoftPBX.cxx(483) GK SoftPBX: MakeCall registration of pseudo-endpoint failed
```
|
GnuGk uses an internal endpoint to initiate calls. This endpoint is treated exactly like any other external endpoint and needs to register with GnuGk.
Your quoted trace lines indicate that this registration fails. Make sure it is not blocked by any authorization rule and that it is using an alias that isn't already used by something else:
```
[CTI::MakeCall]
Endpoint=<free alias name>
```
In a level 3 trace you should be able to see the registration of this internal endpoint and the confirm or reject message from GnuGk.
|
This question already has an answer here:Programmatically obtain DNS servers of host(1 answer)Closed9 years ago.
I want to use in my code local DNS addresses and am looking for a library that would produce it. Is there anything like it or do I have to parse /etc/resolv.conf myself?
Thanks
|
You can usethe resolver functionsas described in the answer tothis questionor read the addresses of name servers from the file/etc/resolv.confwhich is a simple text file, such as
```
# Generated by NetworkManager
nameserver x.x.x.x
nameserver y.y.y.y
```
wherex.x.x.xandy.y.y.yare ip addresses.
|
hello everyone I have this snippet of the code:
```
void writer(void* param){
if(NULL == param){
return;
}
param = (param_t*)param;
...
}
```
is it safe code, or not, param is from type param_t*, but I'm sick doing every time casting when I use it in function, do Somebody have another elegant solution? thanks in advance
|
That is a strange no-op.
When you define the function you say param is of typevoid*.Then, with the cast, you explicitly convert it toparam_t*And the compiler implicitly converts thatparam_t*tovoid*with the assignment.
You need another variable
```
void writer(void *param) {
param_t *internal_param;
if (NULL == param) return;
internal_param = param;
/* ... */
}
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:What is the difference between sigaction and signal?
It seems to me that both of them can be used to register a callback for a specific signal.
How do you choose which one to use?
|
TLPI
UNIX systems provide two ways of
changing the disposition of a signal:signal()andsigaction(). The
sigaction() system call is an
alternative to signal() for setting
the disposition of a signal. Although
sigaction() is somewhat more complex
to use than signal(), in return it
provides greater flexibility.
sigactionis also more portable thansignal. Also, withsigactionyou can specify signal handlers that receive additional arguments (sa_sigactionversussa_handler).
```
/* can be installed by signal / sigaction */
void(*) (int);
/* can be installed by sigaction only */
void(*) (int, siginfo_t *, void *);
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Best way to detect integer overflow in C/C++
If I have an expressionx + y(in C or C++) wherexandyare both of typeuint64_twhich causes an integer overflow, how do I detect how much it overflowed by (the carry), place than in another variable, then compute the remainder?
|
The remainder will already be stored in the sum of x + y, assuming you are using unsigned integers. Unsigned integer overflow causes a wrap around ( signed integer overflow is undefined ). See standards reference from Pascal in the comments.
The overflow can only be 1 bit. If you add 2 64 bit numbers, there cannot be more than 1 carry bit, so you just have to detect the overflow condition.
For how to detect overflow, there was a previous question on that topic:best way to detect integer overflow.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.