question
stringlengths
25
894
answer
stringlengths
4
863
I want to use shared memory, but i want only my application instances to be able to access this memory, somehow want to protect it from accessing by other applications... I am coding in C on Windows. Thanks in advance.
UseCreateFileMappingwith specificLPSECURITY_ATTRIBUTES.
I'd like to doprintfstyle printing fromGDB. For instance, I want to print a variable value, but with some text to describe what it is. Can it be done, and if so, can you give an example?
You can very much useprintfingdbas follows: ``` (gdb) printf "%s", x Hello world (gdb) ``` You can do it by usingcallalso ``` (gdb) call printf("%s", x) Hello world (gdb) ``` I prefer the former one! http://beej.us/guide/bggdb/is a simple and good reference forgdb
I want to have two threads to handle windows messages. One for key/mouse input in the client area (this thread also takes care of game logic) and one for the rest because I am making a game and some messages cause DefWindowProc() to block (thus freezing the game). How can I achieve this?
Contrary to what Cody wrote, you most definitely can process messages from multiple threads. However, this is not a customizable free-for-all. Rather, windows have thread affinity: each thread will receive the messages sent or posted to windows created by that thread. There's no way to have any window's messages de...
If I run "emacs -q" (prevents loading of user config, so I know it's not a problem with my setup) and open an empty buffer called foo.C and type: ``` case elSE: ``` And then hit ':', emacs insists on changing "elSE" to "Else". I have no ideawhyit's doing this; I assume it thinks I'm misspelling the "else" keyword, e...
This also happens for me on Emacs 24; it seems to be caused by abbrev-mode - tryM-x abbrev-modeto disable it.
I have to use theSNAPC-library. I compiled my file snap_test.c with the following command: ``` gcc -fopenmp -c -I/home/myName/SNAPDIR/include snap_test.c ``` And then linked it with the library: ``` gcc -fopenmp -o snap_test -L/home/myName/SNAPDIR/lib -lsnap snap_test.o ``` But running the program leads to an err...
You need to add/home/myName/SNAPDIR/libtoLD_LIBRARY_PATH. ``` $ export LD_LIBRARY_PATH+=:/home/myName/SNAPDIR/lib ```
This is a basically duplication ofthis question. However, I'm looking for the same answer that will work in C/C++ - some easy way to add comments to the functions with descriptions of all of the parameters. It was really easy to do in SLickEdit - just press Ctrl+SHift+D. All the answers and methods for the aforementio...
Try Doxygen. You can set it up as follows: Window->Preferences->C/C++ ->Editor->"Documentation tool" Here are more details: A doxygen eclipse plugIn automatically generating stub documentation?
I am trying to read a text file using fscanf.I am working in eclipse in OpenCV on ubuntu. Here are some sample values in the text file 0 5 7 0.547619047619048 1 0.0274509803921569 1 0 6 8 0.541666666666667 1 0.0313725490196078 1 0 8 10 0.533333333333333 1 0.0392156862745098 1 But all fsca...
testd[i][0], etc, is an rvalue. What you need is&testd[i][0].
I try to use fread to read a text file My code is only 2 lines ``` fid = fopen('1.txt', 'r'); c = fread(fid,'double', skipvalue); ``` I have tested different format like double, float32, float64 and different skipvalue from 0 to 8, but none of the combination work. The data is recorded by a c program code fprintf(...
Try thetextscanfunction orfscanf. freadis the counterpart tofwrite, notfprintf. fscanfis the counterpart tofprintf. If you absolutely must usefread, you'd read a string (character array) and then usesscanfto extract the numeric data from it.
I want to use shared memory, but i want only my application instances to be able to access this memory, somehow want to protect it from accessing by other applications... I am coding in C on Windows. Thanks in advance.
UseCreateFileMappingwith specificLPSECURITY_ATTRIBUTES.
I'd like to doprintfstyle printing fromGDB. For instance, I want to print a variable value, but with some text to describe what it is. Can it be done, and if so, can you give an example?
You can very much useprintfingdbas follows: ``` (gdb) printf "%s", x Hello world (gdb) ``` You can do it by usingcallalso ``` (gdb) call printf("%s", x) Hello world (gdb) ``` I prefer the former one! http://beej.us/guide/bggdb/is a simple and good reference forgdb
I wanna use a TUI over telnet connection between two Linux boxes like ncurses, is there a way to do this or to use TUIs through telnet in C?
Do you mean you want to telnet to a server machine and run an ncurses application, or do you somehow want to run a UI on one machine, and a backend on the other. If it's the former, you just need to set the TERM environment variable correctly on the server machine before running your program (i.e.,export TERM=vt100). ...
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. How do i insert data from an iPhone...
In short - you need to have a server (the one with the MySQL database) which defines a layer of 'services' that the iOS application can call. You could design this service layer in PHP, Python, NodeJS, etc.... It doesn't matter how you do it - but you need to have some service layer to handle the interactions. Anoth...
How do I configure eclipse with Turbo C++ compiler.
Short answer: don't! Embarcadero Technologies (which acquired all of Borland's compiler tools with the purchase of its CodeGear division in 2008) discontinued the support of Turbo C++ 2006. Why use a tool that was abandoned 6 years ago? Turbo C++ was succeeded by C++Builder, which has it's own IDE. If you want to d...
I have multiple threads adding, modifying and looking up data in GHashTable. Is it threadsafe, or do I need to implement threadsafety myself?
The documentationstates this pretty clearly: After callingg_thread_init(), GLib is completely thread safe (all global data is automatically locked), but individual data structure instances are not automatically locked for performance reasons. So, for example you must coordinate accesses to the sameGHashTablefrom mult...
``` #include <stdio.h> #define QUOTE(str) #str #define EXPAND_AND_QUOTE(str) QUOTE(str) #define TEST one-of-a-linux int main() { printf(EXPAND_AND_QUOTE(TEST)"\n"); } ``` I get: one-of-a-1 rather than one-of-a-linux Note that "linux" becomes "1" - i.e. the digit one
On my Linux box: ``` $ gcc -dM -E - < /dev/null | grep 'linux\|unix' #define __unix__ 1 #define __linux 1 #define __unix 1 #define __linux__ 1 #define __gnu_linux__ 1 #define unix 1 #define linux 1 $ ``` Note the value ofunixbeing 1 on unix platforms has been used in an IOCCC entry. Winner of the "Best One Liner" in...
I know it is a Macro we are passing to a function. How do you explain what is the use of this macro, and in which scenario i have to use this ?.
_GNU_SOURCEenables GNU extensions to the C and OS standards supported by the GNU C library, such asasprintf. Define it when you're using such non-standard functions and macros.
Is there any way to reverse linked list without using temp variable in C? Thanks in advance. the famous approach: ``` Element *reverse(Element *head) { Element *previous = NULL; while (head != NULL) { // Keep next node since we trash // the next pointer. Element *next = head->next; ...
Note that yourtempusage is actually generating twoswap()calls, and can be replaced with: ``` swap(head->next,previous); swap(previous,head); ``` You can swap without temps using xor, it is calledxor swap.
I am learning how to get arguments in C, however, when I run the code below with the following input, the first one becomes null. Input:./a.out a b c d e f g h i j k Output:(null) b c d e f g h i j k ``` #include <stdio.h> int main(int argc, char *argv[]) { int i = 2, j = 0; char *foo = arg...
At the end of the loop you writeNULLtobar[10], but you have only allocatedbar[0 - 9]. That probably overwritesfoo.
We know some escape sequence '\n' - new line but say we don't know if \a, \b, \c .... \z is an escape sequence. How to write a program that allows us to test every character from a to z and/or A to Z in a printf statement or other way to identify an escape sequence and if it is, then print it's value e.g. ouput may lo...
Read 5.2.2p2 in Standard C99 document. Alphabetic escape sequences are: ``` \a \b \f \n \r \t \v ```
I'm preparing for my UNIX exam and there is a question about memory location of C variables. Let's say we have code like this ``` char sth; int some_function(int arg) { int some_int; // some code here } ``` so I suppose thatsthis located on the heap,some_inton the stack, but where isarglocated? Can somebody pl...
Note that everything of this is implementation dependent. The C standard does not even utter the words stack, heap and so on. It just talks about the behavior that is expected from variables depending on their storage(static,extern,registeretc). Having said so usuallyargwill be located in the stack frame which is pro...
I'm trying to link myCMake-project withpcrelib wich is already is shipped with aCMakeLists.txt, so it promises to be easily. However, I'd like to build it only for C language, no C++. My question is whether it possible to override the list of supported languages? pcre'sCMakeLists.txthas the followingprojectcommand: ...
There is following line in pcre's CMakeLists.txt: ``` OPTION(PCRE_BUILD_PCRECPP "Build the PCRE C++ library (pcrecpp)." ON) ``` I suppose, you should set this var toOFF.
Could anybody tell me please how can I get framerate of WM_PAINT message in frames per second? I'm trying to make a software renderer, and framerate is very important for debugging.
This question was asked previouslyhere. As an additional hint, you can use a dynamically allocated structure to store your FPS-related variables and useSetWindowLongPtrto store a pointer to this structure.
I am trying to write Pro*C/C/C++ code to handle a query like this: ``` SELECT col1, col2, col3, col4 FROM table WHERE param IN(<set of values>); ``` I can have a C struct to retrieve the result and pass individual parameters but I can't seem to find a way to do this without explicitly specifying every value in the l...
I asked that same question atHow to specify a variable expression list in a Pro*C query? I came up myself with a rather clumsy solution that works in my specific case. It might not apply to yours.
I want to use an array of string the same as this: ``` char arr[][20] = {"username1", "username2"}; ``` after i have not problem to get values, for example : ``` printf("%s", arr[0]); // for "username1" ``` i have problem to insert new string to this array, something like this!? : ``` arr[2] = "username3"; // or...
You're trying to insert achar*into an array ofchar[20]. That won't work. You could usestrcpyas ``` strcpy(arr[2], "username3"); ``` ifyou had allocated sufficient space for a third string, which you haven't. I suggest you read up onmallocand friends; you can't just append a string to this array.
Here is my code ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char f[] = "First"; char s[] = "Second"; char *tmp = malloc(strlen(f) + strlen(s) + 2); strcpy(tmp, f); strcpy(tmp, s); printf("%s", tmp); free(tmp); return 0; } ``` I'm trying to concatenate f and s. The problem i...
strcpycopies the string to the beginning of the destination, you wantstrcatinstead.
I recently noticed this while working on an app- why is it that when you import a file you use ``` #import "SomeFile.h" ``` but when you are manipulating a string you use the @ symbol before the string, such as ``` NSLog(@"Hello World"); ``` I know these two are not interchangeable, so is there a specific reason t...
Its because#importis a preprocessor macro, that is compiled before the objc runtime is even a part of the picture. All import is is a wrapper around#includethat makes sure you don't include the same file twice.
I'm trying to use the library gcrypt.h but show this error: undefined reference to `gcry_md_get_algo_dlen' The code is: ``` int algo = GCRY_MD_SHA1; unsigned int hash_len = gcry_md_get_algo_dlen(algo); unsigned char hash[hash_len]; ``` How can I fix it?
Make sure you have the most recent version of the libraryhttp://www.gnupg.org/download/#libgcrypt If you have the right version make sure you added the library itself to your linker settings in Eclipse. To do so: Right-Click on your project -> Properties / C/C++Build / Settings / GCC C++ Linker / Libraries There y...
I am using cvCanny function in opencv 2.3 it compiles fine,but while executing it gives an error saying 'tbb.dll' not found. What is the use of this dll and where can I find this?? thanks,
It's part of Intel'sThreading Building Blockslibrary. You can find a copy of it in your OpenCV install in/build/common/tbband under the platform and compiler your are using. For example, inc:\OpenCV-2.3.1\build\common\tbb\intel64\vc9
I'm preparing for my UNIX exam and there is a question about memory location of C variables. Let's say we have code like this ``` char sth; int some_function(int arg) { int some_int; // some code here } ``` so I suppose thatsthis located on the heap,some_inton the stack, but where isarglocated? Can somebody pl...
Note that everything of this is implementation dependent. The C standard does not even utter the words stack, heap and so on. It just talks about the behavior that is expected from variables depending on their storage(static,extern,registeretc). Having said so usuallyargwill be located in the stack frame which is pro...
I'm trying to link myCMake-project withpcrelib wich is already is shipped with aCMakeLists.txt, so it promises to be easily. However, I'd like to build it only for C language, no C++. My question is whether it possible to override the list of supported languages? pcre'sCMakeLists.txthas the followingprojectcommand: ...
There is following line in pcre's CMakeLists.txt: ``` OPTION(PCRE_BUILD_PCRECPP "Build the PCRE C++ library (pcrecpp)." ON) ``` I suppose, you should set this var toOFF.
Could anybody tell me please how can I get framerate of WM_PAINT message in frames per second? I'm trying to make a software renderer, and framerate is very important for debugging.
This question was asked previouslyhere. As an additional hint, you can use a dynamically allocated structure to store your FPS-related variables and useSetWindowLongPtrto store a pointer to this structure.
I am trying to write Pro*C/C/C++ code to handle a query like this: ``` SELECT col1, col2, col3, col4 FROM table WHERE param IN(<set of values>); ``` I can have a C struct to retrieve the result and pass individual parameters but I can't seem to find a way to do this without explicitly specifying every value in the l...
I asked that same question atHow to specify a variable expression list in a Pro*C query? I came up myself with a rather clumsy solution that works in my specific case. It might not apply to yours.
I want to use an array of string the same as this: ``` char arr[][20] = {"username1", "username2"}; ``` after i have not problem to get values, for example : ``` printf("%s", arr[0]); // for "username1" ``` i have problem to insert new string to this array, something like this!? : ``` arr[2] = "username3"; // or...
You're trying to insert achar*into an array ofchar[20]. That won't work. You could usestrcpyas ``` strcpy(arr[2], "username3"); ``` ifyou had allocated sufficient space for a third string, which you haven't. I suggest you read up onmallocand friends; you can't just append a string to this array.
Here is my code ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char f[] = "First"; char s[] = "Second"; char *tmp = malloc(strlen(f) + strlen(s) + 2); strcpy(tmp, f); strcpy(tmp, s); printf("%s", tmp); free(tmp); return 0; } ``` I'm trying to concatenate f and s. The problem i...
strcpycopies the string to the beginning of the destination, you wantstrcatinstead.
I recently noticed this while working on an app- why is it that when you import a file you use ``` #import "SomeFile.h" ``` but when you are manipulating a string you use the @ symbol before the string, such as ``` NSLog(@"Hello World"); ``` I know these two are not interchangeable, so is there a specific reason t...
Its because#importis a preprocessor macro, that is compiled before the objc runtime is even a part of the picture. All import is is a wrapper around#includethat makes sure you don't include the same file twice.
I'm trying to use the library gcrypt.h but show this error: undefined reference to `gcry_md_get_algo_dlen' The code is: ``` int algo = GCRY_MD_SHA1; unsigned int hash_len = gcry_md_get_algo_dlen(algo); unsigned char hash[hash_len]; ``` How can I fix it?
Make sure you have the most recent version of the libraryhttp://www.gnupg.org/download/#libgcrypt If you have the right version make sure you added the library itself to your linker settings in Eclipse. To do so: Right-Click on your project -> Properties / C/C++Build / Settings / GCC C++ Linker / Libraries There y...
I am using cvCanny function in opencv 2.3 it compiles fine,but while executing it gives an error saying 'tbb.dll' not found. What is the use of this dll and where can I find this?? thanks,
It's part of Intel'sThreading Building Blockslibrary. You can find a copy of it in your OpenCV install in/build/common/tbband under the platform and compiler your are using. For example, inc:\OpenCV-2.3.1\build\common\tbb\intel64\vc9
In C11, a new string literal has been added with the prefix u8. This returns an array of chars with the text encoded to UTF-8. How is this even possible? Isn't a normal char signed? Meaning it has one bit less of information to use because of the sign-bit? My logic would depict that a string of UTF-8 text would need t...
Isn't a normal char signed? It's implementation-dependent whethercharissignedorunsigned. Further, the sign bit isn't "lost", it can still be used to represent information, andcharis not necessarily 8 bits large (it might be larger on some platforms).
Based on "IEEE" spec : "When either an input or result is NaN, this standard does not interpret the sign of a NaN." However theprintfprintsNaNvalues as signed:nanor-nanCan someone point me the set of rules(from spec?) whennanand when-nanis printed For example , I checked thatprintf(-1.0f)prints-nanThank you
The underlying representation of a NaN contains a sign bit, and this is whatprintflooks at when deciding if it should print the minus or not. The reason why the standard says that the sign bit should be ignored is to allow things likenegateorabsoluteto simply modify the sign bit, without being forced to check if the ...
Тhese are my calculations ``` float c = 5.0 * (12.0 - 32.0) / 9.0; printf("%f.2", c); ``` Result is -11.111111.2 but I expected to be -11.11. What is wrong ?
The format specifier should read"%.2f". In what you have right now, the.2is misplaced. This is why you get more digits than expected, and why the.2appears verbatim at the end of the output.
I want to perform a canny edge detection in opencv 2.3,coding in c language. But when I am using cvCanny for the same purpose it gives an error as unresolved external symbol _CvCanny,though I have used a proper prototype of CvCanny. Is there any library that i have forgot to include or what? Regards,
You cannot link because you didn't add the correct path/ libraries to your project
This question already has answers here:Closed11 years ago. Possible Duplicate:What is the best way to communicate with a MySQL server? Is there a simple way to access and modify a mySQL database on a Web Site or XAMMP using C/C++? How is this usually done? If a library is needed, is there one that is not extremely d...
I haven't used either, but there is a C APIthat comes with MySQL, and if you prefer C++, there's also aC++ wrapper available.
In C on a 32-bit system, which data type will store (and can therefore print) the largest integer? Is itlong longorunsigned long? Is there anunsigned long long? And which is the most precise and politically correct?
Your question is a bit unclear, butintmax_tis the largest signed integer-valued type (anduintmax_tis the largest unsigned integer type). These are typedefs defined in<stdint.h>, but if you are printing them, you need<inttypes.h>instead, and the PRInMAX macros for various values ofn.
I'm writing a game in C using the Gtk libraries, in which the player controls a movable character. However, I want the player to be able to hold a key to continuously move in one direction. How do I override the normal behavior for holding a key, in which a key event is generated, there is a brief pause, and then key ...
Connect to GTK'skey_press_eventandkey_release_eventsignals. They will work as you describe. It will be your responsibility to track whether the keys you are interested in are currently pressed at a given time.
What is the preferred way to compile.c/.cppfiles similar togcc(Linux) incmd(Windows)? What are the most common compilers?
I've never used this but it looks like it might be what you're looking for.http://www.mingw.org/ I think most people use Cygwin.http://www.cygwin.com/
How can I send a key press or key release event to a window (the currently active window) from another program usingXCB? I found some tutorials usingXLib, however I would like to useXCB. I guess I will have to callxcb_send_event, however I have no idea what to pass it as parameters.
You should be able to use the XTEST extension to fake input to the active window, using the xcb_test_fake_input() function. ``` #include <xcb/xtest.h> ... xcb_test_fake_input(c, XCB_KEY_PRESS, keycode, XCB_CURRENT_TIME, XCB_NONE, 0, 0, 0); xcb_test_fake_input(c, XCB_KEY_RELEASE, keycode, XCB_CURRENT_TIME, XCB_NONE, 0...
Here is my code snippet ``` main() { char *filename; if(1 > 2) { filename = "file.txt" } if(filename != NULL (also tried 0) { do something } return 0; } ``` My question is how to check if filename var have assigned value. I can use strcmp but rvalue can be different of...
Change: ``` char *filename; ``` To: ``` char *filename = NULL; ``` Then yourNULLtests will work. When you don't initialize this pointer, its value isundefined. That's why your tests were failing. The compiler assumed that you didn't care what value it had.
Here is my program. ``` #include <stdio.h> void help(const char *argv); int main(int argc, const char *argv[]) { const char *p; int x; for(x = 0; x < argc; x++) { p = argv[x]; if(*p == '-') { p++; } switch(*p) { case 'h': help...
That should be ``` help(argv); ``` and ``` void help(const char **argv) { fprintf(stderr, "Usage %s: [option]\n", argv[0]); } ``` Using achar**because you are passing an array of strings (aka pointers to char).
This question already has answers here:Closed11 years ago. I want to pass variable arguments tomakecontextfunction as follows. ``` void a(...) { .... makecontext( &stack, &func, ?, ? ); .... } ``` In the third parameter (?), I should have the number of variable arguments, while in the next?, I should have all t...
There's no way a variadic function can know the number of parameters it got. This information is not passed to it in any way.The only way is by convention, which the caller will need to respect.Two common conventions:1. One of the first parameters would be the number of parameters.2. All parameters are pointers, the l...
Consider this code: ``` #include <iostream> int main() { int iTemp = 0; iTemp += 1; // Valid iTemp + = 1; // This gives an error ( note the space between '+' and '=') return 0; } ``` Should the parser not automatically have consumed this space and checked for the presence of '=' as '+=' is al...
No, the parser should not have. The specification of the language calls for this behavior, and that's the end of the story.
I know that this may be common knowledge, but is there a way to edit RGB values of pixels of Windows window fromC/C++without using libraries likeOpenGLorDirectX? If there is, what are the built-in functions to manipulate pixel buffer directly?
In yourWM_PAINThandler you can callSetPixel.
This question already has answers here:Closed11 years ago. Possible Duplicate:Is it ever possible to get the current (member) function name in C++? If given a functionint func(args)in C or C++ is there a way to get the name, or even signature, of the function fromwith in the body offunc I would like to be able to d...
There is__PRETTY_FUNCTION__predefined identifier with gcc: ``` void func(void) { printf("%s\n", __PRETTY_FUNCTION__); } ``` it will print : ``` void func() ``` with gcc in C++ and ``` func ``` with gcc in C Note that this identifier is a gcc extension. In Standard C, there is the predefined identifier__fu...
I have an unsigned char* type and want to assign it an integer value. How can I do it in C?
Just do it, with an appropriate cast: ``` unsigned char *pointer = (unsigned char *) 0xdeadf00d; ``` This does exactly what you asked for, it assigns an integer value to a pointer tounsigned char. This is not a veryusefulthing to be doing, but that's how you do it. Of course there's no requirement (that I'm aware o...
Do you know of any HTTP client library in C (with SSL support) that also allows direct communication with the remote server? I have a client-server application where the client uses HTTP to start a session in the server and then tells the server to switch the connection from HTTP to a different protocol. All communic...
Notice that libcurl doesn't do the SSL part by itself, it uses OpenSSL. So, if you can get the socket handle from libcurl after the first HTTP interactions, AND the session key it uses (some spelunking required) you can go on directly with OpenSSL from that point.
Since Objective-C is basically an extension of C, Does the code get converted to pure C code before it is compiled to native code ? If so, does the conversion happens on RAM or a temporary file containing C code on disk is created by the compiler which is further compiled by C compiler to native code ?
That Objective-Csyntaxis an extension of C syntax does not mean that it could not have its own compiler. C++ is the same way - its syntax is compatible with C (for the most part, anyway) but it has its own set of tools. Compilers for C, C++, and Objective-C can reuse parts of each other for preprocessing, syntactic an...
I want to know that how can we allocate a memory block atrun-timein C or C++ without usingmallocandcallocfunctions.
In C, usemalloc. Don't forget tofreeafter use. In C++, usenewand don't forget todelete. Or better, usestd::vectorif you want a dynamic array.
Does these's two codes mean the same? Assambler -> ``` _asm INCF PR4,0,ACCESS CPFSLT TMR4,ACCESS _endasm ``` C -> ``` ++PR4; if (PR4 < TMR4) PIR3bits.TMR4IF = 1; ``` If not, how should the assambler code be translated? Kind regards :)
The first answer is no, but Im unsure how to translate it! INCF PR4,0,ACCESS //(INCF f,d) (Increment f) (f + 1 -> d) "Increment PR4 Register "Working register (accumulator)" in ACCESS in other words: Get PR +1 to WREG ``` WREG = PR +1; ``` CPFSLT TMR4,ACCESS //(CPFSLT f) (Compare f/w, skip if f< w) (f-W, skip if f...
Lets have an array of type int:- ``` int arr[5]; ``` Now, ``` if arr[0] is at address 100 then Why do we have; arr[1] at address 102 , arr[2] at address 104 and so on. ``` Instead of ``` arr[1] at address 101 , arr[2] at address 102 and so on. ``` Is it because an integer takes 2 by...
Your first example is consistent with 16-bitints. As to your second example (&arr[0]==100,&arr[1]==101,&arr[2]==103), this can't possibly be a valid layout since the distance between consecutive elements varies between the first pair and the second.
Hello guys! Here: ``` #include <stdio.h> char* getStr( char *c ){ scanf( "%s" , c ); return c; } int main(){ char str[ 100 ]; getStr( str ); printf( "%s" , str ); return 0; } ``` Could you please explain why is the string printed only until the first "space". i.e. input: asd asd output: ...
That's the contract ofscanf(seehttp://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html). It reads until the next whitespace encountered. You could change your format string to read in two strings as"%s %s"which will read two strings separated by whitespace.
Does this code have defined behaviour? ``` char *str = NULL; printf("%s\n",str); ``` In context of C++ (98/03 and 11) and C (99) standards.
undefined behavior in C (C99, 7.19.6.1p8) "s If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type." with some compilers / libc it prints(null)and with some other it segfaults. (Note: in C violation of ashallthat is not a constraint is undefined...
I got one issue while implementing theCtime()in C using MS VC++ 2008 for running the application. By using thectimeI will get current time format asSun Jan 09 14:38:09 2011. Is there any way to convert the above format as2012-01-09 14:38:09(in MYSQL). Is there any direct functions in C. Any suggestion to do this?
You can convert yourtime_tto astruct tmwithlocaltime()(orgmtime()), then usestrftime()to format the date as you want. Example: ``` char out[20]; time_t t0 = time(0); struct tm *tm0 = localtime(t0); strftime(out, sizeof out, "%Y-%m-%d %H:%M:%S", tm0); ``` If you need differenttime_tvalues for different database co...
I wish to move bits 0,8,16,24 of a 32-bit value to bits 0,1,2,3 respectively. All other bits in the input and output will be zero. Obviously I can do that like this: ``` c = c>>21 + c>>14 + c>>7 + c; c &= 0xF; ``` But is there a faster (fewer instructions) way?
``` c = (((c&BITS_0_8_16_24) * BITS_0_7_14_21) >> 21) & 0xF; ``` Or wait for Intel Haswell processor, doing all this in exactly one instruction (pext). Update Taking into accountclarified constraintsand assuming32-bit unsigned values, the code may be simplified to this: ``` c = (c * BITS_7_14_21_28) >> 28; ```
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Your best bet isKissFFT- as its name implies it'ssimple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.
Just playing with pointers, trying to pass the address of a pointer to a function, using: ``` void changer(int **ptr) { if(**ptr==NULL) { *ptr=(int *)malloc(sizeof(int)); **ptr=2; } } int main() { int *ptr; clrscr(); changer(&ptr); printf("%d",*ptr); getch(); r...
You have an extra dereference ofptrin theNULLcheck, and you are not initializing the pointer. The program should look like this after the fix: ``` #include <stdio.h> #include <stdlib.h> void changer(int **ptr) { if(*ptr==NULL) // Dereference once, not twice { *ptr=(int *)malloc(sizeof(int)); ...
here i want to understand the architecture of bluez (Bluetooth Stack Protocol). I understood how bluetooth enable in module. its enable by up the BT_EN pin in this Bluetooth Chip. After attacth this device withHCI UARTto Bluez for communication. i want to know about bluez architecture and how its works. Here i put ...
BlueZ Core in that diagram is the main host stack software. It communicates with the BT hardware using HCI protocol to do general control of the hardware. You would have to read the BT spec to get a full picture of what all of the HCI protocol commands do. But at a high level there are things like reading HW featur...
I get the following error:error C2102: '&' requires l-valuewhen compiling the following line: ``` if (&(obj->getTranslation()).y ==5) ``` I am trying to get the y-axis coordinate of an object, but I seem to be missing something. Could you please help me out.
Pretty sure you just want this: ``` if (obj->getTranslation().y ==5) ``` If get Translation returns a pointer then you'll want to dereference it, so you may have been looking for: ``` if ((*obj->getTranslation()).y ==5) ``` But you could just use the dereference operator you're using on obj: ``` if (obj->getTrans...
In C on a 32-bit system, which data type will store (and can therefore print) the largest integer? Is itlong longorunsigned long? Is there anunsigned long long? And which is the most precise and politically correct?
Your question is a bit unclear, butintmax_tis the largest signed integer-valued type (anduintmax_tis the largest unsigned integer type). These are typedefs defined in<stdint.h>, but if you are printing them, you need<inttypes.h>instead, and the PRInMAX macros for various values ofn.
I'm writing a game in C using the Gtk libraries, in which the player controls a movable character. However, I want the player to be able to hold a key to continuously move in one direction. How do I override the normal behavior for holding a key, in which a key event is generated, there is a brief pause, and then key ...
Connect to GTK'skey_press_eventandkey_release_eventsignals. They will work as you describe. It will be your responsibility to track whether the keys you are interested in are currently pressed at a given time.
What is the preferred way to compile.c/.cppfiles similar togcc(Linux) incmd(Windows)? What are the most common compilers?
I've never used this but it looks like it might be what you're looking for.http://www.mingw.org/ I think most people use Cygwin.http://www.cygwin.com/
How can I send a key press or key release event to a window (the currently active window) from another program usingXCB? I found some tutorials usingXLib, however I would like to useXCB. I guess I will have to callxcb_send_event, however I have no idea what to pass it as parameters.
You should be able to use the XTEST extension to fake input to the active window, using the xcb_test_fake_input() function. ``` #include <xcb/xtest.h> ... xcb_test_fake_input(c, XCB_KEY_PRESS, keycode, XCB_CURRENT_TIME, XCB_NONE, 0, 0, 0); xcb_test_fake_input(c, XCB_KEY_RELEASE, keycode, XCB_CURRENT_TIME, XCB_NONE, 0...
Here is my code snippet ``` main() { char *filename; if(1 > 2) { filename = "file.txt" } if(filename != NULL (also tried 0) { do something } return 0; } ``` My question is how to check if filename var have assigned value. I can use strcmp but rvalue can be different of...
Change: ``` char *filename; ``` To: ``` char *filename = NULL; ``` Then yourNULLtests will work. When you don't initialize this pointer, its value isundefined. That's why your tests were failing. The compiler assumed that you didn't care what value it had.
Here is my program. ``` #include <stdio.h> void help(const char *argv); int main(int argc, const char *argv[]) { const char *p; int x; for(x = 0; x < argc; x++) { p = argv[x]; if(*p == '-') { p++; } switch(*p) { case 'h': help...
That should be ``` help(argv); ``` and ``` void help(const char **argv) { fprintf(stderr, "Usage %s: [option]\n", argv[0]); } ``` Using achar**because you are passing an array of strings (aka pointers to char).
This question already has answers here:Closed11 years ago. I want to pass variable arguments tomakecontextfunction as follows. ``` void a(...) { .... makecontext( &stack, &func, ?, ? ); .... } ``` In the third parameter (?), I should have the number of variable arguments, while in the next?, I should have all t...
There's no way a variadic function can know the number of parameters it got. This information is not passed to it in any way.The only way is by convention, which the caller will need to respect.Two common conventions:1. One of the first parameters would be the number of parameters.2. All parameters are pointers, the l...
Consider this code: ``` #include <iostream> int main() { int iTemp = 0; iTemp += 1; // Valid iTemp + = 1; // This gives an error ( note the space between '+' and '=') return 0; } ``` Should the parser not automatically have consumed this space and checked for the presence of '=' as '+=' is al...
No, the parser should not have. The specification of the language calls for this behavior, and that's the end of the story.
I know that this may be common knowledge, but is there a way to edit RGB values of pixels of Windows window fromC/C++without using libraries likeOpenGLorDirectX? If there is, what are the built-in functions to manipulate pixel buffer directly?
In yourWM_PAINThandler you can callSetPixel.
This question already has answers here:Closed11 years ago. Possible Duplicate:Is it ever possible to get the current (member) function name in C++? If given a functionint func(args)in C or C++ is there a way to get the name, or even signature, of the function fromwith in the body offunc I would like to be able to d...
There is__PRETTY_FUNCTION__predefined identifier with gcc: ``` void func(void) { printf("%s\n", __PRETTY_FUNCTION__); } ``` it will print : ``` void func() ``` with gcc in C++ and ``` func ``` with gcc in C Note that this identifier is a gcc extension. In Standard C, there is the predefined identifier__fu...
I have an unsigned char* type and want to assign it an integer value. How can I do it in C?
Just do it, with an appropriate cast: ``` unsigned char *pointer = (unsigned char *) 0xdeadf00d; ``` This does exactly what you asked for, it assigns an integer value to a pointer tounsigned char. This is not a veryusefulthing to be doing, but that's how you do it. Of course there's no requirement (that I'm aware o...
Do you know of any HTTP client library in C (with SSL support) that also allows direct communication with the remote server? I have a client-server application where the client uses HTTP to start a session in the server and then tells the server to switch the connection from HTTP to a different protocol. All communic...
Notice that libcurl doesn't do the SSL part by itself, it uses OpenSSL. So, if you can get the socket handle from libcurl after the first HTTP interactions, AND the session key it uses (some spelunking required) you can go on directly with OpenSSL from that point.
Since Objective-C is basically an extension of C, Does the code get converted to pure C code before it is compiled to native code ? If so, does the conversion happens on RAM or a temporary file containing C code on disk is created by the compiler which is further compiled by C compiler to native code ?
That Objective-Csyntaxis an extension of C syntax does not mean that it could not have its own compiler. C++ is the same way - its syntax is compatible with C (for the most part, anyway) but it has its own set of tools. Compilers for C, C++, and Objective-C can reuse parts of each other for preprocessing, syntactic an...
I want to know that how can we allocate a memory block atrun-timein C or C++ without usingmallocandcallocfunctions.
In C, usemalloc. Don't forget tofreeafter use. In C++, usenewand don't forget todelete. Or better, usestd::vectorif you want a dynamic array.
Does these's two codes mean the same? Assambler -> ``` _asm INCF PR4,0,ACCESS CPFSLT TMR4,ACCESS _endasm ``` C -> ``` ++PR4; if (PR4 < TMR4) PIR3bits.TMR4IF = 1; ``` If not, how should the assambler code be translated? Kind regards :)
The first answer is no, but Im unsure how to translate it! INCF PR4,0,ACCESS //(INCF f,d) (Increment f) (f + 1 -> d) "Increment PR4 Register "Working register (accumulator)" in ACCESS in other words: Get PR +1 to WREG ``` WREG = PR +1; ``` CPFSLT TMR4,ACCESS //(CPFSLT f) (Compare f/w, skip if f< w) (f-W, skip if f...
Lets have an array of type int:- ``` int arr[5]; ``` Now, ``` if arr[0] is at address 100 then Why do we have; arr[1] at address 102 , arr[2] at address 104 and so on. ``` Instead of ``` arr[1] at address 101 , arr[2] at address 102 and so on. ``` Is it because an integer takes 2 by...
Your first example is consistent with 16-bitints. As to your second example (&arr[0]==100,&arr[1]==101,&arr[2]==103), this can't possibly be a valid layout since the distance between consecutive elements varies between the first pair and the second.
I working on a system, which need to compile and match a lot of regexes. But these regexes are usually not reusedso I want to deallocate them, when I don't need them anymore. After scanning throughPCRE API specI didn't found a function that can be used to this. There must be a way to do this somehow. I cannot imagin...
It is up to the caller to free the memory (viapcre_free) when it is no longer required. Source:API docs
This question already has answers here:Closed11 years ago. Possible Duplicate:How an uninitialised variable gets a garbage value? So when an undefined (but declared) variable is used, it contains strange value each time. How does it have such value? Is it randomly generated purposely?
It is not randomly generated, it is just residual memory. It would be highly inefficient to clear all unused memory every time. So the memory is released to the OS and made available. When you request new memory, you get some of this memory, which is not owned by anyone but still has garbage in it since it was just f...
I am using VC2010. I defined FALSE to be false using ``` #define FALSE=false ``` and then I tried to use it as follows ``` bool *bPtr; if(some condition) *bPtr=FALSE; ``` the compiler flags FALSE and says "Expected an expression". I used false instead of the defined 'FALSE' and it accepts it. I am wondering as wh...
Just this: ``` #define FALSE false ``` with whitespace and without=.
How do I figure out the type of an object in C? My goal with this is to create a linked-list container in C. Let's assume I have a function that takes a void pointer: ``` ... Foo *f; f = Allocate(f); ... void *Allocate(void *item) { return malloc(sizeof(f.GetType)); } ``` How do I make the above syntax possible...
That's not possible. Avoid *pointer, is just a pointer to the memory, nothing more, no more information is attached to it. It's impossible to do what you are asking, you can't know how many bytes tomalloc. That's why, theqsortfunction fromstdlib.hlibrary takes as a parameter thesizein bytes of each array element. If ...
This question already has answers here:Closed11 years ago. Possible Duplicate:What does 'unsigned temp:3' means I have been trying to learn raw socket programming in C and have come across this: ``` unsigned char iph_ihl:5, iph_ver:4; ``` I am confused about what the ':' does. Does it even do anything? Or is ...
You're looking at bitfields. Those definitions have to be inside a structure, and they mean thatiph_ihlis a 5-bit field andiph_veris a 4-bit field. Your example is a bit strange, since anunsigned charwould be an 8-bit type on most machines, but there are 9 bits worth of fields declared there. In general bitfields a...
I'm trying to generate a random Gaussian double in Objective-C (the same asrandom.nextGaussianin Java). Howeverrand_gauss()doesn't seem to work. Anyone know a way of achieving this?
This linkshows how to calculate it using the standardrandom()function. I should note that you'll likely have to make theranf()routine that converts the output ofrandom()from[0,MAX_INT]to be from[0,1], but that shouldn't be too difficult. From the linked article: The polar form of the Box-Muller transformation is bo...
I have thisCmacro: ``` #define syscall(number) \ ({ \ asm volatile ( \ ".set noreorder\n" \ "nop\n" \ "syscall "#number"\n" \ );\ }) ``` It works great when I call it with integer: ``` syscall(5); ``` However when I do something like this: ``` #define SYSCALL_PUTC 5 syscall(SYSCA...
Usestringificationlike this: ``` #define xstr(s) str(s) #define str(s) #s #define syscall(number) \ ({ \ asm volatile ( \ ".set noreorder\n" \ "nop\n" \ "syscall "xstr(number)"\n" \ );\ }) ``` For more info on stringification, see this gcc page: http://gcc.gnu.org/onlinedocs/cpp/Stri...
I am writing a file watcher and stat for some reason cant get a hold of file information, why? ``` struct stat info; int fd = open(path, O_EVTONLY); if (fd <= 0){ exit(-1); } int result = fstat(fd, &info); if (!result){ exit(-1); //This happens! Errno says "No such file or directory" but that cant be because ...
``` int result = fstat(fd, &info); if (!result){ exit(-1); } ``` Checkfstatman page, on success 0 is returned.
I want to change owner and group of a file in C. I google it, but if find only some code that usesystem()andchmodcommand or relative functions. Is there a way to do this withoutsystem()functions and Bash commands?
To complete the answer, on Linux the following can be used (I've tested onUbuntu): ``` #include <sys/types.h> #include <pwd.h> #include <grp.h> void do_chown (const char *file_path, const char *user_name, const char *group_name) { uid_t uid; gid_t gid; struct pa...
``` A[10][10] B[10][10] ``` Inccan we use ``` A[5]=B[4]; ``` is this legal or we have to replace each element one by one?
With your definitions ofAandB, the assignmentA[5] = B[4];is illegal. You can easily replace each element one by one ``` for (size_t i = 0; i < 10; i++) A[5][i] = B[4][i]; ``` or, assuming the arrays are of the same base type, usememmove()(ormemcpy()because arrays do not overlap) ``` #include <string.h> memmove(A[5...
``` the_project.c:73:22: error: subscripted value is neither array nor pointer nor vector ``` it gives the error above and the line 73 is the following. ``` customer_table[my_id][3] = worker_no; ``` I declared the array global as follows ``` int *customer_table; //All the info about the customer ``` This line...
You're declaring apointer-to-int. Socutomer_table[x]is an int, not a pointer. If you need a two-dimensional, dynamically allocated array, you'll need a: ``` int **customer_table; ``` and you'll need to be very careful with the allocation. (See e.g.dynamic memory for 2D char arrayfor examples.)
I am writing a c application for decoding binary files and I need to be sure about the sizes of my chunks. Reading the documentation I understood that only the minimum size is stated while the maximum depends on the compiler or/and architecture... so could I do something like : ***PSEUDOCODE ``` unsigned char byte; ...
Use the typesintN_tanduintN_tfromstdint.hadded in C99 (common values forNare 8, 16, 32, 64). They're guaranteed to have fixed size.
I'm writing a command line game that should work at 4-40 FPS (will choose later). But, I have a problem. Drawing an "image" consisting of 1920 colored characters using putchar() takes 0.2-0.3 seconds, and I can see my image getting drawn line by line. However, for example, in Firefox, I can draw 64000 RGB pixels on ca...
Don't useputchar. Make a buffer full of your characters, representing the screen state, and usewriteto send your buffer all at once to stdout, then flush it. For example:write(STDOUT_FILENO, buffer, buffer_size); fflush(stdout);
Imagine there is a file of size 5 MB. I open it in write mode in C and then fill it up with junk data of exactly 5 MB. Will the same disk sectors previously used be overwritten or will the OS select new disk sectors for the new data?
It depends on the file system. Classically, the answer would be 'yes, the same sectors would be overwritten with the new data'. With journalled file systems, the answer might be different. With flash drive systems, the answer would almost certainly be 'no; new sectors will be written to avoid wearing out the curren...
``` the_project.c:73:22: error: subscripted value is neither array nor pointer nor vector ``` it gives the error above and the line 73 is the following. ``` customer_table[my_id][3] = worker_no; ``` I declared the array global as follows ``` int *customer_table; //All the info about the customer ``` This line...
You're declaring apointer-to-int. Socutomer_table[x]is an int, not a pointer. If you need a two-dimensional, dynamically allocated array, you'll need a: ``` int **customer_table; ``` and you'll need to be very careful with the allocation. (See e.g.dynamic memory for 2D char arrayfor examples.)
I am writing a c application for decoding binary files and I need to be sure about the sizes of my chunks. Reading the documentation I understood that only the minimum size is stated while the maximum depends on the compiler or/and architecture... so could I do something like : ***PSEUDOCODE ``` unsigned char byte; ...
Use the typesintN_tanduintN_tfromstdint.hadded in C99 (common values forNare 8, 16, 32, 64). They're guaranteed to have fixed size.
I'm writing a command line game that should work at 4-40 FPS (will choose later). But, I have a problem. Drawing an "image" consisting of 1920 colored characters using putchar() takes 0.2-0.3 seconds, and I can see my image getting drawn line by line. However, for example, in Firefox, I can draw 64000 RGB pixels on ca...
Don't useputchar. Make a buffer full of your characters, representing the screen state, and usewriteto send your buffer all at once to stdout, then flush it. For example:write(STDOUT_FILENO, buffer, buffer_size); fflush(stdout);
Imagine there is a file of size 5 MB. I open it in write mode in C and then fill it up with junk data of exactly 5 MB. Will the same disk sectors previously used be overwritten or will the OS select new disk sectors for the new data?
It depends on the file system. Classically, the answer would be 'yes, the same sectors would be overwritten with the new data'. With journalled file systems, the answer might be different. With flash drive systems, the answer would almost certainly be 'no; new sectors will be written to avoid wearing out the curren...