question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
How can I generate a random boolean with a probability ofp(where 0 <= p <= 1.0) using the C standard libraryrand()function?
i.e.
```
bool nextBool(double probability)
{
return ...
}
```
|
```
bool nextBool(double probability)
{
return (rand() / (double)RAND_MAX) < probability;
}
```
or (after seeing other responses)
```
bool nextBool(double probability)
{
return rand() < probability * ((double)RAND_MAX + 1.0);
}
```
|
```
char* temp;
temp = (char*) malloc (strlen(window->entry.value)+1);
//strncpy( temp, window->entry.value, sizeof(temp) ); DOESN"T WORK
memcpy (temp, window->entry.value, strlen(window->entry.value) + 1); //WORKS
```
(where window->entry.value is a string.)
Thanks.
|
sizeof(temp)doesn't do what you think it does. It tells you the size, in bytes, of a pointer to char, which is whattempis. Most likely on your system either 4 or 8.
This has nothing to do with the length of any particular string, or the size of any particular buffer returned frommalloc.
It's pure fluke that you've passed the right length when usingmemcpy, and the wrong length when usingstrncpy.memcpywould also not work if passedsizeof(temp)as the length, andstrncpywould work if passed the right length.
|
hi all is it possible to declare to native methods in java so that one method is defined in c and other method is defined in c++.m getting confusion in it . please help me in this.
|
Yes. As long as the interface uses the standard C calling convention, Java doesn't really care in which language it's implemented. That means you have to surround the declarations in anextern "C"block if you happen to be writing C++:
```
#include <jni.h>
#ifdef __cplusplus
extern "C" {
JNIEXPORT jstring MyNativeMethod(JNIEnv *, jobject);
}
#endif
```
It's up to you whether to implementMyNativeMethodin C, C++ or any other language.
Of course, this is already done for you in the header file generated byjavah,extern "C"and all.
|
Is it posible to use the type of a prefiously declared function as a function pointer without using a typedef?
function declaration:
```
int myfunc(float);
```
use the function declaration by some syntax as function pointer
```
myfunc* ptrWithSameTypeAsMyFunc = 0;
```
|
Not as per the 2003 standard. Yes, with the upcoming C++0x standard and MSVC 2010 and g++ 4.5:
```
decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0;
```
|
Is there any good tool to generate java (+JNI support if needed) from a header file so that a C or C++ library can be used as-is. Kind of a reverse of javah. The real functionality would be in the C/C++, the Java would be only a shim on top for certain users.
I'm no expert on JNI but as far as I can see Javah forces you to do this back to front. It forces you to have JNI-isms penetrating unecessarily into the C code unless you write a conversion layer yourself. And writing a conversion layer by hand is basically a waste of time, since all the information is there in the header file to begin with.
|
For C, you can useJNA. You do have to declare function signatures redundantly in Java, but do not have to write any glue code. JNA is very easy to use.
For C or C++, you can useSWIG. SWIG is a little more complex to use, but automatically generates Java wrappers for C++ classes. I'm enjoying it.
|
I'm converting a header file for a DLL written in C to Delphi so I can use the DLL.
My question is what is the difference between
```
int* i
```
and
```
int *i
```
I convert the first to
```
i: PInteger;
```
But i'm not sure what the correct conversion is for the second one in Delphi.
from my understanding the first is a simple typed pointer.
The second is a pointer variable. but i'm not sure what the difference is.
|
As far as C goes they both do the same thing. It is a matter of preference.int* ishows clearly that it is an int pointer type.int *ishows the fact that the asterisk only affects a single variable. Soint *i, jandint* i, jwould both createias an int pointer andjas an int.
|
I wish to profile CPU (sample if possible), with as small a performance impact as possible (hence similar to GCC's-pg), binaries compiled with Clang. Is there an alternative that uses instrumentation of the code, or produces output similar to gprof?
|
I received agood answeron theClang mailing list. To summarize, the use ofGoogle Performance Toolswas the best fit.
|
Suppose you have to related structures defined in 2 header files like below:
a.h contents:
```
#include b.h
typedef struct A
{
B *b;
} A;
```
b.h contents:
```
#include a.h
typedef struct B
{
A *a;
} B;
```
In such this case, this recursive inclusion is a problem, but 2 structures must point to other structure, how to accomplish this?
|
Don't #include a.h and b.h, just forward-declare A and B.
a.h:
```
struct B; //forward declaration
typedef struct A
{
struct B * b;
} A;
```
b.h:
```
struct A; //forward declaration
typedef struct B
{
struct A * a;
} B;
```
You might want to think about how tightly coupled the classes are. If they're very tightly coupled, then maybe they belong in the same header.
Note: you'll need to#includeboth a.h and b.h in the.cfiles to do things likea->b->a.
|
I have a loop as follows
```
while(1)
{
int i;
}
```
Doesiget destroyed and recreated on the stack each time the loop occurs?
|
Theoretically, it gets recreated. In practice, it might be kept alive and reinitalized for optimization reasons.
But from your point of view,it gets recreated, and the compiler handles the optimization (i.e, keep it at it's innermost scope, as long as it's apodtype).
|
I have an IP address stored inin_addr_tand I want to create the corresponding string representation of this data type (e.g.in_addr_tto10.0.0.1).
How can I do that?
|
Useinet_ntop()- convert IPv4 and IPv6 addresses from binary to text form.
|
Suppose you have a string which is NOTnullterminated and you know its exact size, so how can you print that string withprintfin C? I recall such a method but I can not find out now...
|
There is a possibility with printf, it goes like this:
```
printf("%.*s", stringLength, pointerToString);
```
No need to copy anything, no need to modify the original string or buffer.
|
I got the most simple code to display sizeof() of a datatype, say an int.
```
#include <stdio.h>
int main() {
printf('%i', sizeof(int));
}
```
No matter what I do, such as put sizeof(int) into an integer, or use 'zu' instead of 'i', it hands me this error:
```
error: invalid conversion from ‘int’ to ‘const char*’
```
Is there something wrong with my compiler? I do not get why I cannot print such a simplesizeof..
EDIT: It seems aprintf('%s', 'foo');STILL tells me I am convertinginttoconst char*, how on earth??
|
```
printf("%zu", sizeof(int));
```
printf, notprintdouble quotes, not single quotes%zu, not%i(becausesizeofreturns an unsigned value, not an integer)
|
I am fairly comfortable coding in languages like Java and C#, but I need to use C for a project (because of low level OS API calls) and I am having some difficulty dealing with pointers and memory management (as seenhere)
Right now I am basically typing up code and feeding it to the compiler to see if it works. That just doesn't feel right for me. Can anyone point me to good resources for me to understand pointers and memory management, coming from managed languages?
|
k&r -http://en.wikipedia.org/wiki/The_C_Programming_Language_(book)
nuff said
|
I am implementing a queue in C. I have a struct like:
```
struct Node {
Node* next;
Node* previous;
// data
}
```
Becausenextandpreviousare just pointers, does it make a difference if I useNode*orint*? eg:
```
struct Node {
int* next;
int* previous;
// data
}
```
|
Not only does it bring clarity to your code (which is important, the larger your project gets), pointer math only works properly if you're doing the math on the correct type. In your instance, adding 1 to a Node* would result in adding sizeof(Node) to the base pointer, which is almost guaranteed not to be == sizeof(int).
For the example you gave, it wouldn't likely matter (but you'll need a cast).. but do yourself a favor and get in the good habit now of using the correct types.
|
When you see a line like:
```
#define IX(i,j) ((i)+(N+2)*(j))
```
is that equivalent to:
```
int IX(int i, int j) {
return ((i)+(N+2)*(j));
}
```
How do you know the return type etc?
|
Macros never get seen by the compiler - the preprocessor replaces the text.
So, when you write:
```
result = IX(5, 3);
```
The compiler will see this:
```
result = ((5)+(N+2)*(3));
```
This can have impacts on behaviour, but it depends on your macro. In this case, not so much (there are also performance and debugging differences, but let's not worry about them here).
Had, for example, you defined your macro like this (note second use ofivariable)
```
#define IX(i,j) ((i)+(i+2)*(j))
```
And called it like so:
```
result = IX(++i, j);
```
Then the macro and function would have different behaviour.
|
Say I write in a file
```
Mesh: 1
Vertices: 345
Indices: 123
V: 1,3,4 1,4,5 ..
Mesh: 2
Vertices: 456
Indices: 42
etc.
```
How do I go about seeking at any position? E.g. I want to go to Vertices: of Mesh 2 or V: of Mesh 3 etc.
What's the proper way to go about these things?
|
You would normally use a binary format. One way would be to allocate a certain amount of space as a header in the file. Here, you put the mesh numbers, vertex and index counts, and an offset into the file where the vertex data begins. You read the header when loading the file, then seek to the appropriate place to read the data you want.
|
is there any nice GNU way how to measure average (worst case, best case) execution time of some command line program? I have image filter, unspecified amount of pictures, filtering them using for-loop in bash. So far I am usingtime, but I can't find a way how to get some statistics.
|
You can send the output of time to some file, and then "work" that file
```
echo "some info" >> timefile.txt
time ( ./yourprog parm1 parm2 ) 2>> timefile.txt
```
|
In the code below, the value of prod is not 9,000,000; it gets a garbage value. Why do we need num1 and num2 to be of type long?
```
#include <stdio.h>
int main()
{
int num1 = 3000, num2 = 3000;
long int prod = num1 * num2;
printf("%ld\n", prod);
return 0;
}
```
|
When num1*num2 is computed, it is stored in an intermediate variable that is of the same type (i.e., an int), which comes up as garbage because it's not big enough. Then, the intermediate variable is stored in a long int, but the computed answer was already turned into garbage.
The solution is to cast one of the arguments of the multiplication.
```
long int prod = (long int)num1 * num2;
```
This way, the intermediate computation will use the bigger of the two types, and store it temporarily as a long int.
|
Can socket send / recv set errno 27 (EFBIG) on Solaris? Under which condition this happens?
|
man recvdoesn't documentEFBIGmeaning that if you see it, you have encountered a bug in the OS. Contact theSunOracle Solaris support.
If you are on the OpenSolaris,the dumb searchreveals that sockets themselves do not returnEFBIG(no matches undersys/common/inet/; compare e.g. with search forENOBUFS). To me that tells that you might:
have a parameter exceeding some safety limit. e.g. classical-1ubytes which would be caught even before reaching the sockets API. (unlikely for that other error codes are used.)use send/recv on a wrong socket/file descriptor.
|
```
struct letter
{
char ch;
struct letter *ptr_next;
}
*ptr_first,*ptr_this;
//ptr this contains the address of the first node and ptr this contains the address of last node added.
```
A word chair has to be inserted in the linked list such that C goes into the first node,h in the second and so on..
The attached picture is the memory diagram to fill.
I also added what i tried.Please guide me if i am wrong.Thanks in advance..
|
the answer to your question: no.
no, because you left one question mark unresolved at ff15.
|
Say we have a struct of an int array, a float array etc. and we need to write them into a binary format file for fast reloading. Can this be done in a simple way?
Should the files be several for each of the array?
|
Unless you have a huge amount of data, just write a standard text format. If you can assume c99 on both ends, use the%aformatter for floating-point data to insulate yourselves from the vagaries of binary-decimal conversion.
If the amount of data is huge, or you need to use a "raw data" format for other reasons, you will want to convert your data into a known endianness before writing, and convert back to the host endianness after reading. Any reasonably sane OS has library routines for doing these conversions.
|
While debugging a C program in Visual Studio 2008, is it possible somehow to get the size of variables (in bytes)?
P.D. Of course I can print sizeof(var) for each of them
|
You can use theImmediate Windowto evaluatesizeof(...)or any other expression while debugging.
|
I am trying to implement shared memory on embedded device with uClinux.
My C source
```
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <errno.h>
//using namespace std;
int main() {
int segment_id;
segment_id = shmget(04, getpagesize(), IPC_CREAT | 0666);
printf("Page size - %d\n",getpagesize());
printf("Error in socket - %d\n",errno);
}
```
I get an error
```
Page size - 4096
Error in socket - 38
```
Can anyone help me?
Thanks.
|
You need to test segment_id value, and use errno only if segment_id == -1.
|
Situation I'm using matchbox keyboard which is X11 based application. When any application is in full screen mode matchbox keyboard cannot be visible as the full screened application is on TOP. So is there a way to launch X11 based application over full screened applictions ?
|
You can look at the source of those GTK functions and see how they are implemented for the X11 backend:
```
gtk_window_set_keep_above()
gtk_window_set_keep_below()
gtk_window_set_transient_for()
```
I think it is the best way to know how you can do that, surely the solution GTK adopted should be portable.
|
I am starting to learn to debug C programs with Visual Studio 2008. When running in debug mode, how is it possible to know the address of a initialized variable? I choose to watch it but can only know about the value. Thanks
|
You can type in a&in front of the variable, which will display it's address.
|
There is a file which is locked by another process for editing.
Is there any way to open the file in exclusive mode using the C program?
|
Yes, kill the other process. An OS otherwise of course does not provide a way to allow you to open a locked file, that would utterly defeat the point of supporting locking.
Fwiw, a pretty common mistake is to try to open a file that another process has opened for writing and specifying only read sharing. Can't work, the other process already gained write access. You must specify read+write sharing.
|
While debugging a C program in gdb I have a breakpoint in a for loop. I cannot print the value of "i" ( I get : No symbol "i" in current context.). I can print the value of all the other variables. Is it normal?
Here is the loop:
```
for (i=0; i < datasize; i++){
if ( feature_mask[i] > 0 ){
k = feature_mask[i] - 1;
if (neighbors[k][nmax-1] != 0){
neighbors[k][nmax-1] = bvalue;
feature_mask[i] = -feature_mask[i];
}
}
}
```
|
It has probably been optimised out of your compiled code as you only usefeature_mask[i]within the loop.
Did you specify an optimization level when you called your compiler? If you were using gcc, then just omit any-Ooptions and try again.
|
I was reading about the licensing of software and one question that came to my mind is that "how software detect the change in system time and block themselves if someone changes system time?". Since there is no other reference available(provided we don't have internet connection, otherwise we can use time servers as reference), how such software manages to do it? Are there standard algorithms or any standard libraries(C/C++) available for implementing the same. Please suggest.
|
You cannot assume that because the clock goes backwards, it is caused by someone trying to circumvent your licensing.
Consider, for example, the situation where someone accidentally sets the clock way into the future, then resets it to the correct time?
Crippling your software by attempting to time-restrict it is not the right thing to do. Consider making decent software instead.
|
I have the following function in my code:
```
int numberOverflow(int bit_count, int num, int twos) {
int min, max;
if (twos) {
min = (int) -pow(2, bit_count - 1); \\ line 145
max = (int) pow(2, bit_count - 1) - 1;
} else {
min = 0;
max = (int) pow(2, bit_count) - 1; \\ line 149
}
if (num > max && num < min) {
printf("The number %d is too large for it's destination (%d-bit)\n", num, bit_count);
return 1;
} else {
return 0;
}
}
```
At compile time I get the following warning:
```
assemble.c: In function ‘numberOverflow’:
assemble.c:145: warning: incompatible implicit declaration of built-in function ‘pow’
assemble.c:149: warning: incompatible implicit declaration of built-in function ‘pow’
```
I'm at a loss for what is causing this... any ideas?
|
You need to includemath.h
Andwhy exactly do we get this warning?
|
Will the right side of the expression get evaluated first or the left ?
```
void main ()
{
int i = 0 , a[3] ;
a[i] = i++;
printf ("%d",a[i]) ;
}
```
|
The order of evaluation of the operands of the assignment operator is unspecified: the operands may be evaluated in any order.
However, this expression (a[i] = i++) yields undefined behavior because you both modifyi(usingi++) and you separately readi(usinga[i]) without a sequence point in between those actions.
|
I'm interested in writing a Gtk application that uses an embedded SVG canvas for graphics, and I'm wondering what the current state-of-the-art is for using SVG in Gtk. I know that it's possible to embed Webkit inside of Gtk, and so that seems like one approach, but I would like to add interactivity to DOM elements in the embedded SVG canvas using C instead of JavaScript, and I'm not sure if the embedded Webkit exposes its DOM APIs to the embedding C context. I'm wondering if there might be a better approach. The last article I was able to find on the subject was from 2004:http://www.osnews.com/story/6460
|
librsvgis the preferred way to draw SVG into GTK+ widgets. However, to my knowledge, it doesn't support any kind of interactivity (only drawing).
Regarding WebKit, it does expose the DOM throughwebkit_web_view_get_dom_document. Have a look at the WebKitGtktestsfor some examples.
|
i m looking for a bayesian network library that work on the iphone.
any tip ?
|
I've never used it, but there's one on Github called BayesianKit:https://github.com/lok/BayesianKit
|
The code cant find any device, I want to know what does pcap_lookupdev() do ? thanks
```
#include <pcap.h>
int main(int argc, char *argv[])
{
pcap_t *handle;
char *dev;// = "eth0";
char errbuf[PCAP_ERRBUF_SIZE];
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
return(2);
}
printf("Device: %s\n", dev);
return(0);
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
return(2);
}
}
```
|
pcap_lookupdev seems to just return the first device it can find(if any) except the loopback device.
Do you run this as root ? Normal users won't be allowed to open or inspect these devices.
Personally I find pcap_lookupdev rather useless as you don't really have control over what device it gives you.
|
Could not find a direct answer to this anywhere. Can someone shed some lights.
Thanks.
|
There's no such command built into the language. Sockets need to be used but they are platform dependent.
|
Why can't we declare a static variable within a structure in the C programming language?
|
In C++, a struct is basically a class with all members public, so a static variable makes good sense there.
In C, a struct is a contiguous chunk of memory with fields. A static variable can not be created without changing that (as to implement a static you need to refer to a single memory location from all structs of that type), and that would be a big difference in complexity without much benefit.
|
In php/perl we can simply say $a='hi" and then $a=1 without needing to declare its type. But there are type casting errors in java for the same.
Why this difference?
|
PHP is dynamically typed, while Java and C are statically typed.
With static typing, type checking can be done at compile time and this can catch many errors, so it's not necessarily a bad thing. This also allows them to be much faster than dynamic languages.
See:http://en.wikipedia.org/wiki/Type_system
|
I'm writing a program to read a file and display the number of lines and words in said file, simple stuff. What I want is to be able to run the program from terminal (running Ubuntu) by simply typing:
count
But I'm not sure how to get the filename into a variable in the C program. Little help please?
Thanks in advance.
|
I think you are looking forargv.
|
iOS / Objective-C: I have a large array of boolean values.
This is an inefficient way to store these values – at least eight bits are used for each element when only one is needed.
How can I optimise?
|
see CFMutableBitVector/CFBitVector for a CFType option
|
I have a function, and I want to pass an array of char* to it, but I don't want to create a variable just for doing that, like this:
```
char *bar[]={"aa","bb","cc"};
foobar=foo(bar);
```
To get around that, I tried this:
```
foobar=foo({"aa","bb","cc"});
```
But it doesn't work. I also tried this:
```
foobar=foo("aa\0bb\0cc");
```
It compiles with a warning and if I execute the program, it freezes.I tried playing a bit with asterisks and ampersands too but I couldn't get it to work properly.
Is it even possible? If so, how?
|
Yes, you can use a compound literal. Note that you will need to provide some way for the function to know the length of the array. One is to have a NULL at the end.
```
foo((char *[]){"aa","bb","cc",NULL});
```
This feature was added in C99.
|
```
#include <Windows.h>
#include <stdio.h>
int count = 0;
FILE* pFile = 0;
long Size = 0;
void *memfrob(void * s, size_t n)
{
char *p = (char *) s;
while (n-- > 0)
*p++ ^= 42;
return s;
}
int main()
{
fopen_s(&pFile, "***", "r+");
fseek(pFile, 0, SEEK_END);
Size = ftell(pFile);
char *buffer = (char*)malloc(Size);
memset(buffer, 0, Size);
fread(buffer, Size, 1, pFile);
fclose(pFile);
memfrob(buffer, Size);
fopen_s(&pFile, "***", "w+");
fwrite(buffer, Size, 1, pFile);
fclose(pFile);
}
```
Hi, fread isn't reading anything from file to buffer and I can't figure out why. Could someone give me a hint or a push in the right direction?
|
You need to seek back to the beginning of the file before you fread.
|
I am writing a udp chat application in c. I need to test if messages are received in an incorrect order. CAn anyone please tell me of a tool I can use to delay certain messages? also please tell me how to use it? thank you very much in advance! also I am using ubuntu x86_64 and OSX 10.6.4. A tool in either OS will work
|
When I created a syslog server I needed to see if it was catching the messages.
I usedWiresharkfromhttp://www.wireshark.org/. This is a free tool that shows you all traffic passing your network cable. Even packages not intended for your computer.
Have fun...
|
I wish to Call mysql_real_escape on each argument of a vararg list before it is then passed on to vsprintf to include into an SQL string, is there anyway I can do this easilly?
Seems I missed prepared statements, this seems to be usefull though anyway.
|
Callva_start()(andva_end()) twice.
The first time in a loop withva_arg()inside to test (and change) each argument;and the next time forvsprintf
```
/* check args */
va_start(val, parm);
while (MORE_ARGUMENTS) {
arg = va_arg(val, char*);
/* mysql_real_escape(arg); */
}
va_end(val);
/* print */
va_start(val, parm);
vsprintf(buf, FORMAT_STRING, val);
va_end(val);
```
|
I have the following function in my code:
```
int numberOverflow(int bit_count, int num, int twos) {
int min, max;
if (twos) {
min = (int) -pow(2, bit_count - 1); \\ line 145
max = (int) pow(2, bit_count - 1) - 1;
} else {
min = 0;
max = (int) pow(2, bit_count) - 1; \\ line 149
}
if (num > max && num < min) {
printf("The number %d is too large for it's destination (%d-bit)\n", num, bit_count);
return 1;
} else {
return 0;
}
}
```
At compile time I get the following warning:
```
assemble.c: In function ‘numberOverflow’:
assemble.c:145: warning: incompatible implicit declaration of built-in function ‘pow’
assemble.c:149: warning: incompatible implicit declaration of built-in function ‘pow’
```
I'm at a loss for what is causing this... any ideas?
|
You need to includemath.h
Andwhy exactly do we get this warning?
|
Will the right side of the expression get evaluated first or the left ?
```
void main ()
{
int i = 0 , a[3] ;
a[i] = i++;
printf ("%d",a[i]) ;
}
```
|
The order of evaluation of the operands of the assignment operator is unspecified: the operands may be evaluated in any order.
However, this expression (a[i] = i++) yields undefined behavior because you both modifyi(usingi++) and you separately readi(usinga[i]) without a sequence point in between those actions.
|
I'm interested in writing a Gtk application that uses an embedded SVG canvas for graphics, and I'm wondering what the current state-of-the-art is for using SVG in Gtk. I know that it's possible to embed Webkit inside of Gtk, and so that seems like one approach, but I would like to add interactivity to DOM elements in the embedded SVG canvas using C instead of JavaScript, and I'm not sure if the embedded Webkit exposes its DOM APIs to the embedding C context. I'm wondering if there might be a better approach. The last article I was able to find on the subject was from 2004:http://www.osnews.com/story/6460
|
librsvgis the preferred way to draw SVG into GTK+ widgets. However, to my knowledge, it doesn't support any kind of interactivity (only drawing).
Regarding WebKit, it does expose the DOM throughwebkit_web_view_get_dom_document. Have a look at the WebKitGtktestsfor some examples.
|
i m looking for a bayesian network library that work on the iphone.
any tip ?
|
I've never used it, but there's one on Github called BayesianKit:https://github.com/lok/BayesianKit
|
The code cant find any device, I want to know what does pcap_lookupdev() do ? thanks
```
#include <pcap.h>
int main(int argc, char *argv[])
{
pcap_t *handle;
char *dev;// = "eth0";
char errbuf[PCAP_ERRBUF_SIZE];
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
return(2);
}
printf("Device: %s\n", dev);
return(0);
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
return(2);
}
}
```
|
pcap_lookupdev seems to just return the first device it can find(if any) except the loopback device.
Do you run this as root ? Normal users won't be allowed to open or inspect these devices.
Personally I find pcap_lookupdev rather useless as you don't really have control over what device it gives you.
|
Could not find a direct answer to this anywhere. Can someone shed some lights.
Thanks.
|
There's no such command built into the language. Sockets need to be used but they are platform dependent.
|
Why can't we declare a static variable within a structure in the C programming language?
|
In C++, a struct is basically a class with all members public, so a static variable makes good sense there.
In C, a struct is a contiguous chunk of memory with fields. A static variable can not be created without changing that (as to implement a static you need to refer to a single memory location from all structs of that type), and that would be a big difference in complexity without much benefit.
|
In php/perl we can simply say $a='hi" and then $a=1 without needing to declare its type. But there are type casting errors in java for the same.
Why this difference?
|
PHP is dynamically typed, while Java and C are statically typed.
With static typing, type checking can be done at compile time and this can catch many errors, so it's not necessarily a bad thing. This also allows them to be much faster than dynamic languages.
See:http://en.wikipedia.org/wiki/Type_system
|
I'm writing a program to read a file and display the number of lines and words in said file, simple stuff. What I want is to be able to run the program from terminal (running Ubuntu) by simply typing:
count
But I'm not sure how to get the filename into a variable in the C program. Little help please?
Thanks in advance.
|
I think you are looking forargv.
|
iOS / Objective-C: I have a large array of boolean values.
This is an inefficient way to store these values – at least eight bits are used for each element when only one is needed.
How can I optimise?
|
see CFMutableBitVector/CFBitVector for a CFType option
|
I have a function, and I want to pass an array of char* to it, but I don't want to create a variable just for doing that, like this:
```
char *bar[]={"aa","bb","cc"};
foobar=foo(bar);
```
To get around that, I tried this:
```
foobar=foo({"aa","bb","cc"});
```
But it doesn't work. I also tried this:
```
foobar=foo("aa\0bb\0cc");
```
It compiles with a warning and if I execute the program, it freezes.I tried playing a bit with asterisks and ampersands too but I couldn't get it to work properly.
Is it even possible? If so, how?
|
Yes, you can use a compound literal. Note that you will need to provide some way for the function to know the length of the array. One is to have a NULL at the end.
```
foo((char *[]){"aa","bb","cc",NULL});
```
This feature was added in C99.
|
```
#include <Windows.h>
#include <stdio.h>
int count = 0;
FILE* pFile = 0;
long Size = 0;
void *memfrob(void * s, size_t n)
{
char *p = (char *) s;
while (n-- > 0)
*p++ ^= 42;
return s;
}
int main()
{
fopen_s(&pFile, "***", "r+");
fseek(pFile, 0, SEEK_END);
Size = ftell(pFile);
char *buffer = (char*)malloc(Size);
memset(buffer, 0, Size);
fread(buffer, Size, 1, pFile);
fclose(pFile);
memfrob(buffer, Size);
fopen_s(&pFile, "***", "w+");
fwrite(buffer, Size, 1, pFile);
fclose(pFile);
}
```
Hi, fread isn't reading anything from file to buffer and I can't figure out why. Could someone give me a hint or a push in the right direction?
|
You need to seek back to the beginning of the file before you fread.
|
I am writing a udp chat application in c. I need to test if messages are received in an incorrect order. CAn anyone please tell me of a tool I can use to delay certain messages? also please tell me how to use it? thank you very much in advance! also I am using ubuntu x86_64 and OSX 10.6.4. A tool in either OS will work
|
When I created a syslog server I needed to see if it was catching the messages.
I usedWiresharkfromhttp://www.wireshark.org/. This is a free tool that shows you all traffic passing your network cable. Even packages not intended for your computer.
Have fun...
|
I wish to Call mysql_real_escape on each argument of a vararg list before it is then passed on to vsprintf to include into an SQL string, is there anyway I can do this easilly?
Seems I missed prepared statements, this seems to be usefull though anyway.
|
Callva_start()(andva_end()) twice.
The first time in a loop withva_arg()inside to test (and change) each argument;and the next time forvsprintf
```
/* check args */
va_start(val, parm);
while (MORE_ARGUMENTS) {
arg = va_arg(val, char*);
/* mysql_real_escape(arg); */
}
va_end(val);
/* print */
va_start(val, parm);
vsprintf(buf, FORMAT_STRING, val);
va_end(val);
```
|
I have to open a file using ZwOpenFile API. This is my requirement. When I set the path in object name parameter. I could see fields Length and maximumlength in the object name.
Length is just length of the path and I usually keep maximumlength as the value of Length.
It worked mostly, however some times it doesnot work. In some cases I solved it via maximumlength = length *2. Even this computation doesn't work for few other cases.
I am very much puzzled with the Maximumlength value computation.
Can some one help.
|
Look at UNICODE_STRING structure definition:link
Length is wcslen(str.Buffer) * sizeof(WCHAR) == * 2
MaximumLength field may be Length + sizeof(WCHAR) == Length + 2
ZwOpenFile will not write to this string, so we shouldn't care about capacity of string.
|
I feel like writing a (rich) text editor mainly to be used for note-taking, in either C or C++, using most probably GTK or Qt for the UI.
The problem is that I can't really decide what to use. I know both C and C++, C a little better. I've never used Qt but I'm completely fine with learning, and I have some experience with GTK.
Is there any particular combination you would give preference to and why? In particular, do you think there is any advantage to using C++, or will C do just fine?
|
I'm writing an editor myself, and I too have choose C++ and Qt.
The reasons for this:
C++ is CPU- and memory-efficient. Ihateslow text editors with a passion.Supporting libraries are almost always written in C or C++, so I can interface nicely with them (and extend them if needed).Qt is a great, well supported, cross-platform/-system GUI library, and it contains a lot of generally useful base classes/algorithms. It makes C++ actually fun to use.
|
Just a quick question: What are people's practices when you have to define the (arbitrary) maximum that some array can take in C. So, some people just choose a round number hoping it will be big enough, others the prime number closer to the round number (!), etc., other some more esoteric number, like the prime number closer to... and so on.
I'm wondering, then, what are some best practices for deciding such values?
Thanks.
|
There is no general rule. Powers of twos work for buffers, I use 1024 quite often for string buffers in C but any other number would work. Prime numbers are useful for hash tables where simple modulo-hashing works well with prime-number sizes. Of course you define the size as a symbolic constant so that you can change it later.
|
I am just doing a little work this morning making some static libraries. Why do static libraries end with '.a'?
No one in my office knew, so I thought I would ask around on Stack Overflow. We are writing code in C++, C, and Objective-C.
|
I think the .a convention comes from using an "archiver" to place the object files into a static library.
|
what 0 indicates in following line?
what are other flags i can use?
```
server = socket(AF_UNIX, SOCK_STREAM, 0)
```
|
As others have likely said, the third argument tosocketis generally anintindicating the protocol.0indicates that the caller does not want to specify the protocol and will leave it up to the service provider.
Other than zero, another common one isIPPROTO_TCP.
Full details can be found on the man page usingman 2 socketon your machine or visitinghere.
|
It's a beginners question: Why is this breaking/giving an error?
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strtrim_right(char *p)
{
char *end;
int len;
len = strlen( p);
while (*p && len)
{
end = p + len-1;
if(isalpha(*end))
*end =0;
else
break;
}
return(p);
}
int main ()
{
char *x="PM123BFD";
strtrim_right(x);
printf("%s", x);
return 0;
}
```
|
Change
```
char *x="PM123BFD";
```
to
```
char x[]="PM123BFD";
```
You cannot modify a string literal, so instead pass the function achararray which it can modify.
|
I have a C array in Objective C defined as follows:
```
id keysArray;
```
Then in an if block, i would like to redefine the array based on a condition:
```
if (somethingIsTrue){
id keysArray[4][3];
}
else {
id keysArray[6][1];
}
```
Then outside of the if block, when i access the array, i get errors saying thekeysArraydoes not exist.
Thanks.
|
That's because when you leave the scope of the if, all local variables defined within that scope are destroyed. If you want to do this, you will have to use dynamic allocation. I don't know the Objective C way of doing things, but in regular C you shall use malloc.
|
I need to be able to unzip some AES (WinZip) encrypted zip files from within some C/C++ code on Windows. Has anybody got a way to do this? I'm hoping for either some appropriate code or a DLL I can use (with an example usage). So far my searches have proved fruitless.
The commonly prescribed InfoZip libraries do not support AES encryption.
The best solution I have at the moment is calling the 7z.exe command line program from my program, but considering I'll be unzipping 100 files or so, this is less than ideal.
|
Here is the minizip zlib contribution with AES support for both encryption and decryption.https://github.com/nmoinvaz/minizip
|
Hi I'm trying to compile about 30 C sources written in 1997.
Based on required header files such as XmAll.h and Xlib.h and the use of "Widget" syntax, I found that these sources depend on the Motif programming tool kits, so it seems they should be compiled in Linux or Unix system.
I have no any experience with X Windows Programming and Motif programing, but I must compile them.
I really tried to compile them in Mac OSX or Windows, but of course it didn't work.
Do I have to install Linux as virtual OS first and install Open Motif in it to compile them?
Could you give any other suggestion?
Thank you so much!
Kyu
|
If you want to build it on Windows, you could try installingCygwin- when you're selecting packages, you'll need all the build tools (likegcc,make...), X11 (eg.xorg-server), andlesstif(Open source Motif clone).
You will probably need to be prepared to massage the source a bit - I doubt it will work "out of the box".
|
I am a beginner in C++
I am average at C.
I have written the following code in C++ (file.cpp)
```
#include <iostream>
int main(){
std::cout<<"My name is ANTHONY";
}
```
Then I tried to compile the above code usingcpp file.cppbut got some errors.
I don't know whats wrong
When I tried to compile my C program (changed<iostream>to<stdio.h>andstd::couttoprintf) using cc file.c, I didn't get any errors.
What is happening here?
|
Then I tried to compile the above code usingcpp file.cppbut got some errors.
That is becausecppisC(C++)preprocessor. It is a separate program invoked by the compiler (g++) as the first part of translation.
Try compiling your code usingg++ file.cpp. :)
|
Is is possible to put something at the top of the C source file, like
```
// GCC_OPTIONS=-g,-Wall
```
that will add those options automatically to gcc every time you compile this file?
|
Yes it is, at least for some flags. You can push and popdiagnostic settingslike this:
```
#pragma GCC diagnostic error "-pedantic"
#pragma GCC diagnostic warning "-Wall"
```
This is also possible foroptimization levels on a per-function level:
```
#pragma GCC optimize ("string"...)
```
These#pragmadefinitions affect all code after them in a source file.
See these other questions for more information:
Switching off optimization for a specific function in gcc 4.2.2Selectively disable GCC warnings for only part of a translation unit?
|
I'm wondering which is the better way to catch exceptions that I throw: is it a __try / __except block or a try / catch block?
I'm writing in C++ and the program will only be used on Windows, so portability is not an issue.
Thanks!
|
They are twoverydifferent things. try/catch are the familiar C++ keywords you know.__try/__exceptis used to catch SEH exceptions. Exceptions raised by Windows itself, like DivisionByZero or AccessViolation. It is well described in theMSDN Library articlefor it.
You can also use it to catch C++ exception because it leverages the Windows SEH feature. You however can't get the thrown exception object out of it so there will be zero context if you actually want the handle the exception. Which is madness. The number one approach is to not ever catch SEH exceptions, they are always gross. If you do need to marry the two then use _set_se_translator() to convert the SEH exception to a C++ exception.
|
The following program doesn't output desired data (on VC2008 compiler)
```
#include <stdio.h>
#include <string.h>
int main(void)
{
int i;
int dest[10] = {1};
int src [] = {2, 3, 4, 5, 6};
memcpy(dest, src, 5);
for (i=0; i<10; i++) printf("%i\n", dest[i]);
return 0;
}
```
whereas usingchararrays instead, every thing goes fine!
where is the problem here?
|
memcpy takes a number of bytes to copy - not a number of objects.
```
memcpy(dest,src,5*sizeof(dest[0]))
```
|
Is there a way to sort an array of strings in alphabetical order where the strings contain both capital and lowercase letters?
Because capital letters have a lower ASCII value so functions like strcmp would always show that it is before a lower case letter. For example, lets say we wanted to sort "ABCD", "ZZZZ", "turtle", "JAVA", "water".
When using functions like strcmp to sort these strings, it becomes:
ABCD
JAVA
ZZZZ
turtle
water
when it should be:
ABCD
JAVA
turtle
water
ZZZZ
|
Use qsort with either strcasecmp or strcoll as the compare function.
strcasecmp is likely to be faster, but strcoll is more flexible and uses the programs locale so that non-ASCII strings work.
|
Currently I have a command line OSX executable that I am compiling in xcode. I'm wondering if there is a way to call functions / interact with a flash or flex project. I found some information about a flex c++ bridge, but apparently it is only for windows.
Can this be done with air?
|
I don't know of any way to call C functions directly, butAIR has a "native process API"for "communicating with native processes using standard input and output", which can work with a command line executables.
|
When I continuously do "step into",it switches between different threads.
But how's that scheduled in visual studio,how does it know which thread to activate for next instruction?
|
It's not up to Visual Studio which thread runs next, it's up to the Windows scheduler. There's usually a way to "freeze" the other threads in the process so that they won't run while you're trying to look at a particular thread, though I don't know how to do it in Visual Studio.
-scott
|
Is there any C compiler which takes the default type of char as unsigned unless explicitly mentioned by the user in the file or project settings?
/Kanu_
|
GCC does. But only when compiling for platforms where an unsigned char is the convention, including ARM linux[*]. When GCC compiles for x86, the default is for char to be signed.
[*] Or at least it has been in the past. For all I know linux has switched to a different default ABI on ARM since.
Update '2013:ARM compilers (gcc, clang) for Android NDK default tounsigned char. The x86 and MIPS compilers default tosigned char.
|
I am trying to compile ncurses-5.7 from source and after running ./configure I get the following error:
```
configure: error: Your compiler does not appear to recognize prototypes.
You have the following choices:
a. adjust your compiler options
b. get an up-to-date compiler
c. use a wrapper such as unproto
```
how can I fix this error?
|
As configure output suggests, you should either install an HPUX version of gcc or use unproto as a wrapper
|
Does a good manual exist for the standard C libraries? Like man for Linux or Java API.
Edit
I am working in Visual Studio 2010 Express.
I prefer something like Java API to see all libraries and not like man that show function that I know already exists without giving me the all list of function, and also man not exist in Windows.
Thanks
|
If you are working on Unix systems theGLibC Manualis really good. Although it covers more than is available in standard C
|
I have written a program that prints a table. I have not included the return syntax in the main function, but still whenever I type echo $? it displays 12.
My source code :
```
#include <stdio.h>
int main(void)
{
int ans,i,n;
printf("enter the no. : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
{
ans = n*i;
printf("%d * %d = %d\n",n,i,ans);
}
}
```
I have not written return 12, but still it returns 12 every time I execute the program.
Thanks.
|
As swegi says, it's undefined behavior.As Steve Jessop et al say, it's an unspecified value until C89, and specified in C99 (the observed behavior is non-conformant to C99)
What actually happens in most environments is that the return value from the lastprintfis left in the register used for return values.
So it'll be 11 for n == 0, 12 if n is one digit, 14 for two digit n, 16 for three digit n, etc.
|
How can i make that the console, with the output, will not disapear after the program ends in VS 2010 express C++?
i write in c and not in c++, soo i need a function and include path to library.
Thanks
|
You can simply poll for input. This performs a block so that the function only returns when the user gives more input - usually enter. If you're on Windows you can also use system("PAUSE").
|
How to Generate the random number from 0.5 to 1.0 .
|
You can try:
```
float RandomBetween(float smallNumber, float bigNumber)
{
float diff = bigNumber - smallNumber;
return (((float) rand() / RAND_MAX) * diff) + smallNumber;
}
```
|
Is there a limit on the number of arguments that we pass tomain()in C? As you all know, it is defined asint main(int argc, char *argv[]).
When I call the program, I can pass arguments like so:
```
$ prog.exe arg1 arg2 arg3.....argn
```
Is there an upper bound in the number of argument that we may supply tomain()in this way?
|
According to the POSIX spec forexec, there is a macroARG_MAXdefined in<limits.h>which defines the maximum number of bytes for the arguments + environment variables.
But since C doesn't define anything about that, no, there isn't an inherent cross-platform limit. You have to consult your OS manual if it doesn't define that macro.
|
I could see from MSDN documentations that a new windows service will be stored in the registryHKLM\System\CurrentControlSet\Services
However the services registry key does not hold a value for the "service running status"
Can anyone let me know where the service running status will be stored?
|
The service running status is not stored in the registry - it's a runtime property which you can query withControlService()service management function.
|
Something like this, I'd like to see the full syntax.
Pseudo Code:
```
var = user_input
if var > 5:
output = 'var > 5'
else:
output = 'var < 5'
```
|
How about something along the lines of:
```
#include <stdio.h>
#include <string.h>
int main (void) {
int var;
char buff[100];
printf ("Enter number> ");
fflush (stdout);
if (fgets (buff, sizeof(buff), stdin) == NULL) {
printf ("\nfgets() failed\n");
return 1;
}
if (sscanf (buff, "%d", &var) != 1) {
printf ("\nsscanf() failed\n");
return 1;
}
if (var > 5)
printf ("%d is greater than 5\n", var);
else
printf ("%d is less than 6\n", var);
return 0;
}
```
with a couple of test runs:
```
pax> testprog
Enter number> 99
99 is greater than 5
pax> testprog
Enter number> -5
-5 is less than 6
```
|
What is the C equivalent to the C++cinstatement? Also may I see the syntax on it?
|
cinis not a statement, it's a variable that refers to the standard input stream. So the closest match in C is actuallystdin.
If you have a C++ statement like:
```
std::string strvar;
std::cin >> strvar;
```
a similar thing in C would be the use of any of a wide variety of input functions:
```
char strvar[100];
fgets (strvar, 100, stdin);
```
Seean earlier answerI gave to a question today on one way to do line input and parsing safely. It's basically inputting a line withfgets(taking advantage of its buffer overflow protection) and then usingsscanfto safely scan the line.
Things likegets()andcertain variationsofscanf()(like unbounded strings) should be avoided like the plague since they're easily susceptible to buffer over-runs. They're fine for playing around with but the sooner you learn to avoid them, the more robust your code will be.
|
I have a simple question that I can't find anywhere over the internet, how can I convert UTF-8 to ASCII (mostly accented characters to the same character without accent) in C using only the standard lib? I found solutions to most of the languages out there, but not for C particularly.
Thanks!
EDIT: Some of the kind guys that commented made me double check what I needed and I exaggerated. I only need an idea on how to make a function that does: char with accent -> char without accent. :)
|
Take a look atlibiconv. Even if you insist on doing it without libraries, you might find an inspiration there.
|
There are a lot of example implementations of daemons on the net. Most that I saw do not use the daemon(3) function to run the program in the background. Is that just a matter of taste, ignorance, or is there a good reason to write my own daemonize function? Is there a specific disadvantage in using daemon(3)? Is it insecure?
|
The daemon() function was not historically available in all flavors of Unix, so a lot of "portable" code doesn't use it. There's really no reason to roll your own recipe as long as all the target platforms you care about have daemon().
|
My question's pretty basic, but it's been a while. I'm reading in a text file and saving numbers in the text to a struct 'Record'. After I read text to my Record buffer, I want to place it in an area of memory.
```
typedef struct
{
int line_status[64];
float line_data[64], relativetime;
unsigned long blkhdr_ticks;
} Record;
Record *storage;
storage = (Record*)malloc(nRange*sizeof(Record));
Record buffer;
```
Where nRange is some random number, and buffer is a Record with values, though I haven't listed my code that assigns these to the buffer. I thought the syntax was something like:
```
&storage = buffer;
```
But I know that's not right. Any help would be greatly appreciated.
|
You can also treat storage as an array.
```
storage[0] = buffer;
storage[1] = anotherBuffer;
...
storage[nRange-1] = lastBuffer;
```
|
I want to initialize a two-dimensional array of variable size to zero.
I know it can be done for a fixed-sized array:
```
int myarray[10][10] = {0};
```
but it is not working if I do this:
```
int i = 10;
int j = 10;
int myarray[i][j] = {0};
```
Is there a one-line way of doing this or do I have to loop over each member of the array?
Thanks
|
You cannot initialize it with an initializer, but you canmemset()the array to 0.
```
#include <string.h>
int main(void) {
int a = 13, b = 42;
int m[a][b];
memset(m, 0, sizeof m);
return 0;
}
```
Note: this isC99.InC89the declaration of m (int m[a][b];) is an error.
|
I have a system that returns a void* to a memory block. This memory block stores contiguous data records of different types(int,char,double etc.) and gives the number of bytes of each field in each record.I essentially look up the type of the record and get the value of the record. To retrieve all the records, I do
```
switch(type)
{
case 'int' : \*(int*)(ptr+index)
case 'char': \*(char*)(ptr+index)
}
```
When I have to go through 300000 records this is taking a lot of time.Is there a faster way to go through all the records?
|
If a single block can be of multiple types that can only be resolved at runtime, you will have to dispatch to handlers in aswitchstatement. Note that:
unions are usually used in C for such things to save spaceswitchstatements are very fast and translate to constant-time lookup tables
|
How can I make a copy of a tree data structure in memory to disk in C programming language?
|
You need to serialize it, i.e. figure out a way to go through it serially that includes all nodes. These are often calledtraversal methods.
Then figure out a way to store the representation of each node, together with references to other nodes, so that it can all be loaded in again.
One way of representing the references is implicitly, by nesting like XML does.
|
I have major issue with GNU gdb (GDB) SUSE (6.8.50.20090302-1.5.18).
It takes ages to print the value of a nested symbol and hitting Ctrl-C has no effect.
Do you know the reason? Is there any workaround?
Thanks
|
Try GDB 7.2. There have been many fixes since 6.8, e.g.
```
2009-07-23 Paul Pluzhnikov <[email protected]>
* symtab.c (search_symbols): Add QUIT.
```
The fix above should make Control-C work. Other fixes sped up searching for symbols, so you may not have a reason to hit Control-C in the first place :-)
|
why do i get error: 'strcmp': identifier not found in visual studio 2010 C++ Express
```
#include <string.h>
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d",(int)strcmp( "str1", "str2" ));
return 0;
}
```
Thanks
|
```
:( #include <string.h> :(
#include "stdafx.h"
```
Fun quirk of the MSVC compiler, it generates the exact same error when you compile it like that. Yes, not a lot of 'fun'. It skips everything to find the stdafx.h precompiled header include directive. The string.h doesn't actually get included. Fix:
```
#include "stdafx.h"
#include <string.h>
```
Always put the stdafx.h include first.
|
which visual studio project type should i choose that will best for c basic library(uni studies).
the problem in visual studio 2010 express that its gives _tmain instead int main().
Thanks
|
I usually select "Win32 Console Application" and then "Empty project". Add a new source file and type in the main() by hand.
I have no idea what R is talking about with his absurd comment.
|
I have the following files:a.h,a.c,b1.c,b2.cand in both b1 and b2 I have some macro definitions which are identical.
Is it ok if I move them ina.hor is it more common to leave them in the file where they are being used ? Which way is the proper way to do it in C ?
|
It is common to move macro definitions which are shared between files into a header which both of those files include. You should make sure that the file you move that definition into is a sensible file for it to be in; don't move it into a completely unrelated header just because it's included in both files. If there is no logical related header file for bothb1.candb2.c, perhaps you ought to create ab.hto be shared between them.
|
Recently I reviewed some C code and found something equivalent to the following:
```
struct foo {
int some_innocent_variables;
double some_big_array[VERY_LARGE_NUMBER];
}
```
Being almost, but not quite, almost entirely a newbie in C, am I right in thinking that this struct is awfully inefficient in its use of space because of the array member? What happens when this struct gets passed as an argument to a function? Is it copied in its entirety on the stack, including the full array?
Would it be better in most cases to have adouble *some_pointerinstead?
|
If you pass by value yes it will make a copy of everything.
But that's why pointers exist.
```
//Just the address is passed
void doSomething(struct foo *myFoo)
{
}
```
|
Suppose you have 2 numbers:
```
int x = 1;
int y = 2;
```
Using bitwise operators, how can i representx-y?
|
When comparing the bits of two numbersAandBthere are three posibilities. The following assumes unsigned numbers.
A == B: All of the bits are the sameA > B: The most significant bit that differs between the two numbers is set inAand not inBA < B: The most significant bit that differs between the two numbers is set inBand not inA
Code might look like the following
```
int getDifType(uint32_t A, uint32_t B)
{
uint32_t bitMask = 0x8000000;
// From MSB to LSB
for (bitMask = 0x80000000; 0 != bitMask; bitMask >>= 1)
{
if (A & bitMask != B & bitMask)
return (A & bitMask) - (B & bitMask);
}
// No difference found
return 0;
}
```
|
Under Linux what would be the best way for a program to restart itself on a crash by catching the exception in a crashhandler (for example on a segfault)?
|
simplest is
```
while [ 1 ]; do ./program && break; done
```
basically, you run program until it is return 0, then you break.
|
I've got a Nvidia Tesla s2050; a host with a nvidia quadro card.CentOS 5.5 with CUDA 3.1
When i run cuda app, i wanna use 4 Tesla c-2050, but not including quadro on host in order not to lagging the whole performance while split the job by 5 equally.any way to implement this?
|
I'm assuming you have four processes and four devices, although your question suggests you have five processes and four devices, which means that manual scheduling may be preferable (with the Tesla devices in "shared" mode).
The easiest is to use nvidia-smi to specify that the Quadro device is "compute prohibited". You would also specify that the Teslas are "compute exclusive" meaning only one context can attach to each of these at any given time.
Runman nvidia-smifor more information.
|
```
wprintf(L"Selecting Audio Input Device: %s\n",
varName.bstrVal);
if(0 == wcscmp(varName.bstrVal, L"IP Camera [JPEG/MJPEG]"))
{
...
}
hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, (void **)&pGrabberF);
```
The above is from a .cpp file ,but as you see its content is quite c-style.
Will you call it a c or c++ project?
|
It simply depends how you compile it.
Some code will compile as both, it's considered C++ code if it gets compiled by a C++ compiler.
C is NOT an exact subset of C++by the way.
Often you can deduce with a fast glance simply by the file's extension, although it's possible to put C code in a .cc extension or .cpp extension and you can also put C++ code in a .c extension, but that would be pretty rare.
|
I may miss the obvious, but how/is it possible to retrieve interrupt counters for a specific interrupt without manually parsing/proc/interruptsfrom inside a C/C++ program?
Thanks in advance!
Best regards, Martin
|
/proc/interruptsand/proc/statobtain their data by calling the kernel functionkstat_irqs_cpu(). The only way to read it without opening the files in /proc is, I think, writing your own kernel driver which would call the same function and return the results via ioctl() or some other way.
|
Why does++x || ++y && ++zcalculate++xfirst, even though the precedence of operator&&is higher than||?
|
Huh?
If you're saying that&&binds tighter than||(which is true), the expression is then equivalent to
```
++x || (++y && ++z)
```
Since||short-circuits, it needs to evaluate the left-hand side first.
If you mean that it ought to be equivalent to
```
(++x || ++y) && ++z
```
The same is still true, since&&also short-circuits, meaning the||needs to be evaluated first, which in turn makes++xthe first thing to evaluate.
|
I've a program which links to many libraries.g++, by default, prefers to link to shared libraries, even if the corresponding archive exists.
How can I change this preference to prefer static archives over dynamic libraries, if a static archive exists?
Note, I used-staticoption, but it tries to find static archive for all libraries which is not what I want.
|
```
g++ -Wl,-Bstatic -lz -lfoo -Wl,-Bdynamic -lbar -Wl,--as-needed
```
Will linkzlibandlibfooas static, andlibbaras dynamic .--as-neededwill drop any unused dynamic library.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.