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 don't understand how. How does the function "zeroit" calculates the correct address?
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()freezes the program until it gets an input) and at the same time read info coming from the port? Maybe I have to use another way (not the bigwhile), so ideas are welcome!
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 better approach would be moving as much code as possible out of the signal handler and using the signal handler itself only to set a flag that will get picked up by another part of your program after the signal handler returns.
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 direction? EDIT: Ok so I'm thinking: ``` char p[80]; memset(p, '\0', 80); memcpy(p, addr, size); ``` And then dereference as *p. If there is a better way or a correct way, please let me know
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, try: ``` void print(const char *addr, int size) { printf("%.*s", size, addr); } ```
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 like. Is there any low level Carbon/C API that would let me do this?
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-paint like app.
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 look blurry. A good alternative for OpenGl in your case would be SDL. It is simpler and pixel based.
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: 0x%p\n", address); *address = 0xdead; printf("Content of the address is: 0x%p\n", *address); return 0; } ``` What is the most appropriate way of doing such a thing in C++?
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 a = dataIn.readInt(); ``` How to do this in C? thanks
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], "-hello") == 0returns true... but why can't I use the equality operator to compare two C strings?
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 has a maximum value of either 127 or 255 depending on if it is signed or unsigned on your compiler). This is the same as being able to: ``` unsigned long long x = 0; unsigned int y = x; ``` yis assigned from axwhose type is bigger thany's type, butx's value is well within those whichycan represent, so no data is lost when the top bits (all 0s) are chopped off.
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) $(LIBS) ```
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 assigned to the variableSRC. Lets say there are two C source filefoo.candbar.c. Your makefile effectively gets expanded to: ``` test: foo.c bar.c gcc -o test foo.c bar.c -Wall -lkernel32 -luser32 -lgdi32 -lopengl32 ```
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 following command: ``` gcc abc.o b.o c.o ....strings.o -o abc ``` It shows the following error, although i have used strings.o for creating executable file: ``` strings.o: In function `string_IntToString': strings.c:(.text+0x5d3): undefined reference to `log10' strings.c:(.text+0x606): undefined reference to `log10' collect2: ld returned 1 exit status ``` Could you suggest me what can be the wrong here?
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 ofstructs?
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]meansnoff (zero) bits. Speed is absolutely crucial, we are looking to save every clock cycle we can as it is part of a greater solution that needs to evaluate billions of states in a reasonable amount of time. A working solution is not required, but some pseudo code would do just fine :)
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 like. Is there any low level Carbon/C API that would let me do this?
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-paint like app.
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 look blurry. A good alternative for OpenGl in your case would be SDL. It is simpler and pixel based.
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: 0x%p\n", address); *address = 0xdead; printf("Content of the address is: 0x%p\n", *address); return 0; } ``` What is the most appropriate way of doing such a thing in C++?
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 a = dataIn.readInt(); ``` How to do this in C? thanks
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], "-hello") == 0returns true... but why can't I use the equality operator to compare two C strings?
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 has a maximum value of either 127 or 255 depending on if it is signed or unsigned on your compiler). This is the same as being able to: ``` unsigned long long x = 0; unsigned int y = x; ``` yis assigned from axwhose type is bigger thany's type, butx's value is well within those whichycan represent, so no data is lost when the top bits (all 0s) are chopped off.
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) $(LIBS) ```
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 assigned to the variableSRC. Lets say there are two C source filefoo.candbar.c. Your makefile effectively gets expanded to: ``` test: foo.c bar.c gcc -o test foo.c bar.c -Wall -lkernel32 -luser32 -lgdi32 -lopengl32 ```
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 following command: ``` gcc abc.o b.o c.o ....strings.o -o abc ``` It shows the following error, although i have used strings.o for creating executable file: ``` strings.o: In function `string_IntToString': strings.c:(.text+0x5d3): undefined reference to `log10' strings.c:(.text+0x606): undefined reference to `log10' collect2: ld returned 1 exit status ``` Could you suggest me what can be the wrong here?
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 ofstructs?
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]meansnoff (zero) bits. Speed is absolutely crucial, we are looking to save every clock cycle we can as it is part of a greater solution that needs to evaluate billions of states in a reasonable amount of time. A working solution is not required, but some pseudo code would do just fine :)
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 to define a const structure as: ``` B newList[] = { { {"david","smith"} }, { {"john","doe"} {"joe","doe"} } }; ``` len(newList[0].inList)is different fromlen(newList[1].inList). This can be built dynamically, but how would you build this into a const variable in C?
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(again, Java based must work on Linux).???? Even if there is another XSLT processor working on Linux, in my experience Saxon 9.x is factors of magnitude faster than any other existing XSLT 2.0 processor. It is also one of the most compliant.
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 looking into installers, like NSIS? Any tutorials or starting points would be greatly appreciated.
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 should be a lot of existing stuff. I remember i had to implement a simple first-fit heap allocator myself in university courses twice. For C++ it must not use the standard c++ libraries or templates.
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 ?Thank you - Khayralla
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 - a sinle "message" from the peer may take several calls torecv. Hence you should read the message in a loop.You have a lot to learn about network programming.
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,num,sizeof(island[0]),cmp); // "num" is the number of the input data //when I do print,it seems that if num<10 is right,else wrong for(i=0;i<num;i++) { printf("%g\t",island[i].right); } ```
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 through.
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 fix the problem: ``` #ifndef FALSE #define FALSE (0) #endif #ifndef TRUE #define TRUE (!FALSE) #endif ```
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 option that allows you to perform operations without being preempted that's somewhat more system friendly (but only available on Vista and beyond) is to use theMultimedia Class Scheduler Service (MMCSS).
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) { Function2(char * color); return; } ``` I have to mention that the pointers in function1 and 2 are used as a return value.
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 ); free( cpMyPreciuos ); } ``` hth Mario
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 Linux,udevis responsible for creating entries in /dev. You can configure udev withrulesthat allow you to create your the device node with a specific name and location. In the embedded world it might be mdev with busybox that's responsible for populating /dev or even it could simply be the deprecated devfs.
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", &a, &b) == 1 ) { printf("%f\n", (a - b) / (a * b)); } return (EXIT_SUCCESS); } ```
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 on ternary logic. Reference:http://en.wikipedia.org/wiki/Ternary_logic
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 value exists)false/False (if it has a boolean type) Anything else is truthy and evaluates to true. Edit:Made the answer a bit less biased towards JavaScript
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 or file. The reason you don't want to close those then reopen, is that there is no guarantee you will receive the same number descriptor back in the next open call. That is why you would use open() to get a file descriptor, thendup2(new_descriptor, 1);to force descriptor 1 to go somewhere other than the console.
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 - this isn't going to work in 2000". To which the reply was "yeah but this system wont be in use by then, that's 25 years away". 2038 is 28 years away.
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 on ternary logic. Reference:http://en.wikipedia.org/wiki/Ternary_logic
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 value exists)false/False (if it has a boolean type) Anything else is truthy and evaluates to true. Edit:Made the answer a bit less biased towards JavaScript
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 or file. The reason you don't want to close those then reopen, is that there is no guarantee you will receive the same number descriptor back in the next open call. That is why you would use open() to get a file descriptor, thendup2(new_descriptor, 1);to force descriptor 1 to go somewhere other than the console.
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 - this isn't going to work in 2000". To which the reply was "yeah but this system wont be in use by then, that's 25 years away". 2038 is 28 years away.
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/ncg_goldberg.html
``` 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,*right; } *avlTree; ``` I have set the balance factor as per the definition given onWikipedia. Do I need to have a pointer to the parent node in each node?
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 an in-depth study of the topic: http://www.stanford.edu/~blp/avl/
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, Sebastian
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 command line app or a service will be quite a bit easier.
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 developers? is it clear to send to it's bug tracker?
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 have to list them twice. Consider e.g. libfoo.a depends on stuff in libbar.a ,and libbar.a depends on something in libfoo.a . You'll have to do:g++ -o fooprogram libbar.a libfoo.a libbar.a
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(non ASCII) in C?
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 < inputfile.txt Thanks.
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 automatically multithreaded and how. Thanks P.D. To get an idea about my code, let's say that it is something like this: ``` main(...) for(i=0;i<=ntimes;i++)get_result(x[i],y[i],result[i]); ``` ... ``` void get_result(float x,float y,float result){ result=sqrt(log (x) + log (y) + cos (exp (x + y)); (and some more similar mathematical operations) } ```
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 (image); } ```
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-expression, or(expression).
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. (see part 5: "Data types for implementation" on the linked page) This seems sound to me, but I've looked through many sites and no site confirms that this works. I also remember reading somewhere that it is much easier to implement lengths in adjacent matrices but stopped short of saying whether it possible to implement lengths in adjacency lists at all or just harder.
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; private void Form1_Load() { PortMapper.SharedInstance.Start(); PortMapping pm = new PortMapping(localPort, publicPort, PortMappingTransportProtocol.TCP); PortMapper.SharedInstance.AddPortMapping(pm); } private void Form1_FormClosing() { PortMapper.SharedInstance.StopBlocking(); } ``` What I plan to do with it? I want to create easy in use with Google App Engine free plan distributed (cloud like) file server that would be generaly based on my app users computers... so to say they use my app they houst it=)
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. (Who'd a thunk it?)
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_US"] autorelease]; NSDate *compiledOn = [NSDate dateWithNaturalLanguageString:dateString locale:enLocale]; return [compiledOn dateByAddingTimeInterval:days*24*60*60]; } ```
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 Properties->GCC c++ linker- but the program say/usr/bin/ld: cannot find -llibgompcan i know where i am wrong
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 other occasions I find it hard (with labor) to detect where exactly the problem is. Can you suggest some platform or tool which allows you to put the new version and old version of the program side by side and mark the changes that were employed on the new version. I am using gcc 4.3.2 to compile c programs on Ubuntu 10.04 OS. Any suggestion is welcome. regards, Anup
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 C compiler?
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 whereimplodeis defined. Or you can usehttp://lxr.php.net/.
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 way? e.g. ``` void foo(char *p); ``` ... ``` foo(p1); foo(p2); ```
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.height) return false; return true; ``` Which one you use should be dependent upon whether you anticipate more collisions or more misses.
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 add/subtract as I read the number from the disk and not risk running out of RAM. For multiplying/dividing, simply do the above in a loop. But what about taking the nth root of a HUGE number?
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) { // Do my daemon stuff } // Let's pretend it exits sometime exit(); } // Continue execution in parent without blocking..... ```
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()? something like : ``` char * getFormatString(int n) { char * buffer; sprintf(buffer, "Value with %%d decimals is %%.%df", n); return buffer; } void foo() { int decimals = 2; float pi = 3.141592; printf(getFormatString(decimals), decimals, pi); // should output "Value with 2 decimals is 3.14" } ``` Is this even possible ? So far, I get a seg fault when executing it.
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, x is printed as 2.
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 help centerfor guidance.Closed12 years ago. So with Microsoft .NET, you get the advantage of language interoperability. But I've heard that this is slower than native applications. What if you only need one language? Then what are the advantages. I am a C and C++ programmer, and .net seems to be heavily tied with C#. Is this the case? And is dot net portable, or tied to windows? And lastly, is .net worth taking a look at, from the perspective of a C++ programmer who doesn't need language interoperability? Thankyou.
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 from ignoring you and writing all over your file. There are no COMPULSORY locking primitives. You can use permissions to your advantage, but you'll never have full guarantees -- the root user can always override your limitations. I don't think there's a way to work around that.
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 seem related to other questions with this error.
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 allocate(&p,1); //The pointer has been modified to point to proper memory location //Hence this statement will work *p=10; //Free the memory allocated free(p); return 0; } ```
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(button, (GtkWidget *) image); ``` Is there something I'm missing?
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, this is a rather recent change in Gnome - for some reason, they decided for icons not to appear on buttons as default (this also seems to apply to the standard MS Windows theme).
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 * create() { ... } ``` Here you can wrap this into a non-exception program, likely returning null if you can't create the object.
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 occurred, so it was still hard to track down). I eventually managed to find a place in the code where a malloc call was allocating too little memory and that solved the problem. However, it bothers me that this problem was never detected on the Linux side. Are there any switches or something that would enable this detection feature on Linux?
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 -0, and so the range for an 8-bit quantity is -127 to +127.