question
stringlengths
25
894
answer
stringlengths
4
863
There are certain common library functions in erlang that are much slower than their c equivalent. Is it possible to have c code do the binary parsing and number crunching, and have erlang spawn processes to run the c code?
Of course C would be faster, in the extreme case, after optimizations. If by faster you mean faster to run. Erlang would be by far, faster to write. Depending on the speed requirements you have Erlang is probably "fast enough", and it will save you days of searching for bugs in C. C code will only be faster after optimizations. If you spend the same amount of time on C and Erlang you will come out with about the same speed (note that I count time spent debugging and error fixing in this time estimation. Which will be a lot less in Erlang). So: ``` faster writing = Erlang faster running (after optimisations) = C faster running without optimisations = any of the two ``` Take your pick.
This question already has answers here:Closed13 years ago. Possible Duplicate:Is there a printf converter to print in binary format? Consider this small C application ``` int main () { int bits = 100 >> 3; printf("bits => %d", bits); return 0; } ``` How can I print thebitsvariable so I can see it as a binary value (with the bits clearly shifted), e.g.00001100? I'm also learning, so feel free to correct any terminology.
This should work (not tested): ``` #define PRINT_BITS 7 void printbits(int input){ int i, mask; for(i=PRINT_BITS; i >= 0; i--){ mask = 1 << i; if(input & mask){ printf("1"); }else{ printf("0"); } } } ```
Any help with this problem would be fantastic. I appreciate all contributions! Let us say I'm running a daemon that is observing the behaviour of the app that has keyboard focus. I have it's PID and process name. Is there any way I can see what files that application is accessing? I'm programming in Objective-C, Cocoa and C. Thanks! EDIT: Sorry, I should have clarified. I want to be doing this programmatically from the daemon. Thanks
There's a command line tool called lsof that shows you every file that's open and what program has it open. You could look at its source, then do the same thing periodically. I don't think you can intercept reads and writes, though—not without using DTrace, which requires root powers.
``` /*you cannot change anything from here below*/ main() { exit(0); } /*you cannot change anything from here up*/ ``` This was asked during an interview. I was told to print something on console. anybody?
Really surprised that nobody posted this yet: ``` #include <stdio.h> #if 0 /*you cannot change anything from here below*/ main() { exit(0); } /*you cannot change anything from here up*/ #endif int main() { printf("Hello, World!"); return 0; } ``` Prints at runtime and no undefined behavior whatsoever.
I need to print this value as a time string to Mon 16-Aug-2010 06:24 format or something similar. ``` unsigned int t = 1281920090; ```
You can use the functionsgmtimeandasctimeas: ``` #include <stdio.h> #include <time.h> int main() { time_t timestamp = 1281920090; printf("%s", asctime(gmtime(&timestamp))); return 0; } ``` Output: ``` $ gcc a.c && ./a.out Mon Aug 16 00:54:50 2010 ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been done so far to solve it.Closed9 years ago.Improve this question I've looked for a lot of sites but didn't find any examples by glib. I've seen only discription types and functions... Perhaps do you know a good source? PS. Thanks for your answers! =)
Here's a tutorial, a little old but still applicable:http://www.ibm.com/developerworks/linux/tutorials/l-glib/ Here's a tutorial on the GObject part of GLib:http://www.arbingersys.com/2009/07/missing-gobject-tutorial-sample.html Also check out the excellent book 'Foundations of GTK Development' by Andrew Krause, it has a chapter on GLib:http://www.gtkbook.com/
Does the following program invokeUndefined Behaviourin C? ``` int main() { printf("Printf asking: Where is my declaration ?"); } ``` In the above program there is an implicit declaration ofprintf(), so is the above code fully standard compliant or it just has some implementation specific behaviour?
Yes it does. Not having a declaration in scope is UB. J.2 Undefined behavior— For call to a function without a function prototype in scope where the function is defined with a function prototype, either the prototype ends with an ellipsis or the types of the arguments after promotion are not compatible with the types of the parameters (6.5.2.2). Also, note that falling off main is okay in C99 (i.e. semantically equivalent to areturn 0;). For pre-C99 compliant compilers you need a return statement wherethe return type of the main function is a type compatible withint.
How I should allocate dynamic arrays in C? Currently I have a function I wrote calledmalloc2Dthat looks like this: ``` void* malloc2D(size_t unitSize, uint firstCount, uint secondCount) { void** pointer = malloc(sizeof(id) * firstCount); for (int i =0; i < firstCount; i ++){ pointer[i] = malloc(unitSize * secondCount); } return pointer; } ``` It works fine however I have been told that it puts a lot of strain on the memory allocating separately. What is the best or most conventional way to do this?
You could allocate the entire block at once: ``` int ** foo; foo = malloc(sizeof(int*) * firstCount); foo[0] = malloc(sizeof(int) * firstCount * secondCount); for (int i=1; i<firstCount; i++) { foo[i] = foo[0] + i * secondCount; } ```
If I create a button in the Win32 API, the default conrol theme looks like a Windows 95/98 button. I remember in the past the Microsoft forums told me how to get the XP style, but I don't recall how to do this. Is there a way to programatically or manually change the control themes in a Win32 application? Thanks.
You want toEnable Visual Stylesby adding a manifest dependency to the common control 6 assembly to your applications manifest. If you use DevStudio it should be as simple as adding the #pragma directive from the linked page: ``` #pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") ```
I wanna to write something to a .txt file in .c file, but required to name that file with the current timestamp as the postfix, just like filename_2010_08_19_20_30. So I have to define the filename char array first and process the filename by myself?Assign the character one by one? Is there any easy way to do that?
There's a function calledstrftimethat exists for the express purpose of writing a time value into a human-readable string. Documentation:http://linux.die.net/man/3/strftime An example: ``` #include <time.h> #include <stdio.h> int main() { FILE* file; char filename[128]; time_t now; struct tm tm_now; now = time(NULL); localtime_r(&now, &tm_now); strftime(filename, sizeof(filename), "filename_%Y_%m_%d_%H_%M.txt", &tm_now); file = fopen(filename, "w"); fprintf(file, "Hello, World!\n"); fclose(file); return 0; } ```
Hallo, I'm looking for a really simple and easily hackable tar library for C or C++. Ideally it should have a permissive license (BSD/LGPL) and not have a ton of Unix/Windows OS dependencies, as I plan to use it from an embedded RTOS... Any ideas?
I haven't used it myself, but have you triedlibtar? It is written in C and BSD licensed.
I want to display the machine code of a specific function. For example, in Linux I would enter: ``` objdump -D x.out | grep -A20 main.: ``` What would the equivalent be in Windows?
What would the equivalent be in windows? Off the top of head, you just save the output into a file: ``` objdump -D x.out > x.out.dump ``` then open the file (x.out.dump) in the text editor of choice. On Windows to peek into the object code I find myself mostly using GUI debuggers. Windows is not very command-line friendly environment. Otherwise, you might want to install theCygWin, start bash in terminal or the cmd.exe and use the grep as if you were under Linux.
I have a GtkLabel and a GtkDrawingArea within a VBox, I want to center the label relative to a X-coordinate of the GtkDrawingArea (which is below of the label in the VBox), how can I tell GTK to center that label relative to that "anchor" point ? This point should be the center of the label.
Since your GtkLabel and GtlDrawingArea are inside a GtkVBox, then their position are relative to each other. The following should set the alignment of the label to the center: ``` gtk_misc_set_alignment(GTK_MISC(label), 0.5F /*X*/, 0.5F /*Y*/); ``` If you don't want to center the text of the GtkLabel, then you might use GtkAlignment widget: ``` GtkWidget* helper; helper = gtk_alignment_new(0.5F /*X*/, 0.5F /*Y*/, 0.0F, 0.0F); gtk_container_add(GTK_CONTAINER(helper), label); gtk_box_pack_start_defaults(GTK_BOX(vbox), helper); ``` You can realign it again by callinggtk_alignment_setfunction.
Is there a built in function to convert ints to Big-endian or little-endian for sending over the network? like htonl and ntohl in c Also, is there something similar to strings, datetime, etc.. Thanks
Java streams use network byte order. That means you only have to worry about things likehtonlandntohlin C and it ilk.
``` // Create test video frame void CreateFrame(char * buffer, int w, int h, int bytespan) { int wxh = w * h; static float seed = 1.0; for (int i = 0; i < h; i ++) { char* line = buffer + i * bytespan; for (int j = 0; j < w; j ++) { // RGB line[0] = 255 * sin(((float)i / wxh * seed) * 3.14); line[1] = 255 * cos(((float)j / wxh * seed) * 3.14); line[2] = 255 * sin(((float)(i + j) / wxh * seed) * 3.14); line += 3; } } seed = seed + 2.2; } ``` can any one please tall me what isline += 3;for? and how to create such function analog in C#?
line += 3increments the pointerlineby 3 bytes, so that it points to the next pixel.linehere is a pointer to a 3-byte pixel, so it really should be called something else, likepPixel.
John Regehr's blog postA Guide to Undefined Behavior in C and C++, Part 1contains the following "safe" function for "performing integer division without executing undefined behavior": ``` int32_t safe_div_int32_t (int32_t a, int32_t b) { if ((b == 0) || ((a == INT32_MIN) && (b == -1))) { report_integer_math_error(); return 0; } else { return a / b; } } ``` I'm wondering what is wrong with the division (a/b) when a = INT32_MIN and b = -1. Is it undefined? If so why?
I think it's because the absolute value of INT32_MIN is 1 larger than INT32_MAX. So INT32_MIN/-1 actually equals INT32_MAX + 1 which would overflow. So for 32-bit integers, there are 4,294,967,296 values.There are 2,147,483,648 values for negative numbers (-2,147,483,648 to -1).There is 1 value for zero (0).There are 2,147,483,647 values for positive numbers (1 to 2,147,483,647) because 0 took 1 value away from the positive numbers.
I have to retrieve process status(whether process is running or stopped) whose procees id is given from my c program(i am using linux). i planned to use exec command and written below statement execv("ps -el|grep |awk '{print $2}'",NULL); But it is not giving me desired output. Please let me know where i am wrong.
The third field in/proc/<pid>/statcontains the process status:Rif it's Running,Sif it's Sleeping (there's a few others too, likeDfor Disk Wait andZfor Zombie).
Apple introduced a closure in C as name of 'block'. Should I manage memory for the blocks? If so, what do I have to do?
Like variables with function scope in plain C, blocks literals in functions have automatic storage duration. When you think of a block literal as a pointer type you see what can go wrong: When you return a block from a function you are returning a pointer to local memory, which is no longer valid. The solution is to use theBlock_copy()function whenever you want to return a block and theBlock_release()when you no longer need it. More information inthis tutorialthat has a separate section on blocks in C.
Check out this code ``` #include<stdio.h> int main() { const int a=7; int *p=&a; (*p)++; printf("*p=%d\np=%u\na=%d\n&a%u",*p,p,a,&a); getch(); } ``` The output you get for this is ``` *p=8 p=1245064 a=8 &a1245064 ``` How is this possible?? We declared variable a as constant. Doesnt this mean that the location pointed to by a can never be changed during the course of pgm execution??
That's undefined behavior - in your case it is working as you described, but it could just as well crash the program or cause any other problems. In your caseconstdoesn't prevent the compiler from allocating the variable in modifiable memory, so you technically can modify it by obtaining a pointer to that variable and working through the pointer.
Jus check out this program.Logically it seems fine but its giving 000000000000000000000 for everything ``` #include<stdio.h> void main() { int n=25,k=32; printf("binary equivalent\n"); while(k!=0) { if((n>>1&0x01)!=0) printf("1"); else printf("0"); k--; } } ```
You don't ever changen. Don't try and cram everything into one line, be a little more verbose so that things are clearer. ``` while(k!=0) { if((n & 0x01) != 0) printf("1"); else printf("0"); k--; n >>= 1; } ```
Inlimits.h, there are #defines forINT_MAXandINT_MIN(and SHRT_* and LONG_* and so on), but onlyUINT_MAX. Should I defineUINT_MINmyself? Is0(positive zero) a portable value?
It's an unsigned integer - by definition its smallest possible value is 0. If you want some justification besides just common sense, thestandardsays: 6.2.6.2 Integer typesFor unsigned integer types other thanunsigned char, the bits of the object representation shall be divided into two groups: value bits and padding bits (there need not be any of the latter). If there areNvalue bits, each bit shall represent a different power of 2 between 1 and 2^(N−1), so that objects of that type shall be capable of representing values from 0 to 2^(N−1) using a pure binary representation; this shall be known as the value representation. The values of any padding bits are unspecified.
how does a call from c++ to c work internally??
The C++ compiler 'does the right thing' and uses the correct calling convention for the C function - a lame sounding answer but I don't know that there's much more that can be said!
I'm trying to achieve something close to what Adobe Illustrator does with the brush tool. It correctly analyzes and simplifies the path, including its bezier handles. I implemented theRamer–Douglas–Peucker_algorithmhowever, it wound up not really being what I needed. It works very well for line segments, but doesn't factor in bezier handles. Is there an algorithm that can do like this algorithm, but take into consideration cubic bezier handles? The problem with this one is that a curve could be at an angle but the algorithm only sees a straight line. Thanks
You probably want to explore least squares fitting for Bezier curves. Here'sone threadanda pdfthat may be helpful.. I did this sort of thing several years ago, and found one ofGerald Farin's bookshelpful, but I can't remember which one.
``` char* func( char* a, const char* b ) { while( *a ) { char *s = a, *t = b; while( (*s++ == *t++) && *s && *t ); if( *t == 0 ) return a; a++; } return 0; } ``` The above code was written to search for the first instance of string "b" inside of string "a." Is there any problem with the above program? Is there any approach to improve the efficiency of it?
If a points to "cat" and b points to "ab", func will return a pointer to "at" (the wrong value) instead of 0 (the intended value) because the pointer t is incremented even though the comparison (*s++ == *t++) fails. For completeness' sake and in order to answer the second question, I'd offer one solution (surely among other viable ones): Have the result of the comparison be assigned to another variable, e.g.while( ( flag = ( *s++ == *t++ ) ) && *s && *t );and thenif( flag && *t == 0 ).
I'm trying to learn how to reverse engineer software and all the tricks to understand how the code looks like before the compiler optimizations. I found something like this several times: ``` if (a < 0) a = -2147483648 - a; ``` I originally thought it was anabs(): a underflows so you get the positive value. But sinceais negative (see the if), this is equivalent to: ``` if (a < 0) a = -2147483648 + abs(a); ``` Which will be a very small negative number, and not the absolute value ofaat all. What am I missing?
It is converting the number so that bit 31 becomes a sign bit, and the rest bits (0...30) denotes the absolute magnitude. e.g. if a = -5, then after the operation it becomes 0x80000005.
I am trying to detect whether I am running on a Gnome or KDE desktop environment. I know I can check via a ps -aux and grepping either gnome or KDE but that's not good: 1) what if I am on a gnome desktop but I have the KDE libs loaded? 2) I need to do it from code without using system() or popen() or other fork/exec combination. I can read files, or env. variables or whatever. Any ideas? thanks, any help is appreciated.
Not sure how standard this is, but it is consistent in Fedora 21, Slackware 14.1 and Ubuntu 14.04. (More welcome) try ``` $ echo $DESKTOP_SESSION ``` Hope this helps.
I've got the following printf statement: ``` printf("val=%-4.2lf", val); ``` However, val is never padded with spaces so the space taken up by val is different if there are 3 or 4 digits before the decimal. Shouldn't the 4 in the format specifier guarantee that there are at least 4 spaces? Sorry for the newb question but it's been frustrating me.
The 4 specifies the minimumtotalfield with - you also have the decimal point and the 2 digits after the decimal that are taking a minimum of 3 characters out of that 4 character field width. So if you want a minimum field width of 4 characters before the decimal point, you'd want to use a format of%-7.2lf.
I am little confused with logical AND operator. I have these 2 lines of code. Herenumandjare both int. I have a situation where both the conditions are satisfied, but I don't know why it's not printing the value ofj. Can anybody point out the mistakes? Thanks in advance. ``` if(k==1 && num%j==0) printf("%d",j); ```
In plain English, the expressionk == 1 && num % j == 0is true if and only ifkequals 1andthe remainder from dividingnumbyjis 0. Not much more I can say.
In applications like Adobe Illustrator, they have a way to simplify a path. I'm not sure how this works exactly. Given a path with points which have 2 bezier handles each (for cubic bezier), how could I go about simplifying the path? Thanks
Look atDouglas–Peuckerit is an algorithm for reducing the number of points in a curve that is approximated by a series of points. It is frequently used in GIS solutions.
hello i got a problem with returning an array of linklists in c lets say i got arrlinklist = {linklist1 , linklist 2...,linklist5} and i want my function to return arrlinklist. how do i do that... thx in advance. i wanted to know how to define the signature of my function i tried linkedlist* CreateArrayOfList();
In C you cannot return an array, you can only return a pointer to the first element of the array.
What would it take to portlibeioto windows?
Almost a year later, what you may want to look into (you, or anyone else finding this via search or Google) islibuv, formerly liboio. Contrary to the the accepted answer, it's not so much that Windows is, or at the time was, bereft of the concept of evented i/o, it just wasn't well-known outside of the arcane circle of deep-knowledge Windows API developers. In the Windows space, a similar concept is implemented asI/O Completion Ports, so it's not so much that a libeio version/port/fork/analog would need to reimplement the wheel, it'd just have to have a libeio-looking API to something that was using IOCP under the hood.
im porting c code to windows 32 bit using visual studio expressnow i have 3 functions that i can't find any alternatives in windowsthey are:alarmbzerobcopywhat are the equivalent methods in C win32 ?
alarm you are going to need to dig for the other two are: ``` #define bzero(b,len) (memset((b), '\0', (len)), (void) 0) #define bcopy(b1,b2,len) (memmove((b2), (b1), (len)), (void) 0) ```
so far, i m working on the array with 0th location but m in need to change it from 0 to 1 such that if earlier it started for 0 to n-1 then now it should start form 1 to n. is there any way out to resolve this problem?
C arrays are zero-based and always will be. I strongly suggest sticking with that convention. If youreallyneed to treat the first element as having index 1 instead of 0, you can wrap accesses to that array in a function that does the translation for you. Why do you need to do this? What problem are you trying to solve?
For code, ``` while(1) { /* ..... */ } ``` MSVC generates the following warning. ``` warning C4127: conditional expression is constant ``` MSDNpage for the warning suggests to usefor(;;)instead ofwhile(1). I am wondering what advantagefor(;;)is giving and why it warns for the constant usage inwhile? What flag should I use on GCC to get the same warning?
Constant conditionals are often enough simply bugs. Consider this: ``` unsigned k; ... while (k>=0) { ... } ``` The conditionk>=0would make sense if k was a signed int, but not for unsigned. A careless developer forgets that k was declared unsigned and he/she would use it as if it was usable as a negative number. The compiler tries to be helpful and warn you about this andwhile(1)falls for the compiler into the same problem class.for(;;)is preferable because it unambiguously means `loop forever
My application has a static control which inside has a tab control. It looks like this:alt text http://img834.imageshack.us/img834/5645/topbar.png and I want to handle the topbar's paint event so that after it has drawn itself (and its children), have it floodfill to look more like this: alt text http://img230.imageshack.us/img230/9620/topbarb.png Given that I'v subclassed the topbar and can override any of its events, how could I do this? Thanks
The first thing I'd try would be to fill it in response toWM_ERASEBKGND(and I'd useFillRect, notFloodFill).
It's been awhile since I've played with c, and now I find something I've never seen before: ``` printf("%-16llu", my_var); ``` It would seem to be saying print 16 characters of a long unsigned int. But, what's the second 'l' for? long long?
``` %llu ``` Is forunsigned long long. This was added in C99 (and much, much after K&R wrote the book).
The following (test withgcc -E blah.c): ``` #define UNUSED(type) type UNUSED_ ## __COUNTER__ UNUSED(char const *) UNUSED(int) ``` Generates: ``` char const * UNUSED__COUNTER__ int UNUSED__COUNTER__ ``` I'm expecting: ``` char const * UNUSED0 int UNUSED1 ``` I've tried calling another macro, wrapping the arguments in brackets to no avail. If I don't paste the tokens it seems to work fine. Thedocumentationspecifically mentions the use of__COUNTER__in token pasting. What am I doing wrong?
Experimenting with gcc 4.4, this works: ``` #define UNUSED(type) UNUSED_(type, __COUNTER__) #define UNUSED_(type, counter) UNUSED__(type, counter) #define UNUSED__(type, counter) type UNUSED_ ## counter UNUSED(char const *) UNUSED(int) ``` But it doesn't work if I take out even one level of intermediates.
Isvoida data type in the C programming language? If so, what type of values can it store? If we haveint,float,char, etc., to store values, why isvoidneeded? And what is the range of void?
Void is considered a data type (for organizational purposes), but it is basically a keyword to use as a placeholder where you would put a data type, to represent "no data". Hence, you can declare a routine which does not return a value as: ``` void MyRoutine(); ``` But, you cannot declare a variable like this: ``` void bad_variable; ``` However, when used as a pointer, then it has a different meaning: ``` void* vague_pointer; ``` This declares a pointer, but without specifying which data type it is pointing to.
Is there a way to ensure that all WM_KEYDOWN events find their way into my main window regardless of who has focus? this is mainly for global things such as Delete, and hotkeys such as CTRL A and CTRL S. The problem is if another control has focus, all of these stop working. Is there maybe a better way of doing this than putting them in my main window's WM_KEYDOWN event? Thanks
Yes, you do it in your message loop. At the exact location where a traditional message loop has the TranslateAccelerator() call. Which performs the same kind of operation, catching short-cut keystrokes and turning them into WM_COMMAND messages. A typical class library implements this with a "PreProcessMessage" method.
what is the difference between array and list?
Although there isnothing like alistinCper sebut you sure could be talking about a linked lists implementation. Array:Random access, predefine size.Linked List:Sequential access, size at runtime. Other languages like, say Python, may have have bothlists andarrays inbuilt and their meaning may differ. Useful comments from below: You could add array lists. Lists which internally is an array which is doubled when needed and halved when only 1/4 full. This gives O(1) for add, remove, get(index) amortized. –lasseespeholt Python'slistis not a linked list. And the distinction between Pythonlistandarrayislistcan store anything while array can only store primitive types (int,float, etc). –KennyTM
In GTK I can't figure out what callback to setup so that when the user clicks in a window, I can get the X/Y co-ords of the click.
You're looking for thebutton-press-eventsignal ofGtkWidget.
I would like to know the best way to parse a large amount of xml from stdin (data getting piped) into a program I am writing usinglibxml2. I can parse fine using a reader from the functionxmlTextReaderPtr reader = xmlNewTextReaderFilename(filename)when I have achar *to the name of the file. I would preferably like to wind up with a reader so the rest of my program remains the same. Thank you.
I believe the best thing to do is to use the opening function that contains a file descriptor as the parameter and passSTDIN_FILENO. http://www.xmlsoft.org/html/libxml-xmlreader.html#xmlReaderNewFd
I have a loop that has to go from N to 0 (inclusively). Myivariable is of typesize_twhich is usually unsigned. I am currently using the following code: ``` for (size_t i = N; i != (size_t) -1; --i) { ... } ``` Is that correct? Is there a better way to handle the condition? Thanks, Vincent.
Yes, it's correct and it is a very common approach. I wouldn't consider changing it. Arithmetic on unsigned integer types is guaranteed to use modulo2^Narithmetic (whereNis the number of value bits in the type) and behaviour on overflow is well defined. The result is converted into the range0to2^N - 1by adding or subtracting multiples of2^N(i.e. modulo2^Narithmetic). -1converted to an unsigned integer type (of whichsize_tis one) converts to2^N - 1.--also uses modulo2^Narithmetic for unsigned types so an unsigned type with value0will be decremented to2^N - 1. Your loop termination condition is correct.
I'm pretty much using GDB for the first time. I run ``` $ gdb ``` then I'm running ``` attach <mypid> ``` then I see that my process is stuck (which is probably ok). Now I want it to continue running, so I run ``` continue ``` and my process continues running but from here I'm stuck if I want again to watch my current stack trace etc. I couldn't get out of continuing... I triedCtrl-Detc. but nothing worked for me... (was just a guess).
You should interrupt the process that is attached by gdb. Do not interrupt gdb itself. Interrupt the process by either ctrl-c in the terminal in which the process was started or send the process the SIGINT by kill -2 procid. With procid the id of the process being attached.
To make a string a null string i wrote this: ``` #include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[15]="fahad uddin"; strlen(str); puts(str); for(int i=0;str[i]!='\0';i++) strcpy(&str[i],"\0") ; puts(str); getch(); return 0; } ``` Before this i tried: ``` #include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[15]="fahad uddin"; strlen(str); puts(str); for(int i=0;str[i]!='\0';i++,strcpy(&str[i],"\0")) ; puts(str); getch(); return 0; } ``` In the first example, the program runs all right while when in the second example it prints the first letter of the string (in this example F). Why is this?
C strings are null-terminated. As long as you only use the functions assuming null-terminated strings, you could just zero the first character. ``` str[0] = '\0'; ```
Lets say i have the following cstring ``` char array[1000]; ``` How i can convert it to NSString and vice verse. Thanks.
Apple's Developer Reference has agood articleon this subject. Basically, you will do something like this: ``` NSString *stringFromUTFString = [[NSString alloc] initWithUTF8String:utf8String]; ``` if the string is UTF8 encoded. Otherwise, you can useinitWithCString:encoding:with which you can specify the encoding. Here is alist of available string encodings.
It's been awhile since I've played with c, and now I find something I've never seen before: ``` printf("%-16llu", my_var); ``` It would seem to be saying print 16 characters of a long unsigned int. But, what's the second 'l' for? long long?
``` %llu ``` Is forunsigned long long. This was added in C99 (and much, much after K&R wrote the book).
The following (test withgcc -E blah.c): ``` #define UNUSED(type) type UNUSED_ ## __COUNTER__ UNUSED(char const *) UNUSED(int) ``` Generates: ``` char const * UNUSED__COUNTER__ int UNUSED__COUNTER__ ``` I'm expecting: ``` char const * UNUSED0 int UNUSED1 ``` I've tried calling another macro, wrapping the arguments in brackets to no avail. If I don't paste the tokens it seems to work fine. Thedocumentationspecifically mentions the use of__COUNTER__in token pasting. What am I doing wrong?
Experimenting with gcc 4.4, this works: ``` #define UNUSED(type) UNUSED_(type, __COUNTER__) #define UNUSED_(type, counter) UNUSED__(type, counter) #define UNUSED__(type, counter) type UNUSED_ ## counter UNUSED(char const *) UNUSED(int) ``` But it doesn't work if I take out even one level of intermediates.
Isvoida data type in the C programming language? If so, what type of values can it store? If we haveint,float,char, etc., to store values, why isvoidneeded? And what is the range of void?
Void is considered a data type (for organizational purposes), but it is basically a keyword to use as a placeholder where you would put a data type, to represent "no data". Hence, you can declare a routine which does not return a value as: ``` void MyRoutine(); ``` But, you cannot declare a variable like this: ``` void bad_variable; ``` However, when used as a pointer, then it has a different meaning: ``` void* vague_pointer; ``` This declares a pointer, but without specifying which data type it is pointing to.
Is there a way to ensure that all WM_KEYDOWN events find their way into my main window regardless of who has focus? this is mainly for global things such as Delete, and hotkeys such as CTRL A and CTRL S. The problem is if another control has focus, all of these stop working. Is there maybe a better way of doing this than putting them in my main window's WM_KEYDOWN event? Thanks
Yes, you do it in your message loop. At the exact location where a traditional message loop has the TranslateAccelerator() call. Which performs the same kind of operation, catching short-cut keystrokes and turning them into WM_COMMAND messages. A typical class library implements this with a "PreProcessMessage" method.
what is the difference between array and list?
Although there isnothing like alistinCper sebut you sure could be talking about a linked lists implementation. Array:Random access, predefine size.Linked List:Sequential access, size at runtime. Other languages like, say Python, may have have bothlists andarrays inbuilt and their meaning may differ. Useful comments from below: You could add array lists. Lists which internally is an array which is doubled when needed and halved when only 1/4 full. This gives O(1) for add, remove, get(index) amortized. –lasseespeholt Python'slistis not a linked list. And the distinction between Pythonlistandarrayislistcan store anything while array can only store primitive types (int,float, etc). –KennyTM
In GTK I can't figure out what callback to setup so that when the user clicks in a window, I can get the X/Y co-ords of the click.
You're looking for thebutton-press-eventsignal ofGtkWidget.
I would like to know the best way to parse a large amount of xml from stdin (data getting piped) into a program I am writing usinglibxml2. I can parse fine using a reader from the functionxmlTextReaderPtr reader = xmlNewTextReaderFilename(filename)when I have achar *to the name of the file. I would preferably like to wind up with a reader so the rest of my program remains the same. Thank you.
I believe the best thing to do is to use the opening function that contains a file descriptor as the parameter and passSTDIN_FILENO. http://www.xmlsoft.org/html/libxml-xmlreader.html#xmlReaderNewFd
I have a loop that has to go from N to 0 (inclusively). Myivariable is of typesize_twhich is usually unsigned. I am currently using the following code: ``` for (size_t i = N; i != (size_t) -1; --i) { ... } ``` Is that correct? Is there a better way to handle the condition? Thanks, Vincent.
Yes, it's correct and it is a very common approach. I wouldn't consider changing it. Arithmetic on unsigned integer types is guaranteed to use modulo2^Narithmetic (whereNis the number of value bits in the type) and behaviour on overflow is well defined. The result is converted into the range0to2^N - 1by adding or subtracting multiples of2^N(i.e. modulo2^Narithmetic). -1converted to an unsigned integer type (of whichsize_tis one) converts to2^N - 1.--also uses modulo2^Narithmetic for unsigned types so an unsigned type with value0will be decremented to2^N - 1. Your loop termination condition is correct.
I'm pretty much using GDB for the first time. I run ``` $ gdb ``` then I'm running ``` attach <mypid> ``` then I see that my process is stuck (which is probably ok). Now I want it to continue running, so I run ``` continue ``` and my process continues running but from here I'm stuck if I want again to watch my current stack trace etc. I couldn't get out of continuing... I triedCtrl-Detc. but nothing worked for me... (was just a guess).
You should interrupt the process that is attached by gdb. Do not interrupt gdb itself. Interrupt the process by either ctrl-c in the terminal in which the process was started or send the process the SIGINT by kill -2 procid. With procid the id of the process being attached.
To make a string a null string i wrote this: ``` #include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[15]="fahad uddin"; strlen(str); puts(str); for(int i=0;str[i]!='\0';i++) strcpy(&str[i],"\0") ; puts(str); getch(); return 0; } ``` Before this i tried: ``` #include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[15]="fahad uddin"; strlen(str); puts(str); for(int i=0;str[i]!='\0';i++,strcpy(&str[i],"\0")) ; puts(str); getch(); return 0; } ``` In the first example, the program runs all right while when in the second example it prints the first letter of the string (in this example F). Why is this?
C strings are null-terminated. As long as you only use the functions assuming null-terminated strings, you could just zero the first character. ``` str[0] = '\0'; ```
Lets say i have the following cstring ``` char array[1000]; ``` How i can convert it to NSString and vice verse. Thanks.
Apple's Developer Reference has agood articleon this subject. Basically, you will do something like this: ``` NSString *stringFromUTFString = [[NSString alloc] initWithUTF8String:utf8String]; ``` if the string is UTF8 encoded. Otherwise, you can useinitWithCString:encoding:with which you can specify the encoding. Here is alist of available string encodings.
hello i am progremming in c with linux enviroment and facing a difficulty with blank rows while reading from afile. i am using strtok function for seperating the string with delimiter "," and getting segmentation error whenever the file that i am reading from contains blank lines thanks in advance
You seem to be getting the error because you're passing an invalid parameter to strtok - Try checking that the line isn't empty before passing it to strtok. A more robust solution would be to check that the line read from the file complies with your data format before parsing it - eg with a regex
i am trying to extract the username from this uri field in ANSI C code on linux using gcc ``` mail:[email protected] ``` so i need to strip the mail: and everything after the @. Are there any built in functions in C to extract substrings
``` char *uri_field = "mail:[email protected]"; char username[64]; sscanf(uri_field, "mail:%63[^@]", username); ``` If you might have other "junk" at the beginning (not necessarily justmail:), you could do something like this instead: ``` sscanf(uri_field, "%*[^:]:%63[^@]", username); ```
On Posix systems, the st_blksize member of the stat structure contains the optimal block size for IO for a given file. It looks like the Win32 implementations of stat (_stat & _stat64) do not support this field. What is the Win32 equivalent way of determining the optimal IO block size for a given file or filesystem?
I'm not sure if this will always return the optimal number, but the Win32 callGetDiskFreeSpacereturns, among other things,lpBytesPerSectorandlpSectorsPerCluster; multiply those to get the bytes per cluster which is (perhaps) a reasonable value to use as a buffer size. This call doesn't apply to files, but rather file systems, so you'd have to figure out what root the file lives on before using it.
One strategy that I though of myself is allocating 5 megabytes of memory (or whatever number you feel necessary) at the program startup. Then when at any point program'smalloc()returnsNULL, you free the 5 megabytes and callmalloc()again, which will succeed and let the program continue running. What do you think about this strategy? And what other strategies do you know? Thanks, Boda Cydo.
Handle malloc failures by exiting gracefully. With modern operating systems, pagefiles, etc you should never pre-emptively brace for memory failure, just exit gracefully. It is unlikely you will ever encounter out of memory errors unless you have an algorithmic problem. Also, allocating 5MB for no reason at startup is insane.
I wonder if there is ways for communicate actionscript with c/c++, as well as the level of complexity..
You're looking forAdobe Labs Alchemy: Welcome the preview release of codename "Alchemy." Alchemy is a research project that allows users to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2). The purpose of this preview is to assess the level of community interest in reusing existing C and C++ libraries in Web applications that run on Adobe® Flash® Player and Adobe AIR®.
My friends tell me that a special loop exists that isn't a 'while' loop or a 'do while' loop. Does anyone know what it's called and the correct syntax for it's use?
A for loop maybe? ``` for (i = 0; i < 15; ++i) { /* do stuff */ } ```
``` #include<stdio.h> int main(int argc, char **argv) { int a,b,c; printf("enter two numbers:-"); if( scanf("%d \t %d",&a,&b) == 2 ) { c=a+b; printf("addition of numbers= %d",c); } else { printf("please enter a valid input"); getchar(); } } ``` How to debug this code line by line in the c-debugger? I'm using linux platform.
Which debugger? In MS Visual Studio Express just place a breakpoint at the first line of the code and then start "Debug". On a Linux platform, compile the code with debugging flags (-g) and then run the resulting executable undergdb. Suppose your file istest.c. Compile: ``` gcc -g -o test test.c ``` Then debug: ``` gdb test ``` Seethis articlefor more details. Google "linux debug c program" for even more.
How does a variable in C/C++ work? I mean, a pointer stores an address from a variable and then you have to dereference it to access the object to which it refers, so I think that a variable is a pointer that is dereferenced automatically when used... does that make any sense?
A variable is an abstraction (a convenient name) for a memory position on the computer. In C/C++ if the variable is of typeintit will be a convenient name for a memory address holding an integer value. And a variableis nota pointer automatically dereferenced. A variable just holds the value it is supposed to hold. If it is a pointer, it will hold a memory address, if it is an integer it will hold an integer value, if it is a float, it will hold a floating point number... And so on and so forth...
how does realloc know the size of original data? ``` void *realloc(void *ptr, size_t size); ``` So, if the implementation is like this: ``` temp = malloc(size); memcpy(.. // How much to copy? free(ptr); return temp; ``` I realize this is not the original implementation, and realloc doesn't always do free, but when it does, how much does it copy? Edit: Thanks for the answers. But how can I then implement realloc in my code with malloc/free/..?
It knows becausemallocrecorded that information when you called it. After all, the system has to keep track of the sizes of allocated blocks anyway so that it doesn't allocate a particular region of memory twice. If you mean, "how does it know how much of the array I've written in so far", it doesn't need to. It can just copy any uninitialised garbage as well.
I am dealing with a math example. I need to use 12 digit number for my code. So which datatype should i use, to use the number in my functions?
If you have a 64-bit integer type, I'd go with that, since it gives you the (18 full digits) range: ``` −9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 ``` For other tasks (even bigger integers or massive floating point values), I useGMP, the GNU multi-precision library. It's performance is impressive.
With respect tothisquestion, we can declare a function that returns pointer to array as: ``` int (*function())[3] ``` which returns Ax3 array, ok. How is the proper way to declare a function pointer that points this kind of function?
``` f -- f *f -- is a pointer (*f)() -- to a function *(*f)() -- that returns a pointer (*(*f)())[3] -- to a 3-element array int (*(*f)())[3] -- of int ```
I have completed implementingOperationof Linear Linked List usingC, Now inorder to test my ability i need to solve some problems based on Linear Linked List, and there you people can help me by suggesting some problems/assignments ... I think there is nothing wrong in asking this type of help from my community members .
Determine whether the linked list contains cycle or not.In the circular linked list add new node at the end without traversing the list.Reverse the list.Print the nodes in the list in reverse order without reversing the list.Make a list Circular linked list.Sort the list.Merge two sorted lists.
It is usually said callbacks are implemented with function pointers. When I check PortAudio's source code, I see that callback function is declared as an ordinary function (not a f. pointer). Is it normal/legal/advisable? ``` typedef int PaStreamCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ); ```
It is fine as long as the parameter is used asPaStreamCallback*(which is apointerto afunction), like ``` PaError Pa_OpenStream ( PaStream ** stream, const PaStreamParameters * inputParameters, const PaStreamParameters * outputParameters, double sampleRate, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback * streamCallback, // <--- void * userData ) ```
I want to take a screenshot of desktop while Windows is locked (with Win+L). Standard methods make a black screen, with code of pixel: ``` COLORREF color = GetPixel(hdc, x, y); ``` equal -1. Neither a user mode program nor a service could capture a useful image. Any ideas?
GetPixelandBitBltwon't work when the desktop isn't physically displayed on the monitor. You may have some luck capturing individual windows withPrintWindow. However, not all applications respond toPrintWindowcalls the same way, so you may see glitches and/or blackness. You'll also need to capture each window individually.
I'm searching for something on the level of GNU extensions for C, but a little beyond (some basic data structure management). Best would be something BSD/MIT licensed. If there is something for just strings containing GNU extensions equivalents plus adding some more it would be great. I would prefer something that can be simply compiled into a project (no external libraries) based totally on the C standard (ANSI C89 if possible). Edit: its for an OpenSource project that has a weird license, so no GPL code can't be added and working with plain K&R/ANSI C is pure pain.
This question already seems to be addressedhere. I actually wrote a somewhat lengthy response (recommending Glib and mentioning that Lua since 5.0 is MIT, not BSD), however my machine crashed half-way through :(
include ``` static int i = 10; int main() { static int i = 20; printf ( "i = %d\n", i ); return 0; } ``` There are two static variables, one in global scope and one in function scope. The compiler is not throwing "multiple definition" error. Could you please let me know where the two static vars are stored?
The two variables are stored separately because they are distinct - it is the compiler's problem to ensure that they are separate. The variables are both initialized before the program starts - this is C, not C++, where the rules are slightly different. Insidemain()as shown, you cannot access the global variablei(again, this is C, not C++). GCC's-Wshadowcompiler flag would warn you about the localishadowing the global one.
GCC is normally instructed to output to a file via the-oswitch. If this isn't provided it seems to decide on an appropriate name and output to that. How do I make GCC write its generated output to stdout?
``` gcc -o /dev/stdout foo.c ``` Note that/dev/stdoutis defined as a symlink:/dev/stdout -> /proc/self/fd/1.
I need to set up a cron job that runs an executable compiled using gcc once every hour. I logged in as root and typedcrontab -e Then I entered the following and saved the file. ``` 0 * * * * /path_to_executable ``` However, the cron job does not work. I see that when I type/...path_to_executableI get a segmentation fault. I can only execute the executable from the folder it is located in. Is there a way I can solve this problem?
``` 0 * * * * cd folder_containing_exe && ./exe_name ``` should work unless there is something else that needs to be setup for the program to run.
The question was asked to me in an interview and my answer was "computer memory". But where exactly..? is it the Random Access Memory or the hard drive?
They were probably looking for "the heap". This is an area of memory that's separate from "the stack", which is where all your local variables, parameters, return values, etc., are stored. And yes, it's all in RAM, not on the hard drive.
I basically am looking for a cross platform way to do basic things such as accept connections and send and receive data. What library would work in Linux, Windows and Mac? Thanks
Winsock is based on the BSD sockets API, which is natively supported on both Linux and OS X (ie.socket(),connect(),accept(),send(),recv(),select()and so forth). There are some differences, but they are such that it's usually easier to port from Winsock to true BSD sockets than the reverse.
I'm using getaddrinfo to start a local server accepting connections only on the localhost: ``` struct addrinfo *res; struct addrinfo hints = {0}; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; getaddrinfo(NULL, portbuf, &hints, &res); ``` This seems to work fine, giving me the IPv6 address ::1 when IPv6 is present and IPv4 address when it is not.Except sometimes on Windows 2008 R2 (at least that's the only system where I've seen it, but I saw it twice, both times on a customer system) it gets bound to 127.0.0.1 instead of IPv6!This then messes me up because if you bind ::1 it will accept both connections to 127.1 and to ::1, but if you bind 127.1, then IPv6 connections are not accepted.
getaddrinfo()returns you alistof matching addresses, in an unspecified order. You should traverse the list (following theai_nextpointer), and create a listening socket bound to each address returned.
Is there a way to enumerate environment variables and retrieve values using C?
Take a look at theenvironglobal variable. ``` extern char **environ; ``` It might be defined inunistd.h(take a look at theenviron (5)man page above). Here's a little code demo I wrote: ``` #include <stdio.h> extern char **environ; int main() { for (char **env = environ; *env; ++env) printf("%s\n", *env); } ``` Here's how to use it: ``` matt@stanley:~/Desktop$ make enumenv CFLAGS=-std=c99 cc -std=c99 enumenv.c -o enumenv matt@stanley:~/Desktop$ ./enumenv ORBIT_SOCKETDIR=/tmp/orbit-matt SSH_AGENT_PID=1474 TERM=xterm SHELL=/bin/bash ... (so forth) ```
I was just reading some code and found that the person was usingarr[-2]to access the 2nd element before thearr, like so: ``` |a|b|c|d|e|f|g| ^------------ arr[0] ^---------- arr[1] ^---------------- arr[-2] ``` Is that allowed? I know thatarr[x]is the same as*(arr + x). Soarr[-2]is*(arr - 2), which seems OK. What do you think?
That is correct. From C99 §6.5.2.1/2: The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). There's no magic. It's a 1-1 equivalence. As always when dereferencing a pointer (*), you need to be sure it's pointing to a valid address.
It come across to me that function like printf() have not limited the number of parameters. But when debugging program on Solaris, I noticed it will push at most 5 parameters into stack, common register will be used if there are more than 5 parameters. So what will happen if even common register is not enough in function like printf ? Did compiler do something for me ?
The behaviour is controlled by the ABI for the platform. If there are more parameters than fit in the registers, then they will be handled in a different way. There isn't a simple upper limit on the number of arguments that can be passed, so the compiler and the ABI define a mechanism that works on the hardware in question. What works on SPARC does not necessarily work on, for example, Intel IA32.
I was looking at this questionHerein regards to this library. However it is still unclear to me if this library can do like glu tesselator does and return a series of triangles which I can then render with OpenGL. If it can do this, how is this done? I'm just not clear on this from reading the docs. So essentially what i'm trying to find out is, if it can in fact triangulate, once I add my contours, how do I get the triangle verticies so I can render them with opengl? Thanks
GPC will either produce contour (polygon boundary) output, or will give a result as a series of triangle strips for the solid rendering of polygon interiors. Two functions select between the two kinds of output: gpc_polygon_clip() and gpc_tristrip_clip(). Cheers, --Toby Howard, GPC Licensing Manager.
I'm trying to retrieve the entire rectangle of a scrollable window using the WIN32 API. I thought thatGetClientRectwould return what I need, but that function appears to return only the current viewport. Is there a specific function call that returns the entire scrollable region as a RECT or must I callGetScrollRangeto calculate the region myself?
It doesn't work like that. As far as Windows is concerned, a scrollable window isn't a small viewport onto a larger region whose dimensions you can set or retrieve, it's just a rectangle with a scroll bar control at the edge. It's up to you to determine the appearance of the scroll bar by calculating the portion of the notional region that is visible within the viewport provided by the window, and to paint the window contents accordingly.
I'm trying to convert this C printf to C# ``` printf("%c%c",(x>>8)&0xff,x&0xff); ``` I've tried something like this: ``` int x = 65535; char[] chars = new char[2]; chars[0] = (char)(x >> 8 & 0xFF); chars[1] = (char)(x & 0xFF); ``` But I'm getting different results. I need to write the result to a file so I'm doing this: ``` tWriter.Write(chars); ``` Maybe that is the problem. Thanks.
In .NET,charvariables are stored as unsigned 16-bit (2-byte) numbers ranging in value from 0 through 65535. So use this: ``` int x = (int)0xA0FF; // use differing high and low bytes for testing byte[] bytes = new byte[2]; bytes[0] = (byte)(x >> 8); // high byte bytes[1] = (byte)(x); // low byte ```
I've got a project that I need to get working with 3 compilers (Borland, gnu, and Microsoft). It works on 2/3 and now I just need to get it working with Microsofts. It seems to crash in places where it works fine with the other compilers, so I'm wondering if there is a way to debug with the command line, maybe to get a stack trace or get the line which caused the crash, something similar togdbwith gnu.
(Full disclosure: I work on the Visual Studio team) If you're using the Microsoft C++ compiler, do you have Visual Studio installed already? If so, you can use the built-in debugger. If not, I would recommend tryingVisual C++ 2010 Expressfor free. It has an excellent native debugger. You can break on first chance exceptions (C++, SEH, Win32 exceptions) and go right to the line where it happened along with the call stack, locals, etc.
I can't figure out the prototype for this simple function: In stack: Function call: That's what I got so far, and it causes an error. ``` //No idea void CameraDeviceCreate(int one,int two,int* three); ``` There are three registers used (R0,R1,R2) so there should be three arguments. Third one refers to a stack variable (I still don't get how that works). #0x28(var_28) is only mentioned in the ADD call, not sure what it could be.Where did I make a mistake? If I missed some info out tell me and I'll add it. This is fromCamera.frameworkby the way.
Why do you think you have it wrong? Note, there is no guarantee that the third parameter is 'int*' - you need to look at what is in R4 at that point - I would guess its actually some sort of structure being pointed at, rather than an int.
I'd like to know the maximum value of size_t on the system my program is running. My first instinct was to use negative 1, like so: ``` size_t max_size = (size_t)-1; ``` But I'm guessing there's a better way, or a constant defined somewhere.
A manifest constant (a macro) exists in C99 and it is calledSIZE_MAX. There's no such constant in C89/90 though. However, what you have in your original post is a perfectly portable method of finding the maximum value ofsize_t. It is guaranteed to work with any unsigned type.
This question already has answers here:Closed13 years ago. Possible Duplicate:What’s the “condition” in C interview question? ``` void main() { if(CONDITION) printf("Hello "); else printf("World"); } ``` Replace CONDITION with such a condition that both the printf statements get executed. You can't have a loop or other things in main() I found this code online,i am trying to think the logic behind it but i cant. Please help me out Thanks
``` if(fork() == 0) ... ```
I want to declare a bitfield with the size specified using the a colon (I can't remember what the syntax is called). I want to write this: ``` void myFunction() { unsigned int thing : 12; ... } ``` But GCC says it's a syntax error (it thinks I'm trying to write a nested function). I have no problem doing this though: ``` struct thingStruct { unsigned int thing : 4; }; ``` and then putting one such struct on the stack ``` void myFunction() { struct thingStruct thing; ... } ``` This leads me to believe that it's being prevented by syntax, not semantic issues. So why won't the first example work? What am I missing?
The first example won't work because you can only declare bitfields inside structs. This is syntax, not semantics, as you said, but there it is. If you want a bitfield, use a struct.
I have aUNICODE_STRINGthat I would like to compare to a null-terminated ANSI string to check if they are the same. I'm using C. I would like to avoid includingwinternl.hforRtlInitUnicodeString. What is the preferred method doing this? Or, alternatively, is there any problem with me usingMultiByteToWideChar()to convert the ANSI string to a wide-character representation and then comparing that to theUNICODE_STRING.buffer(with the understanding that the buffer might not be null-terminated)?
WideCharToMultiByte seems the more logical route. It can handle strings that aren't zero-terminated and produces a terminated one. And it tries to do something meaningful with codepoints that don't have a character in the system code page. Then just strcmp().
we have one of Cirque touchpads.http://www.cirque.com/downloads/docs/tsm9925.pdf now we want to read absolute position of tap from this touchpad using c\c++ application. unfortunately company developed only windows drivers but we need to read positions in the linux. we tried to use /dev/input/eventN subsystem but received only direction of finger moving and speed of finger moving. is it possible and how can we do this?
From your supplied link: ``` For custom functionality at the product design stage, we offer software that allows OEMs to enable, disable or personalize advanced settings and/or reprogram the touch sensitive area. ``` I'd suggest contacting Cirque directly
I have a number of private frameworks I want to use, however I cannot find any headers for them. Is there a de-facto way of getting arguments fromCfunction calls usingIDA Pro? (NotObjCmessages). Edit: Oops, I meantCnotC++.
Access r0-r3 and the stack pointer?
I am new to using the PARI C library. How can I perform bitwise ('and' or 'or') operations on the GEN type variables?
usinggbitandandgbitor? Declared inarith2.cseethis link(sorry for the not so direct link): ``` GEN gbitand(GEN x, GEN y) GEN gbitor(GEN x, GEN y) ```
just wanted to know how to call php script from running C code on Linux and pass a couple of parameters. Thanks
``` system("/usr/bin/php /path/to/program.php param1 param2"); ```
I want to create a header file in C and add it to a library. How do I create the header file and add/access it to/from the library.
Some header: ``` //header.h #ifndef HEADER_H #define HEADER_H int ThisReturnsOne() { return 1; } #endif //HEADER_H ``` Some c file: ``` //file.c #include "header.h" int main() { int x; x = ThisReturnsOne(); //x == 1 } ``` So the contents of "header.h" are available to "file.c". This assumes they are in the same directory. Edit: Added include guards. This prevents the header file from being included in the same translation unit twice.
I'm using one 3rd party SDK which get hwnd (window handle) and paints something on my window. And i want to specify window painting region (left, right, top, bottom) ? How it's possible to do it ? I'm found WINAPI function SetWindowRgn, but it's not good for me because this function specify whole window region. I need specify just window painting area.
SetWindowRgn() is exactly what you need. You can create your region from a rectangle using CreateRectRgn(). A good introduction to window regions can be foundhere. Alternatively you can modify the non-client area of your window, but I would not recommend that, because it has several side-effects.
I can't decide how I should loop over ranges. This way: ``` for (int i = 0; i < max_i; i++) { for (int j = 0; j < max_j; j++) { // first way - two loops } } ``` Or this way: ``` for (int k = 0; k < max_i*max_j; k++) { // second way - one loop } ``` Thanks, Boda Cydo.
It depends on what you will be doing with the indices. If you're using two values separately (for example you're iterating over all permutations of the values in the two loops) then the two loop solution is more clear. The one-loop strategy is better if you don't care about the individual values but just their product instead. Either way, choose the strategy which expresses your intent more clearly. The performance implications are trivial in comparison to the importance of the simplicity of maintaining the code.
What is the right way to typedef a type and the same type's pointer? Here is what I mean. Should I do this: ``` typedef unsigned int delay; typedef unsigned int * delayp; ``` Or should I do this: ``` typedef unsigned int delay; typedef delay * delayp; ``` Or perhaps I should not typedef pointer at all and just usedelay *instead ofdelaypeverywhere I find necessary? Thanks, Boda Cydo.
The right way is not to do it. Hiding the fact that something is a pointer is commonly seen as bad style.
I would like to know why spin locks are used instead of semaphores inside an interrupt handler.
Semaphores cause tasks to sleep on contention, which is unacceptable for interrupt handlers. Basically, for such a short and fast task (interrupt handling) the work carried out by the semaphore is overkill. Also, spinlocks can't be held by more than one task.
When you write a program in c which has a lot of printf for a lot purpose: debuggin, information, etc. I would like to do something like that in gtk, having some widget that would display all the printf messages I usually would do in a normal c program Thanks, ---UPDATE--- I'm using vte as ptomato advised. Although some problems came up. I was using glade-3 and when the file glade was open the vte widget didn't show. I notice that a lot of Warning and 2 Critical errors would display while opening. One of those critical was ``` Unable to load module 'vte' from any search paths ``` I installed libvte-dev throug apt-get and know i see as in the widget palette
You can use VTE, a terminal emulator widget. I'm not sure, but I think you can redirect your program'sstdoutto the widget usingvte_terminal_set_pty().