question
stringlengths
25
894
answer
stringlengths
4
863
I saw this example when I was trying to figure out how to pass pointers to dynamically allocated 2d arrays to functions: ``` void zeroit(int **array, int nrows, int ncolumns) { int i, j; for(i = 0; i < nrows; i++) { for(j = 0; j < ncolumns; j++) array[i][j] = 0; } } ``` I tried it and it works, but I do...
Here you are:http://www.eskimo.com/~scs/cclass/int/sx9a.htmlhttp://www.eskimo.com/~scs/cclass/int/sx9b.html
I'm using C (gcc) and ncurses, to make a program that will be monitoring data coming from the serial port. The program has a bigwhile, where it reads the data coming from the port and at the same time, it prints that info in the screen... But the problem is here: How can it read input from my keyboard, (sincegetch()...
makegetcha non-blocking call usingnodelayoption. ``` nodelay(stdscr,TRUE); ``` More info can be found athttp://www.gsp.com/cgi-bin/man.cgi?topic=nodelay
Is there a POSIX function equivalent to _malloc_r and _free_r from CYGWIN? Is there a POSIX reentrant library? Please advice. Many thanks.
No, and for good reason. Demanding reentrancy ofmalloc, even if only for special_rfunctions, would impose massive performance costs and likely precludes many high-performance implementations to begin with. Why do you need reentrancy? If you're trying to allocate memory from a signal handler, you might usemmap, but a b...
I am trying to print the value pointed to by an address but the problem is I need to dereference this pointer based on the size that is passed to me. So something of this sort: ``` void print(Address addr, Int size) { ... } ``` I am a little confused on how to achieve this. Can someone point me in the right directio...
Your question is very unclear. If you mean you want to dump arbitrary binary data from the address passed, you want something like: ``` void print(const unsigned char *addr, size_t size) { while (size--) printf("%.2x", *addr++); } ``` Or if you mean you want to print character data that's not null-terminated, tr...
I need a way to get complete hard drive info on OS X, meaning all hard drive model names, SATA/ATA controllers, volumes, disk identifiers, etc. I checked outdiskutil, but it doesn't contain SATA controller info,system_profilerhas all the information I need but its XML output is not necessarily organized as well as I'd...
Look intoIOKit. There's also this question on Stack Overflow:How to get serial number from Mac hard disks?
I have an array of double (size more than 60k entries), I have the frequency value. Now I want to create a sound from it using C/C++ which I can play on speaker. My OS is linux. Thanks. I hope I am clear enough.
http://www.linuxjournal.com/article/6735 This is a link to an article in Linux Journal about programming with the ALSA (Advance Linux Sound Architecture). It contains some example code.
I'm looking to do a custom hash table implementation in C. Is there an MD5/SHA1 hash function already in the GNU library or do I have to use an external library for this? Here's kinda what I'm looking for: ``` int hashValue; hashValue = MD5_HASH(valToHash); ```
You can take a look at Bob Jenkin's survey and analysis of many hash functions: http://www.burtleburtle.net/bob/hash/doobs.html Or just drop his lookup3 routines (which he's put into the public domain) into your project: http://www.burtleburtle.net/bob/c/lookup3.c
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I'm looking for one to build a MS-p...
OpenGL is for making 3D applications. Using it for pixel-based things like a paint program will make things very hard. The closest thing I can imagine is to paint the pixels for the ellipse to texture surface and then show it as sprite. Be sure that you always have identity transform set, otherwise the result may loo...
This question already has an answer here:Pointer to a specific fixed address(1 answer)Closed3 years ago. An interesting discussion about this startedherebut no one have been able to provide the C++ way of doing: ``` #include <stdio.h> int main(void) { int* address = (int *)0x604769; printf("Memory address is: ...
In C++, always preferreinterpret_castover a C-cast. It's so butt ugly that someone will immediately spot the danger. Example: ``` int* ptr = reinterpret_cast<int*>(0x12345678); ``` That thing hurts my eyes, and I like it.
In one side I have a Java client writing ints into its outputstream: ``` int a = 20; dataout.writeInt(a); dataout.flush(); ``` From the other side I have a C server listening the connection: ``` int client = accept(...); ``` How to read the int sent by Java? If I had a Java server, i could easily write: ``` int ...
Read it into a char buffer and useatoi()to convert the string into a int.
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed2 years ago. ``` int main (int argc, **argv) { if (argv[1] == "-hello") printf("True\n"); else printf("False\n"); } ``` ``` # ./myProg -hello False ``` Why? I realizestrcmp(argv[1], ...
Becauseargv[1](for instance) is actually a pointer to the string. So all you're doing is comparing pointers.
``` char ch = 'a'; ``` Here ch is a character variable, so it's size is one byte. 'a' is a character constant,so it's ASCII value will be stored which is 2 byte.But how could it possible to store a 2 byte value in an 1 byte variable ?
A character literal, such as'a', will be treated as an integer literal, such as97or0x61. C compilers tend to want every integer to be stored in anintunless told otherwise, sosizeof('a')will probably besizeof(int). You should notice, though, that the value of'a'is less than 127 so it can be stored in a char (which ha...
This question already has answers here:Closed12 years ago. Possible Duplicate:makefile aliases Please explain$@ $^in the makefile below ``` LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall # (This should be the actual list of C files) SRC=$(wildcard '*.c') test: $(SRC) gcc -o $@ $^ $(CFLAGS) $(LI...
These arespecial variables: $@means the target so in your case it istest. $^means the names of all the prerequisites, with spaces between them. In your case its the list of all the.cfiles. SRC=$(wildcard '*.c')makes use of thewildcard functionto get the list of all the.cfiles in the directory, which is then assigne...
I have created a C source file using the modules from other source files. Suppose the created source file is abc.c .Mine C file compiles fine using the following command. ``` gcc -c abc.c ``` I have compiled each and every source file that are linked to the abc.c .While creating the executable file using the follow...
You forgot to link against libm. ``` gcc ... -lm ... ```
Do these two structs have the same memory layout? (C++) ``` struct A { int x; char y; double z; }; struct B { A a; }; ``` Further can I access x, y, z members if I manually cast an object of this to anA? ``` struct C { A a; int b; }; ``` Thanks in advance. EDIT: What if they wereclassesinstead...
Yes and yes. The latter is commonly used for emulating OO inheritance in C.
Is it possible to get the list of #defines(both compile time and defined in the source code) used in a C program while execution. Because i am having a project having lot of C source files. Is there any compile time option to get that?
GNUcpptakes various-doptions to output macro and define data. See their man pages for more details.
Given a 64 bit integer, where the last 52 bits to be evaluated and the leading 12 bits are to be ignored, what is the fastest way to loop every single combination of 7 bits on and all other bits off? Example: First permutation: ``` 0[x57]1111111 ``` Last permutation ``` 00000000000011111110[x45] ``` Where0[xn]me...
I think you'll be interested in this article:http://realtimecollisiondetection.net/blog/?p=78 It solves your problem in very efficient way.
This question already has answers here:Closed12 years ago. Possible Duplicate:C# driver development? Why do we use C for device driver development rather than C#?
Because C# programs cannot run in kernel mode (Ring 0).
I need a way to get complete hard drive info on OS X, meaning all hard drive model names, SATA/ATA controllers, volumes, disk identifiers, etc. I checked outdiskutil, but it doesn't contain SATA controller info,system_profilerhas all the information I need but its XML output is not necessarily organized as well as I'd...
Look intoIOKit. There's also this question on Stack Overflow:How to get serial number from Mac hard disks?
I have an array of double (size more than 60k entries), I have the frequency value. Now I want to create a sound from it using C/C++ which I can play on speaker. My OS is linux. Thanks. I hope I am clear enough.
http://www.linuxjournal.com/article/6735 This is a link to an article in Linux Journal about programming with the ALSA (Advance Linux Sound Architecture). It contains some example code.
I'm looking to do a custom hash table implementation in C. Is there an MD5/SHA1 hash function already in the GNU library or do I have to use an external library for this? Here's kinda what I'm looking for: ``` int hashValue; hashValue = MD5_HASH(valToHash); ```
You can take a look at Bob Jenkin's survey and analysis of many hash functions: http://www.burtleburtle.net/bob/hash/doobs.html Or just drop his lookup3 routines (which he's put into the public domain) into your project: http://www.burtleburtle.net/bob/c/lookup3.c
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I'm looking for one to build a MS-p...
OpenGL is for making 3D applications. Using it for pixel-based things like a paint program will make things very hard. The closest thing I can imagine is to paint the pixels for the ellipse to texture surface and then show it as sprite. Be sure that you always have identity transform set, otherwise the result may loo...
This question already has an answer here:Pointer to a specific fixed address(1 answer)Closed3 years ago. An interesting discussion about this startedherebut no one have been able to provide the C++ way of doing: ``` #include <stdio.h> int main(void) { int* address = (int *)0x604769; printf("Memory address is: ...
In C++, always preferreinterpret_castover a C-cast. It's so butt ugly that someone will immediately spot the danger. Example: ``` int* ptr = reinterpret_cast<int*>(0x12345678); ``` That thing hurts my eyes, and I like it.
In one side I have a Java client writing ints into its outputstream: ``` int a = 20; dataout.writeInt(a); dataout.flush(); ``` From the other side I have a C server listening the connection: ``` int client = accept(...); ``` How to read the int sent by Java? If I had a Java server, i could easily write: ``` int ...
Read it into a char buffer and useatoi()to convert the string into a int.
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed2 years ago. ``` int main (int argc, **argv) { if (argv[1] == "-hello") printf("True\n"); else printf("False\n"); } ``` ``` # ./myProg -hello False ``` Why? I realizestrcmp(argv[1], ...
Becauseargv[1](for instance) is actually a pointer to the string. So all you're doing is comparing pointers.
``` char ch = 'a'; ``` Here ch is a character variable, so it's size is one byte. 'a' is a character constant,so it's ASCII value will be stored which is 2 byte.But how could it possible to store a 2 byte value in an 1 byte variable ?
A character literal, such as'a', will be treated as an integer literal, such as97or0x61. C compilers tend to want every integer to be stored in anintunless told otherwise, sosizeof('a')will probably besizeof(int). You should notice, though, that the value of'a'is less than 127 so it can be stored in a char (which ha...
This question already has answers here:Closed12 years ago. Possible Duplicate:makefile aliases Please explain$@ $^in the makefile below ``` LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall # (This should be the actual list of C files) SRC=$(wildcard '*.c') test: $(SRC) gcc -o $@ $^ $(CFLAGS) $(LI...
These arespecial variables: $@means the target so in your case it istest. $^means the names of all the prerequisites, with spaces between them. In your case its the list of all the.cfiles. SRC=$(wildcard '*.c')makes use of thewildcard functionto get the list of all the.cfiles in the directory, which is then assigne...
I have created a C source file using the modules from other source files. Suppose the created source file is abc.c .Mine C file compiles fine using the following command. ``` gcc -c abc.c ``` I have compiled each and every source file that are linked to the abc.c .While creating the executable file using the follow...
You forgot to link against libm. ``` gcc ... -lm ... ```
Do these two structs have the same memory layout? (C++) ``` struct A { int x; char y; double z; }; struct B { A a; }; ``` Further can I access x, y, z members if I manually cast an object of this to anA? ``` struct C { A a; int b; }; ``` Thanks in advance. EDIT: What if they wereclassesinstead...
Yes and yes. The latter is commonly used for emulating OO inheritance in C.
Is it possible to get the list of #defines(both compile time and defined in the source code) used in a C program while execution. Because i am having a project having lot of C source files. Is there any compile time option to get that?
GNUcpptakes various-doptions to output macro and define data. See their man pages for more details.
Given a 64 bit integer, where the last 52 bits to be evaluated and the leading 12 bits are to be ignored, what is the fastest way to loop every single combination of 7 bits on and all other bits off? Example: First permutation: ``` 0[x57]1111111 ``` Last permutation ``` 00000000000011111110[x45] ``` Where0[xn]me...
I think you'll be interested in this article:http://realtimecollisiondetection.net/blog/?p=78 It solves your problem in very efficient way.
This question already has answers here:Closed12 years ago. Possible Duplicate:C# driver development? Why do we use C for device driver development rather than C#?
Because C# programs cannot run in kernel mode (Ring 0).
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question in how many languages/* ........... */work as a comment? other than CSS
Taking the list on Wikipedia as a starting point: ActionScriptAutoHotkeyCCHILLC++C#CSSDGoJavaJavaScriptJ++J#Objective CObjective C++PHPPL/IPL/SQLREXXSASScalaSQLTSQLVisual Prolog and probably others too...
I am attempting to create a const structure in C but can't seem to figure it out. ``` typedef struct sA{ char* fname; char* lname; } A; ``` To use as an Array: ``` A list[] = {{"david","smith"},{"john","smith"}}; ``` However, if I have use a second struct: ``` typedef struct sB{ A inList[]; } B; ``` I want t...
All the objects of a struct will always have same size. What you are trying do will result in different object of a struct having different sizes, which is not possible. So what you are trying to do is not correct
Dear fellow go enthusiasts, I would need xslt support in a go program. As far as I know there will be no xslt library in the the near future and currently there is no binding to a xslt library in go. What is the FASTEST library on linux or cross platform to do 1) xslt 1.0 transformation 2) xslt 2.0 transformation
I hope the following could be used in a GO program: XSLT 1.0 on Linux: Saxon 6.5.5(Java based and should work on Linux)LibXSLT(C-based) I don't know which one is faster -- one shouldn't make a bold conclusion based just on the fact that one is Java based and the other is C-based. XSLT 2.0 on Linux: Saxon 9.2(agai...
I am surprised to see this code segment print the same address for all the three pointers. ``` int main(int argc,char *argv[]) { int arr[3][3]; printf("%p\n%p\n%p\n",arr,*arr,arr[0]); return 0; } ``` Why this is so ?
SeeSo what is meant by the ``equivalence of pointers and arrays'' in C? The address of an array is the address of its first element. And,arr[i]is equivalent to*(arr + i)for any arrayarr. Therefore,arr[0]is the same as*(a + 0).
How many different ways are there to define constants in C or C++? I am already aware of using theconstkeyword and the#definedirective. I heard somewhere that there are two more ways to define constants, but I've never seen any others. Are there any others?
enum, as inenum { some_constant= 2 }; EDIT: I also forgot the additions ofconstexprand user defined literals in the C++0x standard. So there are actually three additional ways.
Let's say I have this line of code in a program: ``` int * number=0; int mystery=&6[number]; ``` Mistery is a number and I can use &5 or &4 obtaining other numbers. But what does the "&6[]" mean? Thanks!
6[number]is exactly equivalent tonumber[6], so you're getting the address that's six integers away fromnumber. Since number is0and anintis 4 bytes long, the result is24.
I created a program in C that uses OpenCV. In addition to distributing the source and make files, I would like to distribute a Win32 binary that will run when an end-user clicks on it. Presumably I would need an easy way for the user to install the OpenCV libraries. What is the best way to do this? Should I be looki...
Just include the dll files of OpenCV along with your program. Put those files where your main .exe file is and it will run whether you have OpenCV installed or not.
Assuming the FILE* is valid, consider: ``` char buf[128]; if(fgets(buf,sizeof buf,myFile) != NULL) { strlen(buf) == 0; //can this ever be true ? In what cases ? } ```
Yes. Besides passing 1 (as noted by Ignacio),fgetsdoesn't do any special handling for embedded nulls. So if the next character in theFILE *is NUL,strlenwill be 0. This is one of the reasons why I prefer the POSIXgetlinefunction. It returns the number of characters read so embedded nulls are not a problem.
Can someone point me to a few open source heap implementations which are not part of a huge library like GLIB. I need one with the following features: Single ThreadedThe whole heap can be freed with a single call.Small footprint because i need to use one heap for each list/tree widget in my GUI. I think there shoul...
Have a look at:http://www.25thandclement.com/~william/projects/libarena.html You might also want to watch this presentation:http://www.slideshare.net/emery/composing-highperformance-memory-allocators-with-heap-layers
I have a dll written in C. I would like to send data to a socket and receive the answer in the same function.e.g.: ``` BOOL SendToSocketAndRecv(...) { // ... send(...); retval = recv(...); // ... } ``` In another word, my dll should not follow Client Server pattren. Is this possible ?any help ?T...
YesYou may work in either blocking (synchronous) or non-blocking (asynchronous) mode. Depending on this you may or may not send more data before you receive something from the peer."Stream" sockets (like TCP) are "tunnels". If the peer sends several packets you may receive them in a single call torecv, and vice-versa ...
What must this code segment return ? 16 16 16 right ? ``` int main(int argc,char *argv[]) { int a=2,*f1,*f2; f1=f2=&a; *f2+=*f1+=a+=2.5; printf("%d %d %d\n",a,*f1,*f2); return 0; } ``` strangely, it returns 8 8 8 to me ???? :-(
For an actual understanding of the issue here trycomp.lang.c FAQarticle onsequence points.
``` #include<stdio.h> #include<stdlib.h> #define MAX 1000 struct island{ double left; //gobal double right; } island[MAX]; ... int cmp(const void *ptr1,const void *ptr2 ) { return (*(struct island*)ptr1).right > (*(struct island*)ptr2).right; } qsort(island,...
Yourcmpfunction is supposed to return 1or greater if the left value is>the right value0if the values are equal-1or less if the left value is<the right value Your comparison only returns1(for the>case) or0(all other cases).
``` void move_paddle(PADDLE pad, bool alongX) { if(alongX!=TRUE) { if((pad.py+pad.length/2)>=B || (pad.py-pad.length/2)<=BB) pad.pvx*= -1; } else if((pad.px+pad.length/2)>=A || (pad.py-pad.length/2)<=AA) pad.pvx*= -1; } ``` What is the actual error ? M unable to get thr...
There is noTRUEkeyword in standard C language. Most probably, this is a macro declaration that you are missing. Where to get it depends on what compiler and libraries you are using. If you cannot find its definition, putting this code before the usage of TRUE (in the beginning of the file, but after all includes) will...
I have the following problem - I want to set my C++ application'sBase priorityto 31 if that is possible or at least set its current priority to 31. So I need a simple example like set priority to 31;for (i=0;i<100000;++i) { printf("hello world"); }set priority to 8 or keep 31 if possible
In order to set your priority class to the realtime priority class, you need to be running with elevated privileges (as an admin). As others have asked, are you SURE you want to do this? If you set your priority that high, it will lock out all other processing on the system (even the mouse will stop working). One o...
I have a ``` char** color; ``` I need to make a copy of the value of ``` *color; ``` Because I need to pass *color to a function but the value will be modified and I cannot have the original value to be modified. How would you do that? The whole code would look like this ``` Function1(char** color) { Function...
Version 1 ``` functionTwo( const char* color ) { //do what u want } functionOne( char** color ) { functionTwo( *color ); } ``` or version two ``` functionTwo( const char* color ) { //do what u want } functionOne( char** color ) { char* cpMyPrecious = strdup( *color ); functionTwo( cpMyPrecious ...
Question: How to (where to find additional information i.e., examples) programatically create apseudo device-nodeunder/devfrom akernel module?
From your question I'm guessing your talking about Linux (since you are talking about kernel modules). In that case I'd strongly recommend readingLinux Device Driver. I'd recommend looking atchapter 14to understand better how device work. It should also be noted that in most current desktop and server distribution of...
This scanf should always return true until I input none numeric input, but this scanf never executes while loop. Why? Sample input: ``` 10.0 5.0 Press [Enter] to close the terminal ... ``` Code: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { float a, b; while ( scanf("%f %f",...
scanfreturns the number of items read, which in this case is 2.
``` int main () { int * b; b = (int*) malloc (1); *b=110000; free (b); return 0; } ``` Why does heap corruption happen atfree (b);? IMO, heap corruption already happens at*b=110000;.
malloc()'s argument is the number of bytes to allocate. You need to use: ``` b = (int*) malloc(sizeof(int)); ``` You've allocated too small a block, and then written more bytes to it than you've allocated, which overwrites bookkeeping information next to the block, corrupting the heap.
I always find that some people (a majority from India) are using turbo C. I cannot find any reason to use such outdated compiler... But I don't know what reasons to give when trying to tell them to use modern compiler(gcc,msvc,...).
Turbo C is a DOS only product. This means that it no longer runs "natively" on 64-bit versions of Windows, and must be run inside the XP compatibility penalty box.
UPDATE:Question still unanswered.@Alastair_Pitts:Unless I'm missing something, it's a two part question. The second part, "If so, why is this done?" and not been answered. Believe the question is clear, but if you have any questions -- just let me know. Thanks! undefined = unknownand is a reference to system based...
In many, if not most, languages values are either falsy, meaning that something doesn't exist or lacks value, or truthy, meaning that something exists or has value. The list of falsy values is usually: (these evaluate to false) 0 (zero, the number)'' (an empty string)null (if this value exists)undefined (if this valu...
I have a string in the following format: "R: 625.5m E:-32768m" What's the most efficient way to pull out the 625.5?
Your best bet is to usesscanfto read formatted information from the string. ``` sscanf(mystr, "R: %f", &myFloat); ```
I have a question regardingdup2(). What does it exactly do? Copies the File Descriptor? I don't quite understand the use ofdup2(). I tried Google, and still don't quite understand what it means.
It takes two parameters that are descriptors. It makes the second one equivalent to the first one. You can use them interchangeably with a few minor exceptions... see the man page for more details on the use cases. You would do this, for example, to redirect the console descriptors 1, 2, or 3, to some other device ...
This question already has answers here:Closed12 years ago. Possible Duplicate:What should we do to prepare for 2038? I don't mean 'people' in the abstract. I mean areyoudoing anything and if so what? I am an ancient programmer and recall when I wrote COBOL in the late 70's saying to others in my team "you know - th...
I add a disclaimer to the release notes of my software that says:Best before 2038.
I always find that some people (a majority from India) are using turbo C. I cannot find any reason to use such outdated compiler... But I don't know what reasons to give when trying to tell them to use modern compiler(gcc,msvc,...).
Turbo C is a DOS only product. This means that it no longer runs "natively" on 64-bit versions of Windows, and must be run inside the XP compatibility penalty box.
UPDATE:Question still unanswered.@Alastair_Pitts:Unless I'm missing something, it's a two part question. The second part, "If so, why is this done?" and not been answered. Believe the question is clear, but if you have any questions -- just let me know. Thanks! undefined = unknownand is a reference to system based...
In many, if not most, languages values are either falsy, meaning that something doesn't exist or lacks value, or truthy, meaning that something exists or has value. The list of falsy values is usually: (these evaluate to false) 0 (zero, the number)'' (an empty string)null (if this value exists)undefined (if this valu...
I have a string in the following format: "R: 625.5m E:-32768m" What's the most efficient way to pull out the 625.5?
Your best bet is to usesscanfto read formatted information from the string. ``` sscanf(mystr, "R: %f", &myFloat); ```
I have a question regardingdup2(). What does it exactly do? Copies the File Descriptor? I don't quite understand the use ofdup2(). I tried Google, and still don't quite understand what it means.
It takes two parameters that are descriptors. It makes the second one equivalent to the first one. You can use them interchangeably with a few minor exceptions... see the man page for more details on the use cases. You would do this, for example, to redirect the console descriptors 1, 2, or 3, to some other device ...
This question already has answers here:Closed12 years ago. Possible Duplicate:What should we do to prepare for 2038? I don't mean 'people' in the abstract. I mean areyoudoing anything and if so what? I am an ancient programmer and recall when I wrote COBOL in the late 70's saying to others in my team "you know - th...
I add a disclaimer to the release notes of my software that says:Best before 2038.
Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of aTreeView, but is it available for general widgets?
For C/C++:gtk_widget_set_size_request() Sets the minimum size of a widget; that is, the widget's size request will be width by height. PyGTK:def set_size_request(width, height)
This question already has answers here:Closed12 years ago. Possible Duplicate:strange output in comparision of float with float literal ``` float a = 0.7; if (a < 0.7) ; ``` Why does the expression here evaluate to true?
Floating point numbers have limited precision. 0.7 most likely can't be exactly represented, so the value in a might be 0.6999999999982 or so in a float. This compared to a double 0.7 (which is more precise: 0.6999999999999999999999999384) will show that it is less. Check this out:http://docs.sun.com/source/806-3568/...
``` int main() { int i = -3, j = 2, k = 0, m; m = ++i || ++j && ++k; printf("%d %d %d %d\n", i, j, k, m); return 0; } ``` i thought that && has more precedence that || as per this logic++jshould execute, but it never does and the program outputs-2 2 0 1. What is going on here? What are the intermediate steps...
&&does have higher precedence than||, which means that++i || ++j && ++kparses as++i || (++j && ++k). However this does not change the fact that the RHS of||only executes if the LHS returns0. Precedence does not affect order of evaluation.
After performing a rotation to balance an AVL tree, immediately after an insertion, how can I change the balance factor of all the parent nodes (appropriately, by -1 or 1)? Each node of the AVL tree has the following structure: ``` typedef struct _avlTree { nutbolt part; int balanceFactor; struct _avlTree *left,*...
You either need a parent pointer for each node, which will need modification too whenever you change the tree structure. Or you need to keep track of all visited nodes beginning from the root, either automatically by the recursion or manually in an array if you have an iterative approach. You shouldn't miss this for ...
I want to make a program that reads a serial port (V.24). with the info from the serial port I need to split a string up, and add it to a MySQL database. I don't know C very well, so I need some help with what functions I should use The program has to run under windows XP, and I have to make it an service. thanks, ...
Services are a pain to debug. I suggest writing your code as a normal application first - command line will do - and then, once it works, converting it to a service (which is a mechanical process). In general, Windows GUI based apps in C are a PITA to write for the first time. Very finicky, very sensitive. A comma...
lets make the simpliest application: result: ok. it works. lets add some SDL with default dynamic linking here! result: works great. at stdout.txt we can see "puchuu" lets change our makefile a little. just group 2 object files to the static lib: result: Who is to blame? Me or mingw develope...
mingw is not to blame. With the (GNU) linker, static libraries have to be listed in the reverse dependency order. g++ -o program.exe libpuchuu.a -lSDLwill not work if something in libpuchuu.a depends on something in libSDL. It should beg++ -o program.exe -lSDL libpuchuu.a If you have a cyclic dependency, you even ...
I'm not even sure what sliding average is, but someone told me it would help with something I'm working on. I have a table of random values --table[n] = random(100) / 100 I need to populatetable2with their sliding averages. I think this is the terminology. Let me know if it doesn't make sense.
TheMoving averageentry on Wikipedia might be a good start.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. Can I work with Begali charachters(...
Absolutely. Look into libiconv or ICU.
How to read command line inputs using a C program.by command line inputs, I don't mean command line arguments!! example: * I have a text file 'inputfile.txt' with few lines of names.* Assume my program name is names.exe.* I have to run the program using windows command line using following command:c:>names.exe < inp...
Read from thestdinFILE*.
I have a number crunching application written in C. It is kind of a main loop that for each value calls, for increasing values of "i", a function that performs some calculations. I read about multithreading, and I am considering learning a bit about it, in C. I wonder if somehow general code like mine could be automat...
If the task is highly parallelizable and your compiler is modern, you could try OpenMP.http://en.wikipedia.org/wiki/OpenMP
I've come across some code that surrounds the return value from a method/function in parentheses. What does that do? The code I saw took an image, resized it and then returned it. ``` - (UIImage *)resizeImage:(UIImage *)image { // // some fascinating, but irrelevant, resizing code here // return (i...
At least as far as C is concerned, it makes no difference. The parens aren't necessary, but they don't change the meaning of the return statement. The grammar of the return statement is ``` return-statement:returnexpressionopt; ``` and one of the productions of theexpressionnon-terminal is aparenthesized-expressio...
Where would be the best place to put the edge length in an adjacency list implementation?I using this site as reference. What I am thinking is to put it in the edge node so to find the length from one vertex to another, you go to one of the vertex nodes and find its connecting edges and access the relevant member. (se...
TheedgeTagis the perfect place for the edge length. And about the graph representation, it depends on your needs - adjacency matrix is ineffective for sparse graphs(to find the adjacent nodes you must check them all), although it is a little bit easier to work with it.
I need a library with simple API. Defining simple: perfect solution for me would be something like describedherebut addopted for crossplatform use in Java (crossplatform for me is stand alone desctop app for Win, Mac, Lin)... So how API I would like to see looks like? Like oneI have in C#: ``` using TCMPortMapper; p...
I recommend you have a look at"Punching Holes with Java RMI, it might be helpful.
``` #include<stdio.h> int main(void) { static int i=i++, j=j++, k=k++; printf("i = %d j = %d k = %d", i, j, k); return 0; } ``` Output in Turbo C 4.5 : i = 0 j = 0 k = 0 In gcc I'm getting the error: Initializer element is not constant Which one is logically correct ? I'm in bit confusion..
Standard says about initialization (6.7.8): 4   All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals. (That's from C99, but C89 says almost exactly the same thing.) So it looks as though GCC is more correct than 15-year old abandonware...
Is it possible to generate an embedded Unix timestamp via a preprocessor macro? For instance:#define VERSION_EXPIRE __TIMESTAMP__ The reason for this is, that i have beta versions and i want to generate an expire timestamp on compile time (in a special build configuration).
I've solved it as follows: ``` #define VERSION_TIMESTAMP __DATE__" "__TIME__"\x0" ``` In some other class ``` + (NSDate *)versionExpiresInDays:(NSUInteger)days { NSString *dateString = [NSString stringWithUTF8String:VERSION_TIMESTAMP]; NSLocale *enLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en...
i am new to open mp and i tried an sample program from the official site ``` #include <omp.h> #include <stdio.h> int main() { #pragma omp parallel printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads()); } ``` and i have set the library in the eclipse as libgomp in project Properti...
Try linking withgompinstead oflibgomp: library names must be passed to the linker without thelibprefix, which it adds automatically. Hence the error, it is trying to findliblibgomp. Don't forget the compiler flag-fopenmp, otherwise the OpenMP pragmas will simply be ignored.
This function definition is found here.: ``` static void (*resolve_memcpy (void)) (void) { return my_memcpy; // we'll just always select this routine } ``` I don't understand what it means.
resolve_memcpy is a function taking no arguments and returning a pointer to a function taking no arguments and returning void. EDIT: Here's a link where you can read more about this kind of syntax:http://unixwiz.net/techtips/reading-cdecl.html
I am writing a C program. What I have seen from my earlier experiences is that I make some changes on a correct version of my program, and after that change, the program is computing incorrectly. Now, for one occasion it may be easy to detect where I made that change and undo it or do it in some other way, and for ot...
Use a version control system. I recommend Subversion. This will allow you to compare your newer version with the older one to see exactly what changed and you can revert to the older working version if you break your code.
When browsing the source of a project on web I've found somereturnstatement in main that looks weird to me: ``` int main() { /* ... */ return 0x1; } ``` So main is returning0x1 radix 16, but that's1 radix 10! Shouldn't main return0? That is incorrect, right? By the way is it Okay toreturn 0x0?
It returns 1.0x1Is just a hex value of 1. You are free to return 0x0, too. It's just a different representation of 0. You could use octal, too, if you like :)
In my source code, if I write 1.23 as a literal, e.g. doThis(1.23), gcc assumes it's a double. Rather than type doThis((float) 1.23), is there a way to use floats for decimal literals/constants unless otherwise specified in an individual source file? Mega-bonus points, is there a way that works across (nearly) every...
Yes, the standard way is to write1.23f. It works with every C compiler, since it is defined in ISO C99 section6.4.4.2 Floating constants. ISO C90 and K&R have similar definitions.
PHP's C source can be found athttp://svn.php.net/viewvc/php/php-src/trunk/. If I want to find the implementation of a specific PHP function, how to quick locate it in that SVN source?
Checking out the repository (or extracting the tarball), and greppign forPHP_FUNCTION(functionname)should do it. For example: ``` $ grep -Rn "PHP_FUNCTION(implode)" * ext/standard/php_string.h:40:PHP_FUNCTION(implode); ext/standard/string.c:1131:PHP_FUNCTION(implode) ``` Line1131ofext/standard/string.cis whereimplo...
This question already has answers here:Closed12 years ago. Possible Duplicate:What is the difference between char s[] and char *s in C? I was wondering what is the difference between ``` char *p1 = "some string"; ``` and ``` char p2[] = "some string"; ``` in terms of memory, can these not be treated in the same ...
All is explained here:http://c-faq.com/aryptr/aryptr2.html
My rectangle structure has these members: x, y, width, height. Given a point x, y what would be the fastest way of knowing if x, y is inside of the rectangle? I will be doing lots of these so speed is important.
This is how I usually do it. Given a point that is outside of the rectangle, this will do fewer tests in 3 out of 4 cases. And sometimes only one test is done. ``` if(point.x < rect.x) return false; if(point.y < rect.y) return false; if(point.x >= rect.x + rect.width) return false; if(point.y >= rect.y + rect.heigh...
I'm compiling some C code, and I get the error ``` typedef 'A' is initialized (use decltype instead) ``` On one of my struct declarations. What could be causing this?
I am able to reproduce that with the simple program ``` typedef int A = 3; ``` typedefdeclares an alias to a type; it does not declare a variable. So if you want an instance ofstruct my_structnamedA, you cannot also havetypedef struct my_struct { ... } my_structin the same declaration.
As the title says, I always wonder whyscanfmust take theaddress ofoperator (&).
Because C only has "pass-by-value" parameters, so to pass a 'variable' to put a value into, you have to pass its address (or a pointer to the variable).
By huge numbers, I mean if you took a gigabyte (instead of 4/8 bytes etc.) and tried to add/subtract/multiply/divide it by some other arbitrarily large (or small) number. Adding and subtracting are rather easy (one k/m/byte at a time): ``` out_byteN = a_byteN + b_byteN + overflowBit ``` For every byte, thus I can a...
Are you asking for something like "The GNU Multiple Precision Arithmetic Library" (athttp://gmplib.org/)?
This would be easy with fork(), but I've got no MMU. I've heard that vfork() blocks the parent process until the child exits or executes exec(). How would I accomplish something like this?: ``` pid_t pid = vfork(); if (pid == -1) { // fail exit(-1); } if (pid == 0) { // child while(1) { // D...
It seems there is no way to do this exactly as you have it here.execor_exithave to get called for the parent to continue execution. Either put the daemon code into another executable andexecit, or use the child to spawn the original task. The second approach is the sneaky way, and is described here.
Learning C at University. This is not a homework, but I was trying to do something (some "creative" part of the assignment) and got stuck. I understand that this is possible ``` printf("%d\n", printf("23.4")); // -> 23.44 (i.e. 23.4 + 4 bytes written) ``` but how can I usesprintf()as first argument ofprintf()? som...
Usingsprintffor this purpose is perverse. Instead try: ``` printf("Value with %d decimals is %.*f", decimals, decimals, pi); ```
``` #include <stdio.h> int main() { int x = 4, y, z; y = --x; z = x--; printf("%d %d %d", x, y, z); } ``` Output:2 3 3 Can anyone explain this?And what doesi =+ jmean (supposei = 1andj = 2)?
y = --xmeans "decrease x by one, then store the result in y" z = x--means "save a temp of x. Decrease x by one. Store the temp value in z" Hence: x starts at 4.It gets decreased by 1 (to 3). 3 is stored in y.x is saved to a temp. x is decreased again (to 2). then the temp (3) is stored in z.y and z are printed as 3...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Then what are the advantages ... You get all the .NET classes.
If my process is trying to read from a file, then how do I ensure from my code (C Language) that no other process either writes to it or deletes it (include system commands for deleting the file)? Also, can this be achieved on all OS (Windows, Linux, Solaris, HP-UX, VxWorks etc)?
Edit: I'll answer for Unix/Linux As gspr and others said, take a look at file locking usingfcntl,flock, etc. However, be warned that those areADVISORY LOCKINGmethods. What does this mean? It means you can warn other processes that you are currently accesing a file, or a portion of it, butyou can't forcibly keep them...
There are 2 servers, they need to know the status(live oe dead) each other. my method is a long tcp connecting, Is there any better method? thanks.
I`m no sysadmin, but why not simply use nmap or the likes to check if the ports your servers are listening on are still open? I mean, you simply want to know if they are alive or dead, right? When one of your server crashes, the port shouldn´t be open anymore.
Can you please point me to library(ies) for face detection (NO RECOGNITION NEEDED!)? Any good-working libraries except OpenCV(!!!). Preferably free of charge - open source is not required.
What bothers you about OpenCV? Their API or something else? There islibfacewhich is an opencv wrapper for face detection and recognition.
How do I mark the end of a char* vector with '\0' to null-terminate it? If i have char* vector: ``` char* param[5]; ``` I thought of either ``` param[4] = '\0'; ``` or ``` char c = '\0'; param[4] = &c; ``` but none of them seem to work? param is a char-pointer vector, supposed to point to 5 strings(char-vectors...
Ok you are trying to end a vector of strings, something similar to what is passed tomainasargv. In that case you just need to assign a null pointer: ``` param[4] = 0; ```
I have this struct type definition: ``` typedef struct { char *key; long canTag; long canSet; long allowMultiple; confType *next; } confType; ``` When compiling, gcc throws this error: ``` conf.c:6: error: expected specifier-qualifier-list before ‘confType’ ``` What does this mean? It doesn't s...
You used confType before you declared it. (for next). Instead, try this: ``` typedef struct confType { char *key; long canTag; long canSet; long allowMultiple; struct confType *next; } confType; ```
" Double pointers are also sometimes employed to pass pointers to functions by reference " can somebody can explain me the above statement, what exactly does point to function by reference means ?
I believe this example makes it clearer : ``` //Double pointer is taken as argument void allocate(int** p, int n) { //Change the value of *p, this modification is available outside the function *p = (int*)malloc(sizeof(int) * n); } int main() { int* p = NULL; //Pass the address of the pointer ...
I have a GtkButton inside a GtkHButtonBox that doesn't show the image I'm adding to it. It just shows the text. Here's the code: ``` GtkImage *image = (GtkImage *) gtk_image_new_from_file("Gateway-LT21-netbook-2-540x359"); GtkButton *button = (GtkButton *) gtk_button_new_with_label("test"); gtk_button_set_image(butto...
Make sure that the "gtk-button-images" setting is set to true. ``` GtkSettings *default_settings = gtk_settings_get_default(); g_object_set(default_settings, "gtk-button-images", TRUE, NULL); ``` Note: This should follow the construction of the first window (and of course precede the main loop). If I'm not mistaken...
I have to interface with some C code from C++ class constructor (Intel library) ``` class A{ A{ x = ippiMalloc(); if(x==NULL) ... } } ``` In the constructor malloc function (intel version) is used. If ippiMalloc function do not succeed what is the correct way to handle it. Throw exception?
Yes, an exception would likely be the most appropriate way to handle the error here -- at least it would be the cleanest way. This is also what the "new" operator would do on failure. If your app isn't exception aware than you have a problem. In which case a factory method on the class might make sense. ``` static A...
I developed a command-line (non GUI) C program on Linux using QT Creator, which internally uses gdb as its debugger. When I debugged the program on Windows using Visual Studio, it reported that it was writing outside the bounds of allocated memory (although it did not report the violation at the exact time it occurre...
There are many in-code memory validators that work both for Windows and Linux. CheckWikipediafor their list. However, most Linux users useValgrindas the ultimate tool for memory debugging.
Why the range of signed character is-128to127but not-127to128?
That is because of the waytwo's complementencoding works: 0 is treated as a "positive" number (signed bit off), so, therefore, the number of available positive values is reduced by one. Inones' complementencoding (which is not very common nowadays, but in the olden days, it was), there were separate values for +0 and...