question
stringlengths
24
425
answer
stringlengths
5
405
Came across this conditional in some uncommented Objective-C code: ``` if (w & (w - 1)) { i = 1; while (i < w) { i *= 2; } w = i; } ``` Wherewis asize_tgreater than1. Update:Added the code contained by the conditional for context.
It tests whether more than one bit is set inw, i.e. whether it's not an exact power of two. Seehere.
When reading/writing a file in my application, I want to exit(1) if the file is not closed correctly. On Windows it works well, but on Linux this error appears: ``` ‘exit’ was not declared in this scope ``` How can I solve that? Thanks.
If this is in C, did you#include <stdlib.h>?
I can't figure out how to display something (like hello world) in every 3 seconds. I'm writing in only C programming with gcc compiler in linux. We can stop it by Ctrl+c. I just want simplest and easiest way to manipulate thet code with my project. Thank you so much in advance!
``` while(1) { printf("something\n"); Sleep(3000); //this function counts in milliseconds, so this is what 3 seconds looks like. } ```
``` int *i; *i=123; ```
Yes. There is no allocated memory to place the value123. Like initializing a variable likeintis not guaranteed to be0, anint*isn't guaranteed to be a safe address. It also could potentially lead to data corruption.
I have installed visual studio 2008 and i want to create some simple applications using C language. I do this by creating c++ console applications but i want the compiler to work for C not C++. Any way to accomplish this or i need another compiler if i want to deal with C?
Use .c file extension instead of .cpp, those files will be compiled as C-only code by default in a C/C++ Visual Studio project.
I am using GCC, what switches do I need to add to link with Xlib? After searching, all I could find was-lX11, but that gave meld: library not found for -lX11 I am using a mac (10.6), but I would not like anything that is Mac specific.
You can usually usepkg-configto determine the flags you need to pass: ``` gcc my-program.c $(pkg-config --cflags --libs x11) -o my-program ```
``` int *i; *i=123; ```
Yes. There is no allocated memory to place the value123. Like initializing a variable likeintis not guaranteed to be0, anint*isn't guaranteed to be a safe address. It also could potentially lead to data corruption.
I have installed visual studio 2008 and i want to create some simple applications using C language. I do this by creating c++ console applications but i want the compiler to work for C not C++. Any way to accomplish this or i need another compiler if i want to deal with C?
Use .c file extension instead of .cpp, those files will be compiled as C-only code by default in a C/C++ Visual Studio project.
I am using GCC, what switches do I need to add to link with Xlib? After searching, all I could find was-lX11, but that gave meld: library not found for -lX11 I am using a mac (10.6), but I would not like anything that is Mac specific.
You can usually usepkg-configto determine the flags you need to pass: ``` gcc my-program.c $(pkg-config --cflags --libs x11) -o my-program ```
linux gcc 4.4.1 C99 I am wondering what is the best way to test the performance of a C program. I have some functions that I have implemented. However, I could have used a different design for each function. Basically, I should want to test to see which design gives better performance. Many thanks,
Take a look atthis poston code profilers.
I want to create a thread in C so that the thread automatically call after two seconds. I am using Visual Studio and Windows platform for development. How do I get started?
You are going to need to use OS specific libraries to do threading. On Posix, you will want to look intopthreads(and specificallypthread_create). On Windows, you'll wantCreateThreador _beginthreadex.
I am reading a file with fgetc, so each time it reads a character, the cursor positio gets changed. Is it possible to know, after each read, the "coordinates" of the cursor on the file in terms of column and line number? Thanks
You can useftell It does not give you the position in terms of row and column but gives the current position in the stream from the start.
As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?
Take a look at theC10Kpage for a great overview and comparison of I/O frameworks and strategies.
I mean i want the input to be invisible like inputing password when i log in Linux. How can I implement it both in C under linux and windows. thanx
There is no single solution that will work across platforms. For Linux you can use thegetpass() function. For windows you can try_getch().
What is the result of the following line: ``` int* ptr; printf("%x, %x\n", ptr, &ptr); ``` I know thatptris an address in a memory, but what is&ptr?
&ptr would be the address for the memory location that ptr is held in. Essentially it is a pointer to a pointer.
I'm trying to enumerate some operators, my code line is : ``` enum operations{+=4,-,%,<,>} ``` when i'm trying to compile this line , gcc says : expected identifier before ‘+’ token So, how can I enumerate these operators. Can we use some escape characters for them ?
Your best bet is something like this: ``` enum Operations { Plus=4, Minus, Mod, LessThan, MoreThan } ```
How to inform the server if a client is interrupted, and then close the socket?
If the other end of a socket is closed, your end will be marked as readable and return0fromread- this is the "end of file" indication. If you try towriteto such a socket, you will recieve theSIGPIPEsignal, and thewritewill return error with errno set toEPIPE("Broken Pipe"). You must be prepared to handle this event, because the other end can close the socket atanytime.
I am reading a file with fgetc, so each time it reads a character, the cursor positio gets changed. Is it possible to know, after each read, the "coordinates" of the cursor on the file in terms of column and line number? Thanks
You can useftell It does not give you the position in terms of row and column but gives the current position in the stream from the start.
As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?
Take a look at theC10Kpage for a great overview and comparison of I/O frameworks and strategies.
I mean i want the input to be invisible like inputing password when i log in Linux. How can I implement it both in C under linux and windows. thanx
There is no single solution that will work across platforms. For Linux you can use thegetpass() function. For windows you can try_getch().
What is the result of the following line: ``` int* ptr; printf("%x, %x\n", ptr, &ptr); ``` I know thatptris an address in a memory, but what is&ptr?
&ptr would be the address for the memory location that ptr is held in. Essentially it is a pointer to a pointer.
Is it possible to compile C code into a Visual C++ dll? I'm looking at using some C code with a .Net project and trying to determine whether this is even an option. Thanks, Becky
yes. If you want to get rid ofname manglinguse"extern "C" { /*...*/ }construct. Also, refer FAQ :How to mix C and C++
``` #ifndef NULL #define NULL NULL #endif ``` This code compiles in gcc with no warnings/errors. Can someone explain what the preprocessor is doing here?
Anywhere the compiler sees the text "NULL" it will replace it with the text "NULL". It's like doing a search-and-replace in your code for "NULL" and replacing with "NULL". Not illegal, just weird :)
Managed to create a simple bootloader... and with VESA 2.0 I managed to change the resolution to 1024x768x32, also managed to setup a Linear Frame Buffer... Where can I find tutorials for using the frame buffer? Like lets say to display a picture before it finishes to load? So far I saw one sample on how to "draw" an ipod...called CdPod
If you have the address of the linear framebuffer all you need to do is to copy the raw image data to it's location.
Is it necessary to code RTOS in C language always? Why can't that be coded in java or some other technology..?? Is that because of the absence of pointer concept in java?
Garbage collection is the big reason against Java being Real Time. JIT is another, but it could be overcome. In general though, C being effectively portable assembly gives very predicable run-time performance, and that's essential for reliable real-time execution.
I am writing a C project. Now I just doubt one function in the whole project may be take the most of computational complexity. If I can make sure about this, I can further improve this function with a more clear target. Or, is there any tools for this usage?? I mean to find the most "expensive" function in the whole program or project?? Any advices? Thanks!
The gprof profiler comes with theGCCcompiler suite. Theres a manual for ithere.
I have a binary search tree created in C. The problem is I can't find a efficient way to delete all the nodes with e.g., id>5. When I traverse the tree, if I delete a node, the recursion is getting error, because the structure is not the same. Is there any way, instead of using a helping stack to keep the data before delete them from the tree?
Did you try postorder?Delete the node after its children.
I need to prevent application's memory pages from being swapped out of RAM on Windows. Is there a WinAPI function equivalent of POSIXmlockall()to achieve that?
Yes, VirtualLock(). There's a limit on how many pages you can lock, you can't hog RAM. Details are in theMSDN article.
I'm currently exploring interfacing C and R (using R's .Call for speed). I've only used C for trivial integer computation and text processing applications, and I've never had to worry about issues with float variables, underflow, etc. What tests can I write for functions to ensure numerical accuracy?
For a great overview of possible edge cases, see thisWikipedia article. Then for unit tests seeThe pitfalls of verifying floating-point computations.
Any idea what this means? Not sure of the language. (void *) 0x00
In C, it means a NULL pointer, i.e., a pointer that points to no relevant data. Trying to access this data raises a Segmentation Fault, at least on Unix/Linux.
I need to work out if a massive integer (I mean 20 digits...) is prime. I'm trying to use the brute-force method, but (of course) I need to use doubles to contain the original number. However, the modulo operator (%) is an integer operator - thus it is useless to me!
That's not possible, a double only has 15 significant digits. Look for an implementation of aBigInt class.C specific is discussedhere.
I have a binary search tree created in C. The problem is I can't find a efficient way to delete all the nodes with e.g., id>5. When I traverse the tree, if I delete a node, the recursion is getting error, because the structure is not the same. Is there any way, instead of using a helping stack to keep the data before delete them from the tree?
Did you try postorder?Delete the node after its children.
I need to prevent application's memory pages from being swapped out of RAM on Windows. Is there a WinAPI function equivalent of POSIXmlockall()to achieve that?
Yes, VirtualLock(). There's a limit on how many pages you can lock, you can't hog RAM. Details are in theMSDN article.
I'm currently exploring interfacing C and R (using R's .Call for speed). I've only used C for trivial integer computation and text processing applications, and I've never had to worry about issues with float variables, underflow, etc. What tests can I write for functions to ensure numerical accuracy?
For a great overview of possible edge cases, see thisWikipedia article. Then for unit tests seeThe pitfalls of verifying floating-point computations.
Any idea what this means? Not sure of the language. (void *) 0x00
In C, it means a NULL pointer, i.e., a pointer that points to no relevant data. Trying to access this data raises a Segmentation Fault, at least on Unix/Linux.
I need to work out if a massive integer (I mean 20 digits...) is prime. I'm trying to use the brute-force method, but (of course) I need to use doubles to contain the original number. However, the modulo operator (%) is an integer operator - thus it is useless to me!
That's not possible, a double only has 15 significant digits. Look for an implementation of aBigInt class.C specific is discussedhere.
I'm looking for a nice and efficient implementation of Xiaolin Wu's anti-aliased line drawing algorithm in C, does anyone have this code they could share with me? Thanks
Wikipedia haspseudo code. Google has many examples likethis oneorthis one. And your question reminded me this nice article onantialiasing. EDIT: It's time to discoverHugo Helias's websiteif you don't know it already.
gcc 4.4.1 I am maintaining someone's code and I have come across something that I don't understand. ``` #define RES_API(name, func) name##_##func ``` Can anyone explain? Many thanks,
The##is a concatenation operator. UsingRES_API(name1, func1)in your code would be replaced withname1_func1. More informationhere.
I'm looking to build a Morse decoder (and eventually a coder) in C. I'd like to use the audio port as input, and sample the incoming voltage on the port. How do I go about reading the voltage on a microphone audio port in Windows using C?
The simplist way is to use thewaveInfunctions provided by the Win32 API. You can readRecording and Playing Sound with the Waveform Audio Interfacefor an overview, or just dive into theAPI documentation.
How would I P/Invoke a C function which returns a union'ed struct?
You would need to use aStructLayoutof explicit and theFieldOffsetattribute. An example of usage: ``` <StructLayout(LayoutKind.Explicit, Size:=4)> _ Public Structure DWord <FieldOffset(0)> Public Value As Int32 <FieldOffset(0)> Public High As Int16 <FieldOffset(2)> Public Low As Int16 End Structure ```
See question. Also any links to example code or example code on how to validate an xml file against multiple schemas would be helpful. EDT: Sorry forgot to mention that this is for LINUX
libxml2is portable, pure C andimplements XML Schema. It is also open-source (MIT license) and has an active developer community.
say you have a source file namedsum.cthat looks like this: ``` #include "sum.h" int sum(int x, int y) { return x+y; } ``` What's the point of including method's header in it's own definition file? Aren't you supposed to include it only in source files that call thesumfunction?
This way you avoid possible problems if the definitions in the header and in the source files differ.
I would like someone to give a working example ofSetWindowPoson how to make a window "topmost" (be on top and stay there) using either C/C++/C#. Thanks in advance!
C/C++: ``` // This doesn't size or move the window, just makes it top-most. SetWindowPos( hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE ); ```
Is the there a way to forceanotherwindow to be on top?Notthe application's window, butanotherone, already running on the system. (Windows, C/C++/C#)
``` SetWindowPos(that_window_handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); ``` BringWindowToTopmoves the window to the top of the Z-order (for now) but doesnotmake it a topmost window.
It looks like g_strncasecmp is deprecated, so I am looking for another function to do the same thing.
From the docs athttp://library.gnome.org/devel/glib/stable/glib-String-Utility-Functions.html#g-strncasecmp "There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8."
I creates program in c/c++ in turbo c . but i am facing problem is that i am not able to make it full screen in windows vista. please tell me how to do it?
Why are you still living in the Turbo era? Switch on to some better compiler. gcc and MSVC++ Professional Edition are better ones. On windows use IDEs like DevCpp or Code::Blocks, both support MinGw port of gcc.
It looks like g_strncasecmp is deprecated, so I am looking for another function to do the same thing.
From the docs athttp://library.gnome.org/devel/glib/stable/glib-String-Utility-Functions.html#g-strncasecmp "There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8."
I creates program in c/c++ in turbo c . but i am facing problem is that i am not able to make it full screen in windows vista. please tell me how to do it?
Why are you still living in the Turbo era? Switch on to some better compiler. gcc and MSVC++ Professional Edition are better ones. On windows use IDEs like DevCpp or Code::Blocks, both support MinGw port of gcc.
It looks like g_strncasecmp is deprecated, so I am looking for another function to do the same thing.
From the docs athttp://library.gnome.org/devel/glib/stable/glib-String-Utility-Functions.html#g-strncasecmp "There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8."
I creates program in c/c++ in turbo c . but i am facing problem is that i am not able to make it full screen in windows vista. please tell me how to do it?
Why are you still living in the Turbo era? Switch on to some better compiler. gcc and MSVC++ Professional Edition are better ones. On windows use IDEs like DevCpp or Code::Blocks, both support MinGw port of gcc.
I have the string:"foo$bar@baz" I'm looking to write a C program which will extra all three sub-strings ("foo","bar"and"baz") and put each into it's own string. P.S. Don't worry, this isnothomework.
What you are looking for isstrtok. It allows for you to set the delimiters as well.