question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to get GCC (or clang) to consistently use the SSE instruction for sqrt instead of the math library function for a computationally intensive scientific application. I've tried a variety of GCCs on various 32 and 64 bit OS X and Linux systems. I'm making sure to enable sse with -mfpmath=sse (and -march=core2 to satisfy GCCs requirement to use -mfpmath=sse on 32 bit). I'm also using -O3. Depending on the GCC or clang version, the generated assembly doesn't consistently use SSE's sqrtss. In some versions of GCC, all the sqrts use the instruction. In others, there is mixed usage of sqrtss and calling the math library function. Is there a way to give a hint or force the compiler to only use the SSE instruction?
Use thesqrtssintrinsic__builtin_ia32_sqrtss?
Windows hooks allows you to poke inside other processes and sometimes alter their behaviors. Is there such thing for Mac OS X? Thanks!
SetWindowsHookExis more like the oldInputManagerhack, in the sense that you change the code of an app from inside a shared library / a plugin loaded to it. SeeSIMBLfor a ready-made code injector to another process. For Objective-C classes, you then need to usemethod swizzling. I haven't tried replacing C functions / C++ classes myself, but surely it can be done usingmach_override. See alsothis blog post. But usually if you want to modify a GUI app, tapping into Objective-C classes would be sufficient.
I'm making a program that displays some info in ncurses, and then opens vim (usingsystem) to allow the user to edit a file. After vim is exited, though, the ncurses screen won't redraw.refreshandwrefreshdon't do anything, resulting in the complete trashing of my beautiful menu. So, I get sent back to the command line. The menu items redraw when I move to them. Moving around a bit results in something that looks like this: As you can see, I no longer am in my pretty ncurses environment,. I could tear down ncurses completely and set things up again, but then some stuff (like menu position) is not preserved. How do I do this correctly? Is there a better way to call some external program and return here gracefully?
I've never had to restart curses entirely. what if you do something like def_prog_mode()thenendwin() execute system call and refresh() should restore it
In c if I wanted to search a string for a particular character I can just do the following ``` char *p; p = (char *)strchr(buffer,'('); if(p){ .... ``` but what if I want to search for more than one character (or a character range) for example "any digit". I know I could do something like ``` char *p=0; char *i; for(i=buffer;*i!='\0';i++){ if(*i >= '0' && *i <=9){ p=i; } } if(p){ ... ``` assuming a properly terminated string etc. But is there a standard library function that already provides this functionality (hopefully more safely)
What aboutstrpbrk? Sounds like it fits your bill. ``` const char * strpbrk ( const char * str1, const char * str2 ); ``` "Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches." EDIT: Link is to a C++ site, butstrpbrkis part of the standard C library.
I have a method like this: ``` - (CGPoint) _convertCGPointCT2UIKit:(CGPoint)ctPoint{ CGPoint uikitPoint = CGPointMake(ctPoint.x + INITIAL_HORIZ_OFFSET, self.bounds.size.height - ctPoint.y - INITIAL_VERT_OFFSET); return uikitPoint; } ``` Is there any way I can make this a macro? I tried this but I get errors like "; expected before )" and so on. ``` #define CGPointUIKit2CT(p) CGPointMake(p.x - INITIAL_HORIZ_OFFSET, self.bounds.size.height - p.y - INITIAL_VERT_OFFSET); ``` thanks in advance. Ignacio
A couple of rules of thumb to guide you: Wrapeverythingin parenthesesDon't end a macro with a semicolon, that's probably what's generating your errors. Instead put the semicolon in your code when you use it. Here's my answer: ``` #define CGPointUIKit2CT(p) CGPointMake(((p).x) - INITIAL_HORIZ_OFFSET, self.bounds.size.height - ((p).y) - INITIAL_VERT_OFFSET) ```
Even though OOP uses objects and data encapsulation, the code still writes out like a procedure. So what makes OOP loose the procedural label? Is it just because it is considered "high-level"? Thank You.
It's not that Object-orient Programming is "non-Procedural"; it's just that the code we call "Procedural" is not Object-oriented (and not Functional and probably not a couple others) It's not so much an either-or case, but a slow gradiate: Spaghetti code -> Structured Code -> Object-oriented code -> Component code. (UPDATE: Removed "Procedural" from the chart above, since it refers to all of the right 3/4rds of it)
This question already has answers here:Closed13 years ago. Possible Duplicate:C programming, why does this large array declaration produce a segmentation fault? This is my first time here so sorry if I break some rules or if this has been answered before. I recently made a C program in which I had a matrix of ``` char buff[NR][1024*1024]; ``` I needed NR = 128. So the program would alocate 128MB. This was in main(). I tried it on a few systems with enough memory with no error on compile. At runtime I recieved segmentation fault on all systems. It worked for NR = 7, but not 8. I moved that code outside of main making it global. It didn't crash anymore even for 128. Does anyone know why this happened? The compiler was GCC
The problem is you are overflowing the stack which is typically just a few MB in size (the exact size depends on the system and your compiler options). You could allocate the memory on the heap instead usingmalloc.
I need to run some code on storage device mounting and unmounting.How can i listen for these events on linux? I was thinking on adding someudevrules to run some script (any know-how in this matter is appreciated).But I would much rather listen for events from the kernel in some netlink socket with my daemon (just like udev does) or something like that.
You can uselibudevor the more convenient, glib basedgudevto monitor udev events in C.
I want to iterate over each pixel color in ajpgformat image, which library should I refer to to do this so that the code can be as short as possible?
I can think of eitherImageMagickorCImg. Here is aCImg tutorialfor you. They abstract away a lot of the decompression details and just give you a grid to work with. If you go with CImg, you only need to use thedatacall. You can probably do something like: ``` CImg<unsigned char> src("image.jpg"); int width = src.width(); int height = src.height(); unsigned char* ptr = src.data(10,10); // get pointer to pixel @ 10,10 unsigned char pixel = *ptr; ```
I want to write a console application in C in VS 2008. What project type do I need to select and what properties I must set in order to do this?
C++ - Projects - Win32 Project - Console Application. When application is created, rename .cpp files to .c. In the Project Properties, C++, Advanced, select Compile As C code (/TC).
Programming in a sense is easy. But bugs are something which always makes more trouble. Can anyone help me with good debugging tricks and softwares in c?
From"The Elements of Programming Style"Brian Kernighan, 2nd edition, chapter 2: Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? So from that; don't be "too clever"! But apart from that and the answers already given; use a debugger! That is your starting point tool-wise. You'd be amazed how many programmers struggle along without the aid of a debugger, and they are fools to do so. But before you even get to the debugger, get your compiler to help you as much as possible; set the warning level to high, and set warnings as errors. A static analysis tool such as lint, pclint, or QA-C would be even better.
How do I print#include<conio.h>in C ``` #include<stdio.h> #include<conio.h> void main() { printf("#include<conio.h>"); } ``` How to get the output as ``` #include<conio.h> ``` you have to put getch(); and press Ctrl+f9 instead of alt+f5
I don't think you need to do anything else. You have written the solution yourself. All you have to do is justCompileandRun......... :)
I am currently writing a programming language in C/C++ as an exercise (but mostly for fun). At the moment it compiles into a list of commands that are then executed (kind of like a low-level API). Its working fantastically, however, I think it would be more exciting if instead of having a interpreter executable, having the language actually compile into a .exe file. I don't know if it is possible or how challenging this might be. I could not find any resources to help me with this. - Thanks in advance.
You could consider writing afrontendfor LLVM (tutorial) or GCC (article from linux journal) - if thats still fun for you is a different question.
I tried to use several implementations, but all of them had bugs.Search at SO gave mehttp://www-igm.univ-mlv.fr/~lecroq/string/node14.html- looks nice, but this implementation gave me wrong results - sometimes it doesn't found a string.I spent couple hours to find the bug. Following line looks fine: ``` j += MAX(bmGs[i], bmBc[y[i + j]] - m + 1 + i); ``` butyis char * and char issigned! It means that y[i + j] could be negative (what happens in one of my tests). My question is: Where to find correct implementation of Boyer Moore algorithm?
charisn't definitively signedorunsigned - it's unspecified, and left up to the implementation to define. If the algorithm depends on char being unsigned, then it should explicitly cast the input pointers tounsigned char(which is how the C standard library string handling functions are defined to work - all comparisons are done treating the characters in the string asunsigned char).
I'm wondering if simply compiling my msvc project with sse/sse2 will have any effect. I do for example vector normalization and dot product but I do these wth math, not any specific function. Is there like sse_dot() and sse_normalize() that I should be using to actualyy take advantage, or will the compiler know? Thanks
As I understand it, using the sse2 compiler option will result in the compiler using the scalar not vector sse2 instructions in place of normal fpu code. I don't think it will do any vectorisation. The sse2 scalar stuff is quicker than fpu for sure. To use the vector unit you need to use either intrinsics directly ( xmmintrin.h ) or use 3rd party libs that do. If you're just doing simple vector/matrix stuff for rendering, the Bullet SDK has an sse optimised vector math lib that's not bad. IIRC the DirectX/XNAmath lib is sse optimised too. If neither of those take your fancy, Google should turn up a number of alternatives.
I made a program which removes spaces and makes a string upper case by preprocessor directives .its not changing to uppercase ``` #include <stdio.h> #include <conio.h> # define TOUPPER(x) (x-32) void main(void) { int i,j; char str[100],*p; clrscr(); printf("Enter the string:\n"); gets(str); for(i=0; ;i++) { if(str[i]=='\0') break; if(str[i]==' ') { for(j=i; ;j++) { str[j]=str[j+1]; if(str[j]=='\0') break; } } if(str[i]<='a'||str[i]>='z') { *p=str[i]; TOUPPER('p'); } } puts(str); getch(); } ```
YourTOUPPER('p')does exactly what it should, nothing. You're subtracting 32 from the numeric value of'p'and then throwing it away. Note that I'm referring to 'p' the character, notpthe pointer.
The main() function in an avr-gcc program saves the register state on the stack, but when the runtime calls it I understand on a microcontroller there isn't anything to return to. Is this a waste of RAM? How can this state saving be prevented?
How can the compiler be sure that you aren't going to recursively call main()?
C/C++ would be good option to write some of the performance critical aspects of a Ruby Application. I know this is possible. I would like to know how to add C/C++ code into Ruby code; any other language for that matter. Are there any practical applications of this which you noticed in open source projects or else?
Besides "Extending Ruby", here are two other resources: README.EXT (extension.rdoc)- shows you more about how to build C extensions. A good compliment to "Extending Ruby"Ruby Inline- This is a library that tries to make it easier to build C extensions by having you call methods in ruby to compile C code.
I can't get the codes right. Can somebody help? ``` #include<stdio.h> int main() { int n, sum,i,j; printf("Please enter an integer, n = "); scanf("%d", &n); for(i=1;i<=n;i++) for(j=1;j<=i;j++) sum = sum + n; printf("sum = %d", sum); return 0; } ```
You are not initialisingsum. Initialise it with0.You shouldn't be addingnat each step, butj. Of course, this is to fix your current code. There are better approaches to solving the problem, which others have already mentioned. Edit: Just for fun, here's a formula that allows you to solve the problem inO(1): Your sum is equal ton*(n + 1)*(2*n + 1) / 12 + n*(n + 1) / 4. This is obtained by writing it as a sum and using the fact that the sum of the firstnconsecutive squares isn(n + 1)(2n + 1) / 6and the sum of the firstnpositive ints isn(n + 1)/2. +1 if you can find a nicer form of the formula.
Where are the garbage value stored, and for what purpose?
C chooses to not initialize variables to some automatic value for efficiency reasons. In order to initialize this data, instructions must be added. Here's an example: ``` int main(int argc, const char *argv[]) { int x; return x; } ``` generates: ``` pushl %ebp movl %esp, %ebp subl $16, %esp movl -4(%ebp), %eax leave ret ``` While this code: ``` int main(int argc, const char *argv[]) { int x=1; return x; } ``` generates: ``` pushl %ebp movl %esp, %ebp subl $16, %esp movl $1, -4(%ebp) movl -4(%ebp), %eax leave ret ``` As you can see, a full extra instruction is used to move 1 into x. This used to matter, and still does on embedded systems.
When I link to the one under Release/ ,got a fatal error: ``` LINK : fatal error LNK1146: no argument specified with option '/machine:' ``` Then I tried to link to the.libunderDebug/and this time it works. But what can be different?
Usually, no optimization is done to debug assemblies, while release assemblies are optimized. Debug assemblies will also often contain cruft like source file line numbers.
I have 2 froms, primary and secondary in my gtk+ application. In second from i have GtkButton - close. How can i close this form when button clicked. Not hide, i need close form. Thank you
If you are adding the form to the main window, in the callback function you can remove that from from the main window using the corresponding API and destroy the widget. Your form is of type GtkWidget and hence you can remove and destroy the form. After this set the current form to the prev form on the main window. Andgtk_widget_show_all(main_window);
Is there any function to import a C library (.so) file in the Solaris operating system? In Windows I can useWin32::API, how about Solaris? Thank you.
XSLoaderlooks to be the simple interface. DynaLoaderlooks to be the more complex interface. But your modules have to be tailored to be imported into Perl; theSWIGtoolkit may be the best tool to marshal data between native C and native Perl.
I want to initialize an double array with size 200, and its value is from 0 to 199 from index 0 to 199 in c++. i know i can do it by a simple For loop, but is there a way just to initialize the double array like this? Thanks
Not really. A for loop is your best option: ``` double array[200]; for(int i = 0; i < 200; i++) array[i] = static_cast<double>(i); ```
I was talking with a co-worker about C and C++ and he claimed that C is object-oriented, but I claimed that it was not. I know that you can do object-oriented-like things in C, but C++ is a true object-oriented language. What are your thoughts? Also, it triggered discussion on who decides what it means to be object-oriented and that it's tough to say what object-oriented really officially means. What are you thoughts on this?
If by "is C object oriented?" you mean "is C designed with facilities specifically to support object oriented programming?" then, no, C is clearly not object oriented.
which function do i use to give such linux terminal calls in my c program?
systemwould be the correctposix call. It takes a pointer to char as the command to be executed. Seeman 3 system. Howeversystemcan be completely corrupted by environment variables and an harder-to-use alternative isexec(seehere). A little example to illustrate: ``` system("xeyes"); system("rm -rf $HOME"); /* never ever try this, really */ ```
I was going through are-entrancy guideon recommended practices when writing re-entrant code. What other references and resources cover this topic? What lint-like tools can be used to check for these issues?
Do use local variables.Don't use static locals or global variables, even TLS will not help you with recursion / reentrancy.Restore all your invariants before doing callbacks.Don't hold locks while you do callbacks. If you absolutely must (and I would still go looking for a way to avoid it) then make sure you know what happens if you try to re-enter your lock on the thread that already holds it. At a minimum you have to test for this, otherwise depending on the lock you'll get deadlocks or broken invariants (i.e. corruption).
I have 2 froms, primary and secondary in my gtk+ application. In second from i have GtkButton - close. How can i close this form when button clicked. Not hide, i need close form. Thank you
If you are adding the form to the main window, in the callback function you can remove that from from the main window using the corresponding API and destroy the widget. Your form is of type GtkWidget and hence you can remove and destroy the form. After this set the current form to the prev form on the main window. Andgtk_widget_show_all(main_window);
Is there any function to import a C library (.so) file in the Solaris operating system? In Windows I can useWin32::API, how about Solaris? Thank you.
XSLoaderlooks to be the simple interface. DynaLoaderlooks to be the more complex interface. But your modules have to be tailored to be imported into Perl; theSWIGtoolkit may be the best tool to marshal data between native C and native Perl.
I want to initialize an double array with size 200, and its value is from 0 to 199 from index 0 to 199 in c++. i know i can do it by a simple For loop, but is there a way just to initialize the double array like this? Thanks
Not really. A for loop is your best option: ``` double array[200]; for(int i = 0; i < 200; i++) array[i] = static_cast<double>(i); ```
I was talking with a co-worker about C and C++ and he claimed that C is object-oriented, but I claimed that it was not. I know that you can do object-oriented-like things in C, but C++ is a true object-oriented language. What are your thoughts? Also, it triggered discussion on who decides what it means to be object-oriented and that it's tough to say what object-oriented really officially means. What are you thoughts on this?
If by "is C object oriented?" you mean "is C designed with facilities specifically to support object oriented programming?" then, no, C is clearly not object oriented.
which function do i use to give such linux terminal calls in my c program?
systemwould be the correctposix call. It takes a pointer to char as the command to be executed. Seeman 3 system. Howeversystemcan be completely corrupted by environment variables and an harder-to-use alternative isexec(seehere). A little example to illustrate: ``` system("xeyes"); system("rm -rf $HOME"); /* never ever try this, really */ ```
I was going through are-entrancy guideon recommended practices when writing re-entrant code. What other references and resources cover this topic? What lint-like tools can be used to check for these issues?
Do use local variables.Don't use static locals or global variables, even TLS will not help you with recursion / reentrancy.Restore all your invariants before doing callbacks.Don't hold locks while you do callbacks. If you absolutely must (and I would still go looking for a way to avoid it) then make sure you know what happens if you try to re-enter your lock on the thread that already holds it. At a minimum you have to test for this, otherwise depending on the lock you'll get deadlocks or broken invariants (i.e. corruption).
I am working on a programming language. Currently it compiles to C. I would like to be able to include parallel programming facilities natively in my language so as to take advantage of multiple cores. Is there a way to write parallel C programs which is cross-platform? I would prefer to stick to straight C so as to maximize the number of platforms on which the language will compile.
Depending on what you want to do,OpenMPmight work for you. It is supported by GCC, VC++, ICC and more.
I use libexif in my C/gtk+ application. But i want to make it optional. What must i to write in my configure file for to do this? Thank you
You can check conditional compilationhere. And define the calls under those flags.
Is there any portable way (on POSIX systems) to determine if a file descriptor is seekable? My thought is to uselseek(fd, 0, SEEK_CUR);and check if the return value is -1, but I'm uncertain if this could give false negatives or false positives. Usingfstatand making assumptions about what types of files are seekable/nonseekable does not sound like a good idea. Any other ideas?
Thelseekmethod seems reasonable. It certainly can't cause a false negative - if it did, something is seriously wrong with the implementation. Also, according to thePOSIX spec, it is supposed to fail if the descriptor is a pipe, FIFO or socket, so theoretically you shouldn't have false positives either. The only remaining question is how well different systems comply with the specs. However, it seems like any other methods, whatever they may be, would definitely be less portable than this.
When we subtract a pointer from another pointer the difference is not equal to how many bytes they are apart but equal to how many integers (if pointing to integers) they are apart. Why so?
The idea is that you're pointing to blocks of memory ``` +----+----+----+----+----+----+ | 06 | 07 | 08 | 09 | 10 | 11 | mem +----+----+----+----+----+----+ | 18 | 24 | 17 | 53 | -7 | 14 | data +----+----+----+----+----+----+ ``` If you haveint* p = &(array[5])then*pwill be 14. Goingp=p-3would make*pbe 17. So if you haveint* p = &(array[5])andint *q = &(array[3]), thenp-qshould be 2, because the pointers are point to memory that are 2 blocks apart. When dealing with raw memory (arrays, lists, maps, etc) draw lots of boxes! It really helps!
I'm wondering whether static constant variables are thread-safe or not? Example code snippet: ``` void foo(int n) { static const char *a[] = {"foo","bar","egg","spam"}; if( ... ) { ... } } ```
Any variable that is never modified, whether or not it's explicitly declared as const, is inherently thread-safe. constis not a guarantee from the compiler that a variable is immutable.constis a promise thatyoumake to the compiler that a variable will never be modified. If you go back on that promise, the compiler will generate an error pointing that out to you, but you can always silence the compiler by casting away constness.
Here is the context of the code: ``` void THREAD_CC server_thread(void *arg) { BIO *client = (BIO *)arg; ... } ``` Does the expression(BIO *)argtransform the void pointerarginto a pointer that points to BIO? I'm not sure if I got this right or not. Any help would be much appreciated! Z.Zen
It's called a cast; it doesn't transform the pointer, it persuades the compiler to take your word that the incoming pointer (which is untyped) is actually a pointer to BIO, and to treat it as such.
Can we compile C library as .Net dll (containing and opening access to all C libs functions) by just compiling cpp project containing code like ``` extern "C" { #include <library.h> } ``` with/clr:pureargument with VS? (VS10) Or we should do something more trickey?
This may be of interest to you:Compiling your C code to .NET Create a C compiler occil.exe To create a .NET dll from a c code e.g stack.c Step1: build stack.c to IL code ``` occil /ostackdll.il /c /Wd /9 /NStackLib.Stack stack.c ``` Step2: build to generated IL code to .NET DLL ``` ilasm /DLL stackdll.il ``` Then you canreference the stack.dllin a c# program and call the C function in stack.c
The following code seems to always generate wrong result. I have tested it on gcc and windows visual studio. Is it because of float overflow or something else? Thanks in advance:) ``` #include <stdio.h> #define N 51200000 int main() { float f = 0.0f; for(int i = 0; i < N; i++) f += 1.0f; fprintf(stdout, "%f\n", f); return 0; } ```
floatonly has 23 bits of precision. 512000000 requires 26. Simply put, you do not have the precision required for a correct answer.
How can we use any C library inside our C++ code? (Can we? Any tuts on that?) (I use VS10 and now talking about libs such as x264 and OpenCV)
Yes, the only thing you need to do is to wrap the#includestatement withextern "C"to tell the C++ compiler to use the C-semantics for function names and such: ``` extern "C" { #include <library.h> } ``` During linking, just add the library like any normal C++ lib.
How do I, without using third-party tools, craft TCP (and even UDP for that matter) packets in ANSI C? I want to be able to set all option flags, source ip address etc. So full control. Haven't found any good text about it online. Or I'm just using the wrong search criteria.
When I started cooking raw sockets on my own, I foundBeej'sguide to network programming as valuable as venerable Stevens "TCP/IP Illustrated" books serie.
I noticed Firefox 4, Opera and Chrome, and IE 7/8 put buttons and controls in the title/caption bar, how is this done? Thankshttp://img199.imageshack.us/img199/3307/slayerf.png alt text http://img199.imageshack.us/img199/3307/slayerf.png
What they probably do is turn the caption bar off entirely (by excluding the WS_CAPTION window style), add a glass area to the top of the window, and then draw their own controls. Seehttp://msdn.microsoft.com/en-us/magazine/cc163435.aspxfor more on glass.
I have a C# VS10 project. I want its part to be pure C. So I will have pure C library and A C# file that will have part with C code calling that pure Lib. So I'll have C part of code - not precompiled DLL but C code and C# code files. So is it possible to have inside one C# file C code like we have C code inside C++ code? like Inline C code inside C#... (I know it can sound strange but I really need it) Is it possible? Will I have posebilety to pass data from that C part to C#?
You can useP/Invoketo call C methods from C#. However, unless you have very good reasons, Ihighlyrecommend that use stick to C# and not use C. It is not possible to mix C and C# code in the same file. However, you can replicate any C code (except for callingCreateRemoteThread) in raw C# usingunsafecode and/or P/Invoke.
valgrind is reporting uninitialized memory errors from code like this: ``` unsigned char buf[100]; struct driver_command cmd; cmd.len = sizeof(buf); cmd.buf = buf; ioctl(my_driver_fd, READ, &cmd); for(i = 0; i < sizeof(buf); i++) { foo(buf[i]); /* <<--- uninit use error from valgrind */ } ``` If I memset() the buf before the driver call, the error goes away. Can valgrind detect whether the linux driver is properly writing to the buffer? (I looked at the driver code, and it seems to be correct, but maybe I'm missing something.) Or does it just pass the driver call through and has no way of knowing that the buffer has been written inside the kernel? Thanks.
Valgrind obviously can't trace execution into the kernel, but it does know the visible semantics of most system calls. Butioctlis too unpredictable. If you had coded your driver so that that was areadcall, it would get it right. That's better practice anyway.
I am doing some file IO with c code. I have a particular pattern in my file. I can verify this by a shell commandcat abc.txt | grep abc | wc -l. When I execute the same command usingSystem(), it give proper output, but I have no clue how can I get its output into a variable and compare it in my c code itself. I tried looking into man pages which suggest usingWEXITSTATUS(). This actually returns the status of execution and not output. F1 !!
You don't wantsystem(3)for that. Trypopen(3)and friends.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question I was wondering if there was a library or another way to produce multi contour polygons in OpenGL. I did code profiling and the GLUTesselator is killing my loop. Thanks Bounty+50 for a library with a GPL-compatible license, and ideally 3D (second best would be 2.5D like GLUtesselator itself.)
There's alwaysGPC. EDIT: Some others: Flipcodemystery triangulator. Slower than GPC in my extremely limited, probably wrong tests. poly2triis BSD-licensed. EDIT2:Earcut.hppis now a thing.
I want to change keyboard layout in Linux by programming, What X11's API function does this?
I found one good solution. It's a c++ class wrriten by Jay Bromley, that I can add to my app and using it. source code It's very easy to use: ``` #include "XKeyboard.h" XKeyboard xkb; std::string cGrpName=xkb.currentGroupName(); //return somethings like "USA" std::string cGrpSymb=xkb.currentGroupSymbol(); //return somethings like "us" xkb.setGroupByNum(0);//set keyboard layout to first layout in available ones ``` you can read source code and found some another useful functions. for compiling standalone version you need to un-comments "int main" function present in "XKeyboard.cpp" (or write your own main.cpp) and use somethings like this: ``` g++ *.cpp -o getxkblayout -L/usr/lib -lX11 ```
I have two c files, foo.c with the functionality and test_foo.c which test the functions of foo.c. Is there a way to access the struct typedefBARI defined in foo.c in test_foo.c without using a header file? So far, I was able to avoid a h file so that the whole program would consist of foo.c. Thanks. ``` foo.c typedef struct BAR_{...} bar; BAR *bar_new(...) {..} test_foo.c extern BAR *bar_new(...) ``` error: expected declaration specifiers or ‘...’ before ‘BAR’
The answer is that there is one, and you should use an header file instead. You can copy the definition of the structtypedef struct BAR_{...} bar;intotest_foo.cand it will work. But this causes duplication. Every solution that works must make the implementation of struct available to the compiler intest_foo.c. You may also use an ADT if this suits you in this case.
I'm looking for a function which can return the 'short' (8.3 notation) path for a given 'long' path. However, theGetShortPathNamefunction (which seemed like a perfect fit) doesn't work for me since it requires thata file with the given long path exists already. What other options do I have for computing the 8.3 path for a given long path?
If the file does not exist, it does not have an 8.3 name. The 8.3 name is created when the file is created. You can of course get the 8.3 pathname for the directory it's in usingGetShortPathNameon the directory itself, if you need that. Regardless, this is 2010. It's really backwards to be using 8.3 names foranything.
In C, what is meant by "functions with a variable number of parameters"?
printfis a nice example of that :) ``` printf("Call with no other variables"); printf("Call with %d variables", 1); printf("Call with %d variables. The other variable: %d", 2, 5); ```
Does today's C or C++ compilers use theclrscrsystem function?
clrscr()is a nonstandard function (neither mentioned inISO C99nor inISO C++-98) defined in<conio.h>(which is not standard compliant itself). However some compilers (likeTurbo C/C++) support it as an extension.
How i can know the size of all data type in my computer?
The following program should do the trick for the primitive types: ``` #include <stdio.h> int main() { printf("sizeof(char) = %d\n", sizeof(char)); printf("sizeof(short) = %d\n", sizeof(short)); printf("sizeof(int) = %d\n", sizeof(int)); printf("sizeof(long) = %d\n", sizeof(long)); printf("sizeof(long long) = %d\n", sizeof(long long)); printf("sizeof(float) = %d\n", sizeof(float)); printf("sizeof(double) = %d\n", sizeof(double)); printf("sizeof(long double) = %d\n", sizeof(long double)); return 0; } ``` This prints the number of "bytes" the type uses, withsizeof(char) == 1by definition. Just what 1 means (that is how many bits that is) is implementation specific and likely depend on the underlying hardware. Some machines have 7 bit bytes for instance, some have 10 or 12 bit bytes.
This question already has answers here:C++ type suffix _t, _type or none(4 answers)Closed4 years ago. I am confused when should I add the trailing_ttotypedef'ed types? For example, should I do this: ``` typedef struct image image_t; ``` or this: ``` typedef struct image image; ``` What are the general rules? Another example, should I do this: ``` typdef enum { ARRAY_CLOSED, ARRAY_OPEN, ARRAY_HALFOPEN } array_type_t; ``` or this: ``` typdef enum { ARRAY_CLOSED, ARRAY_OPEN, ARRAY_HALFOPEN } array_type; ``` Please enlighten me. Thanks, Boda Cydo.
In POSIX, names ending with_tare reserved, so if you are targeting a POSIX system (e.g., Linux), you should not end your types with_t.
I know how to do X amount of leading zeros, and I know how to do X amount of decimal points. But how do I do them both? I am looking to have 4 leading zeros with a decimal precision of 2:0000.00. Therefore43.4would be0043.40
Try thisprintf(C,Perl,PHP) format string: ``` "%07.2f" ```
Is there a way to print the name of the compiler and the version that was used to compile a program, something like; ``` printf("This is compiled with %s version %s\n", COMPILER, COMPILER_VERSION); ``` ?
You can do this with the pre-processor: Reference:http://predef.sourceforge.net/precomp.html For gcc: ``` #if defined(__GNUC__) # if defined(__GNUC_PATCHLEVEL__) # define __GNUC_VERSION__ (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) # else # define __GNUC_VERSION__ (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100) # endif #endif ``` For MSVC just use: ``` _MSC_FULL_VER ```
When talking about a process' memory, I heard about things likecode memoryanddata memory. And for thedata memory, there are 2 major managing mechanisms, stack and heap. I am now wondering how is thecode memorymanaged? And who manages it? Pardon me if my statement is not so clear. Thanks.
I recommendhttp://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory(and the other memory related articles) if you're interested in finding out more about the details of process' memory management. code memory = Text segment Notice how the address space is 4GB. When the kernel creates a process it gives it virtual memory. Below is an example of a 32 bit OS. The kernel manages what addresses get mapped to actual RAM via the processor'sMMU. So, the kernel and the MMU manage code memory, just as they manage the entire address space of a process. (source:duartes.org)
Currently, while compiling a C program which uses pthread library function I have to specify compiler option -lpthread explicitly. Please suggest a way to configure ldconfig so that the pthread library could be used without specifying it on the command line. presently lpthread -p gives the following output := ``` [root@localhost lib]# ldconfig -p | grep pthread libpthread.so.0 (libc6, OS ABI: Linux 2.6.9) => /lib/libpthread.so.0 libOpenIPMIpthread.so.0 (libc6) => /usr/lib/libOpenIPMIpthread.so.0 ```
I don't believe you can do that. The LD_LIBRARY_PATH and ldconfig program are used to set up the paths to shared libraries that are used to resolve dependencies in your executable atruntime. When compiling you will have to specify which libraries to include in the linking phase, i.e. -lpthread
``` int size=2; char *a0; char **allargs; short *a1; void **args; allargs=(char **)malloc(size*sizeof(char *)); allargs[0]="a"; allargs[1]="100"; args=(void **)malloc(size*sizeof(void *)); a0 = malloc(sizeof(char *)); *a0=(*allargs[0]); args[0]=(void *)&a0; fprintf(stderr,"assigned %c %c\n",*a0,*((char *)args[0])); a1 = malloc(sizeof(short *)); *a1=atoi(allargs[1]); args[1]=(void *)&a1; fprintf(stderr,"assigned %d %d \n",*a1,*((int *)args[1])); ``` for some reason i am getting the following for the output assigned a (should be a a ) assigned 100 166696 (should be 100 100)
You should cast args[0] and args[1] to char** and int**. ``` fprintf(stderr,"assigned %c %c\n",*a0,**((char **)args[0])); fprintf(stderr,"assigned %d %d \n",*a1,**((int **)args[1])); ```
char * x="a"; how would i convert it to char y='a'; also if i have a short char * a="100" how can i convert it to short b=100 thanks
``` char * x = "a"; char y = *x; //or x[0] char * a = "100"; short b = atoi(a); ``` Note that assigning return value ofatoito a short might lead to overflow. Also read whystrtol is preferred over atoifor string to number conversions.
I can never understand how to printunsigned longdatatype in C. Supposeunsigned_foois anunsigned long, then I try: printf("%lu\n", unsigned_foo)printf("%du\n", unsigned_foo)printf("%ud\n", unsigned_foo)printf("%ll\n", unsigned_foo)printf("%ld\n", unsigned_foo)printf("%dl\n", unsigned_foo) And all of them print some kind of-123123123number instead ofunsigned longthat I have.
%luis the correct format forunsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?
I have an application loading a library containing a callback function for a global GetMessage hook. I get the procedure and pass it to SetWindowsHookEx to be set for all running threads. The problem is that I want the DLL function to, under a certain circumstance like a keypress, tell the original application to exit, not all applications. The only way I can think of is to create a window in the application and have the DLL call SendMessage(HWND_BROADCAST) to send a custom message that the application recognizes to exit. But I want to verify if this is the best method to do this? Another problem arises as well. Let's say I want the DLL to perform some one-time initialization such as opening a file. If I do this in DllMain then it seems to do this multiple times because it's being loaded multiple times. Is this a fix for this? Thanks.
Try to use WinAPICreateEventfunction
I've always wondered the reasoning behind why we must always defineD3DVERTEX. Is it because Microsoft wants to allow the opportunity to put this in a class and overload operators, or is there another reason? Thanks
It's so you can use whatever is convenient for your application. If you need a normal as part of your vertex, you can have that. If you don't need a normal then you save 12 bytes per vertex. If you need colour information, texture coordinates, specular parameters and so on then you choose to define them or not depending on your specific needs. If Microsoft were to provide a "D3DVERTEX" structure you'd either have 500 different versions, with different combinations of fields, or you'd have one enormous one that included every possible value, killing your bandwidth.
I am using C. I have a wchar_t pointer which pointing a a file path. I was wondering, how I can check, whether it is ended with L".xls"? Any function call I can use?
Check that the string is at least 4 longSee if the last 4wchar_tare ".xls" Thus, this should be it: if(wcslen(str) >= 4 && wcscmp(str + wcslen(str) - 4, L".xls") == 0)
``` function() { FILE *ptr; ptr = fileopen(file1.txt) fprint(ptr, some text) //print to file 1 if(second file needed) { ptr = fileopen(file2.txt) //open a second file, assign to same file pointer fprint(ptr, some text) //print to file 2 not working here? } } ``` EDIT:Not printing to second file...However, fprint() does not return a negative value.
Yes you can, however, you should ensure that the first file is closed before doing so.
I was told this is a buggy code, but I don't know why, some could explain it to me. why there would not be an array out of bound exception when I compile? ``` int a[10]; int j; void main () { int i, j = 42; for (i = 0; i <=10; i++) a[i] = i; printf("%d", j); } ```
You've allocated 10 spaces. You fill 11.
Suppose I want to add a runtime conditional to a Makefile generated by Automake. Is there any way to tell Automake about this conditional?
You've asked a pretty general question so I can only provide a pretty general answer. Your project'sMakefile.amis whatautomakeparses to produce theMakefile.infile which ultimately produces theMakefile. You can generally just add your custom rules toMakefile.amfor most cases (assuming this is under your control). Seeherefor more details or googleMakefile.am
I recently switched from using Makefiles to using Automake, and I can't figure out how to write the following simple if statement using automake: ``` DEBUG ?= 1 ifeq (${DEBUG},1) CXXFLAGS:=$(CXXFLAGS) -g else CXXFLAGS:=$(CXXFLAGS) -O3 -DNDEBUG endif ``` Is this even possible to do if I'm using automake? Since it generates the makefile from automatically, does it make sense writing it in the Makefile template? Or should I try to find some way of adding it the automatically generated Makefile?
No, you cannot use such a syntax with Automake. There is no exact equivalent for the first two lines. You could do something close using an Automake conditional (seeUsage of Conditionalsin the Automake manual for examples), and setDEBUGfrom./configure. However I see little point in doing that: if you want to changeCXXFLAGSglobally, simply alter this variable inconfigure, not in theMakefile.am.
I need to use shared memory and fork to do this:Multipling random 512x512 matrixes using 4 processes and shared memory.I know how to fork one child butHow can I fork 4 processes that do 1/4 of work? Thanks
``` ct = 0; while (ct < 3 && fork() == 0) { ct++; } ``` ctwill tell you which thread you are. You should probably check for a return of-1fromfork(), though.
I have a vc++ method that uses fprintf to write values to a file in the hard disc. I want to change this method so that instead of writing the values to disc, I want to return a pointer to the data. I know in advance the size I have to allocate. Is there any way to pass a memory stream or unsigned char pointer to fprintf? thanks
You can usesprintfor better yet snprintf [_snprintf/snprintf_sfor VC++] (as Michael Burr pointed out and as it's noted in the Remarks section of the sprintf link). And, since it's tagged C++, better yet usestd::stringstream.
I have a set of C files that I would like to use. Can I just copy them to my include directory, or do I have to compile them. I would think they would be compiled in the final binary.
You need to compile those C files if you want to use them. To make use of what's in those C files, you'll nead a header file that declares what's inside them. Those header files is what you'd put in your include folder, and you'll compile the C files together with your other C files. (Or you could make a library out of those C files)
Suppose I have a string"qwerty"and I wish to find the index position of theecharacter in it. (In this case the index would be2) How do I do it in C? I found thestrchrfunction but it returns a pointer to a character and not the index.
Just subtract the string address from what strchr returns: ``` char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string); ``` Note that the result is zero based, so in above example it will be 2.
The formula simply isn't executing. I tried usingprintfto debug and it printed out 0 foriat the end of the code ``` #include <stdio.h> int main() { int i, base, height; printf("Lumber Cross-Sectional Moment of Section\n"); printf("Size Area Inertia Modulus\n"); for (i = 0; i > 35; i++) { if (i == 6 || i == 12 || i == 18|| i == 24 || i == 30) { base = base * 2; height = 2; } if (i != 6 || i != 12 || i != 18 || i != 24 || i != 30) { height = height * 2; } printf("%d x %d %d %d %d \n", base, height, base * height, base * 2 + height); }//for return (0); }//main ```
Should be ``` for (i = 0; i < 35; i++) ``` The body of the loop will only execute when the condition is true.
I am writing a commandline calculator in C, and it would be very useful if it had the ability to move the cursor each time you close (for example) a parenthesis highlighting the previous one, like in emacs, etc. For example, if you launch emacs, and type: ``` (blah) ``` then for a while after you type the closing parenthesis, the first one is highlighted. I've tried some googling, but I don't really know what to search for. Is there a simple and multiplatform (at the very least it's fine if it'd work on Linux, but I'd like it to work at least on Windows as well) way to move the cursor in this way?
If you want better control over the console, take a look at thencurseslibrary. The Linux console can also be controlled throughconsole codes. No libraries needed, justprintfthe appropriate codes tostdout.
In ruby, ``` begin # ... rescue # ... end ``` won't catch exceptions that aren't subclasses ofStandardError. In C, ``` rb_rescue(x, Qnil, y, Qnil); VALUE x(void) { /* ... */ return Qnil; } VALUE y(void) { /* ... */ return Qnil; } ``` will do the same thing. How can Irescue Exception => efrom a ruby C extension (instead of justrescue => e)?
Ruby needs more documentation. I had to go into the ruby source code, and this is what I found: ``` VALUE rb_rescue(VALUE (* b_proc)(ANYARGS), VALUE data1, VALUE (* r_proc)(ANYARGS), VALUE data2) { return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError, (VALUE)0); } ``` So, the answer to my question (i guess) would be: ``` rb_rescue2(x, Qnil, y, Qnil, rb_eException, (VALUE)0); VALUE x(void) { /* ... */ return Qnil; } VALUE y(void) { /* ... */ return Qnil; } ```
This question already has answers here:Closed13 years ago. Possible Duplicate:“static const” vs “#define” in C I started to learn C and couldn't understand clearly the differences between macros and constant variables. What changes when I write, ``` #define A 8 ``` and ``` const int A = 8 ``` ?
Macros are handled by the pre-processor - the pre-processor does text replacement in your source file, replacing all occurances of 'A' with the literal 8. Constants are handled by the compiler. They have the added benefit of type safety. For the actual compiled code, with any modern compiler, there should be zero performance difference between the two.
For a project that I intend to start on soon, I will need to play back compressed and uncompressed audio files. To do that, I intend to use the Core Audio framework. However, I have no prior experience in audio programming, and I'm really not sure where to start. Are there any beginner level resources or sample projects that can demonstrate how to build a simple audio player using Core Audio?
Apreview of a book on Core Audiojust came out. I've started reading it and as a beginner myself I find it helpful. It has a tutorial style teaching method and is very clear in its explanations. I highly recommend it.
I know how to do X amount of leading zeros, and I know how to do X amount of decimal points. But how do I do them both? I am looking to have 4 leading zeros with a decimal precision of 2:0000.00. Therefore43.4would be0043.40
Try thisprintf(C,Perl,PHP) format string: ``` "%07.2f" ```
Is there a way to print the name of the compiler and the version that was used to compile a program, something like; ``` printf("This is compiled with %s version %s\n", COMPILER, COMPILER_VERSION); ``` ?
You can do this with the pre-processor: Reference:http://predef.sourceforge.net/precomp.html For gcc: ``` #if defined(__GNUC__) # if defined(__GNUC_PATCHLEVEL__) # define __GNUC_VERSION__ (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) # else # define __GNUC_VERSION__ (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100) # endif #endif ``` For MSVC just use: ``` _MSC_FULL_VER ```
Is there any widely known general purpose library for standard C. I'm thinking of something like what Boost is for C++. I found the C POSIX library... any other?
GLib,GObject, andGTK+(links to Wikipedia) are good places to start. (GLib,GObject, andGTKare part of theGTK+ Project). For numerical functions and algebra, there are theGNU Scientific Library, and implementations ofCLAPACKand CBLAS (GSL includes CBLAS). Please see alsoWikipedia's list of numerical libraries. If you find more, consider contributing to the Wiki.
if i have int temp=(1<<31)>>31. How come the temp becomes -1? how do i get around this problem? thanks
Ints are signed by default, which usually means that the high bit is reserved to indicate whether the integer is negative or not. Look upTwo's complementfor an explanation of how this works. Here's the upshot: ``` [steven@sexy:~]% cat test.c #include <stdint.h> #include <stdio.h> int main(int argc, char **argv[]) { uint32_t uint; int32_t sint; int64_t slong; uint = (((uint32_t)1)<<31) >> 31; sint = (1<<31) >> 31; slong = (1L << 31) >> 31; printf("signed 32 = %d, unsigned 32 = %u, signed 64 = %ld\n", sint, uint, slong); } [steven@sexy:~]% ./test signed 32 = -1, unsigned 32 = 1, signed 64 = 1 ``` Notice how you can avoid this problem either by using an "unsigned" int (allowing the use of all 32 bits), or by going to a larger type which you don't overflow.
I like to compile my code with -Wall, and sometimes even -pedantic. It's partly a style thing, and partly the fact that it does occasionally emit very, very useful warnings (such as using = rather than ==). However, the writers of some of my headers are clearly not such sticklers. Compiling with either of the two warning levels yields a tremendous mess of output, completely defeating the purpose of compiling that way in the first place. So how can I make my compiler ignore those warnings?
Alternatively toJS Bangs' answer, you can have GCC treat them assystem headers, which disablesallwarnings (excepting#warningdirectives) for those headers. If the-isystemswitch is unhelpful, you can wrap all of the offending headers with simpler headers that contain only the appropriate line: ``` #pragma GCC system_header ```
This was an actual interview question. o_O Let's leave aside the issues of asking such a question in an interview. I'm wondering what alternatives to the ol' TCP sockets approach are readily available (as libraries, for instance), for use in C or C++. I'm making no assumptions on platform, compiler etc - take your pick. I'm not asking you guys to actually write the program, but merely to point at technologies that may be usable for the purpose, and possibly at an example or tutorial using that technology in C/C++.
I'm making no assumptions on platform, compiler etc - take your pick. ``` main() { system("apache -start") system("telnet 127.0.0.1 80") } ``` ;-)
So I'm writing some C code to connect to a server that is expecting me to provide a certificate for authentication. I'm using OpenSSL to do the SSL communications and I've got the socket code worked out, and I have code to do the SSL part worked out to, but what I can't seem to get simply because the docs are so sparse is how to implement the function: SSL_CTX_set_client_cert_cb If any one has any tips I would greatly appreciate it.
You do not need to useSSL_CTX_set_client_cert_cb(). The simplest way is to useSSL_use_certificate_file()to set the certificate andSSL_use_PrivateKey_file()to set the corresponding private key,beforecallingSSL_connect().
How do I get the ASCII value as an int of a character in Cocoa? I found an answer for doing this in python, but I need to know how to do this in Cocoa. ( I am still a noob in Cocoa).Python method:use function ord() like this: ``` >>> ord('a') 97 ``` and also chr() for the other way around: ``` >>> chr(97) 'a' ``` how do I do this in Cocoa?
Character constants are already integers: ``` int aVal = 'a'; // a is 97, in the very likely event you're using ASCII or UTF-8. ``` This really doesn't have anything to do with Cocoa, which is a library. It's part of C, so it's not specific to Objective-C either.
I'm working on a little (not so little actually) project in C (ref.this question) , and I need a little function in C that'd generate a unique and random string. I need a small one that I can include as a utility function in a .c file. Please help me with your brains, and show me how smart this could be done! Thanks and a virtual BIG hug for the best solution :) EDIT: (What I just said to msw below) I actually think that I just need a random string as a key (which would look like a uuid) and I thought that'd be done with timestamps or such. (I don't want to add a bunch of files to my project just for a random key generation) Sorry for the confusion, everyone! EDIT2: Thank you all for your input, I'll finally use theOSSP uuid libwith SHA-1 it looks easier to implement/integrate
Don't re-invent the wheel, there is probably a function that is already written on your platform of choice:http://en.wikipedia.org/wiki/Uuid#Implementations
I was looking at theGolden Ratio formulafor finding the nth Fibonacci number, and it made me curious. I know Python handles arbitrarily large integers, but what sort of precision do you get with decimals? Is it just straight on top of a C double or something, or does it use a a more accurate modified implementation too? (Obviously not with arbitrary accuracy. ;D)
almost all platforms map Python floats to IEEE-754 “double precision”. http://docs.python.org/tutorial/floatingpoint.html#representation-error there's also thedecimal modulefor arbitrary precision floating point math
Quoting the code for computing the integer absolute value (abs) without branching fromhttp://graphics.stanford.edu/~seander/bithacks.html: ``` int v; // we want to find the absolute value of v unsigned int r; // the result goes here int const mask = v >> sizeof(int) * CHAR_BIT - 1; r = (v + mask) ^ mask; ``` Patented variation: ``` r = (v ^ mask) - mask; ``` What isCHAR_BITand how use it?
CHAR_BITis the number of bits inchar. These days, almost all architectures use 8 bits per byte but it is not the case always. Some older machines used to have7-bit byte. It can be found in<limits.h>.
I was wondering about the standard C libraries that contain all the functions/definitions like abs(), cout streams, printf, etc. I'm familiar with the header files (stdio.h, cmath.h, time.h, etc etc) but there doesn't seem to be any corresponding .lib or .dll anywhere (ie. stdio.lib, time.dll, etc). Where is the actual code for the functions in these header files? Am I misunderstanding something? Is there like, one huge lib file that contains all the standardized stuff, or one for each header? Any help appreciated!! Thanks!
It depends on the implementation. On Windows, the standard library functionality is inthe C and C++ runtime libraries. The C runtime library is always linked in automatically; the C++ runtime library is linked in automatically if you include one of the standard library headers.
if I have ``` int a= 5; long b= 10; int count0 = 2; void ** args0; args0 = (void **)malloc(count0 * sizeof(void *)); args0[0] = (void *)&a; args0[1] = (void *)&b; ``` how can I convert from args[0] and args0[1] back to int and long? for example ``` int c=(something im missing)args0[0] long d=(something im missing)args1[0] ```
Assuming that your &a0 and &b0 are supposed to be &a and &b, and that you mean args0[1] for setting up long d, you have stored a pointer to a in args0[0] and a pointer to b in args0[1]. This means you need to convert them to the correct pointer types. ``` int c = *((int *)args0[0]); int d = *((long *)args0[1]); ```
Is there a way to set the background color. I thought of making a dummy window and then using TBSTATE_TRANSPARENT, but I thought there might be a cleaner solution? Thanks None of these solutions work for a toolbar using visual styles
Check outTB_SETCOLORSCHEME.
I was looking at this vector drawing application called Creative Docs .Net . I noticed that I can have hundreds of shapes and moving, rotating and scaling do not lag at all. Given that all verticies must be modified, how do applications generally do these transformations as quickly as possible? Thanks
One typical way to do it is to apply a 3x3 (or 3x2, or 2x3) affine transformation matrix to the coordinates, which can describe things like position, rotation, scale and shear. If you use OpenGL or Direct3D you can use the graphics hardware to do the actual transformations for you. If you do it in software, rasteration is probably going to be the bottleneck, not transforming the vertices.
I have grep function in C( embedded programming ) that takes a void pointer as a parameter. the function needs to be able to handle different kinds of types of variables like chars ints and longs. How can I code the function so it can figure out by itself what type of variable i am passing ?? I dont know if this is possible. thanks ie. ``` void grep( void *t ) { if( t == char ) { do this } if( t == int ) { do that } ... } ```
It is not possible to do with any accuracy. A 4 byte integer could easily be interpreted as a string for example. For example, a null terminated string "ABC" would be the same as the integer value 1094861568 (depending on byte order).
when i try ``` char bla[32] = "foobar"; int i; putchar(bla[i]); ``` withstrlen(bla) < i < 32,bla[i]is always\0. but isn't this in fact undefined behaviour, and should be avoided?
In section 6.7.8 of the C99 Standard, paragraph 21 states: If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration. And paragraph 10 states that static arithmetic types (which would include char) are initialized to zero. Based on that, you should expect the rest of the array to be initialized to zero when using a string literal as the initializer.
In c++, setw function is used to set the number of characters to be used as the field width for the next insertion operation. Is there any function in C, I mean, in standard c library, which does the same thing?
printf ("%5d", 42); Will print 42 using 5 spaces. Read the man pages of printf to understand how character padding, overflow and other nuances work. EDIT: Some examples - ``` int x = 4000; printf ("1234567890\n"); printf ("%05d\n", x); printf ("%d\n", x); printf ("%5d\n", x); printf ("%2d\n", x); ``` Gives the output ``` 1234567890 04000 4000 4000 4000 ``` Notice that the%2dwas too small to handle the number passed to it, yet still printed the entire value.
``` char *a=NULL; char *s=NULL; a=(char *)calloc(1,(sizeof(char))); s=(char *)calloc(1,(sizeof(char))); a="DATA"; memcpy(s,a,(strlen(a))); printf("%s",s); ``` Can you plz tell me why its printing DATA½½½½½½½½■ε■????How to print only DATA?? Thanks
Strings in C are terminated by a zero character value (nul). strlen returns the number of characters before the zero. So you are not copying the zero. printf keeps going, printing whatever is in the memory after s until it hits a zero. You also are only creating a buffer of size 1, so you are writing data over whatever is after s, and you leak the memory calloc'd to a before you set a to be a literal. Allocate the memory for s after finding the length of the string, allocating one more byte to include the nul terminator, then copy a into s. You don't need to allocate anything for a as the C runtime looks after storing the literal "DATA".
I tried loading C shared library .so in Python using ctypes.CDLL class (Linux). Here is thelinkto which tells what I did. As I see the documentation it says CDLL class assumes that function returns int types. I've a doubt here what if I need to return variable of type other than the int type from a function in C?. And to what extent we can use C functions in Python i mean what are the limits/restrictions on using C shared libraries and functions Thanks in Advance
Bydefault, it assumes int, but you can setrestypeto any of thesupported typesto override that. E.g., from the docs: ``` strchr.restype = c_char_p ``` This means thatstrchrreturns a pointer to a char, which corresponds to a Python string (orNone, for aNULLpointer).
if I use the following code... ``` message = TTF_RenderText_Solid( font, "Lorem Ipsum", textColor ); ``` Do I need to freemessagebefore I can do this ``` message = TTF_RenderText_Solid( font, "Lorem Ipsum part 2", textColor ); ``` i.e. does it give me a new surface (and so I have to clean up the old one) or does it just blit over the old one?
Yes, you should freemessagewithSDL_FreeSurfacewhen you're done with it. The returned SDL_Surface is allocated withSDL_AllocSurface(), and is not reused, so you'll leak if you don't free it in this case.
Do they repeatedly check for the condition and execute if the condition is met. Ex, how the OS knows exactly when a USB device is plugged in, or how MSN knows exactly when you get an email. How does this work? Thanks
At the low level, the OS kernel "knows" when something happens, because the device in question sends the CPU a hardware interrupt. So when, say a network packet arrives, the network controller sends an interrupt, and the OS kernel responds as appropriate. At the program level, it works quite differently - most application programs run an "event loop", where they fetch a message (say, a message from the OS saying that "the mouse was clicked on this point in your application"), perform the appropriate actions in response to that, and then, listen for more messages. If there is no message, the OS sleeps the thread until it has a message to deliver.