question
stringlengths
25
894
answer
stringlengths
4
863
I was wondering if I can usea library-written in C++- inC#The problem is that library has its own structures and classes.. Will I be able to use it in C#? Thanks EDITThis library is open source..so if my requirements needs something special in C++ code, I will be able do it...
You cannot directly use C++ classes in managed code. The chief problems are not being able to use the same memory allocator as used by the C++ code and not being able to invoke the constructor and destructor easily. A Microsoft employee posteda blog postto show that it is not impossible. I would not recommend doing this. COM is a solution but that invariably requires a fairly big rewrite and good COM programming skillz. Amanaged class wrapperin the C++/CLI language is usually the best solution. You could take a peek at theSWIG toolto consider auto-generating those wrapper classes. Beware however that this tool can easily create more problems than it solves.
can I do something like this on Assemblybne jsr swap, if not how can I solve this problem from C, thanks in advance ``` if(start!=pivot_index){ swap(board,start,pivot_index); } ``` I was taught that I must writejsrandsub-routinebut can I do something like thisbne sub-routine
In assembly that would usually be translated into something like this (pseudo-assembly): ``` load [start] compare [pivot_index] branch-if-equal label1 push [pivot_index] push [start] push [board] call swap add-stack-pointer 12 label1: ``` ie. theifstatement is converted into a jump that jumps over the body of theifif the controlling expression is not true.
I want to use cairo to enhance gtkentry look. For this, I have connected a callback to 'expose-event'. In callback, I call gtkentry's original expose-event handler. After that, I create cairo context and draw some lines and destroy the cairo. I return 'TRUE' as return value of callback function so that expose-event does not propagate. Now my problem is, I am drawing line from (0,0) to (100,100). But line appears only over the border areas of the gtkentry. The place where text is, it does not appear. Please help. Kind Regards -Durgesh O Mishra
GtkEntryuses an additionalGdkWindowfor the text area. It is sort-of-private, but you could access it using the following code: ``` GDK_WINDOW (gdk_window_peek_children (GTK_WIDGET (entry)->window)->data); ``` So, you can pass this window togdk_cairo_create(). If you have problems applying this to your code, paste the code — it's hard to guess what to do without having any way to test.
Having a string of whitespaces: ``` string *str = new string(); str->resize(width,' '); ``` I'd like to fill length chars at a position. In C it would look like ``` memset(&str[pos],'#', length ); ``` How can i achieve this with c++ string, I tried ``` string& assign( const string& str, size_type index, size_type len ); ``` but this seems to truncat the original string. Is there an easy C++ way to do this? Thanks.
In addition tostring::replace()you can usestd::fill: ``` std::fill(str->begin()+pos, str->begin()+pos+length, '#'); //or: std::fill_n(str->begin()+pos, length, '#'); ``` If you try to fill past the end of the string though, it will be ignored.
Lets say I have an array like ``` int arr[10][10]; ``` Now i want to initialize all elements of this array to 0. How can I do this without loops or specifying each element? Please note that this question if for C
The quick-n-dirty solution: ``` int arr[10][10] = { 0 }; ``` If you initialiseanyelement of the array, C will default-initialise any element that you don't explicitly specify. So the above code initialises the first element to zero, and C sets all the other elements to zero.
I would really like to actually only allocate 64KB of memory, not 128KB and then do the alignment manually - far too wasteful. VirtualAlloc on windows gives precisely this behavior. Supposedly there's code in SquirrelFish for doing this on just about every platform, but I haven't managed to locate it. Is there a space efficient way to allocate 64KB on a 64KB boundary in POSIX? Failing that, in Linux?
Check outposix_memalign(3) SYNOPSIS#include <stdlib.h> int posix_memalign(void **memptr, size_t alignment, size_t size);DESCRIPTIONThe posix_memalign() function allocates size bytes of memory such that the allocation's base address is an exact multiple of alignment, and returns the allocation in the value pointed to by memptr. Check out the manpage for further details...
I've written a smalloperating system for embedded projectrunning on small to medium target. I added some automated unit test with a high test code coverage (>95%), but the scope is only the static part.I got some code metrics as complexity and readability.I'm testing my code with a rule checker with MiSRA support, and of course fixed all warnings.I'm testing the code with a static analyzer and again fixed all warnings. What can I do now totest - and improve - the reliability of my OS ?How about the dynamic part ?
Things missing in your list: If you are not already doing it then also run the unit tests on the target hardware, to check for compiler and hardware issues.Code reviews, check especially for race conditions You could also review the generated assembly code, if it is not too big.
Given a array of random integers, sort the odd elements in descending order and even numbers in ascending order. Example input:(1,4,5,2,3,6,7)Output:(7,5,3,1,2,4,6) Optimize for time complexity.
Which language is it, C or C++ (I see both tags) In C++, you can usestd::sort()with appropriate ordering function. In C,qsort()works similarly: ``` #include <iostream> #include <algorithm> bool Order(int a, int b) { if (a%2 != b%2) return a%2; else return a%2 ? b<a : a<b; } int main() { int a[] = {1,4,5,2,3,6,7}; size_t N = sizeof(a) / sizeof(a[0]); std::sort(a, a+N, Order); for(size_t i=0; i<N; ++i) std::cout << a[i] << ' '; std::cout << std::endl; } ```
I was wondering if there was a way to run a thread on a seperate core instead of just a thread on that core? Thanks
If you create a thread, you have by default no control on which core it will run. The operation system's scheduling algorithm takes care of that, and is pretty good at its job. However, you can use theSetThreadAffinityWinAPI to specify the logical cores a thread is allowed to run on. Don't do that unless you have very good reasons. Quoting MSDN: Setting an affinity mask for a process or thread can result in threads receiving less processor time, as the system is restricted from running the threads on certain processors. In most cases, it is better to let the system select an available processor.
I have a file descriptor that is open for reading which may be non-blocking. What I need to do is simply read all data until reaching EOF and write that data to a writable file descriptor. As the process that performs this copying is not "aware" of anything that is going on around it, I don't think that I can do something useful while waiting for data, and I don't want to use awhileloop (whileerrnois notEAGAIN) because I think that it would be wasteful. Is there a way to block or otherwise suspend execution of the copying process until data becomes available?
Your other answer simply unsetsO_NONBLOCK, which sets the file back to blocking. That's perfectly fine, if that works in your situation; but if not, you can useselect()to block until your non-blocking file descriptor is readable.
HI all. I am trying to make little program that reads data from file which has name of user and some data for that user. I am new on C , and how can i calculate this data for its user?line by line reading and adding each char in array? And how can I read line? is there any function? And how can I use this each line users like object?I will make calculation for specific user.
You can usefgetsto read a line at a time from the file. Then you can parse the fields out and add them to an array or some other data structure. Just keep in mind if you use an array then you need to know ahead of time how many entries the file may contain - for example, no more than 1000. Otherwise you will need to use a data structure that can dynamically allocate memory such as a linked list, vector, etc.
In C language, Why doesn++execute faster thann=n+1? ``` (int n=...; n++;) (int n=...; n=n+1;) ``` Our instructor asked that question in today's class. (this is not homework)
That would be true if you are working on a"stone-age"compiler... In case of"stone-age":++nis faster thann++is faster thann=n+1Machine usually haveincrement xas well asadd const to x In case ofn++, you will have 2 memory access only (read n, inc n, write n )In case ofn=n+1, you will have 3 memory access (read n, read const, add n and const, write n) But today's compiler will automatically convertn=n+1to++n, and it will do more than you may imagine!! Also on today's out-of-order processors -despite the case of"stone-age"compiler- runtime may not be affectedat allin many cases!! Related
On Linux, how can I make sure that my program is the only one accessing a file?
I am not sure, but I believe you are referring tofile locking. Seethisandthisand don't forgetthis. Your display name is gcc but if you are doing this on windows, seeLockFileEx.
``` // The first example: char text[] = "henri"; char *p; p = text; *(p + 1) = 'E'; // Output = hEnri // Now If we want to remove the "e" ie hnri, we would go for????? *(p + 1)=????? ``` The obvious answer is to copy the rest of the array "back" one position. But this seems... unpleasant. Surely there is some better way?
Copyingisthe best solution and really the only solution when you're removing elements from an array. (You can special case the element at the end of the array, but that's it.) I don't understand why it's so terrible. You need to do one of two things. Both involve some copying. 1) Copy the 'n' to where the 'E' is, the 'r' to where the 'n' is, the 'i' to where the 'r' is, and then null terminate it. 2) Copy the 'h' to where the 'E' is and then always use the pointer to the 'h's new location. This may not always be an option.
How can we call a method which name isstringat runtime. Can anyone show me how to do that in Java and C.
In java it can be done through the reflection api. Have a look atClass.getMethod(String methodName, Class... parameterTypes). A complete example (of a non-static method with an argument) would be: ``` import java.lang.reflect.*; public class Test { public String methodName(int i) { return "Hello World: " + i; } public static void main(String... args) throws Exception { Test t = new Test(); Method m = Test.class.getMethod("methodName", int.class); String returnVal = (String) m.invoke(t, 5); System.out.println(returnVal); } } ``` Which outputs: Hello World: 5
What is simplest way to assign a bit mask to integer value? For example I want integer with first, third and forth bits = 1, other = 0. Certainly I am looking for code, not for single value! And certainly there lot of possibilities, but I try to find simplest and most descriptive looking
I think the best way to think (!) is to just index bits from 0, and then apply "to set the n:th bit, bitwise-OR with the value (1 << n)": ``` int first_third_and_fourth = (1 << 0) | (1 << 2) | (1 << 3); ```
I am doing this assignment, and there are some stuff (from start-up materials) that I cannot comprehend. ``` typedef enum { NORTH, EAST, SOUTH, WEST, NUM_POINTS } Point; typedef Point Course[NUM_POINTS] ; ``` I don't get the idea behind the last line , and how can I use it in the code?
``` typedef a b; ``` Makesban alias for typea, e.g. ``` typedef int foo; int bar; foo bar; ``` bothbars are equivalent. In your case, ``` typedef Point Course[NUM_POINTS] ; ``` MakesCoursean alias for typePoint[NUM_POINTS](whereNUM_POINTS == 4), so ``` Course baz; Point baz[NUM_POINTS]; ``` are equivalent.
I have 2 processes: 1 is writing to a sqlite database, 1 is reading from the same database. Occasioally, I get SQLITE_BUSY on my selects. Is this normal? Is their some option or way I could open the database so that it blocks until it CAN complete the query? (I tried the FULLMUTEX option on the open call but it appeared to have no effect).
When SQLite needs to write, it locks the entire database so no other thread/process can read or write it. That's why your other process gets SQLITE_BUSY. For that reason, SQLite isn't that great if you need to have multiple threads/processes using the database at the same time. If you only have two processes, you can probably get away with it though. As to the second part of your question, you can tell SQLite to retry with thesqlite3_busy_timeoutfunction, like this: ``` sqlite3_busy_timeout(db, 100); /* Retry for up to 100 ms */ ```
basically I have a texture. I also have a lets say octagon (or any polygon). I find that octagon's bounding box. Let's say my texture is the size of the octagon's bounding box. How could I figure out the texture coordinates so that the texture maps to it. To clarify, lets say you had a square of tin foil and cut the octagon out you'd be left with a tin foil textured polygon.I'm just not sure how to figure it out for an arbitrary polygon. Thanks
SeeTexture mapping an NGon?.
I would like to use OpenBSD's implementation of malloc, realloc and free on my Debian lenny desktop rather than glibc's. Are they simply drop in replacements: will they work on my Linux desktop ?Which are the file(s) that I need and which OpenBSD package contains them ?
Technically it is perfectly portable as it usesmmap(2), but you can't just copy&paste. For reference: The files are: http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/stdlib/malloc.c http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/crypt/arc4random.c , http://www.openbsd.org/cgi-bin/cvsweb/~checkout~/src/lib/libc/include/thread_private.h Plus a pair of defines: PGSHIFTwhich must be the log2 of your system's page size. AndMADV_FREE, a flag which AFAICT is not available in Linux. The threading code needs complete replacement, of course.
How does one determine where the mistake is in the code that causes asegmentation fault? Can my compiler (gcc) show the location of the fault in the program?
GCC can't do that but GDB (adebugger) sure can. Compile you program using the-gswitch, like this: ``` gcc program.c -g ``` Then use gdb: ``` $ gdb ./a.out (gdb) run <segfault happens here> (gdb) backtrace <offending code is shown here> ``` Hereis a nice tutorial to get you started with GDB. Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.
There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes. For example, I have ``` if (a) { if (a->b()) { if (a->b()->c()) { a->b()->c()->DoSomething(); } } } ``` I really don't like the look of this. Is there a way to turn this into something more readable? Ideally, ``` if (a && a->b() && a->b()->c() ) { ... } ``` would be great, but obviously would not work. EDIT - nvm the example that I put up DOES work as everybody has pointed out. I did test it out to see if this works, but there was a bug in my code in my test. duh!
Why would the latter not work? In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops. In fact, you could write: ``` a && a->b() && a->b()->c() && a->b()->c()->DoSomething(); ```
I am doing this assignment, and there are some stuff (from start-up materials) that I cannot comprehend. ``` typedef enum { NORTH, EAST, SOUTH, WEST, NUM_POINTS } Point; typedef Point Course[NUM_POINTS] ; ``` I don't get the idea behind the last line , and how can I use it in the code?
``` typedef a b; ``` Makesban alias for typea, e.g. ``` typedef int foo; int bar; foo bar; ``` bothbars are equivalent. In your case, ``` typedef Point Course[NUM_POINTS] ; ``` MakesCoursean alias for typePoint[NUM_POINTS](whereNUM_POINTS == 4), so ``` Course baz; Point baz[NUM_POINTS]; ``` are equivalent.
I have 2 processes: 1 is writing to a sqlite database, 1 is reading from the same database. Occasioally, I get SQLITE_BUSY on my selects. Is this normal? Is their some option or way I could open the database so that it blocks until it CAN complete the query? (I tried the FULLMUTEX option on the open call but it appeared to have no effect).
When SQLite needs to write, it locks the entire database so no other thread/process can read or write it. That's why your other process gets SQLITE_BUSY. For that reason, SQLite isn't that great if you need to have multiple threads/processes using the database at the same time. If you only have two processes, you can probably get away with it though. As to the second part of your question, you can tell SQLite to retry with thesqlite3_busy_timeoutfunction, like this: ``` sqlite3_busy_timeout(db, 100); /* Retry for up to 100 ms */ ```
basically I have a texture. I also have a lets say octagon (or any polygon). I find that octagon's bounding box. Let's say my texture is the size of the octagon's bounding box. How could I figure out the texture coordinates so that the texture maps to it. To clarify, lets say you had a square of tin foil and cut the octagon out you'd be left with a tin foil textured polygon.I'm just not sure how to figure it out for an arbitrary polygon. Thanks
SeeTexture mapping an NGon?.
I would like to use OpenBSD's implementation of malloc, realloc and free on my Debian lenny desktop rather than glibc's. Are they simply drop in replacements: will they work on my Linux desktop ?Which are the file(s) that I need and which OpenBSD package contains them ?
Technically it is perfectly portable as it usesmmap(2), but you can't just copy&paste. For reference: The files are: http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/stdlib/malloc.c http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/crypt/arc4random.c , http://www.openbsd.org/cgi-bin/cvsweb/~checkout~/src/lib/libc/include/thread_private.h Plus a pair of defines: PGSHIFTwhich must be the log2 of your system's page size. AndMADV_FREE, a flag which AFAICT is not available in Linux. The threading code needs complete replacement, of course.
How does one determine where the mistake is in the code that causes asegmentation fault? Can my compiler (gcc) show the location of the fault in the program?
GCC can't do that but GDB (adebugger) sure can. Compile you program using the-gswitch, like this: ``` gcc program.c -g ``` Then use gdb: ``` $ gdb ./a.out (gdb) run <segfault happens here> (gdb) backtrace <offending code is shown here> ``` Hereis a nice tutorial to get you started with GDB. Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.
There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes. For example, I have ``` if (a) { if (a->b()) { if (a->b()->c()) { a->b()->c()->DoSomething(); } } } ``` I really don't like the look of this. Is there a way to turn this into something more readable? Ideally, ``` if (a && a->b() && a->b()->c() ) { ... } ``` would be great, but obviously would not work. EDIT - nvm the example that I put up DOES work as everybody has pointed out. I did test it out to see if this works, but there was a bug in my code in my test. duh!
Why would the latter not work? In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops. In fact, you could write: ``` a && a->b() && a->b()->c() && a->b()->c()->DoSomething(); ```
Please excuse my C newbiness. Consider the following C procedure: ``` int doSomething() { char *numbers="123456"; ... } ``` Before this procedure exits should I be releasing the 'numbers' pointer?
No, you didn'tmallocit. Why should you release it? Often, the string is placed in a read only section of the executable.
I know that it's possible to compile my C code into a dll, and then use P/Invoke to call that code. What I wondered if it was possible to have a chunk of C code embedded directly in my code, perhaps only available to one class... Something like this (non-working) example: ``` public class MyClass { extern "C" { int do_something_in_c(int i) { return i*2; } } public int DoSomething(int value) { return do_something_in_c(value); } } ``` I've been trying for a few hours using Visual Studio 2008, but I'm not getting anywhere, and I suspect that it isn't actually possible. Can anyone confirm or deny this? Thanks.
It is possible to create a mixed-mode assembly (that is, one that has both managed and native code), but only the C++/CLI compiler can produce one of these. What you're looking to do is not supported by the C# compiler.
According to the documentation of iconv_open() over:http://www.gnu.org/software/libiconv/documentation/libiconv/iconv_open.3.html "//TRANSLIT" means that when a character cannot be represented in the target character set, it can be approximated through one or several characters. and: "//IGNORE" means that characters that cannot be represented in the target character set will be silently discarded. But what is the default behavior, when neither are specified? Thanks, Doori Bar
The default behaviour is to stop conversion and return -1, witherrnoset toEILSEQif an character that cannot be converted to the target character set is encountered. (ie. This is different to both//TRANSLITand//IGNORE).
this doesn't work: ``` void function(char* var) { var = (char*) malloc (100); } int main() { char* str; function(str); strcpy(str, "some random string"); printf("%s\n", str); return 0; } ``` this does: ``` void function(char* var) { //var = (char*) malloc (100); } int main() { char* str; //function(str); str = (char*) malloc (100); strcpy(str, "some random string"); printf("%s\n", str); return 0; } ``` Why?
You have to pass the address of the pointer to assign the address you wantinsidethe function, otherwise you are just passing a copy of it: ``` void function(char** var) { *var = malloc (100); } int main() { char* str; function(&str); strcpy(str, "some random string"); printf("%s\n", str); return 0; } ```
In the code I am writing I needfoo(int, char*)andfoo(int, int)functions. If I was coding this in C++ I would use templates. Is there any equivalent for C? Or should I use void pointers? How?
I think the closest you can get in C to templates is some ugly macro code. For example, to define a simple function that returns twice its argument: ``` #define MAKE_DOUBLER(T) \ T doubler_##T(T x) { \ return 2 * x; \ } MAKE_DOUBLER(int) MAKE_DOUBLER(float) ``` Note that since C doesn't have function overloading, you have to play tricks with the name of the function (the above makes bothdoubler_intanddoubler_float, and you'll have to call them that way). ``` printf("%d\n", doubler_int(5)); printf("%f\n", doubler_float(12.3)); ```
Given a N-dimensional vector of small integers is there any simple way to map it with one-to-one correspondence to a large integer number? Say, we have N=3 vector space. Can we represent a vector X=[(int16)x1,(int16)x2,(int16)x3] using an integer (int48)y? The obvious answer is "Yes, we can". But the question is: "What is the fastest way to do this and its inverse operation?" Will this new 1-dimensional space possess some very special useful properties?
For the above example you have 3 * 32 = 96 bits of information, so without anya prioriknowledge you need 96 bits for the equivalent long integer. However, if you know that your x1, x2, x3, values will always fit within, say, 16 bits each, then you can pack them all into a 48 bit integer. In either case the technique is very simple you just useshift,maskandbitwise oroperations to pack/unpack the values.
I wonder if it's possible for an Apache module to change global config structures. What I want to achieve is injecting new vhosts without Apache restart. Of course I'm aware that the changes would fully take effect after all workers have recycled, but for me - it's still better than a restart. I've written an Apache module before, but the configuration is an unknown land to me. While reading config.c, I noticed that a function called ap_build_config() could be helpful, but how do I call it to do what I need? Is it at all possible?
The mailing list guys have answered this question quite well. http://mail-archives.apache.org/mod_mbox/httpd-modules-dev/201006.mbox/%[email protected]%3e
I'm getting ready to make a drawing application in Windows. I'm just wondering, do drawing programs have a memory bitmap which they lock, then set each pixel, then blit? I don't understand how Photoshop can move entire layers without lag or flicker without using hardware acceleration. Also in a program like Expression Design, I could have 200 shapes and move them around all at once with no lag. I'm really wondering how this can be done without GPU help. Also, I don't think super efficient algorithms could justify that?
Look at this question: Reduce flicker with GDI+ and C++ All you can do about DC drawing without GPU is to reduce flickering. Anything else depends on the speed of filling your memory bitmap. And here you can use efficient algorithms, multithreading and whatever you need.
I want to make an application that can generate point to point gradient (like Photoshop does). I'm familiar with how to generate an up to down gradient but not point to point. How is this conceptually done. Thanks
I can't say if this isexactlyhow Photoshop does it, or that it's the most optimal way of doing it, but this should be the basic principle. Think of the two points as defining a vector. You can find a normal vector for this, which will be perpendicular to the original vector (since that's the definition of a normal vector). For each discrete point (pixel) on the line, calculate the gradient color as you would for an up-down (or left-right) gradient of the same length as your vector. Then draw a line of the selected color, such that it passes through the currently chosen point and is parallel with the normal vector. It's actually very similar to the approach you'd use for an up-down gradient, except it's rotated.
Having been writing Java code for many years, I was amazed when I saw this C++ statement: ``` int a,b; int c = (a=1, b=a+2, b*3); ``` My question is: Is this a choice of coding style, or does it have a real benefit? (I am looking for a practicle use case) I think the compiler will see it the same as the following: ``` int a=1, b=a+2; int c = b*3; ``` (What's the offical name for this? I assume it's a standard C/C++ syntax.)
It's thecomma operator, used twice. You are correct about the result, and I don't see much point in using it that way.
``` union { int i; bool b; } x; x.i = 20000; x.b = true; cout << x.i; ``` It prints out 19969. Why does it not print out 20000?
Aunionis not astruct. In aunion, all of the data occupies the same space and can be treated as different types via its field names. When you assigntruetox.b, you are overwriting the lower-order bits of20000. More specifically: 20000 in binary: 100111000100000 19969 in binary: 100111000000001 What happened here was that you put a one-byte value of 1 (00000001) in the 8 lower-order bits of 200000. If you use astructinstead of aunion, you will have space for both anintand abool, rather than just anint, and you will see the results you expected.
I was wondering if there is a recommended 'cross' Windows and Linux method for the purpose of converting strings from UTF-16LE to UTF-8? or one should use different methods for each environment? I've managed to google few references to 'iconv' , but for somreason I can't find samples of basic conversions, such as - converting a wchar_t UTF-16 to UTF-8. Anybody can recommend a method that would be 'cross', and if you know of references or a guide with samples, would very appreciate it. Thanks, Doori Bar
Change encoding to UTF-8 with PowerShell: ``` Get-Content PATH\temp.txt -Encoding Unicode | Set-Content -Encoding UTF8 PATH2\temp.txt ```
I've got some analysis code (myprog) that sucks in data using the following: ``` if(5 == fscanf(in, "%s%lf%f%f%f", tag, & sec, & tgt, & s1, & s2)) ``` which works just fine. But in the situation where I've got data files that are separated by commas, I'm currently doing something like: ``` sed 's/,/ /g' data | myprog ``` Can I modify the format string in thefscanf()function to accept both delimitation formats?
``` fscanf(in, "%[^, ]%*[, ]%lf%*[, ]%f%*[, ]%f%*[, ]%f", tag, &sec, &tgt, &s1, &s2) ``` Should work?
I have the following code that I'm reading through: ``` if( (i%2) == 0 ){ *d = ((b & 0x0F) << 4); } else{ *d++ |= (b & 0x0F); }; ``` I'm looking specifically at theelsestatement and wondering in what order this occurs? I don't have a regular C compiler, so I can't test this. When we are performing*d++ |= (b & 0x0F);, what order does this occur in?
The ++ is applied on the pointerd, not on the lvalue that is being assigned to,*d. If you really want to, you can think of it like this: The value ofbis bitwise-AND:ed with the constant0x0fThe resulting bit pattern is bitwise-OR:ed into the value thatdpoints at.The pointerdis incremented to point at the next value.
I'm an extension noob. What I want to do is create an extension that doesn't require other libraries to be installed. Is this impossible because the extension has to link against a specific version of libpython at runtime?
You can't make a statically linked extension module because Python needs to load it dynamically at runtime and because (as you reasoned) the module needs to dynamically link against libpython. You could compile your own custom version of Python with your extension statically linked into the interpreter. That's usually more trouble than it's worth. Why do you want to make a statically linked extension? If we have more information about your goals, we might be able to help you achieve them in a different way. Welcome to StackOverflow. :-)
How do I get the UTC time in milliseconds under the Windows platform? I am using the standard library which give me UTC time in seconds. I want to get the time in milliseconds. Is there a reference of another library which give me the accurate UTC time in milliseconds?
UseGetSystemTimeAPI function, or perhapsGetSystemTimeAsFileTimeif you want a single number.
I am usingopen_memstreamin a library of mine, but I would like to port this library to MSVC. It seems there are no equivalent function available, but is there something similar enough? Whatopen_memstreamdoes is it takes a char** destination and size and returns a FILE* which you many write to, the data is stored in a dynamically allocated buffer (accessible from the char** argument). When closing the FILE the char** contains the data that was written to the stream. This makes an easy way to construct large and complex string streams. While it is possible to both read and seek from the memstream I only write to it. Is there a way to open a similar memory FILE stream in MSVC? Also, this is pure C, no C++.
A similar function on Windows would be CreateStreamOnHGlobal(). That however works with the IStream COM interface, it isn't a drop-in replacement for FILE. You might want to take a peek at the Cygwin source code to see what they did.
I have seen some performance figures are represented by MCPS unit, especially in some dsp codec performance. Can anybody clarify me this? /kanu__
It essentially means that some trivial operation can be done N million times each second. For example, the processor could perform up to N million arithmetic operations of certain kind each second and not more.
I just wanted to know how to use C to automatically assign a free port (and see what was used) if a specific port number is not provided. For example, i'm using this: ``` struct sockaddr_in address; address->sin_family = AF_INET; address->sin_addr.s_addr = INADDR_ANY; address->sin_port = htons( port ); ``` But how can I replace the sin_port assignment and let C automatically assign for me? Thanks!
Matt has already answered the "how to assign a free port" part (use sin_port = 0). To answer the second part, i.e. "how to see what was used", usegetsockname()
I have calledgetpeernameon my connected socket and now have an IPv6 address of the connected peer. How do I tell whether my peer's IP address is localhost? Edit: To clarify, I mean specificallylocalhost, as in the loopback IP address.
In IPv6, the loopback address is::1. At the binary level, that is 127 0's followed by a single 1.
I have the coordinates (x,y) of 2 points. I want to build the third point so that these 3 points make an equilateral triangle. How can I calculate the third point? Thank you
After reading the posts (specially vkit's) I produced this simple piece of code which will do the trick for one direction (remember that there are two points). The modification for the other case shold be trivial. ``` #include<stdio.h> #include<math.h> typedef struct{ double x; double y; } Point; Point vertex(Point p1, Point p2){ double s60 = sin(60 * M_PI / 180.0); double c60 = cos(60 * M_PI / 180.0); Point v = { c60 * (p1.x - p2.x) - s60 * (p1.y - p2.y) + p2.x, s60 * (p1.x - p2.x) + c60 * (p1.y - p2.y) + p2.y }; return v; } ```
Quick and easy C question:char* foo How can I test iffoohasn't still been assigned a value? Thanks.
You can't. Instead, initialize it withNULLand check whether it isNULL: ``` char *foo = NULL; ... if(!foo) { /* shorter way of saying if(foo == NULL) */ ```
in Java I think it is possible to cruise through jar files like they were not compressed. Is there some similar (and portable) thing in C/C++ ? I would like to import binary data into memory from a large (zipped or similar) file without decompressing to disk first and afterwards writing to disk in a compressed way. Maybe some trick with shell pipes and the zip utility?
I think you want zlib:http://www.zlib.net/
Does the Windows native API support timers? I am aware that POSIX implementations on Windows support timers, but I am interested in Windows SDK APIs.
Yes there are timers in Win32 API. More details you can check here :Timers In particular you need to check SetTimerKillTimerTimerProcWM_TIMER
what is the best way to create a gradient for a 2D polygon in OpenGL, (Linear, and Radial)? Thanks How can you generate textures for radial gradients on the fly?
Linear is very easy - you just set different colors to different points like ``` red ---- red | | | | | | blue ---- blue ``` for radial texture might be better option to generate it on fly create empty texture then fill it with function sqrt((MAXX - x)^2 + (MAXY - y)^2), then add color to it.
I have created a control and the mosemove for that control makes it change color, but I want to change it back to default when my mouse moves out of that control. I would have thought WM_MOUSELEAVE would do it but it didn't. Thanks
That would be the correct message. Are you callingTrackMouseEvent?
I have a buffer with the UTC time stamp in C, I broadcast that buffer after every ten seconds. The problem is that the time difference between two packets is not consistent. After 5 to 10 iterations the time difference becomes 9, 11 and then again 10. Kindly help me to sort out this problem. I am using<time.h>for UTC time.
If your time stamp has only 1 second resolution then there will always be +/- 1 uncertainty in the least significant digit (i.e. +/- 1 second in this case). Clarification: if you only have a resolution of 1 second then your time values arequantized. The real time,t, represented by such a quantized value has a range oft..t+0.9999. If you take the difference of two such times,t0andt1, then the maximum error int1-t0is-0.999..+0.999, which when quantized is+/-1second. So in your case you would expect to see difference values in the range9..11seconds.
hello everyone I'm working with Eclipse under Windows XP, but I can't find there glut library, all I have inside GL are only gl.h, glu.h and glext.h, can somebody please help me import glut library and explain what is this glext.h, thanks in advance for any help
1.copy all glut files into their corresponding locations include,lib,GL in x64mingw compiler folder ,and copy the glut.dll into c://windows/system32 2.in eclipse , project->properties_>c/c++ build->settings->mingw -> libraries 3.add these libraries glu32,opengl32,freeglut this should add the libraries. :)
For a project I'm trying to read an int and a string from a string. The only problem issscanf()appears to break reading an%swhen it sees a space. Is there anyway to get around this limitation? Here's an example of what I'm trying to do: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { int age; char* buffer; buffer = malloc(200 * sizeof(char)); sscanf("19 cool kid", "%d %s", &age, buffer); printf("%s is %d years old\n", buffer, age); return 0; } ``` What it prints is:cool is 19 years oldwhere I needcool kid is 19 years old. Does anyone know how to fix this?
The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]). ``` sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer); ```
I'm able to download text documents (.html, .txt, etc) but I can't download images or exe's. I'm pretty sure that this is because I'm using a char, and those files are binary. I know that in C# I would use a byte. But what data-type would I use in this case? ``` char buffer[1]; DWORD dwRead; FILE * pFile; pFile = fopen(file,"w"); while (InternetReadFile(hRequest, buffer, 1, &dwRead)) { if(dwRead != 1) break; fprintf(pFile,"%s",buffer); } fclose(pFile); ```
Your problem is not char, it is using fprintf with %s.charcan hold all byte values. When a binary data chunk has a\0(NULL) character in it, fprintf will stop outputting data at that time. You want to usefwritein this case. In Windows, it is also important to use thebspecifier when opening binary files.
To read anintusing scanf we use: ``` scanf("%d", &i); ``` What ifiis alongnotint?? Note: when using%dwithlongit gives me an irritating warning..
Just use ``` long l; scanf("%ld", &l); ``` it gives me an irritating warning.. That warning is quite right. This is begging for stack corruption.
I figured out the answer to this question, but I couldn't find the solution on here, so posting it for posterity. So, in Objective-C, how do you create an object out of a pointer in order to store it in objective-c collections (NSArray, NSDictionary, NSSet, etc) without reverting to regular C?
``` NSValue *pointerObject = [NSValue valueWithPointer:aPointer]; ``` This will wrap the pointer in an NSValue. To get it back out later use NSValue's instance method (pointerValue:)
I have to call several (> 10) .exe command line programs in the background. Creating a Windows Services doesn't sound very appealling in this context - c'mon, that's a bit overpowered for such a simple task. Is there anything like adaemon(3)subroutine for Windows?
You might look into using thesrvany.exeservice wrapper found in theWindows Server 2003 Resource Kit Tools. I have used this method quite successfully under Windows XP, but I cannot comment on how it may work for newer versions of the OS. There seems to beplenty of information available1on how to use this tool. 1 - Google search for srvany+howto
In the sake of debugging purposes, can I get the line number inC/C++ compilers? (standard way or specific ways for certain compilers) e.g ``` if(!Logical) printf("Not logical value at line number %d \n",LineNumber); // How to get LineNumber without writing it by my hand?(dynamic compilation) ```
You should use the preprocessor macro__LINE__and__FILE__. They are predefined macros and part of the C/C++ standard. During preprocessing, they are replaced respectively by a constant string holding an integer representing the current line number and by the current file name. Others preprocessor variables : __func__: function name (this is part ofC99, not all C++ compilers support it)__DATE__: a string of form "Mmm dd yyyy"__TIME__: a string of form "hh:mm:ss" Your code will be : ``` if(!Logical) printf("Not logical value at line number %d in file %s\n", __LINE__, __FILE__); ```
NSLog function accepts printf format specifiers. My question is about %x specifier. Does this print hex codes as sequence on memory? Or does it have it's own printing sequence style? ``` unsigned int a = 0x000000FF; NSLog(@"%x", a); ``` Results of above code on little or big endian processors are equal or different? And how about NSString's -initWithFormat method? Does it follows this rule equally?
%x always prints the most significant digits first. Doesn't matter what kind of processor it is running on.
I'd like to determine the environment's current codepage at runtime from a Unix shell script. What's the most reliable way of doing this? I'm looking into parsing environment variable $LC_ALL, but it isn't always set to a useful value, and its format seems to vary (can be <locale>, or <locale>.<code page>, or <locale>.<code page>@<modifier> etc...). Is there a better way? I'm essentially after a shell equivalent of what I'd get if I called nl_langinfo(CODESET) from C.
Run: ``` locale charmap ```
I read about the Microsoft specific suffix "i64" for integer constants. I want to do an UNsigned shift to a ULONGLONG.ULONGLONG bigNum64 = 0x800000000000000i64 >> myval; In normal C, I would use the suffix "U", e.g. the similar 32 bit operation would beULONG bigNum32 = 0x80000000U >> myval; I do NOT want the 2's complement sign extension to propogate through the high bits. I want an UNSIGNED shift on a 64 bit const number. I think my first statement is going to do a SIGNED shift right. I tried0x800000000000000i64Uand0x800000000000000u64but got compiler errors.
You can use the suffixull, which is the standard (C99 and C++0x) way to specify anunsigned long longinteger literal, and along longis at least 64 bits.
I use EnumChildWindows to get all the Child windows from the main HWND window , But i would like to get only the first child of the given HWND window. ``` BOOL CALLBACK EnumChildProc ( HWND hwndChild, LPARAM lParam) { // logic to call only once } ``` Is it correct ? or any other simple way ? ~UK
``` BOOL CALLBACK EnumChildProc ( HWND hwndChild, LPARAM lParam) { // process first child window return FALSE; } ``` Alternatively,HWND top_child = GetWindow(thisWindow, GW_CHILD);
I need to compute imaginary exponential in C. As far as I know, there is no complex number library in C. It is possible to gete^xwithexp(x)ofmath.h, but how can I compute the value ofe^(-i), wherei = sqrt(-1)?
In C99, there is acomplextype. Includecomplex.h; you may need to link with-lmon gcc. Note that Microsoft Visual C does not supportcomplex; if you need to use this compiler, maybe you can sprinkle in some C++ and use thecomplextemplate. Iis defined as the imaginary unit, andcexpdoes exponentiation. Full code example: ``` #include <complex.h> #include <stdio.h> int main() { complex x = cexp(-I); printf("%lf + %lfi\n", creal(x), cimag(x)); return 0; } ``` Seeman 7 complexfor more information.
in a file, i have usedm-x ucs-insertto insert a hex character9e(which in emacs shows up as\236). however, when this is read in by the C program,9eis becoming0x9ec2. Where is thisc2coming from and how do i get rid of it??
The unicode character U+009E is represented in UTF-8 as the bytes C2 9E (see this handyconverter). It's likely that your emacs is set up to save files in UTF-8. Try loading the file in emacs withM-x find-file-literallyand see if it comes out as\302\236(octal representation of C2 9E). If so, you'll be able to delete the\302and see if that makes the program run better.
I want to create a custom malloc which allocates memory blocks within a given address range. I am writing a pthreads application in which threads are bound to unique cores on a many-core machine. The memory controllers are statically mapped, so that certain range of addresses on main memory are electrically closer to a core. I want to minimize the latency of communication between cores and main memory by allocating thread memory on these "closer" regions. Any ideas would be most appreciated. Thank you! Nandu
There is already libnuma for that purpose. Take a look atnuma_alloc_onnode
How do i add SOCKS support to my application? and where can i get the libs? any help appreciated thanks
You could tryBoost.Asiolibrary. It containsan examplewith SOCKS4 protocol implementation.
Searched through net, could't find a way to read/write file metadata using C or C++, however, there are tools available for this, and also there are API's in C# and Java to do this. But I want to do it from scratch in C or C++. For example, read/write image metadata. Have found out that there are three formats in which metadata is written to files. EXIF, IPTC and XMP. Thanks.
Why would you want to do it from scratch? Anyway, you need documentation and you may also want to look at an existing library for helps, expecially if you have no experience in the field. Have you triedExiv? Exiv2 is a C++ library and a command line utility to manage image metadata. It provides fast and easy read and write access to the Exif, IPTC and XMP metadata of images in various formats. Exiv2 is available as free software and with a commercial license, and is used in many projects.
I have a iPhone application with a few custom-defined colors for my theme. Since these colors will be fixed for my UI, I would like to define the colors in a class to be included (Constants.h and Constants.m). How do I do that? (Simply defining them does not work because UIColors are mutable, and would cause errors - Initalizer not constant). ``` /* Constants.h */ extern UIColor *test; /* Constants.m */ UIColor *test = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]; ``` Thanks!
A UIColor is not mutable. I usually do this with colors, fonts and images. You could easily modify it to use singletons or have a static initializer. ``` @interface UIColor (MyProject) +(UIColor *) colorForSomePurpose; @end @implementation UIColor (MyProject) +(UIColor *) colorForSomePurpose { return [UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]; } @end ```
I am making an iPhone app. I have a code that is in C. The C code contains a lot of pointers and global variables. I want to use this C code in my objective-c project. Can anybody please help me with this?
Objective-C is a perfect superset of C. Just add the file to your Xcode project like you normally would.
Is there a way to get pre-processedC/Objective-C code? I have some files I acquired and would like to see the code produced by some #defines.
From within Xcode: Xcode 3: Select the file, thenBuild → Preprocess.Xcode 4: Select the file, thenProduct → Generate Output → Generate Preprocessed File.
I want to be able to map memory to a file descriptor so I can use some existing functions that need a file descriptor. Here's essentially what I'm looking for: ``` void do_operation1(int fd); char data[DATA_MAX] = { /* embedded binary data */ }; int fd = addr_to_fd(data, DATA_MAX); do_operation1(fd); /* ... operate on fd ... */ ``` What system call, or calls, can I use to accomplish this?
Some implementations havefmemopen(). (Then of course you have to callfileno()). If yours doesn't, you can build it yourself withfork()andpipe().
I am trying to work out if I need to call close on a fstream object if the intial open failed. i.e. ``` std::fstream strm; strm.open( "filename" ); if( ! strm.fail() ) { // Do something strm.close(); // [1] } strm.close(); // [2] ``` Where shouldclosebe called here - should it always be called [2] or only if the open succeeds[1]? I may be going over the top here, but coming from the Windows API way of typically doing this I haveCloseHandle( ... );embedded in my mind :-)
The stream will be automatically closed by the fstream's destructor - there is no need to close it explicitly, unless your program logic demands it, for example if you are going to re-open it. However, closing a stream that didn't open won't cause any problems.
How can I free aconst char*? I allocated new memory usingmalloc, and when I'm trying to free it I always receive the error "incompatible pointer type" The code that causes this is something like: ``` char* name="Arnold"; const char* str=(const char*)malloc(strlen(name)+1); free(str); // error here ```
Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer;freetakes avoid*, not aconst void*: ``` free((char*)str); ```
Given that I have a pointer to a function (provided bydlsym()for example) and a linked list of typed arguments, how can I construct a C function call with those arguments? Example: ``` struct param { enum type { INT32, INT64, STRING, BOOL } type; union { int i32; long long i64; char *str; bool b; } value; struct param *next; }; int call_this(int (*function)(), struct param *args) { int result; /* magic here that calls function(), which has a prototype of f(int, long long, char *, bool); , when args consist of a linked list of INT32, INT64, STRING, BOOL types. */ return result; } ``` The OS is Linux. I would like the solution to be portable across MIPS, PPC and x86 (all 32 bits) architecture, using GCC as the compiler. Thanks!
You'll probably need to uselibffi.
can somebody explain me about redefinition in C: is it possible to do something like this ``` typedef struct NumberContainer* ptrNumberContainer; ``` and after that ``` typedef struct NumberContainer* ptrCall; ``` may it cause some problems during linkage? thanks in advance
No, that's perfectly OK - you have two synonyms for the same underlying type - this is quite common. However, the practice of hiding the fact that something is a pointer by using a typedef is generally viewed as bad practice in C.
i have time of the day in seconds and i have to find the utc time since 1970, is there any api which can directly convert this time to utc time, i m using ansi c , and working on windows platform platform independent api will be preferred thanx in advance.
You can fill in atm structwith the time of day you have (you'd have to convert it into seconds/minutes/hours) and the date. Then convert it withmktime()intime.h.
Plus, The program runs on a arm device running Linux, I can print out stack info and register values in the sig-seg handler I assign. The problem is I can't add -g option to the source file, since the bug may won't reproduce due to performance downgrade.
Compiling with the-goption togccdoesnotcause a "performance downgrade". All it does is cause debugging symbols to be included; it doesnotaffect the optimisation or code generation. If you install yourSIGSEGVhandler using thesa_sigactionmember of thesigactionstruct passed tosigaction(), then thesi_addrmember of thesiginfo_tstructure passed to your handler contains the faulting address.
The question shown below is an interview question: Q) You are given/have a datatype, say X in C. The requirement is to get the size of the datatype, without declaring a variable or a pointer variable of that type, And of course, without using sizeof operator ! I am not sure if this question has already been asked on SO. Thanks and regards Maddy
define sizeof_type( type ) (size_t)((type*)1000 + 1 )-(size_t)((type*)1000) The original is from this discussion.http://www.linuxquestions.org/questions/programming-9/how-to-know-the-size-of-the-variable-without-using-sizeof-469920/
gcc 4.4.3 c89 I have the following source code. And getting a stack dump on the printf. ``` char **devices; devices = malloc(10 * sizeof(char*)); strcpy(devices[0], "smxxxx1"); printf("[ %s ]\n", devices[0]); /* Stack dump trying to print */ ``` I am thinking that this should create an char array like this. ``` devices[0] devices[1] devices[2] devices[4] etc ``` And each element I can store my strings. Many thanks for any suggestions, == Added correction === ``` for(i = 0; i < 10; i++) { devices[i] = malloc(strlen("smxxxx1")+1); } ```
You have allocated memory for an array of pointers. You need to allocate the memory for each element to store the string e.g. ``` #define NUM_ELEMENTS 10 char **devices; devices = malloc(NUM_ELEMENTS * sizeof(char*)); for ( int i = 0; i < NUM_ELEMENTS; i++) { devices[i] = malloc( length_of string + 1 ); } ```
gcc 4.4.3 c89 I have the following code as a sample of what I am trying to do. I don't know the actual size of the array, until I enter the function. However, I don't think I can set the array size after I have declared it. I need it global as some other functions will need to access the device names. Many thanks for any suggestions, ``` /* global */ char *devices_names[]; void fill_devices(size_t num_devices) { devices_names[num_devices]; /* start filling */ } ```
You'll need to allocate the memory dynamically using malloc: ``` char **device_names; void fill_devices(size_t num_devices) { device_names = malloc(num_devices * sizeof(char*)); } ``` And then usefree(device_names);to free the memory when you no longer need it.
I am having a problem in my program that uses pipes. What I am doing is using pipes along with fork/exec to send data to another process What I have is something like this: ``` //pipes are created up here if(fork() == 0) //child process { ... execlp(...); } else { ... fprintf(stderr, "Writing to pipe now\n"); write(pipe, buffer, BUFFER_SIZE); fprintf(stderr, "Wrote to pipe!"); ... } ``` This works fine for most messages, but when the message is very large, the write into the pipe deadlocks. I think the pipe might be full, but I do not know how to clear it. I tried using fsync but that didn't work. Can anyone help me?
You need to close the read end of the pipe in the process doing the writing. The OS will keep data written to the pipe in the pipe's buffer untilallprocesses that have the read end of the pipe open actually read what's there.
I get a ton of errors in cstdio when I add#include <cstdio>to the C program. ``` c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\cstdio(17) : error C2143: syntax error : missing '{' before ':' c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\cstdio(17) : error C2059: syntax error : ':' ``` Thanks EDIT- I would like to usesnprintf, which is why I am trying to include this.
You want#include <stdio.h>.cstdiois the C++ wrapper for the C header. Edit:MSVC only supports the elements in C99 that form a subset of C++. This sitehas a C implementation ofsnprintf()licensed under the GPL.
Searched through net, could't find a way to read/write file metadata using C or C++, however, there are tools available for this, and also there are API's in C# and Java to do this. But I want to do it from scratch in C or C++. For example, read/write image metadata. Have found out that there are three formats in which metadata is written to files. EXIF, IPTC and XMP. Thanks.
Why would you want to do it from scratch? Anyway, you need documentation and you may also want to look at an existing library for helps, expecially if you have no experience in the field. Have you triedExiv? Exiv2 is a C++ library and a command line utility to manage image metadata. It provides fast and easy read and write access to the Exif, IPTC and XMP metadata of images in various formats. Exiv2 is available as free software and with a commercial license, and is used in many projects.
I have a iPhone application with a few custom-defined colors for my theme. Since these colors will be fixed for my UI, I would like to define the colors in a class to be included (Constants.h and Constants.m). How do I do that? (Simply defining them does not work because UIColors are mutable, and would cause errors - Initalizer not constant). ``` /* Constants.h */ extern UIColor *test; /* Constants.m */ UIColor *test = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]; ``` Thanks!
A UIColor is not mutable. I usually do this with colors, fonts and images. You could easily modify it to use singletons or have a static initializer. ``` @interface UIColor (MyProject) +(UIColor *) colorForSomePurpose; @end @implementation UIColor (MyProject) +(UIColor *) colorForSomePurpose { return [UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]; } @end ```
I am making an iPhone app. I have a code that is in C. The C code contains a lot of pointers and global variables. I want to use this C code in my objective-c project. Can anybody please help me with this?
Objective-C is a perfect superset of C. Just add the file to your Xcode project like you normally would.
Is there a way to get pre-processedC/Objective-C code? I have some files I acquired and would like to see the code produced by some #defines.
From within Xcode: Xcode 3: Select the file, thenBuild → Preprocess.Xcode 4: Select the file, thenProduct → Generate Output → Generate Preprocessed File.
I want to be able to map memory to a file descriptor so I can use some existing functions that need a file descriptor. Here's essentially what I'm looking for: ``` void do_operation1(int fd); char data[DATA_MAX] = { /* embedded binary data */ }; int fd = addr_to_fd(data, DATA_MAX); do_operation1(fd); /* ... operate on fd ... */ ``` What system call, or calls, can I use to accomplish this?
Some implementations havefmemopen(). (Then of course you have to callfileno()). If yours doesn't, you can build it yourself withfork()andpipe().
I am trying to work out if I need to call close on a fstream object if the intial open failed. i.e. ``` std::fstream strm; strm.open( "filename" ); if( ! strm.fail() ) { // Do something strm.close(); // [1] } strm.close(); // [2] ``` Where shouldclosebe called here - should it always be called [2] or only if the open succeeds[1]? I may be going over the top here, but coming from the Windows API way of typically doing this I haveCloseHandle( ... );embedded in my mind :-)
The stream will be automatically closed by the fstream's destructor - there is no need to close it explicitly, unless your program logic demands it, for example if you are going to re-open it. However, closing a stream that didn't open won't cause any problems.
How can I free aconst char*? I allocated new memory usingmalloc, and when I'm trying to free it I always receive the error "incompatible pointer type" The code that causes this is something like: ``` char* name="Arnold"; const char* str=(const char*)malloc(strlen(name)+1); free(str); // error here ```
Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer;freetakes avoid*, not aconst void*: ``` free((char*)str); ```
Given that I have a pointer to a function (provided bydlsym()for example) and a linked list of typed arguments, how can I construct a C function call with those arguments? Example: ``` struct param { enum type { INT32, INT64, STRING, BOOL } type; union { int i32; long long i64; char *str; bool b; } value; struct param *next; }; int call_this(int (*function)(), struct param *args) { int result; /* magic here that calls function(), which has a prototype of f(int, long long, char *, bool); , when args consist of a linked list of INT32, INT64, STRING, BOOL types. */ return result; } ``` The OS is Linux. I would like the solution to be portable across MIPS, PPC and x86 (all 32 bits) architecture, using GCC as the compiler. Thanks!
You'll probably need to uselibffi.
can somebody explain me about redefinition in C: is it possible to do something like this ``` typedef struct NumberContainer* ptrNumberContainer; ``` and after that ``` typedef struct NumberContainer* ptrCall; ``` may it cause some problems during linkage? thanks in advance
No, that's perfectly OK - you have two synonyms for the same underlying type - this is quite common. However, the practice of hiding the fact that something is a pointer by using a typedef is generally viewed as bad practice in C.
i have time of the day in seconds and i have to find the utc time since 1970, is there any api which can directly convert this time to utc time, i m using ansi c , and working on windows platform platform independent api will be preferred thanx in advance.
You can fill in atm structwith the time of day you have (you'd have to convert it into seconds/minutes/hours) and the date. Then convert it withmktime()intime.h.
Plus, The program runs on a arm device running Linux, I can print out stack info and register values in the sig-seg handler I assign. The problem is I can't add -g option to the source file, since the bug may won't reproduce due to performance downgrade.
Compiling with the-goption togccdoesnotcause a "performance downgrade". All it does is cause debugging symbols to be included; it doesnotaffect the optimisation or code generation. If you install yourSIGSEGVhandler using thesa_sigactionmember of thesigactionstruct passed tosigaction(), then thesi_addrmember of thesiginfo_tstructure passed to your handler contains the faulting address.
The question shown below is an interview question: Q) You are given/have a datatype, say X in C. The requirement is to get the size of the datatype, without declaring a variable or a pointer variable of that type, And of course, without using sizeof operator ! I am not sure if this question has already been asked on SO. Thanks and regards Maddy
define sizeof_type( type ) (size_t)((type*)1000 + 1 )-(size_t)((type*)1000) The original is from this discussion.http://www.linuxquestions.org/questions/programming-9/how-to-know-the-size-of-the-variable-without-using-sizeof-469920/
gcc 4.4.3 c89 I have the following source code. And getting a stack dump on the printf. ``` char **devices; devices = malloc(10 * sizeof(char*)); strcpy(devices[0], "smxxxx1"); printf("[ %s ]\n", devices[0]); /* Stack dump trying to print */ ``` I am thinking that this should create an char array like this. ``` devices[0] devices[1] devices[2] devices[4] etc ``` And each element I can store my strings. Many thanks for any suggestions, == Added correction === ``` for(i = 0; i < 10; i++) { devices[i] = malloc(strlen("smxxxx1")+1); } ```
You have allocated memory for an array of pointers. You need to allocate the memory for each element to store the string e.g. ``` #define NUM_ELEMENTS 10 char **devices; devices = malloc(NUM_ELEMENTS * sizeof(char*)); for ( int i = 0; i < NUM_ELEMENTS; i++) { devices[i] = malloc( length_of string + 1 ); } ```
gcc 4.4.3 c89 I have the following code as a sample of what I am trying to do. I don't know the actual size of the array, until I enter the function. However, I don't think I can set the array size after I have declared it. I need it global as some other functions will need to access the device names. Many thanks for any suggestions, ``` /* global */ char *devices_names[]; void fill_devices(size_t num_devices) { devices_names[num_devices]; /* start filling */ } ```
You'll need to allocate the memory dynamically using malloc: ``` char **device_names; void fill_devices(size_t num_devices) { device_names = malloc(num_devices * sizeof(char*)); } ``` And then usefree(device_names);to free the memory when you no longer need it.