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 ...
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 = ...
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 vis...
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...
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 ...
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...
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...
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'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...
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" ...
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; ...
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...
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: ``` // ...
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...
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 ...
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 = ...
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 vis...
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...
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 ...
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...
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...
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'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...
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" ...
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; ...
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...
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: ``` // ...
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 2...
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...
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");...
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 ...
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); /...
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/pyt...
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...
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 su...
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 t...
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-Function...
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...
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...
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...
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 <s...
``` 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 i...
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 b...
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 ...
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 ...
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 2...
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...
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...
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...
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 e...
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...
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...
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_acc...
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...
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 con...
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 backg...
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 st...
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...
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; retur...
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 stri...
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...
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 pro...
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 appe...
``` 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 = ...
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 ...
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)> (GetPro...
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...
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 no...
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 basicall...
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 wi...
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>...
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 tha...
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 fi...
``` 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,FA...
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 s...
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. (A...
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 ) pri...
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 Sof...
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 u...
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 sol...
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 (NUL...
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 flexi...
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 variabl...
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 b...