question
stringlengths
25
894
answer
stringlengths
4
863
I'm looking at someone's code and they did: if ( myNum > (num1 && num2 && num3) ) ... with the intent of executing code when myNum is greater than num1, num2, and num3. Will this work? edit: Thanks guys. I didn't think it would work, but I'm no expert, so I thought I'd ask people who are.
Assuming the values are of a type likeint, in C or C++ this would first evaluate ``` (num1 && num2 && num3) ``` as ``` (num1 !=0) && (num2 != 0) && (num3 != 0) ``` The result would be eithertrueorfalsein C++, and either 1 or 0 in C. You would then comparemyNumto that result.
I have a struct of values for a date. ``` struct date { int day; int month; int year; }; ``` Are there any libraries for C for quick and easy date validation.
The standard C library functionmktime()will convert year/month/day (really a fullstruct tm) to atime_t, and tell you if something went wrong.
How to call a varargs function via dbus, like printf? The server is written in C, the client is written in Python. My questions are how to write the XML spec file? And how to write my GObject? Thanks in advance. [I use DBus-GLib.]
There is no way to call a variadic function programmatically with varying number and type of arguments. You could use the corresponding "v" functions (vprintfetc.) but there's no way to make theva_listto pass to them from foreign code and pass it over DBus. In any case you really need to rethink your design. It's uns...
``` int a=0; int b=1; int c=a,b; int d=(a,b); ```
Outside of an initialization, the comma ina,bis thecomma operator, and evaluates tob. The parentheses in the line involvingdmakes this such a case. So that line is really just equivalent to: ``` int d = b; ``` However, in the line involvingc, this is not a use of the comma operator. Instead, it's just a list of v...
Can anyone explain me the double order traversal? ``` A / \ B E / \ / \ C D F G ``` Double order Traversal output : ABCCBDDAEFFEGG I'm interested in explanation rather than the code. Thanks
Assuming you're interested in an explanation of what a double-order traversal does: For each traversal, you Visit NodeTraverse Left ChildVisit NodeTraverse Right Child That's all there is to it. In cases where you don't have a left child (like C, for example), the two "visit node" operations happen back to back, wh...
What is the fastest integer sort implementation for 200-300 bit sized integers? Exact int size is fixed; I have up to 2 gigabytes with such integers (all in RAM). I hear that it is possible to sort such set in average at O(n log log M) or even at O(n sqrt(log log M)) time, wher n is number of integers and M is the la...
ARadix Sortcan be used to sort data with fixed size keys. As this condition is not often met the technique isn't discussed much, but it can be O(n) when the key size is factored out.
I was wondering if there was a way to lower the color scheme of an image. Lets say I have an image that has 32bit color range in the RGB. I was wondering if it would be possible to scale it down to perhaps an 8 bit color scheme. This would be similar to a "cartoon" filter in applications like photoshop or if you chang...
If you want the most realistic result take a look atcolour quantisation. Basically find the blocks of pixels with a similar RGB colour and replace them with a single colour, you are trying to minimize the number of pixels that are changed and the amount each new pixel is different from it's original colour - so it's a...
Given the following C++ code, ``` #ifdef __cplusplus extern "C" { #endif struct foo { void getNum() { } }; #ifdef __cplusplus } #endif int main (int argc, char * const argv[]) { return 0 ; } ``` Is it possible to callgetNum()from C?
No, sincegetNumis a member function, which C doesn't have. A possible solution to that problem is to write a C++ function to return afooinstance as afoo*(wherefoois changed to be an empty struct) to C (I assume this is binary compiled as C++ to which C is linking), then have a free function in C++ calledfoo_getNumor ...
In embedded we often listen word like low footprint library. so how can i know the footprint of my library.so or library.a file..? how can i calculate that is it same as the memory size of that library?
The only real why to find out the memory footprint is by running the executable that uses the library and see how it uses it. An executable typically uses only a subset of a library. For example a library might have a list that holds objects that are dynamically created by the library when a client pushes another item...
I'm converting an ingres C program to Oracle Pro*C. I create and open a cursor to do a SELECT (not a SELECT FOR UPDATE). The existing program does (roughly) ``` EXEC SQL DECLARE N CURSOR for SELECT... EXEC SQL OPEN N EXEC SQL FETCH N INTO :new while (sqlca.sqlcode != 100) { // process the contents of :new EXEC ...
In fact, careful analysis (by which I mean "tons of printf()s") indicates that sqlca.sqlcode is never anything other than null until the loop is complete. So I just changed the condition on the loop to be ``` while (sqlca.sqlcode =='\0') ``` rather than ``` while (sqlca.sqlcode != 100) ``` And all is well.
I have aClibrary code, in whichexternmethod is defined: ``` typedef unsigned int U32; extern U32 iw(U32 b, U32 p); ``` I also have theAssemblercode, in which this method is defined. How can I call thisC(or may be evenAssembler) method from C# code?Can I use theDllImportattribute?
Just be aware that you need to consider calling conventions. Most Win32 APIs are written to usestdcall, soP/Invokeusesstdcallby the default. However VC++ usesCDeclby default. If you run into problems you can either modify your exported function to bestdcall, or you can modify yourP/Invokedeclaration (I think there's...
I need to remove a specific element from an array, that array is dynamically resized in order to store an unknown number of elements withrealloc. To control the allocated memory and defined elements, I have two other variables: ``` double *arr = NULL; int elements = 0; int allocated = 0; ``` After some elements bei...
I think this is the most efficient function you can use (memcpyis not an option) regarding secured - you will need to make sure that the parameters are OK, otherwise bad things will happen :)
I'm writing a C program. It compiles fine but when I try to run the binary I get a seg fault. I ran gdb but I got a problem at the following line ``` *total = a; ``` The problem is right at the beginning of the code. Here it is: ``` main(){ int a[] = {1,1,1,0,0,0,0}; int **total; //array of int arrays *total ...
totalpoints to a pointerpwhich points to an int. By assigning to*total, you're assigning top. Buttotalhasn't been initialized, so you're assigning a value into a random location. You need to initializetotal-- for example ``` int * p; int** total = &p; ```
I need to perform data filtering based on the source unicast IPv4 address of datagrams arriving to a Linux UDP socket. Of course, it is always possible to manually perform the filtering based on the information provided byrecvfrom, but I am wondering if there could be another more intelligent/efficient approach (if p...
If it's a single source you need to allow, then use justconnect(2)and kernel will do filtering for you. As a bonus, connected UDP sockets are more efficient. This, of cource, does not work for more then one source.
Can anyone show (through code) or explain to me how I might use libevent and curl together in a c program? I'm trying to write a high-performance non-blocking data monitor which needs to upload data to a CouchDB instance. I'm familiar with both libevent and curl, but merging curl_multi with libevent has me stumped for...
The key is really thecurl_multi_socket_action() function that should be used as soon as your event library says there's something on a socket to deal with. Event-based libcurl is more complex than "plain" libcurl so doing a very easy example is not that straight forward.
This question already exists:Closed12 years ago. Possible Duplicate:Fastest way to get range complement I have a sorted array of nonoverlaping ranges for example (0,2],(2,4],(6,9] and I wish to get it's complement with (0,12] which shoud return (4,6],(9,12] .Whats the fastest way to do that?
Assume your input data is an array of this form: ``` { 0, 2, 2, 4, 6, 9 } ``` Simply add the new elements 0 and 12 to the beginning and end, and you have ``` { 0, 0, 2, 2, 4, 6, 9, 12 } ``` And reinterpreting consecutive pairs as intervals, you have: (0, 0](2, 2](4, 6](9, 12] The fact that you have degenerate in...
What I need to create is something simila to the CRT unit in Pascal or the old Graphics.h in Turbo C++, I am using the MinGW compiler. Is there any way to implement theGotoXY,ClrScr,Sleep,'SetClr' etc. functions using, maybe the winapi kernel library or something? Or is there already a library made for MinGW that does...
You could use curses , there's a port of pdcurses for mingw herehttp://www.mingw.org/wiki/Community_Supplied_Links curses is a little odd to use, it was originally written for terminals on unix. (You can have that sweet coloured and blincking text 90's gui)
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question I'm writing a program which needs a UI. The program is in haskell. For the UI, I thi...
I don't see any advantages in writing the UI in C and call functions from C. You can choose how you are going to do the UI from several libraries available onHackage: hscursesncursesnanocursesvtyandvty-uiansi-terminal(on windows)brick— there's even avideo tutorialon it. I don't know which is better, there's asmall ...
In C using Xcode, how to change the while loop to mach the first for loop? ``` #include <stdio.h> int main (int argc, const char * argv[]) { int i; i = 0; while ( i++ < 4) printf ("while: i%d\n",i); printf ("after while loop, i=%d\n\n", i ); for (i = 0; i < 4; i++) printf ("fi...
``` while ( i < 4) printf ("while: i=%d\n",i++); ``` will do the trick. The++after theiis a post increment, so theprintfstatement printsi, then increments.
I'm looking for header files for C/C++ which will contain ntdll.dll function definitions. I know those apis are for internal use and undocumented. There is such thing for pascal, I can't beleive there is no for C/C++, though I couldn't find any. thanks
It should not be too hard to convert the ones for Pascal back to C. With a compiler like Embarcadero's C++Builder, you could have it done by the Delphi compiler that comes with it. Just ask someone with C++Builder to add the .pas file to a C++ project and a .hpp file will be generated, which is simply a .h file with a...
I am using Visual Studio 2008 team system. I have C project. I went to project properties and in the code analysis section. I wonder what is mean by ``` `suppress results from generated code` ``` Can someone explain what does this option do when I set it yes or no? Thanks
The Suppress results from generated code check box on the Code Analysis property page of a project enables you to select whether you want to see Code Analysis warnings from code generated by a third-party tool. Reference:http://msdn.microsoft.com/en-us/library/dd742298.aspx
I'm currently trying to do some string based manipulation in an attempt to speed up a section of traditional Perl code. The original Perl code looks like ``` my $value = 'abCdE'; my $uc_value = uc($value); ``` I've looked at the Perl guts API and it seems that I can accomplish this usingtoUPPER()but this works on a ...
Perl does not provide a lot of its functionality to C level extensions, uppercasing is apparently one of those features. At best, you can look at how the coreimplementsthis, but it's really not all that pretty.
i am using ``` DPRINTF(ERROR_LEVEL,"ERROR: error found at file: %s line: %d",__FILE__,__LINE__); ``` it printf like this ``` ERROR: error found at file: /home/jeegar/ full path to that file/main.c line: 102 ``` here i just want to print only ``` ERROR: error found at file: main.c line: 102 ``` i just want file n...
Change: ``` DPRINTF(ERROR_LEVEL,"ERROR: error found at file: %s line: %d",__FILE__,__LINE__); ``` to: ``` DPRINTF(ERROR_LEVEL,"ERROR: error found at file: %s line: %d",basename(__FILE__),__LINE__); ```
I have a Server X and 2 clients A and B behind the same NAT. A and B need to form 10 TCP connections each to X on the same outbound port. X should only accept at most 10 connections from a single client. So I need X to tell A from B right after accept(). Is there any way to do this with just the information in a TCP p...
In IP, the clients are only identified by their IP address. It is not possible to know from which client the connection came from if there is NAT in between. In reality TCP/IP stacks of different operating systems and operating system versions work a bit differently and fingerprinting the clients might be possible. T...
In my C console application, I would like to exit the application and on the same time fire an exit command to close a terminal. However, following code seems not work. Once I run the application, it exit the application, but not close the terminal. ``` int main(void) { system("exit"); return 0; } ``` Please giv...
Your "exit" command is not being sent to the shell that launched your program, but rather a new shell, executed expressly for the purpose of executing your command. It doesn't accomplish anything. There's no way for your program to cleanly exit the shell that launched it without some cooperation from that shell. For ...
Can anyone explain me the double order traversal? ``` A / \ B E / \ / \ C D F G ``` Double order Traversal output : ABCCBDDAEFFEGG I'm interested in explanation rather than the code. Thanks
Assuming you're interested in an explanation of what a double-order traversal does: For each traversal, you Visit NodeTraverse Left ChildVisit NodeTraverse Right Child That's all there is to it. In cases where you don't have a left child (like C, for example), the two "visit node" operations happen back to back, wh...
What is the fastest integer sort implementation for 200-300 bit sized integers? Exact int size is fixed; I have up to 2 gigabytes with such integers (all in RAM). I hear that it is possible to sort such set in average at O(n log log M) or even at O(n sqrt(log log M)) time, wher n is number of integers and M is the la...
ARadix Sortcan be used to sort data with fixed size keys. As this condition is not often met the technique isn't discussed much, but it can be O(n) when the key size is factored out.
I was wondering if there was a way to lower the color scheme of an image. Lets say I have an image that has 32bit color range in the RGB. I was wondering if it would be possible to scale it down to perhaps an 8 bit color scheme. This would be similar to a "cartoon" filter in applications like photoshop or if you chang...
If you want the most realistic result take a look atcolour quantisation. Basically find the blocks of pixels with a similar RGB colour and replace them with a single colour, you are trying to minimize the number of pixels that are changed and the amount each new pixel is different from it's original colour - so it's a...
Given the following C++ code, ``` #ifdef __cplusplus extern "C" { #endif struct foo { void getNum() { } }; #ifdef __cplusplus } #endif int main (int argc, char * const argv[]) { return 0 ; } ``` Is it possible to callgetNum()from C?
No, sincegetNumis a member function, which C doesn't have. A possible solution to that problem is to write a C++ function to return afooinstance as afoo*(wherefoois changed to be an empty struct) to C (I assume this is binary compiled as C++ to which C is linking), then have a free function in C++ calledfoo_getNumor ...
In embedded we often listen word like low footprint library. so how can i know the footprint of my library.so or library.a file..? how can i calculate that is it same as the memory size of that library?
The only real why to find out the memory footprint is by running the executable that uses the library and see how it uses it. An executable typically uses only a subset of a library. For example a library might have a list that holds objects that are dynamically created by the library when a client pushes another item...
I'm converting an ingres C program to Oracle Pro*C. I create and open a cursor to do a SELECT (not a SELECT FOR UPDATE). The existing program does (roughly) ``` EXEC SQL DECLARE N CURSOR for SELECT... EXEC SQL OPEN N EXEC SQL FETCH N INTO :new while (sqlca.sqlcode != 100) { // process the contents of :new EXEC ...
In fact, careful analysis (by which I mean "tons of printf()s") indicates that sqlca.sqlcode is never anything other than null until the loop is complete. So I just changed the condition on the loop to be ``` while (sqlca.sqlcode =='\0') ``` rather than ``` while (sqlca.sqlcode != 100) ``` And all is well.
I have aClibrary code, in whichexternmethod is defined: ``` typedef unsigned int U32; extern U32 iw(U32 b, U32 p); ``` I also have theAssemblercode, in which this method is defined. How can I call thisC(or may be evenAssembler) method from C# code?Can I use theDllImportattribute?
Just be aware that you need to consider calling conventions. Most Win32 APIs are written to usestdcall, soP/Invokeusesstdcallby the default. However VC++ usesCDeclby default. If you run into problems you can either modify your exported function to bestdcall, or you can modify yourP/Invokedeclaration (I think there's...
I need to remove a specific element from an array, that array is dynamically resized in order to store an unknown number of elements withrealloc. To control the allocated memory and defined elements, I have two other variables: ``` double *arr = NULL; int elements = 0; int allocated = 0; ``` After some elements bei...
I think this is the most efficient function you can use (memcpyis not an option) regarding secured - you will need to make sure that the parameters are OK, otherwise bad things will happen :)
I'm writing a C program. It compiles fine but when I try to run the binary I get a seg fault. I ran gdb but I got a problem at the following line ``` *total = a; ``` The problem is right at the beginning of the code. Here it is: ``` main(){ int a[] = {1,1,1,0,0,0,0}; int **total; //array of int arrays *total ...
totalpoints to a pointerpwhich points to an int. By assigning to*total, you're assigning top. Buttotalhasn't been initialized, so you're assigning a value into a random location. You need to initializetotal-- for example ``` int * p; int** total = &p; ```
I need to perform data filtering based on the source unicast IPv4 address of datagrams arriving to a Linux UDP socket. Of course, it is always possible to manually perform the filtering based on the information provided byrecvfrom, but I am wondering if there could be another more intelligent/efficient approach (if p...
If it's a single source you need to allow, then use justconnect(2)and kernel will do filtering for you. As a bonus, connected UDP sockets are more efficient. This, of cource, does not work for more then one source.
Can anyone show (through code) or explain to me how I might use libevent and curl together in a c program? I'm trying to write a high-performance non-blocking data monitor which needs to upload data to a CouchDB instance. I'm familiar with both libevent and curl, but merging curl_multi with libevent has me stumped for...
The key is really thecurl_multi_socket_action() function that should be used as soon as your event library says there's something on a socket to deal with. Event-based libcurl is more complex than "plain" libcurl so doing a very easy example is not that straight forward.
This question already exists:Closed12 years ago. Possible Duplicate:Fastest way to get range complement I have a sorted array of nonoverlaping ranges for example (0,2],(2,4],(6,9] and I wish to get it's complement with (0,12] which shoud return (4,6],(9,12] .Whats the fastest way to do that?
Assume your input data is an array of this form: ``` { 0, 2, 2, 4, 6, 9 } ``` Simply add the new elements 0 and 12 to the beginning and end, and you have ``` { 0, 0, 2, 2, 4, 6, 9, 12 } ``` And reinterpreting consecutive pairs as intervals, you have: (0, 0](2, 2](4, 6](9, 12] The fact that you have degenerate in...
What I need to create is something simila to the CRT unit in Pascal or the old Graphics.h in Turbo C++, I am using the MinGW compiler. Is there any way to implement theGotoXY,ClrScr,Sleep,'SetClr' etc. functions using, maybe the winapi kernel library or something? Or is there already a library made for MinGW that does...
You could use curses , there's a port of pdcurses for mingw herehttp://www.mingw.org/wiki/Community_Supplied_Links curses is a little odd to use, it was originally written for terminals on unix. (You can have that sweet coloured and blincking text 90's gui)
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question I'm writing a program which needs a UI. The program is in haskell. For the UI, I thi...
I don't see any advantages in writing the UI in C and call functions from C. You can choose how you are going to do the UI from several libraries available onHackage: hscursesncursesnanocursesvtyandvty-uiansi-terminal(on windows)brick— there's even avideo tutorialon it. I don't know which is better, there's asmall ...
I've been wondering, is there a way to estimate the mount of shared mem on the different GPGPU's without going out and buying the cards? I currently have a GTS 330M with 16K shared mem in my laptop and a GTX 480 with 16K + 32K = 48K shared mem. I would like to know if getting a tesla card would give me more shared ...
For NVIDIA hardware, the shared memory configuration of every CUDA/OpenCL capable card is described in Appendix F of the CUDA 4.0 programming guide. To answer your question about a Ferm Telsa card, it has the same shared memory configuration as your GTX 480 - 16kb or 48kb of shared memory, user selectable at runtime....
Is it possible to runscanfon input that it is not STDIN? What I mean is if I have astring="hello 1 2 3", can I run scanf on it to extract the string and three integers? Is there another function that can do this?
sscanfon a string (infohere) fscanfon a file (infohere) similarlysprintfandfprintfto write to a string/file.
I was curious if it's possible to implement a sort of variadic version ofscanfin C. What I mean is if the input ispush (1 2 3),scanfwould be able to parse that into%s %d %d %dwith something likescanf("%s (%d)", string, some_list). It would take all instances of%dand append them (in order) to the list... Am I talking...
Isn'tvscanf, vssscanf, vsfcanfis what you are looking for? They are avaialble from C99 onwards. Here is a decription and example of usage ofvscanffunction. Note that C being a compiled and a strongly typed language, you need to give format specifiers properly. Doing something like what higher languages dos is going t...
In the app that I am making, I am using a segmented button to control adding or subtracting a number by one or two, the only problem is that I dont know how to add/subrtact a number by two based on the method that I use to add or subtract by one. This is the code that I have in my app to add or subtract by one: ``` ...
Or more verbal: ``` number = number + n; number = number - n; ``` (Where n is the number you want to add/substract.)
Without resorting to standard library utoa, I'm looking for source code of utoa so I may customise it for specific project. I have unsigned integer (32 bits) with output such as 0xFFFF_FFFF I also looking for source code for unsigned integer and half word to string in binary format.
Try this: ``` char *dec(unsigned x, char *s) { *--s = 0; if (!x) *--s = '0'; for (; x; x/=10) *--s = '0'+x%10; return s; } ``` You call it with a pointer to theendof a caller-provided buffer, and the function returns the pointer to the beginning of the string. The buffer should have length at least3*...
I want to make sure that the project is configured entirely for C(NOT C++). I cannot find any accurate walk through for doing this. I am open to usingEclipse, except that it does not create a working project out of the box (which makes no sense...).
Add/Tcas a command line option.
I have a question about (re-)defining functions. My goal is to have a script where I can choose to define a function or not. Like this: ``` void func(){} int main(){ if (func)func(); } ``` AND without the function, just: ``` int main(){ if (func)func(); } ``` Anybody an idea?
You can do this in GCC using its weak function attribute extension: ``` void func() __attribute__((weak)); // weak declaration must always be present int main() { if (func) func(); // ... } // optional definition: void func() { ... } ``` This works even iffunc()is defined in another .c file or a library.
This question already has answers here:Closed12 years ago. Possible Duplicate:Undefined Behavior and Sequence Points Pleae explain the behaviour of following statements ``` int b=3; cout<<b++*++b<<endl; ``` How will it be calculated?
The behavior here is undefined. Seethis question Relevant standard quote: §5/4.1 Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. The most common sequence point is the end of a statement. Also worth noting from the st...
I want to defer flushing the contents of theFILE*to whenfcloseis called. In other words, I only want to write to disk whenfcloseis called and keep buffering the contents until then. Is it possible to do that withFILE*or I need to write my own code?
If you want to buffer (and under no circumstances write to the disk until the file is closed), then your best bet is to write to a buffer in memory (assuming that it willfitin memory, of course), and then write that buffer in one go and then callfclose().
I'm wondering if there is a nice way to avoid gcc to scream about printf types : 'warning: format ‘%d’ expects argument of type ‘int’, but argument 12 has type foo' This is pretty anoying when you know that you wrote 'typedef int foo' somewhere ... Of course, I'm not looking for the gcc fix for that ( [-Wformat] ). ...
If you havetypedef int foo, gcc shouldn't warn you. Ifgcciswarning you, there's a fair chancefooreally isn't an integer.
My project is implemented in Qt 4.7, and now I want to retrieve some windows log in information. So I am dabbling around and found this code from MSDN (http://msdn.microsoft.com/en-us/library/aa370670(v=vs.85).aspx). Copying and pasting this code in Visual Studio works perfectly however using it in Qt gives the error...
You need to link with netapi32.lib. See thisMSDNexample and pay attention to pragma comment(lib, "netapi32.lib") in the code.
Consider the following function: ``` char *f() { char *s=malloc(8); } main() { printf("%c",*f()='A'); } ``` If I comment the linechar *s=malloc(8);I get an error as if the assignment*f()='A'accessed invalid memory. Since I never return any variable why does above assignment work at all? 2nd question:'A'i...
Assuming return values are passed in registers, the return value from malloc might still be there when returning from f(). By pure chance. When assigning to*f()you are not assigning to a temporary but to the memory returned from malloc. Assigning to ++a is totally different.
I have created a binary heap, which represents a priority queue. It's just classical well known algorithm. This heap schedules a chronological sequence of different events ( the sort key is time ). It supports 2 operation: Insert and Remove. Each node's key of the heap is greater than or equal to each of its childre...
One solution is to add time of insertion attribute to the inserted element. That may be just a simple counter incremented each time a new element is inserted into the heap. Then when two elements are equal by priority, compare the time of insertion.
I'm a bit confused with a void* pointer in C. Especially after reading this question:Is the sizeof(some pointer) always equal to four?, where one person says there is no guarantee that sizeof(int *) == sizeof(double *) My question is: is there a guarantee of sizeof(void*) >= sizeof(any other pointer type)? In other w...
Only data pointers.void *can hold any data pointer, but not function pointers. Here is aC FAQ. void *'s are only guaranteed to hold object (i.e. data) pointers; it is not portable to convert a function pointer to type void *. (On some machines, function addresses can be very large, bigger than any data pointer...
I am trying to read a 32 register,modify its first 8 bits[BIT7:BIT0] and write back its value. Does the code below achieve that? ``` reg_val = register_read(register_object); reg_val = ((reg_val & 0xffffff00) | new_value)); register_write(register_object,reg_val); ``` Also is it the most efficient way to achieve tha...
Unlessnew_valueis guaranteed only 8 bits wide you should ensure it: ``` reg_val = ((reg_val & 0xffffff00) | (new_value & 0xff)); ``` Also is it the most efficient way to achieve that? Any compiler worth its salt will translate that into The Right Thing.
Ex: ``` gcc source-file ``` I think it is dynamic but I'm not sure. Is it system dependent?
It is technically system dependent, but onmostsystems you're likely to develop for, the answer is "dynamic". A few systems (mostly very old, embedded, or otherwise specialized) do not support dynamic linkingat all, but most developers are unlikely to care about those systems. On those systems, the linker will of cour...
I have this structure: ``` typedef struct { int data[10]; } small_structure; ``` and this code: ``` small_structure *s_struct; void * chunk; chunk = malloc(1000); s_struct = chunk; ``` Is it ok to do something like this? Ignore the fact that this is wasting memory.
Yes, it is always legal to allocate more memory than you need, so long as that much memory is available.
any Idea how I could have the follow code output text with a transparent background? ``` SDL_Color co = {tp->col.r, tp->col.g, tp->col.b,tp->col.a}; SDL_Color bco = {255, 0, 255,1}; ts = TTF_RenderText_Shaded(tp->font, text.c_str(),co,bco); ```
TTF_RenderText_Shadeddoesn't allow for transparent backgrounds (as it uses 8bit color), you want to useTTF_RenderText_Blended, seethis.
I have a buffer, I am doing lot of strncat. I want to make sure I never overflow the buffer size. ``` char buff[64]; strcpy(buff, "String 1"); strncat(buff, "String 2", sizeof(buff)); strncat(buff, "String 3", sizeof(buff)); ``` Instead of sizeof(buff), I want to say something buff - xxx. I want to make sure I ne...
Take into consideration the size of the existing string and the null terminator ``` #define BUFFER_SIZE 64 char buff[BUFFER_SIZE]; //Use strncpy strncpy(buff, "String 1", BUFFER_SIZE - 1); buff[BUFFER_SIZE - 1] = '\0'; strncat(buff, "String 2", BUFFER_SIZE - strlen(buff) - 1); strncat(buff, "String 3", BUFFER_SIZE...
Their is a project I would like to start working on but the problem is I use Linux and the project is based off windows. (VC++ v9) I would like to convert it to Eclipse CDT but qmake and different includes are driving me mad. Project Repo 1 - I downloaded Eclipse Indigo CDT2 - Downloaded the latest QT ( qt.nokia.com...
Here's atutorialto do exactly what you're asking. It's geared for OS X, but the same principles would apply.
I have the following C program: ``` #include <stdio.h> int main() { double x=0; double y=0/x; if (y==1) printf("y=1\n"); else printf("y=%f\n",y); if (y!=1) printf("y!=1\n"); else printf("y=%f\n",y); return 0; } ``` The output I get is ``` y=nan y!=1 ``` But when I change the line double x=0; to i...
You're causing the division0/0with integer arithmetic (which is invalid, and produces the exception you see). Regardless of the type ofy, what's evaluated first is0/x. Whenxis declared to be adouble, the zero is converted to adoubleas well, and the operation is performed using floating-point arithmetic. Whenxis decl...
I've tried using the following command: ``` __m128i b = _mm_set_epi32 (y, y, x, x); ``` Where y and x are ints. Where I run the debugger I see that b is of type:unsigned __int64[2] I intended b to be 4 integers of 32 bits each (I think that's what they say here:http://msdn.microsoft.com/en-us/library/019beekt.aspx...
I don't see a problem here - a 128-bit integer is represented by two 64-bit integers, which is the largest native type outside of SSE registers a 64-bit Intel CPU can handle. Your debugger is likely showing the "real" type, not the typedefed or macro'd type.
I wrote a program, that uses a shared library installed on my system. This library is seldom installed on other systems. How do I compile my program so that the library doesn't need to be installed on other systems? I have the source code for the library available. What's the best way? The other systems of course hav...
Compile it as a static library and link that into the executable.
How can I perform a live stack trace on a running UNIX applicaiton, and are there any utilities that are useful in digesting the stack trace once its done? I'm looking to see if any functions are getting called more often than I would have expected them to be - the application works fine, it just recently slowed down...
Profiling tools will show what bits of the program are taking up the CPU time. If you have to dig deeper, you may need other tooling. Depending on what species of unix you're after, the tools will vary, as this is sometimes quite platform specific.This articlediscusses process monitoring on Linux. Different version...
I'm trying to usepopen()to catch the stderr of a call, but of course it doesn't seem to be doing that. Any ideas? My code looks more or less like this: ``` popen("nedit", "r"); ``` But I'm getting all this garbage about non-utf8 on my screen...
popengives you a file handle on a process' stdout, not its stderr. Its first argument is interpreted as a shell command, so you can do redirections in it: ``` FILE *p = popen("prog 2>&1", "r"); ``` or, if you don't want the stdout at all, ``` FILE *p = popen("prog 2>&1 >/dev/null", "r"); ``` (Any other file beside...
This is my function ``` int mkvCopyWord(uint8_t *pBuffer, UINT8 temp): main() { uint8_t a[10]; mkvCopyWord(&a,10); } ``` its says warning : note: expected ‘uint8_t *’ but argument is of type ‘uint8_t (*)[10]’ how to remove this warning..?
Your syntax for passing a pointer-to-array is fine. But you are trying to pass it to something that doesn'twanta pointer-to-array. It just wants a pointer to the beginning element. The simplest way to get that is to allow the array name to decay to a pointer, thusmkvCopyWord(a, 10). The function will assume that the p...
I have a function with definition : ``` int foobar(char *ptr,...) ``` the function call is as follows : ``` int (*fooptr) (char *,...) = foobar; ``` I am not able to understand how is the function getting called ... Thanks in advance
That's not a function call. It is declaring afunction pointervariable calledfooptrthat holds the address of the function. To call that function via the pointer you would do e.g.: ``` int return_value = (*fooptr)(char_ptr, x, y, z); ```
I have a C application that spawns children using fork/exec. My spawn-process runs non-stop and it creates a log file using a unix pipe. Every 24 hours I want to backup the logs. For this I'm using a script. Once the script has finished, I want to kill and restart the process. So far so good. But there might be the ca...
A process doesn't just die when its parent dies. Most likely, your children processes are receiving some signal (SIGHUP?) for some reason. If you want your children to persist, you need to find out what that signal is and ignore it right afterfork.
How to define constant 1 or 2 dimensional array in C/C++? I deal with embedded platform (Xilinx EDK), so the resources are limited. I'd like to write in third-party header file something like ``` #define MYCONSTANT 5 ``` but for array. Like ``` #define MYARRAY(index) { 5, 6, 7, 8 } ``` What is the most common way...
In C++, the most common way to define a constant array should certainly be to, erm,define a constant array: ``` const int my_array[] = {5, 6, 7, 8}; ``` Do you have any reason to assume that there would be some problem on that embedded platform?
``` struct x { char a[10]; char b[20]; int i; char *c; char *d[10]; }; ``` I am filling this struct and then using the values. On the next iteration, I want to reset all the fields to0ornullbefore I start reusing it. How can I do that? Can I usememsetor I have to go through all the members and th...
Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it. For example: ``` static const struct x EmptyStruct; ``` Here I am relying onstatic initializationto set my initial values, but you could use a struct initializer if ...
The following statement is generating a compile-time error. ``` int a=6/2(1+2); ``` Can someone please explain why the compiler generates an error.
You're missing a mathematical sign such as+,-,*,/. You probably want6/(2*(1+2))or(6/2)*(1+2). If you leave the sign out, C interprets it as a function call just like usual functionsprintf("stuff")(indicated via opening parentheses without mathematical operator). So it thinks2(1+2)calls the function2with argument1+2....
How is it possible to access clipboard data on the Mac programmatically?
Apple has aPasteboard Programming Guidethe main class you are looking for isNSPasteboard The example for reading strings is ``` NSPasteboard *pasteboard = <#Get a pasteboard#>; NSArray *classes = [[NSArray alloc] initWithObjects:[NSString class], nil]; NSDictionary *options = [NSDictionary dictionary]; NSArray *cop...
I've heard that in Smalltalk/X and possibly other flavors you can include C code inside a method, is this possible with other Smalltalk implementations? which ones?
Smalltalk/X is the only Smalltalk I am aware of that supports writing C code directly within Smalltalk methods. Of course, most other Smalltalks (Pharo, VisualWorks, GemStone, ...) allow you to write and use primitive methods written in C, but this is rather cumbersome and requires one to use an external C compiler. ...
I am working on 32-bit Fedora 14 system. I'm compiling my source code usinggcc. Does anybody know how to disable warnings while compiling c code? EDIT:Yes i know. Best thing is to fix those Warnings to avoid any undefined/unknown behavior. But currently here, i have written huge code first time and there are lots ...
try to add -w option when compiling http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
I am connecting to my desktop which has an Nvidia card (CUDA compatible) using remote desktop connection. I am doing this because I currently don't have a monitor! Therefore I am temporary using my laptop to connect to my desktop and run my CUDA code. It seams that remote desktop does not recognize the Nvidia card.c...
As said, you cannot use remote desktop. Instead, you can use a VNC client such asSplashtop Remote Desktop, it is free.
Is there a way to do something like the array initialization braces method for a pointer array? ``` myStruct* array = malloc(4*sizeof(myStruct)); array = {a,b,c,d}; //like this ``` The reason I'm interested is because the aforementioned lines are much nicer to look at than: ``` myStruct* array = malloc(4*sizeof(myS...
I think you can do it with C99. The feature is called "compound literals". ``` struct tag { int x; int y; int z; }; struct tag *t; t = &(struct tag){1, 2, 3}; ``` Or, for arrays: ``` int *arr; arr = (int []) {1, 2, 3}; ```
Does anyone know how to obtain lint for Mac, Windows, and Linux?sudo port install lintcan't find it.
I've only seen lint for BSD. There'ssplint, however, a GPL lint rewrite, and it's available on most Linux distributions.
I've been looking throughctagsman pages but I haven't found anything that will tell ctags to only record prototypes forc99 header files. Essentially, I have header files for bothCandC++files, but I only want those that correspond to c99 files (ie: noclassstuff) to be outputted.
ctagshas the option--languagethat can force it to interpret files as being of a specific type.
In pure ansi C, is there any way to show that, given ``` char c1 = 1, c2 = 2; ``` the type of the following: ``` c1 + c2 ``` is int? Thanks. NOTE: I know that according to standards it is, but in C++ you can use the typeid operator to show it. I'd like to be able to showc1 + c2is an int in C.
You can't prove a thing like that. A C compiler is allowed to replace all operations to its liking provided that the observable result is the same as in the abstract machine. You don't have direct access to the result of the adition (being an rvalue) so the type of it is not observable nor is its size, width or signed...
I would like to organize better the following twoifstatements: ``` if(A || B){ do stuff... } if(A && ! B){ do other stuff... } ``` Is there a better way? EDIT:!beforeBon second statement, sorry...
``` if( A || B ) { do some stuff; if( !B ) { do other stuff; } } ``` But the benefits depend on the usage, it could be harder to understand this version.
Consider: ``` #include <stdio.h> int f() { return 20; } int main() { void (*blah)() = f; printf("%d\n",*((int *)blah())()); // Error is here! I need help! return 0; } ``` I want to cast 'blah' back to (int *) so that I can use it as a function to return 20 in theprintfstatement, but it doesn't seem...
This might fix it: ``` printf("%d\n", ((int (*)())blah)() ); ```
I want to make a multi-thread C program with a proper variable alignemt in cache, to avoid "cache sloshing". I get cache-line length from/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size, so I know how to pad my arrays to occupy full cache lines. But, how can I be sure that an array is allocatedexactlyat ...
To allocate memory with a specific alignment, useposix_memalign. (I don't know whether the memory allocator is intelligent enough to allocate on cache-line boundaries automatically, though.)
Fromthis questionit appears it's possible (but perhaps with issues). My question is, can I do this the other way aorund, compile a C/C++ lib in Visual Studio then link it up to xcode and run it on an iOS device. Will Apple have an issue with this if it actually works? I know they're not big fans of DLLs and I'm not to...
You can't do this because the Microsoft compiler targets a different architecture from the architectures that iOS runs on. And that's just for starters. There are no doubt a gazillion other reasons that it won't work, but the architecture is the most obvious block.
see my code ``` #include<stdarg.h> #define DPRINTF(_fmt, ...) debugPrintf(_fmt,__VA_ARGS__) void debugPrintf(const char *fmt, ...) { char buf[128]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); fprintf(stderr,"%s",buf); return; } main() { int a=10; DPRINTF("a is %d...
Just use ``` #define DPRINTF(...) debugPrintf(__VA_ARGS__) ``` variadic macros, other than variadic functions, don't need a fixed argument.
I am using anMSP430F5418with theST7565RLCD controller with easyGUI. I am usingSPIto communicate with the LCD. Suppose I have a screen like this: But sometimes (rarely) when I press a key (anything which make the testing board to move, usually it comes when pressing the key) the screen goes like this: I didn't d...
It sounds like a bug in your code -- I am not familiar with the particulars of easyGUI or the particular controller, so this is just a wild guess, but would it so happen that somewhere in your code you would do aprintforwriteto stdout which then would go to the same device which is also your display, and when one of t...
I am trying to scan in 1-3 words from the user into a string. However, Only the first word will scan.
``` scanf("%s", &area ) ; ``` scanfstops reading from the stream when a space is encountered. You need to usegetlineinstead.
I'd like to use the compiler options describedhereto generate a smaller SQLite3 library. However, these options (including-Osit seems) expressly don't work with the amalgamated source, which is my preference. (I even tried all the same and indeed it won't work.) Is there a good alternative to generating a smaller SQL...
Download the Sqlite3 sources from their Fossil source control system for a particular version, which will give the unprocessed source, before amalgamation. You can then runmake sqlite3.cto create the amalgamation on your own -- and naturally, you can change the command line arguments to omit features you don't need. ...
I am working on a 32-bit system. When I try to print more than one 64 bit value in a single printf, then it cannot print any further (i.e. 2nd, 3rd, ...) variable values. example: ``` uint64_t a = 0x12345678; uint64_t b = 0x87654321; uint64_t c = 0x11111111; printf("a is %llx & b is %llx & c is %llx",a,b,c); ``` W...
You should use the macros defined in<inttypes.h> ``` printf("a is %"PRIx64" & b is %"PRIx64" & c is %"PRIx64"\n",a,b,c); ``` It is ugly as hell but it's portable. This was introduced in C99, so you need a C99 compliant compiler.
How do I use the Python C-API to check if a PyObject* points to the type numpy.uint8 etc? (Note that I want to check if the PyObject* points to the type numpy.uint8, not if it points to an instance of the type numpy.uint8.)
You can usePyType_IsSubtype(child, parent)to see if the child type inherits the parent, but it operates onPyTypeObject*, notPyObject*.
I have this define set up on top and im getting an error when calling it ``` /*-------------------__RETURN DEFINE-----------------*/ #define __return(x) \ pool_err= POOL_PUTSPACE_(i_exit_cb->Pool_addr,&l);\ if ( pool_err != 0 ) \ { exit(EXIT_FAILURE); } \ return(x); /*---END OF __RETURN DEFIN...
The error mention the second (2) parameter and the only function call with 2 parameters is toPOOL_PUTSPACE_. I would guess that the&lmight need a cast.
While I know what the Unix system callbrkand functionsbrkdo, I have no idea what they stand for. Can anyone enlighten me?
It comes from "break value". I quote: "The change is made by resetting the process's break value and allocating the appropriate amount of space. The break value is the address of the first location beyond the end of the data segment." (source:http://www.s-gms.ms.edus.si/cgi-bin/man-cgi?brk+2)
I am accustom to retaining and releasing objects in Objective-C but since I am processing data through an Audio Unit I need to stay at the C level and cannot leverage the iOS framework. In this case I have a struct which holds onto audio data and I need to hold onto a bunch of them at a time. Once I am done I need to ...
There is nothing too fancy to do: malloc for allocation, and free for deallocation, always paired. It more or less works as an Objective-C world without autorelease.
I've got a series of structs (audio data) which I need to hold onto but I can only hold onto a limited amount due to memory constraints. I think the best way to do this is with a queue. If I were do this based on my fuzzy memories of my college classes I would create a linked list with pointers. I would push new items...
GLibhas a good and well-documented collection of data structures implemented in C, give a look at it.
``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, const char *argv[]) { srand(clock()); int num = rand() % 6 + 1; printf("%i", num); return 0; } ``` I get this warning in "srand(clock());" line. Warning: Implicit conversion loses integer precision: 'clock_t' (aka 'unsi...
Don't use srand(clock()) use srand((unsigned)time(NULL)) instead. Better seeds: Use time(NULL) to get the time of day and cast the result to seed srand().time(NULL) returns the number of seconds elapsed since midnight January 1st, 1970.Use rdtsc() to get the CPU timestamp and cast the result to seed srand(). rdts...
I have some .c files that don't automatically highlight in vim. This problem only recently started. I have not edited my .vimrc file: ``` set number nnoremap <F2> :set nonumber!<CR>:set foldcolumn=0<CR> set ignorecase syntax on filetype plugin indent on nnoremap <C-H> :Hexmode<CR> inoremap <C-H> <Esc>:Hexmode<CR> vno...
Try to remove all files in~/.vim/view(eventually make a backup before deleting it).
One can easily define a function that accepts a1d arrayargument like this: ``` int MyFunction( const float arr[] ) { // do something here, then return... return 1 } ``` Although a definition such as:int MyFunction( const float* arr )would work as well. How can one define a function that accepts a2d ar...
In C99, you can provide the dimensions of the array before passing it: ``` void array_function(int m, int n, float a[m][n]) { for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) a[i][j] = 0.0; } void another_function(void) { float a1[10][20]; float a2[15][15]; ar...
``` #include "stdio.h" void Square(int num, int *myPointer); int main(int argc, const char *argv[]) { int originalNum = 5; Square(originalNum, &originalNum); printf("%i\n", originalNum); return 0; } void Square(int num, int *myPointer) { *myPointer = num*num; } ``` I don't understand how we can...
originalNumis an int.&originalNumis a pointer tooriginalNumand thus pointer to an int orint *. In simpler words,&originalNumis the address where theoriginalNumvariable is allocated in the memory. So, when you pass&originalNumyou don't pass5(the value oforiginalNum). Instead, you pass the address where this5is stored....
Suppose that I have the followingcfunction: ``` int MyFunction( const float arr[] ) { // define a variable to hold the number of items in 'arr' int numItems = ...; // do something here, then return... return 1 } ``` How can I get intonumItemsthe number of items that are in the arrayarr?
Unfortunately you can't get it. In C, the following 2 are equivalent declarations. ``` int MyFunction( const float arr[] ); int MyFunction( const float* arr ); ``` You must pass the size on your own. ``` int MyFunction( const float* arr, int nSize ); ``` In case ofcharpointers designating strings the length of the...
What's your idea about simulatingthreadwith"fork() function"and a"shared memory"block ... Is it possible ? How much is it reasonable to do this for a program ? ( I mean , Will it work well..?)
For starters, don'tmix a thread and fork(). A fork gives you a brand new process, which is a copy of the current process, with the same code segments. As the memory image changes (typically this is due to different behavior of the two processes) you get a separation of the memory images, however the executable code r...
I have a linux server process that load big resources on startup. This processes will fork on request. The resources that are loaded on startup are the bigest stuff and will not change while runtime. The folked child processes use read/write control structures to handle requests to the constant resources. How do I fi...
You can get this information from the/proc/$pid/pagemapand/proc/kpagecountand/proc/kpageflagsvirtual files in the proc filesystem. Access to the latter requires root because it could leak privileged information about process memory mappings you don't own. ReadDocumentation/vm/pagemap.txtfrom the kernel docs for detail...
I am looking at some legacy C code and got confused. It is something like: ``` UINT A, B = 1; if((A = B) == 1) { return(TRUE); } else { return(FALSE); } ``` We all know there will be a compiler warning if we do if(A = B), but here it looks like the 'if' is checking A against 1. Am I correct?
First, it assigns the value ofBtoA(A = B), then it checks if the result of this assignment, which isAand evaluates to1, is equal to1. So technically you are correct: On the way it checksAagainst1. To make things easier to read, the code is equivalent to: ``` UINT A, B = 1; A = B; if(A == 1){ return(TRUE); } else...