question
stringlengths
24
425
answer
stringlengths
5
405
Is it guaranteed that a function registered with atexit will ALWAYS be called upon normal program termination? (I encounterd a scenario in FreeBSD where a function that I register with atexit never gets called, even when the program terminates normally).
No. First, the function will not be called ifatexitreturns a non-0 value. Secondly, it won't be called if a function registered before it doesn't return normally.
For example,system("sh /mydir/some-script.sh &")
``` system("sh /mydir/some-script.sh &") ``` executes ``` /bin/sh -c 'sh /mydir/some-script.sh &' ``` systemwill return as soon as outer shell returns, which will be immediately after it launches the inner shell. Neither shell will wait forsome-script.shto finish. ``` $ cat some-script.sh sleep 1 echo foo $ /bin/sh -c 'sh some-script.sh &' ; echo bar ; sleep 2 bar foo ```
I have the following code: ``` int **ptr = (int **)malloc(sizeof(int*)*N); for(int i=0;i<N;i++) ptr[i]=(int*)malloc(sizeof(int)*N)); ``` How can I freeptrusingfree? Should I loop overptrand freeptr[i]or should I just do ``` free(ptr) ``` andptrwill be freed?
Just the opposite of allocation: ``` for(int i = 0; i < N; i++) free(ptr[i]); free(ptr); ```
I'm looking for the reference/documentation of thedos.hAPI. (especially for an openwatcom specific version). Where to get the documentation?
One reasonable starting point would probably be thelibrary documentationat OpenWatcom.
I get a warning warning: comparison between pointer and integer on the line containingiffrom the next piece of code: ``` char cwd[1024]; if (getcwd(cwd, sizeof(cwd)) != (char*)NULL) printf("%s\n",cwd); else error_print("error in pwd"); ``` how and what do I need to fix?
Do you include unistd.h? If not, the error appears because your C compiler is assuming getcwd returns int. The fix? Include unistd.h
Is there any CSS parser for C/C++ with CSS3 support? I found a few but they all don't support CSS3 yet.
If you need CSS3 support before any libraries support it, you could try a non-validating solution such ashtmlcxx.
I am trying to find the syntax that will let me redirect standard input output toward a named pipe after using the mkfifo() function and creating a child process using fork. Which man page should I be looking at for the syntax? Thanks, Aaron
Do you referredthis gives you idea about the syntax.
When i make some opensource project, there is one error: make: flex: Command not found I want to know what is the flex ?
Flexis the Fast Lexical analyzer generator.
is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program. Thanks
You can use theclockfunction in<time.h>along with the macroCLOCKS_PER_SEC: ``` clock_t start = clock() ; do_some_work() ; clock_t end = clock() ; double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ; ``` Nowelapsed_timeholds the time it took to calldo_some_work, in fractional seconds.
When i make some opensource project, there is one error: make: flex: Command not found I want to know what is the flex ?
Flexis the Fast Lexical analyzer generator.
is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program. Thanks
You can use theclockfunction in<time.h>along with the macroCLOCKS_PER_SEC: ``` clock_t start = clock() ; do_some_work() ; clock_t end = clock() ; double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ; ``` Nowelapsed_timeholds the time it took to calldo_some_work, in fractional seconds.
I'm using libltdl in my C code to dynamically load libtool made shared object files. Apparently a reference count is internally kept for each module handle returned by libtool's version of dlopen. Is there any way to access this reference count?
``` const lt_dlinfo *info; info = lt_dlgetinfo(myhandle); printf("refcount is %d\n", info->ref_count); ```
how can i write my own module in C ? is it possible ?
Yes, it is possible. Here's an old article that I used when I wrote my first extension: http://web.archive.org/web/20110222035803/http://devzone.zend.com/article/1021 Things may have changed since then, so you may want to search for similar tutorials for additional references. Oh, and this should be useful: http://www.php.net/manual/en/internals2.php
I would like to, in C code, create more than one terminal processes. As in, I want to runfooin a terminal process, and then in a separate terminal process, I want to runbar. Is this possible? Could I do it withsystem(char *)?
This sounds like a job forposix_spawn(). Here is anexample. Definitely donotcallsystem()to launch new processes.
For example, I want to run: ``` ssh [email protected] -p 2222 ``` in C (viasystem) command. But right after I run that, it asks for input: ``` [email protected]'s password: ``` Then I'm expected to type in the password. How can I do this in C code? Could I please get some code on how I could simulate key presses? Or is there a better way to do this?
There are better ways to do this, such askey-based SSH authentication.
I would like to, in C code, create more than one terminal processes. As in, I want to runfooin a terminal process, and then in a separate terminal process, I want to runbar. Is this possible? Could I do it withsystem(char *)?
This sounds like a job forposix_spawn(). Here is anexample. Definitely donotcallsystem()to launch new processes.
For example, I want to run: ``` ssh [email protected] -p 2222 ``` in C (viasystem) command. But right after I run that, it asks for input: ``` [email protected]'s password: ``` Then I'm expected to type in the password. How can I do this in C code? Could I please get some code on how I could simulate key presses? Or is there a better way to do this?
There are better ways to do this, such askey-based SSH authentication.
I am wondering, how to check if I am opening file which exists with fopen? I want to diplay some message, when user selects file with bad name. Is must be some simple checking, but I am not able to solve it. Thanks
in your param list: ``` FILE pFile ; ``` then: ``` pFile = fopen ("myfile.txt","r"); if (pFile == NULL) printf("No Such File !! "); ```
in my program I will use two parameters. It could look like this: ``` ./myApp -status 7 -file abc.txt ``` My question is how to make conditions like "if(parameter_status==7)" and how to get to abc.txt from -file in my main? Thanks
Use the GNU C Library getopt() call. An example of how to use it is atwww.gnu.org.
I find little things like this throughout the C programming language; something that is very easy to provide, has very little chance of breaking old code, and has an obvious way to standardize it. Is minimalism the reason?
Because they're trivial to compute if you have the "standard" trig functions?
I find little things like this throughout the C programming language; something that is very easy to provide, has very little chance of breaking old code, and has an obvious way to standardize it. Is minimalism the reason?
Because they're trivial to compute if you have the "standard" trig functions?
How do I write a function for this in C language? y = 20 ln (x + 3) ? How do I write the ln function?
``` #include <math.h> double fun(double x) { return 20 * log( x + 3 ); //base-e logarithm! } //usage double y = fun(30); ``` For base-10 logarithm, uselog10().
As all we know: the sequence of evalutation is determined by the priority and associativity. For this example,the associativity determined that a+b,then the result plus c. This is what ANSI C compliant compiler do(leave out the optimization).But will it be evaluated like foregoing manner in the title? In what compiler? In K&R C?
Let me throw this at you: Operator Precedence vs Order of Evaluation
If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?
See theGNU Make Debugger
Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.
float *mat2d = malloc( rows * cols * sizeof( float )); to access a value from the matrix use this adressing scheme: float val = mat2d[ x + y * cols ];
If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?
See theGNU Make Debugger
Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.
float *mat2d = malloc( rows * cols * sizeof( float )); to access a value from the matrix use this adressing scheme: float val = mat2d[ x + y * cols ];
I seem to be able to compile code that callswsprintfwith theMinGWgccif I have these includes (in this order): ``` #include <stdarg.h> #include <wingdi.h> #include <winuser.h> ``` But I feel like there might be some "cleaner" way to do this. Perhaps with only a single header inclusion. I arrived at this list by searching header files for missing symbols and then including headers one-by-one.
Include<Windows.h>
``` enum protocol { ascii_prot = 3, /* arbitrary value. */ binary_prot, negotiating_prot = 4 /* Discovering the protocol */ }; ``` Bothbinary_protandnegotiating_protequals to4?
Yes.
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0? ``` int r = arc4random() % (9); NSLog(@"Random Number: %d",r); ```
int r = (arc4random() % 8) + 1
I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't). Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.
``` enum protocol { ascii_prot = 3, /* arbitrary value. */ binary_prot, negotiating_prot = 4 /* Discovering the protocol */ }; ``` Bothbinary_protandnegotiating_protequals to4?
Yes.
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0? ``` int r = arc4random() % (9); NSLog(@"Random Number: %d",r); ```
int r = (arc4random() % 8) + 1
I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't). Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.
Is there any simple way to create a GUI using OpenCV library or linking some other library with OpenCV. Just Like the trackbar in OpenCV, is there any way to create push buttons also?
OpenCV is a computer vision framework, not a GUI framework (even though OpenCV contains some very basic GUI functions). For a real GUI, better use something like GTK or Qt.
I have already GtkTreeView. And I want hide some cells. There is method ``` gtk_cell_renderer_set_visible (GtkCellRenderer *cell, gboolean visible); ``` But How I can apply this method for some cells? Use iterator?
The only way is to 'mask' your model using aGtkTreeModelFilter. With this, you can supply an extra 'visible' column that tells whether the row should be visible or not; or you can use a function to decide which rows should be visible.
``` void (*a)(char*, char*); ``` is this a function called a. returns void pointer? in c?
This is a functionpointernameda. The function signature ofais a function that returns void and takes twochar *arguments. SeeFunction Pointer Tutorialsfor more information on function pointers.
I have a source file that I can run via the terminal using ``` gcc source.c -I/usr/include/libxml2 -lxml2 -o output ``` but when I#includethe source file which includes the libxml source files, the compiler complains that thelibxml/xmlmemory.h:,libxml/parser.h:,libxml/xpath.hcannot be found : no such file or directory.
You need always to keep the-I/usr/include/libxml2in your gcc statement, so that it can find the header files.
Does anyone know why the following code ``` void foo(const int X) { #pragma omp parallel for private(X) for (int i = 0; i < 100; i++) { } } ``` gives this error error: 'X' is predetermined 'shared' for 'private' and how I can really makeXprivate to each thread?
You are getting an error becauseXis constant. Just removeconstand everything should work.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question Anyone knows what is a kinspect? Is it related to somewhere memory leaks? Someone please help me, if you'll know. Thanks in advance
According to google it's a typo'd version ofLinspect
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question Anyone knows what is a kinspect? Is it related to somewhere memory leaks? Someone please help me, if you'll know. Thanks in advance
According to google it's a typo'd version ofLinspect
Does anybody know how variable arguments are passed in classic C? I did some debugging today and most regular arguments are passed via stack. However it seems that this does not apply for variable arguments. Are those parameters stored somewhere else like constant strings? Thanks in advance!
It depends on the platform./usr/include/stdarg.his the place to start looking for details.
Is there a way to get the names of all files inside a directory using C?
While C itself does not specify a way (or even specify directories), POSIX does. You can either useopendirandreaddiryourself to read an entry at a time, or you can usescandirorglobto get the results all together in memory (and filter which entries get listed).
When i creating TThread i can't pass parameters to thread, so i need use global variables or what? I am using Embarcaderos Rad Studio C++ Builder 2010
You have a class derived from TThread, right? Can you just make your class constructor take additional arguments (beyond thebool suspendedone that seems to be common)?
I'm using OpenAL as the sound engine for my iPhone game, but still learning how to use it. I managed to play sounds with it, however I'm in one point when I need to concatenate (not merge) 2 sound sources (same file in fact, so this needs no conversion I guess) and I'm stuck. Any help would totally be appreciated:D
I wonder if you landed on this:OpenAL Programmers Guide Try looking intoExtAudioFile.
If fopen( path, "w" ) succeeds, then the file will be truncated. If the fopen fails, are there an guarantees that the file is not modified?
No there are no guarantees about the state of a file iffopen(path, "w")fails. The failure could be coming from any operation from opening the file, committing the truncation to disk, etc ... The only guarantee a failure provides is that you don't have access to the file.
I want to delete a string from a particular position in the file. Is thre a function to do that? Can I delete last line of a file through a function?
You have two option To read whole file, remove what you need and write it backIf the file is big, read file sequentially, remove given part, and move content after that forward
When i creating TThread i can't pass parameters to thread, so i need use global variables or what? I am using Embarcaderos Rad Studio C++ Builder 2010
You have a class derived from TThread, right? Can you just make your class constructor take additional arguments (beyond thebool suspendedone that seems to be common)?
I'm using OpenAL as the sound engine for my iPhone game, but still learning how to use it. I managed to play sounds with it, however I'm in one point when I need to concatenate (not merge) 2 sound sources (same file in fact, so this needs no conversion I guess) and I'm stuck. Any help would totally be appreciated:D
I wonder if you landed on this:OpenAL Programmers Guide Try looking intoExtAudioFile.
If fopen( path, "w" ) succeeds, then the file will be truncated. If the fopen fails, are there an guarantees that the file is not modified?
No there are no guarantees about the state of a file iffopen(path, "w")fails. The failure could be coming from any operation from opening the file, committing the truncation to disk, etc ... The only guarantee a failure provides is that you don't have access to the file.
how do you color mask a 32 bit unsigned integer for the red, green, and blue values is it like this? (color_to_be_masked>>8)
This should get you the result you want: ``` short red = (color >> 16) & 0xFF; short green = (color >> 8) & 0xFF; short blue = (color) & 0xFF; ```
I need to know if I can access internet from my proxy, I'm doing this now: ``` if((system("wget -q www.google.it -O /dev/null")); // I don't have access. ``` Is there a better way to solve this problem? Is there a function in C? Thank you very much.
Everyone loves this guide. http://beej.us/guide/bgnet/ It'll help you learn how to get to grips with networking programming in C very easily.
Is there any difference between the computation of small floats - that are close to 0 - and big floats - that are far from 0?
As far as I understand how processors work, there should be absolutely no difference at all
In case a system call function fails, we normally use perror to output the error message. I want to use fprintf to output the perror string. How can I do something like this: ``` fprintf(stderr, perror output string here); ```
``` #include <errno.h> fprintf(stderr, "%s\n", strerror(errno)); ``` Note: strerror doesn't apply\nto the end of the message
Is it possible to put arguments in a systems call? something like ``` system("rm %s %s", string1, string2) ```
The prototype for thesystemfunction is: ``` int system(const char *command); ``` so, no. But, how about: ``` snprintf(buffer, sizeof(buffer), "rm %s %s", target1, target2); system(buffer); ```
I am trying to use a open source library under C++. The README file states that You need to link your program with `svm.cpp'. I am wondering how to link my program with svm.cpp? Do I need to modify the make file to make this happen?
Compilesvm.cppwith not linking, will resultsvn.oobject file, use it object file with your program linking.
Quite a basic question but can someone tell me the difference between downloading src files against downloading binary files?
Source files are uncompiled C/C++ code, while binary files are the compiled programs.
I would like to check if a number is larger than 0. The 0 is in string format How do I either Compare the value to a string representation of 0Cast the string to an int
strtol()
How do i change the c coding style format in emacs ? Specifically i need to change the indentation in the c code shown by emacs from i per block to 2 per block
Type M-x followed by "customize-mode" followed by "c-mode". Then use the built-in customization page to override the default "C Basic Offset" with your new value of "2". When you're done, be sure to select "Save for future sessions" at the top of the page.
I have a very small program which converts a string to double. The problem is everytime it is printing 0.0000. Please help me. Thanks in advance. ``` enter code here $ export LT_LEAK_START=1.5 $ echo $LT_LEAK_START 1.5 #include <stdio.h> int main() { double d; d=strtod(getenv("LT_LEAK_START"), NULL); printf("d = %lf\n",d); } Output: d=0.0000000 ```
Try including ``` #include <stdlib.h> ```
This question already has answers here:Closed12 years ago. Possible Duplicate:How many 1s in an n-bit integer? Hello How to calculate how many ones in bits? ``` 1100110 -> 4 101 -> 2 ``` And second question: How to invert bits? ``` 1100110 -> 0011001 101 -> 010 ``` Thanks
If you can get your bits into astd::bitset, you can use theflipmethod to invert, and thecountmethod to count the bits.
Is there any way to make pointers read a file as a block of memory in C? Can access of a file can be faster...?
Treating a file as memory (and letting the OS do the file IO for you) is termed 'memory mapping'. On POSIX (e.g.Linux), themmap()function does this. OnWindows, theOpenFileMapping()function and friends do this. Microsoft have excellent description of how this works, why to use it, and particulars on their platformhere.
``` int system(const char *) ``` How can I send output of this command (lets say the command is "pwd") to a char*? Its returning an int but I want the results of the command to be sent to a char*.
You can pipe the output of the command directly to a file by using "pwd > tempfile" as command.Another way is to usepopen ``` FILE *output = popen("pwd", "r"); ``` That will give you a file pointer where you can read the output from.
Why would sizeof in the following cases print different values: ``` printf("%d",sizeof("ab")); //print 3 char* t="ab"; printf("%d",sizeof(t)); //print 4 ``` In the first case I have 2 characters... Shouldn'tsizeofprint 2? Because they are 2 bytes?
Strings in C are null terminated. "ab" in memory looks like'a' 'b' '\0' Whiletis a pointer, so size is 4.
I can read values of elapsed seconds since some reference time which appears in the format1301330553(Decimal)/4D90BA79(hex). I would like to convert these seconds in somedate/timeformat inC. The elapsed seconds mentioned above are ofu32 data type.
there's a function called ctime which takes a unix long as a parameter that renders the time in ascii.
I have a C function which accepts a character. I need to extract as well insert bits into that character. I am clear with the extraction part. Can anyone give me an idea of how to insert values to bits?
Pretty vague question, I would suggest you brush up on bitwise operators. This should point you in the right direction. http://www.cprogramming.com/tutorial/bitwise_operators.html
For the following code snippet I get the output as1. I want to know how it came? ``` void main() { int x=10,y=20,z=5,i; i=x<y<z; printf("%d",i); } ```
i=x<y<z;, gets interpreted asi=(x<y)<z, which in turn gets interpreted asi=1<z, which evaluates to 1.
I have a very small program which converts a string to double. The problem is everytime it is printing 0.0000. Please help me. Thanks in advance. ``` enter code here $ export LT_LEAK_START=1.5 $ echo $LT_LEAK_START 1.5 #include <stdio.h> int main() { double d; d=strtod(getenv("LT_LEAK_START"), NULL); printf("d = %lf\n",d); } Output: d=0.0000000 ```
Try including ``` #include <stdlib.h> ```
This question already has answers here:Closed12 years ago. Possible Duplicate:How many 1s in an n-bit integer? Hello How to calculate how many ones in bits? ``` 1100110 -> 4 101 -> 2 ``` And second question: How to invert bits? ``` 1100110 -> 0011001 101 -> 010 ``` Thanks
If you can get your bits into astd::bitset, you can use theflipmethod to invert, and thecountmethod to count the bits.
Is there any way to make pointers read a file as a block of memory in C? Can access of a file can be faster...?
Treating a file as memory (and letting the OS do the file IO for you) is termed 'memory mapping'. On POSIX (e.g.Linux), themmap()function does this. OnWindows, theOpenFileMapping()function and friends do this. Microsoft have excellent description of how this works, why to use it, and particulars on their platformhere.
``` int system(const char *) ``` How can I send output of this command (lets say the command is "pwd") to a char*? Its returning an int but I want the results of the command to be sent to a char*.
You can pipe the output of the command directly to a file by using "pwd > tempfile" as command.Another way is to usepopen ``` FILE *output = popen("pwd", "r"); ``` That will give you a file pointer where you can read the output from.
For example: ``` struct myCar{ int price; int *uniqueID; }; ``` In C, an int has 4 bytes. I'm assuming a pointer also occupies 4 bytes as well? Therefore, 8 bytes total?
Find out: ``` printf("Size of my struct is: %zu\n", sizeof(struct myCar)); ``` The size of a pointer is platform dependent. For that matter, the size of anintis platform dependent. Could be 8 bytes for either if you're on a 64bit machine.
Can a single char be made read-only in C ? (I would like to make '\0' read-only to avoid buffer overflows.) ``` char var[5 + 1] = "Hello"; var[5] = '\0'; // specify this char as read-only ? ```
You can't make a mixedconst/non-constarray or string. The\0not being overwritten should be guaranteed by the invariants in your program.
How would I make a version of sleep in C spin so it uses cpu cycles?
I suppose something like (pseudocode) ``` while (time < endtime) ; ``` The implementation of "time < endtime" is OS-dependent, but you just want to compute the end time based on an argument before your loop starts, and then continuously fetch the system time and compare it to that end time.
``` struct timeval start, end; . . . elapsedTime = (((end.tv_sec * 1000000) - (start.tv_sec * 1000000)) + (end.tv_usec - start.tv_usec)); ``` I just want to double check this returns time in micro sec..
The code is correct, but watch out for overflow. It's slightly safer to do ``` (end.tv_sec - start.tv_sec) * 1000000 ``` then add in theusecdifference.
Is there an option, part of read() that when calling read() on a file descriptor it only prints out the characters up to the null terminator?
Sorry, no, there isn't.read()doesn't look at the data at all; it just reads as many bytes as there are (but not more than your buffer size). I would do this with the higher-levelstdio.hfunctions, by callinggetc()(and writing to a buffer) until I saw a NUL byte, and thenungetc()on the NUL.
I'd like to know how many instructions are needed for a function call in a C program compiled with gcc for x86 platforms from start to finish.
Write some code.Compile it.Look at the disassembly.Count the instructions. The answer will vary as you vary the number and type of parameters, calling conventions etc.
What are the recommended XML parsers for parsing a TMX file(XML based tilemap) in C? What are the pros and cons of each, as I would like to have an efficient one because it will be running on an embedded system.
We used libxml on an embedded product a while back. It may be right for you.
I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that?
%Lgis probably what you want: seehttp://developer.apple.com/library/ios/#DOCUMENTATION/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html.
Createprocess API has a option to create a process with CREATE_SUSPENDED flag. Similarly, is there any possiblity in ShellExecute APIs to create the process in suspended state.
No. ShellExecute doesn't have to imply a process is launched - it's used to perform "shell operations" such as "open" or "print", whichmaylead to a new process being created.
Part of the code is as follows but not work ``` printf("Enter a line of text (Enter to stop): "); fflush(stdin); fgets(input, 256, stdin); if (input == '\0') { exit(0); } ..... ..... ``` i want if the user only press enter, the program will be terminated. how to do it? thanks
Useif(*input == '\n')- iffgetsreads a newline, it's stored in the buffer.
is there any example of using work/pool (or. Producer/Consumer) scheme for MPI? As for everything I have done, I am getting just one going through application and my app is deadlocked then. Thanks
Just googling around for "MPI Master Worker" or "MPI Master Slave", I see a bunch of examples; one good one hosted at Argonne National Labs is: http://www.mcs.anl.gov/research/projects/mpi/tutorial/mpiexmpl/src2/io/C/main.html
Would it be possible to take a users input as a variable to be used in an expresion? ``` scanf("%s", op); //User enters "==" or "!=" if(x op y) //Go. ```
No. The best you can do is something like: ``` scanf("%s", &op); if (strcmp(op, "==") == 0) { result = x == y; } else if (strcmp(op, "!=") == 0) { result = x != y; } // now use result ```
Lately I had a task that included printing base-4 representation of a number. Since I didn't find a function to do it for me, I implemented it (which is not so hard of course), but I wonder, is there a way to do it using format placeholders? I'm not asking how to implement such function, but if such function / format placeholder already exists?
There is no standard C or C++ function, but you may be able to useitoa
I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that?
%Lgis probably what you want: seehttp://developer.apple.com/library/ios/#DOCUMENTATION/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html.
I have two floating point numbers. If I add that 2 numbers means. It will displaying the answer as 4.50000 (I used just %f). If I used (2.%f) means the answer is just 4. I want the answer as 4.5. What do I have to modify in this?
Try the format string%2.1f: ``` $ printf "%2.1f\n" 4.5 4.5 ``` The.1says "one character after the radix".
For example,inttakes 4 bytes on a 32-bit OS, but 8 bytes on a 64-bit OS, does this kind of thing exist in C?
Yes. This is precisely what is meant by "platform-specific definitions" for things like the size ofintand the meaning of system calls. They depend not just on the OS, but also on the target hardware and compiler configuration.
I want to simplify the following code in C. Is there any hash table in C to make it simple? For example "dict" in Python. ``` int a, b, c, d ...... a = get_value_from_sth( A_NAME ) b = get_value_from_sth( B_NAME ) c = get_value_from_sth( C_NAME ) d = get_value_from_sth( D_NAME ) ...... ```
No, C does not have a built-in hash table type like Python's dicts. You may be able to get by with an array, depending on your needs.
The question is self-explanatory. I'm using the C API.
No, but it's easy to implement. It's just: ``` UChar *u_strdup(UChar *in) { uint32_t len = u_strlen(in) + 1; UChar *result = malloc(sizeof(UChar) * len); u_memcpy(result, in, len); return result; } ```
I have two floating point numbers. If I add that 2 numbers means. It will displaying the answer as 4.50000 (I used just %f). If I used (2.%f) means the answer is just 4. I want the answer as 4.5. What do I have to modify in this?
Try the format string%2.1f: ``` $ printf "%2.1f\n" 4.5 4.5 ``` The.1says "one character after the radix".
For example,inttakes 4 bytes on a 32-bit OS, but 8 bytes on a 64-bit OS, does this kind of thing exist in C?
Yes. This is precisely what is meant by "platform-specific definitions" for things like the size ofintand the meaning of system calls. They depend not just on the OS, but also on the target hardware and compiler configuration.
I want to simplify the following code in C. Is there any hash table in C to make it simple? For example "dict" in Python. ``` int a, b, c, d ...... a = get_value_from_sth( A_NAME ) b = get_value_from_sth( B_NAME ) c = get_value_from_sth( C_NAME ) d = get_value_from_sth( D_NAME ) ...... ```
No, C does not have a built-in hash table type like Python's dicts. You may be able to get by with an array, depending on your needs.
I want to share my local saved image and formatted text on Twitter or Facebook using my application. For example, I want to combine both image and bolded text in a single post. Are there any APIs available for it?
I recommend usingShareKitin your iOS application. It is very easy to integrate a variety of Social Networking sites.
While trying to open the file in Class in function oninitdialog(),It throws exception.If I open the file globally , it works. How to overcome this? why the fopen command is behaving like these? Regards, karthik
Actually I made a mistake by creating file descriptor in OninitDialog function in mfc.To overcome this , I create the file descriptor in constructor of the class.
I'm wondering if it is possible to implement the following logical under Linux and using POSIX thread library. ``` given a mutex if (I can get the mutex) { lock the mutex call fun A unlcok the mutex } else { call fun B } ``` I'm new to thread programming under Linux, so just use the pseudo-code to show the logic of the code snippet I'm looking for.
You're looking forpthread_mutex_trylock
I'm trying to write a program that uses tgkill to send a signal to a specific thread, but whenever I compile it with gcc I get an error about an undefined reference to 'tgkill'. I tried compiling with -lpthread but it didn't help. I've googled and googled and can't come up with any answers. How do I get it to compile??
From thetgkill()manpage: Glibc does not provide wrappers for these system calls; call them using syscall(2).
It seems to have no impact on the functionality of sbrk, but in sbrk()'s documentation it says that it requires an intptr_t parameter. It works (or at least seems to work) when passing an int type as a parameter. This is in regular C.
intptr_tchanges size depending on the architecture.intmay or may not change size depending on the architecture- that is, if you are on 64bit, thenintptr_tMUST be 64bits, whereasintmaybe 32bits.
Is there anycorjavaexample implementingBayesian Net? I want to solve some things but Do not where to start?.
Use Weka. It not only implements Bayes Nets, but also a lot of other ML algorithms.
Could someone help me with what the equivalent of this C code is in C#? ``` struct { int left, right; } stack[MAX]; ``` Thanks!
``` public struct PickAName { public int left; public int right; } private const int MAX = 666; PickAName[] stack = new PickAName[MAX]; ``` or: ``` Stack<PickAName> stack = new Stack<PickAName>(); ```
Why is empty struct in C a constraint violation? Why does this rule get changed in C++? Are there any historical reasons?
since you don't have inheritance in C you don't need them. If you just want to have a distinguishable pointer type you can use pointers to incomplete types. ``` struct opaque; struct opaque* stranger = 0; ``` should work fine.