question
stringlengths
25
894
answer
stringlengths
4
863
I am just learning about Cygwin, and it appears to make possible to write C code against the UNIX API, and then have it run on Windows, provided you build it in the Cygwin environment. I have gotten accustomed to the Visual Studio IDE and debugging tools, so wanted to ask: is it somehow possible to write and build C ...
No, because the VS debugging tools (for the most part) depend heavily on it being compiled using the MS C compiler, rather than GCC. So if you manage to bootload it in, you won't get any of the more useful debugging features VS offers. The closest alternative to Visual Studio that supports GCC isEclipse.
Is there any WinAPI to get the selected text in an Edit Box? Take the initial and final position of the cursor? A function where I tell the HWND of editbox and the function return, the selected text?
I'm not aware of a single function that does this. Send theEM_GETSELmessage to an edit control to get the limits of the selection, e.g. ``` DWORD selStart; DWORD selEnd; SendMessage(hWndEdit, EM_GETSEL, &selStart, &selEnd); ``` UseWM_GETTEXTto retrieve all the text from the edit control, and extract the selected su...
In the program given below virtual address for both process is same. I understood the reason for global variables but could not understand for local variables. how is virtual addresses assigned to local variables before running? ``` int main() { int a; if (fork() == 0) { a = a + 5; printf(“%d,%d\n”,...
Virtual addresses are... virtual. That means a same virtual address from two different processes (like a parent process and its child process) points to two different physical addresses.
Consider the following: ``` struct Foo { char c; int i; }; void Bar(void) { struct Foo f = {0}; // use zero initializer // do some stuff f = (struct Foo) {'h', 1}; // copy different data into f, is this dangerous? } ``` Would the cast above be considered dangerous? Is this good style?
It's not a matter of style; that code won't compile without the(struct Foo). It's not a cast, it's part of the syntax for a C99 feature known as acompound literal.
There is the well-knownJoint Strike Fighter(JSF) standard for C++. Is there a similar standard for C which promotes the use of C programmers' quality when coding for mission-critical platform?
There isMISRA Cby the Motor Industry Software Reliability Association: MISRA-C:2004,Guidelines for the use of the C language in critical systems
I'm going to be straight here, I'm an absolute novice when it comes to C and I'm a bit out of my depth here and need a little help. I am tweaking some source code and need to reset some static globals so that they can be used again. I've tried all sorts of things which just end in bad access errors - any help would be...
``` memset(long_options, 0, sizeof(long_options)); memset(short_options, 0, sizeof(short_options)); memset(optmap, 0, sizeof(optmap)); ```
This code causes compilation error " error: redefinition of 'p' with a different type": ``` void fun() { printf("fun"); } void (*p)(); p = &fun; ``` But if modifyvoid (*p)(); p = &fun;tovoid (*p)() = &fun, everything is OK. What's the difference betweenvoid (*p)(); p = &fun;andvoid (*p)() = &fun?
You cannot perform arbitrary assignments in the global scope; try: ``` void fun() { printf("fun"); } void (*p)(); int main(void) { p = &fun; return 0; } ``` void (*p)() = &fun;works because you're creating and initializing a variable. Initialization is allowed in global scope.void (*p)(); p = &fun;creates an...
What is the meaning of the below code? I thought that it is compilation error. But no compilation error occurs. ``` int main() { const int a=1; printf("%c", ++a["Gyantonic"]); } ``` Output in Linux a is segmentation fault. It gives a compilation error ifa[1]is given in place of++a["Gyantonic"]. How does...
``` ++a["Gyantonic"] ``` is equivalent to: ``` ++(a["Gyantonic"]) ``` which is equivalent to ``` ++("Gyantonic"[a]) ``` equivalent to ``` ++("Gyantonic"[1]) ``` "Gyantonic"[1]yields'y'and the++increments the'y'stored in the string literal and yields the result. But"Gyantonic"is a string literal and string liter...
I am confused about working of the below statement: ``` *ptr++->str ``` First++operator is applied toptrwhich returns rvalue. Next operator is->has to be applied. Doesn't->operator require lvalue?
Doesnt->operator require lvalue? No. See section 6.5.2.3 of the C99 standard: The first operand of the->operator shall have type ‘‘pointer to qualified or unqualified structure’’ or ‘‘pointer to qualified or unqualified union’’, and the second operand shall name a member of the type pointed to....A postfix expr...
``` #include <stdio.h> #include <string.h> int main() { char tab[2]={"12"}; FILE *outfile; char *outname = "/home/dir/"; printf("%s", strcat(outname,tab)); outfile = fopen(strcat(outname,btab), "w"); if (!outfile) { printf("There was a problem opening %s for writing\n", outname); } } ``` I have thi...
At least two errors: ``` char tab[2] = {"12"}; ``` You'd better usetab[3]or even bettertab[]-- you need one extra char for the terminating NUL character. Also, ``` char *outname = "etc..."; ``` creates a constant string in the data segment of the executable -- it can't be overwritten, sincestrcatis using its firs...
How do I make something like this work? ``` void *memory = malloc(1000); //allocate a pool of memory *(memory+10) = 1; //set an integer value at byte 10 int i = *(memory+10); //read an integer value from the 10th byte ```
Easy example: treat the memory as an array of unsigned char ``` void *memory = malloc(1000); //allocate a pool of memory uint8_t *ptr = memory+10; *ptr = 1 //set an integer value at byte 10 uint8_t i = *ptr; //read an integer value from the 10th byte ``` You can use integers too, but then you must pay attention ...
I am trying to fit a curve to a number of pixels in an image so I can do further processing regarding it's shape. Does anyone know how to implement a least squares method in C/++ preferably using the following parameters: an x array, a y array, and an answers array (the length of the answers array should tell how many...
If this is not some exercise in implementing this yourself, I would suggest you use a ready-made library likeGNU gsl. Have a look at the functions whose names start withgsl_multifit_, see e.g. the second examplehere.
I'm trying to create a C program in the CodeBlocks IDE (on Windows), and something I need is the library . When I try and build and run, this line errors: ``` #include <sys/times.h> ``` What do I do? Is that a Unix library? Can I download it and just add it somehow to my CodeBlocks environment? I mean, is already t...
Remove -ansi compilation flag fromSettings>Compiler and Debugger>Compiler Optionsin Code::Blocks. If that does not help,<sys/times.h>is unavailable under Windows. Edit:sys/times.his a part of thePOSIXlibrary. POSIX headers are not available under MinGW, and need Cygwin.time.his a standard ANSI header. If you want to...
I'm using the following code to get the output up to 5 decimal characters of any number input by user when divided by 1, I have to typecast it with(float). Can any one tell me how this can be done without typecasting or using float constant? ``` int main() { int n; scanf("%d",&n); printf("%.5 ", 1/(float...
You canuse this piece of codethat uses only integers: ``` printf(n==1?"1.00000":"0.%05d ", 100000/n); ```
This question already has answers here:Closed11 years ago. Possible Duplicate:Why does modulus division (%) only work with integers? This code doesn't work in C and C++ but works in C# and Java: ``` float x = 3.4f % 1.1f; double x = 3.4 % 1.1; ``` Also, division remainder is defined for reals in Python. What is t...
The C committee explained its position of why there is no remainder operator for floating types in theRationaledocument: (6.5.5 Multiplicative operators)The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod (see §7.12.10.1).
``` #include <langinfo.h> #include <stdio.h> int main(int argc, char **argv){ char *firstDayAb; firstDayAb = nl_langinfo(ABDAY_1); printf("\nFirst day ab is %s\n", firstDayAb); return 0; } ``` This code works fine on Mac and Linux but it doesn't work on windows due to absence of langinfo.h. How to avoid using lang...
``` #include <stdio.h> #include <time.h> int main () { struct tm timeinfo = {0}; char buffer [80]; timeinfo.tm_wday = 1; strftime (buffer, 80, "First day ab is %a", &timeinfo); puts (buffer); return 0; } ```
I have a text field that is editable by the user and it contains some example text saying "Tap here to enter details". I would like the text box to clear when the user taps it so that the user does not have to delete my example before inputting their message. Is there an easy way of doing this. The only thing I can th...
There is a property for UITextFieldclearsOnBeginEditing
I have a file which will contains basic mathematical operations. An example: ``` 1 + 23 / 42 * 23 ``` I am scanning the file, putting each "element" into a struct and pushing it onto a stack I created. The problem I have is as follows: ``` char reading; while(!feof(fp)) { fscanf(fp, "%c", &reading); .... ``` T...
fscanfis the wrong tool for this job, because it needs a format string that knows in advance what format to expect. Your best bet is to read a character at a time and build up tokens that you can then interpret, especially if you'll have to accept input like2+2(no spaces), or(1 + 23) / 42, with parentheses.
I am just learning about Cygwin, and it appears to make possible to write C code against the UNIX API, and then have it run on Windows, provided you build it in the Cygwin environment. I have gotten accustomed to the Visual Studio IDE and debugging tools, so wanted to ask: is it somehow possible to write and build C ...
No, because the VS debugging tools (for the most part) depend heavily on it being compiled using the MS C compiler, rather than GCC. So if you manage to bootload it in, you won't get any of the more useful debugging features VS offers. The closest alternative to Visual Studio that supports GCC isEclipse.
Is there any WinAPI to get the selected text in an Edit Box? Take the initial and final position of the cursor? A function where I tell the HWND of editbox and the function return, the selected text?
I'm not aware of a single function that does this. Send theEM_GETSELmessage to an edit control to get the limits of the selection, e.g. ``` DWORD selStart; DWORD selEnd; SendMessage(hWndEdit, EM_GETSEL, &selStart, &selEnd); ``` UseWM_GETTEXTto retrieve all the text from the edit control, and extract the selected su...
In the program given below virtual address for both process is same. I understood the reason for global variables but could not understand for local variables. how is virtual addresses assigned to local variables before running? ``` int main() { int a; if (fork() == 0) { a = a + 5; printf(“%d,%d\n”,...
Virtual addresses are... virtual. That means a same virtual address from two different processes (like a parent process and its child process) points to two different physical addresses.
Let's say I have a very simple C file (called foo.c): ``` int main() { printf("foo"); return 0; } ``` Now I call gcc: ``` gcc foo.c ``` When I call gcc (with no options, as in the above example), what libraries are linked in by default and where are they located? (On Mac OS X 10.7)
The-voption togccwill cause it to dump information about the default options it will use including the library paths and default libraries and object files that will be linked in. If you give the-Wl,--verboseoption, gcc will pass the--verboseto the linker which will dump exactly where it's looking for libraries, incl...
I want to make a launcher for a c program I made and I want it to run in terminal. How would I do this? I don't even have the slightest idea
Just create a text file, save it to the Desktop as e.g.my_C_program.command(note the.commandsuffix), then in the text file you can put whatever terminal commands you like, e.g. ``` # run my_C_program my_C_program arg1 arg2 ``` Note: after saving the.commandfile you need to make sure it is executable: ``` $ chmod +x...
I'm recently read a paper calledExploiting the Hard-Working DWARFon Hackito Ergo Sum 2011. It contains the phrase "not a one-stop memory corruption". What is that?
It's not an exact term, but basically means something like directly overwriting a bookkeeping datastructure, such as the internal bookkeeping ofmalloc. "Not a one-stop memory corruption" would be an indirect corruption. This corruption will then cause a later innocent operation to corrupt memory. In this particular c...
I'm creating windows for debugging like this: ``` cvNamedWindow("a",0); cvShowImage("a", imageA); cvNamedWindow("b",0); cvShowImage("b", imageB); cvNamedWindow("c",0); cvShowImage("c", imageC); ``` OpenCV creates all these windows in the exact same spot, which is not very practical, since only one of them is visible...
No, this is impossible - there's no such feature inUser Interface(I also was wondering about such functionality a month ago). You have to manualy set window(s) position by callingMoveWindow- this is the only solution.
This question already has answers here:Closed11 years ago. Possible Duplicate:Which compiler does Android NDK use? I am wondering if it is possible to compile a Native Android Application through GCC. Is this even possible? o.O
It is possible in principle, but Android is designed to run on many mobile platforms, while gcc will target only one of them at a time. The application therefore will not be portable, and it will be closer to truth to say that it runs on ARM Linux (for example) than that it runs on Android. There is additional detai...
I saw a buggy code in C which was used to check whether addition results in overflow or not. It works fine withchar, but gives incorrect answer when arguments areintand I couldn't figure why .Here's the code withshortarguments. ``` short add_ok( short x, short y ){ short sum = x+y; return (sum-x==y) && (sum-y...
Because in 2s complement, the integers can be arranged into a circle (in the sense ofmodulo arithmetic). Adding y and then subtracting y always gets you back where you started (undefined behaviour notwithstanding).
I need to convert a char * string of 3 characters ("123") to a float with two decimal places(1.23).
You can use atoi, which will convert ASCII to Integer. Then convert that int to a float. ``` int num = atoi(string); float f = num/100.0f; printf ("%.2f", f); ```
I have searched this up rather a lot, but come up with no helpful results. I am currently trying to program simple DirextX game for Windows 8 Metro, and have come across_In_rather a lot. I'm just wondering what it is. Also, I have seen a lot of the use of^as the pointer*which I found odd. On top of this, some classe...
It is aSAL annotation, used for code analysis. The annotations themselves are defined as macros that, in normal builds, expand to nothing. The^andref classare features ofC++/CX, a set of language extensions developed to make it easier to build Metro style apps for Windows 8 in C++. Neither is a part of standard C++...
I'm having some trouble with C standard functions. As an example, I'm getting that error in the memcpy function, even passing the right arguments to it. I've included a header as #include "header.h", and I've included , and so in the "header.h" file. (I'm also getting this error with strcpy, strtok, and some other s...
It seems it was some trouble within eclipse. I right clicked one of those functions, selected Source->Add includes and it solved the problem (but didn't added any header). I hope this can be helpful for someone else
When I try to usereallocto allocate memory for a pointer which has beenfree'd, I get a segmentation fault. Although I don't face this issue if I usemallocinstead. As per my understanding after the variable has beenfree'd it is equivalent to aNULLpointer, then why is this unexpected behavior? Am I missing something?
As per my understanding after the variable has been free'd it is equivalent to a NULL pointer. ANULLpointer is a pointer whose value isNULL; standard functions likereallocknow how to interpret this value. A pointer to some memory that has been freed is now an invalid pointer; its value doesn't change.reallocdoesn't ...
I have a list of server ports in an ini file. to get these and load them into a list I use a for loop. How can i use a variable to get this to work. ``` ServerAmount = 8; int z; ServerPort[]; for ( z = 0; z < ServerAmount; z++ ) { if(getenv('SERVERPORT[z]') != NULL) { ServerPort[z] = getenv('SERVERPORT[z]')...
You should usesprintf, let me know if this works for you: ``` ServerAmount = 8; int z; ServerPort[]; for ( z = 0; z < ServerAmount; z++ ) { char tmp[20]; sprintf(tmp, "SERVERPORT[%i]", z); if(getenv(tmp) != NULL) { ServerPort[z] = getenv(tmp); } } ``` EDIT: By the way,ServerPort[]is not valid. You pr...
I have a problem where I have a pointer to an area in memory. I would like to use this pointer to create an integer array. Essentially this is what I have, a pointer to a memory address of size 100*300*2 = 60000 bytes ``` unsigned char *ptr = 0x00000000; // fictional point in memory goes up to 0x0000EA60 ``` What i...
You can cast the pointer tounsigned int (*)[150]. It can then be usedas ifit is a 2D array ("as if", since behavior ofsizeofis different). ``` unsigned int (*array)[150] = (unsigned int (*)[150]) ptr; ```
This question already has answers here:Closed11 years ago. Possible Duplicate:Set all bytes of int to (unsigned char)0, guaranteed to represent zero? I have the following anonymous union inside a struct: ``` union { unsigned value; char name[4]; }; ``` Can I replace the following code: ``` name[0] = 0; na...
In your simple case it's the same, but only because (most likely)int(andunsignedis short forunsigned int) is 32 bits (i.e. four bytes). If the array is larger, orintis only 16 bits it will not be the same.
I'm installing my driver using dpinst.exe. But before installing my driver I wish to delete all the oem files from inf directory corresponding to my hardware ID. I want to do this programatically. Please suggest me a way to do this. ``` **Update :** ``` I want to do this without device connected as I may pre-instal...
UseSetupDiEnumDeviceInfoandSetupDiGetDeviceRegistryPropertyto match your hardware IDUseSetupDiOpenDevRegKeyandRegQueryValueExto read the correspondingInfPathCallSetupUninstallOEMInf
``` const char *str = "wlan subtype assoc-req or wlan subtype probe-req or wlan subtype probe-resp"; struct bpf_program fp; if((pcap_compile(pkt_handle, &fp, str, 1, PCAP_NETMASK_UNKNOWN)==-1)) { pcap_perror(pkt_handle, "Compile"); } else printf("filter compiled\n"); ``` After running, the program displays "...
As interjay said, you have to callpcap_setfilter()to make the filter take effect. (Making it an answer so that the question shows up ashavingan answer.)
I have a gtk program in which I am calling a gdk function. I am compiling the program using: ``` gcc `pkg-config --cflags --libs gtk+-2.0 cairo glib-2.0` ... ``` and I have included ``` #include <gdk/gdk.h> ``` it gives me the error: ``` undefined reference to `gdk_device_ungrab' ``` Does anyone know what I am d...
You are compiling and linking against gtk 2.x andgdk_device_ungrabis available only starting from gtk 3.0. See:http://developer.gnome.org/gdk3/3.4/GdkDevice.html#gdk-device-ungrab
How do I get the property of a variable? Example: ``` int a = 5; .... .... isConstant(a); //Prints "no!" if 'a' is not a constant at this time. isRegister(a); //Prints "yes!" if 'a' is a register at this time.important. isVolatile(a); //Prints "trusted" if 'a' is volatile. isLocal(a); //If it is temporary. isStat...
I'm pretty sure you can use template metaprogramming forconstandvolatile. IDK aboutregisterand I'm pretty sure you can't forstaticor local scoped variables. In C++11 you have, for example: ``` #include <iostream> #include <type_traits> int main() { std::cout << boolalpha; std::cout << std::is_const<int>::v...
This question already has answers here:Closed11 years ago. Possible Duplicate:Why are Hexadecimal Prefixed as 0x? Memory addresses are often notated as a hexidecimal value prefixed with0x. E.g: ``` > new.env() <environment: 0x21d36e0> ``` Does the0xpart mean anything? Where does this notation come from? Is any oth...
The0xis just a notation to let you know the number is in hexadecimal form. Same as you'd write042for an octal number, or42for a decimal one. So -42 == 052 == 0x2A.
I tried pointers and reference(&) but when I try to get the info(I am only reading from memory) computer "beeps" and program terminates. NO problem when assigning a pointer to a byte (char *). But when I read that computer beeps. ( x=*p;) Windows xp, 1GB + 128 MB RAM. I don't know about my eproom + eeproms. Can I us...
You can't. Modern OSes use virtual mode and memory protection which don't permit this. To access all physical RAM, you'll most likely need to write your own OS or a kernel driver for an existing OS.
I want to use hash tables in my c program. I code: ``` ... #include <glib.h> void main(int argc, char **argv) { GHashTable *g_hash_table; ... g_hash_table = g_hash_table_new(g_int_hash, g_int_equal); ... } ``` Then I compile: ``` $ gcc -I/usr/include/glib-2.0 -I/usr/lib/i386-linux-gnu/glib-2.0/include -lg...
You need to specify libraries in the command lineafterthe source and object files that use them: ``` gcc test.c `pkg-config --cflags --libs glib-2.0` -o test ```
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...
cpis part ofcoreutils. There are also different implementations, for examplebusybox. It's very strange that there is nocpon android. Have you looked thoroughly?
``` %{ #ifdef abc . . . // C declarations . %} . . // Yacc Declaration . %% . . //expected inputs and corresponding actins . %% #endif ``` Although this code compiles for me even then I strongly feel#ifdef abcis not placed correctly. Is this type of code valid for Yacc. I have very little experience in YACC. Than...
The code between%{and%}is put verbatim at the top of the generated C source file, while the code after the rules is also put verbatim but at the end of the generated file. So the answer to your question is: Yes, it's correct in both Yacc and the generated source. However, from a readability point of view, the Yacc-co...
I'm recently read a paper calledExploiting the Hard-Working DWARFon Hackito Ergo Sum 2011. It contains the phrase "not a one-stop memory corruption". What is that?
It's not an exact term, but basically means something like directly overwriting a bookkeeping datastructure, such as the internal bookkeeping ofmalloc. "Not a one-stop memory corruption" would be an indirect corruption. This corruption will then cause a later innocent operation to corrupt memory. In this particular c...
I'm creating windows for debugging like this: ``` cvNamedWindow("a",0); cvShowImage("a", imageA); cvNamedWindow("b",0); cvShowImage("b", imageB); cvNamedWindow("c",0); cvShowImage("c", imageC); ``` OpenCV creates all these windows in the exact same spot, which is not very practical, since only one of them is visible...
No, this is impossible - there's no such feature inUser Interface(I also was wondering about such functionality a month ago). You have to manualy set window(s) position by callingMoveWindow- this is the only solution.
This question already has answers here:Closed11 years ago. Possible Duplicate:Which compiler does Android NDK use? I am wondering if it is possible to compile a Native Android Application through GCC. Is this even possible? o.O
It is possible in principle, but Android is designed to run on many mobile platforms, while gcc will target only one of them at a time. The application therefore will not be portable, and it will be closer to truth to say that it runs on ARM Linux (for example) than that it runs on Android. There is additional detai...
I saw a buggy code in C which was used to check whether addition results in overflow or not. It works fine withchar, but gives incorrect answer when arguments areintand I couldn't figure why .Here's the code withshortarguments. ``` short add_ok( short x, short y ){ short sum = x+y; return (sum-x==y) && (sum-y...
Because in 2s complement, the integers can be arranged into a circle (in the sense ofmodulo arithmetic). Adding y and then subtracting y always gets you back where you started (undefined behaviour notwithstanding).
I need to convert a char * string of 3 characters ("123") to a float with two decimal places(1.23).
You can use atoi, which will convert ASCII to Integer. Then convert that int to a float. ``` int num = atoi(string); float f = num/100.0f; printf ("%.2f", f); ```
I have searched this up rather a lot, but come up with no helpful results. I am currently trying to program simple DirextX game for Windows 8 Metro, and have come across_In_rather a lot. I'm just wondering what it is. Also, I have seen a lot of the use of^as the pointer*which I found odd. On top of this, some classe...
It is aSAL annotation, used for code analysis. The annotations themselves are defined as macros that, in normal builds, expand to nothing. The^andref classare features ofC++/CX, a set of language extensions developed to make it easier to build Metro style apps for Windows 8 in C++. Neither is a part of standard C++...
I'm having some trouble with C standard functions. As an example, I'm getting that error in the memcpy function, even passing the right arguments to it. I've included a header as #include "header.h", and I've included , and so in the "header.h" file. (I'm also getting this error with strcpy, strtok, and some other s...
It seems it was some trouble within eclipse. I right clicked one of those functions, selected Source->Add includes and it solved the problem (but didn't added any header). I hope this can be helpful for someone else
When I try to usereallocto allocate memory for a pointer which has beenfree'd, I get a segmentation fault. Although I don't face this issue if I usemallocinstead. As per my understanding after the variable has beenfree'd it is equivalent to aNULLpointer, then why is this unexpected behavior? Am I missing something?
As per my understanding after the variable has been free'd it is equivalent to a NULL pointer. ANULLpointer is a pointer whose value isNULL; standard functions likereallocknow how to interpret this value. A pointer to some memory that has been freed is now an invalid pointer; its value doesn't change.reallocdoesn't ...
I have a list of server ports in an ini file. to get these and load them into a list I use a for loop. How can i use a variable to get this to work. ``` ServerAmount = 8; int z; ServerPort[]; for ( z = 0; z < ServerAmount; z++ ) { if(getenv('SERVERPORT[z]') != NULL) { ServerPort[z] = getenv('SERVERPORT[z]')...
You should usesprintf, let me know if this works for you: ``` ServerAmount = 8; int z; ServerPort[]; for ( z = 0; z < ServerAmount; z++ ) { char tmp[20]; sprintf(tmp, "SERVERPORT[%i]", z); if(getenv(tmp) != NULL) { ServerPort[z] = getenv(tmp); } } ``` EDIT: By the way,ServerPort[]is not valid. You pr...
I have a problem where I have a pointer to an area in memory. I would like to use this pointer to create an integer array. Essentially this is what I have, a pointer to a memory address of size 100*300*2 = 60000 bytes ``` unsigned char *ptr = 0x00000000; // fictional point in memory goes up to 0x0000EA60 ``` What i...
You can cast the pointer tounsigned int (*)[150]. It can then be usedas ifit is a 2D array ("as if", since behavior ofsizeofis different). ``` unsigned int (*array)[150] = (unsigned int (*)[150]) ptr; ```
What is the difference between the following two assignments? ``` int main() { int a=10; int* p= &a; int* q = (int*)p; <------------------------- int* r = (int*)&p; <------------------------- } ``` I am very much confused about the behavior of the two declarations.When should i use one over the oth...
``` int* q = (int*)p; ``` Is correct, albeit too verbose.int* q = pis sufficient. Bothqandpareintpointers. ``` int* r = (int*)&p; ``` Is incorrect (logically, although it might compile), since&pis anint**butris aint*. I can't think of a situation where you'd want this.
This question already has answers here:Closed11 years ago. Possible Duplicate:How to assign to the nsstring object a NSString with variables? When I try to display that nsstring object, I get this: TOTAL OF TIME: l Instead of that I want to get: 02:35 How to do that ? Thank you! ``` allTime = [NSString stringWit...
Assumingminsandsecsare integers: ``` allTime = [NSString stringWithFormat:@"%02i:%02i", mins, secs]; ``` If you want more information search theString format specifiers
Some lines of a text file contain a line which starts with an open square bracket, has a variable number of characters followed by a close square bracket and then some further text For example: ``` [ABC] why is the sky green? [DEFG] Ou sont les Niegedens d'antan? [I can't code C] (... obviously) ``` How do...
The simplest method would probably be a scanset conversion: ``` char line[256]; while (fgets(line, sizeof(line), stdin)) { char string[256]; sscanf(line, "[%255[^]]", string); printf("%s\n", string); } ```
I cannot figure out which way it goes. It seems like casting it into an int would make more sense because of the whole float point issue but like I said, I am not sure. Does anyone know?
Try this code: ``` #include <stdio.h> int main(void) { if (100.1 == 100) printf("Must be integer compare\n"); else printf("Must be floating point compare\n"); return 0; } ``` Also, think about things likeint i = 10; float j = 100.5 + i;or100.2 == 100. You don't want it to be done with in...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Matrix multiplication is a fairly good starting point. It is parallelizable and also requires some synchronization for the reduction step.
I have the following code: ``` long mins = 02; long secs = 35; NSString *allTime = [[NSString alloc]init]; allTime = @"%i:%i",mins, secs ; ``` But it doesn't work, because when I try to display that nsstring object I got this: %i:%i Instead of that I want to get: 02:35 How to do that ? Thank you! ``` allTim...
You need to usestringWithFormat, see theNSString Class Reference. ``` allTime = [NSString stringWithFormat:@"%d:%d",mins, secs]; ```
devkitprohas been pretty great for development so far. However, I was wondering if there were any other libraries, either independent or based on devkitpro, that would incorporate other languages for me to explore Thanks in advance!
wii.py: Python extension for Wii. Unfortunately lacking sufficient documentation (like most open-source community projects), but still functional nonetheless. Reference:https://github.com/icefire/Wii.py luafwii: Lua player for Wii. Since it's Lua, this is best suited for projects that involve a C base but incorporat...
In Russia the first day of the week is Monday. In the United States - Sunday. On Linuxnl_langinfo(_NL_TIME_FIRST_WEEKDAY)return 0 for Sun or 1 for Mon. How do I get too in MacOS X with c-code?
I haven't tried it myself, but from skimming the docs, you can get aCFLocaleinstance (reference) and get it'sCFCalendarinstance using: ``` CFLocaleGetValue(locale, kCFLocaleCalendar) ``` And get the first day of the week from theCFCalendarinstance usingCFCalendarGetFirstWeekday()(reference).
I am simply trying to make the text bold in aGtkLabel. All I can find are examples for Python and C#. Here is how I currently set upGtkLabels, but I don't know how to make them render the text in bold. ``` GtkWidget* label = gtk_label_new("Text I want to be bold"); ```
A simple way is to callgtk_label_set_markup(), which accepts a string ofPango markup: ``` GtkWidget *label = gtk_label_new(NULL); gtk_label_set_markup(GTK_LABEL(label), "<b>Text to be bold</b>"); ```
I know that to convert any given char to int, this code is possible [apart from atoi()]: ``` int i = '2' - '0'; ``` but I never understood how it worked, what is significance of '0' and I don't seem to find any explanation on the net about that. Thanks in advance!!
In C, a character literal has typeint. [Character Literals/IBM] In your example, the numeric value of'0'is 48, the numeric value of'2'is 50. When you do'2' - '0'you get50 - 48 = 2. This works for ASCII numbers from 0 to 9. SeeASCII tableto get a better picture. Edit:Thanks to @ouah for correction.
I'm trying to understand this code: ``` inline SInt32 smul32by16(SInt32 i32, SInt16 i16) { register SInt32 r; asm volatile("smulwb %0, %1, %2" : "=r"(r) : "r"(i32), "r"(i16)); return r; } ``` Does anybody know what this assembly instruction does? Update:P.S. I use objective C. and I should understand so...
It does signed 32 bit by signed 16 bit multiplication and returns the top 32 bit of 48 bit result. The b specifies to use the bottom 16bit of the third operand. So, translating it into pseudo code: ``` int_48 temp; temp = i32*i16; result = temp >> 16; ```
One of my stand-alone java applications (no sources available) picks random-available port to listen on.At this stage I assume it usesgetaddrinfosystem call to obtain addresses to bind against. Since I'm maintaining hundreds of various servers with assigned ports, the black app sometimes kicks in and pick one of 'the...
You must be able to control it from proc entries - For example, here is a system wide setting : /proc/sys/net/ipv4/ip_local_port_range You can modify them. Or there may beutilitiesavailable for the same purpose.
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. I have one question, I need extract...
Try MiniZiphttp://www.winimage.com/zLibDll/minizip.html Then using the unzGoToFirstFile and unzGoToNextFile you move in the files inside the zip, use the unzGetCurrentFileInfo to obtain the path of the files, if it's the folder you want, unzip it.
Once i use ``` setlocale(LC_ALL, ""); //use system locale ``` printf function does not align right. How do i align string in differnet locales?
Field widths cannot be used for alignment on modern multilingualized systems. Even ifprintfcould count characters instead of bytes when aligning (note: the wideprintf-family functions can do this), that will fail to accommodate for combining characters (which usually use no horizontal space) as well as CJK-wide charac...
I'm trying to create a dynamic printf size for a lcd but it outputs only f= what do i do wrong? ``` sprintf(buffer, "f=%.2f", (d = d + 0.01)); <-- works but not dynamic sprintf(buffer, "f=%.*f", 2 , (d = d + 0.01)); <-- Does not any give warning lcd_puts(buffer); _delay_ms(100); ```
Possibly you need this: ``` char format[10]; int len1 = 5, len2 = 2; sprintf(format, "f=%%%d.%df", len1, len2); sprintf(buffer, format , (d = d + 0.01)); ```
I want to initalize a 3 x 3 matrix with first two rows as 0's and last row as 1's. I have declared a 2D arrayint matrix[3][3] I want to initialize it without using loops as shown below 0 0 00 0 01 1 1 I would also like a solution for N dimiensional array
``` int matrix[3][3] = { { 0, 0, 0 }, { 0, 0, 0 }, { 1, 1, 1 } }; ``` Or, the more compact: ``` int matrix[3][3] = { [2] = { 1, 1, 1 } }; ``` The solution generalizes forNso long asNis fixed. IfNis large, you can use mouviciel's answer tothis question.
``` #include <stdio.h> int main() { int *a[2]; // an array of 2 int pointers int (*b)[2]; // pointer to an array of 2 int (invalid until assigned) // int c[2] = {1, 2}; // like b, but statically allocated printf("size of int %ld\n", sizeof(int)); printf("size of array of 2 (int *) a=%ld\n", s...
You're probably compiling on a 64-bit machine where pointers are 8 bytes. int *a[2]is an array of 2 pointers. Thereforesizeof(a)is returning 16.(So it has nothing to do with the size of anint.) If you compiled this for 32-bit, you'll mostly getsizeof(a) == 8instead.
I am given an amount say $50. I am given some denominations say $1 ,$2 ,$5 etc. and the number of these denominations eg 1 ,5,6 that means 1 coin/note of $1 ,5 coins/notes of $2 and 6 coins/notes of $5. I have to find the number of ways these coins can be used to form this amount $50. I am trying to think an efficien...
I agree that this is not the place for homework, but still... The asker does not expect to get solution, he is only asking for a direction. let's not keep questions open unecessarily Have a look atInteger factorization
This question already has answers here:Closed11 years ago. Possible Duplicate:How to assign to the nsstring object a NSString with variables? When I try to display that nsstring object, I get this: TOTAL OF TIME: l Instead of that I want to get: 02:35 How to do that ? Thank you! ``` allTime = [NSString stringWit...
Assumingminsandsecsare integers: ``` allTime = [NSString stringWithFormat:@"%02i:%02i", mins, secs]; ``` If you want more information search theString format specifiers
Some lines of a text file contain a line which starts with an open square bracket, has a variable number of characters followed by a close square bracket and then some further text For example: ``` [ABC] why is the sky green? [DEFG] Ou sont les Niegedens d'antan? [I can't code C] (... obviously) ``` How do...
The simplest method would probably be a scanset conversion: ``` char line[256]; while (fgets(line, sizeof(line), stdin)) { char string[256]; sscanf(line, "[%255[^]]", string); printf("%s\n", string); } ```
I cannot figure out which way it goes. It seems like casting it into an int would make more sense because of the whole float point issue but like I said, I am not sure. Does anyone know?
Try this code: ``` #include <stdio.h> int main(void) { if (100.1 == 100) printf("Must be integer compare\n"); else printf("Must be floating point compare\n"); return 0; } ``` Also, think about things likeint i = 10; float j = 100.5 + i;or100.2 == 100. You don't want it to be done with in...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Matrix multiplication is a fairly good starting point. It is parallelizable and also requires some synchronization for the reduction step.
I have the following code: ``` long mins = 02; long secs = 35; NSString *allTime = [[NSString alloc]init]; allTime = @"%i:%i",mins, secs ; ``` But it doesn't work, because when I try to display that nsstring object I got this: %i:%i Instead of that I want to get: 02:35 How to do that ? Thank you! ``` allTim...
You need to usestringWithFormat, see theNSString Class Reference. ``` allTime = [NSString stringWithFormat:@"%d:%d",mins, secs]; ```
devkitprohas been pretty great for development so far. However, I was wondering if there were any other libraries, either independent or based on devkitpro, that would incorporate other languages for me to explore Thanks in advance!
wii.py: Python extension for Wii. Unfortunately lacking sufficient documentation (like most open-source community projects), but still functional nonetheless. Reference:https://github.com/icefire/Wii.py luafwii: Lua player for Wii. Since it's Lua, this is best suited for projects that involve a C base but incorporat...
I am going to be pretty vague about this and I am sorry. This is homework assignment I am trying to learn something so don't really want the answer but rather an explanation. The question is ``` What is the datatype of thisThing ``` This is not the actual code but a similar example ``` int* (*thisThing[])(int*, int...
the "datatype" of thisThing is simply an int It's actually an array of function pointers where the pointed-to functions are: ``` int *fun(int *, int *); ``` You should look into thespiral rule.
I'm trying to update an older project using a newer compiler and newer tools (New version of vxWorks but it shouldn't matter). In the code it says: ``` #include <ostream.h> ``` However I get a ton of errors back, most of them stemming from: ``` ostream.h: No such file or directory ``` I looked up the error and a l...
Well, you could create a file namedostream.hwhich consists only of a single line: ``` #include <ostream> ```
I have a basic program in C that I wish to convert to the language brainfsck but cannot find anything on the subject. I find many "brainfuck to C" converters but not the other way around. I found C2BF but do not understand how to use it or if that's what I need.
C2BFis a C program that is distributed as C source code. To build the C2BF you needsvn,Gnu Makeand yacc and flex to be installed. After you have compiled C2BF yourself it should do exactly what you expect it to. If you are using some kind of Linux flavour: ``` cd ${HOME} svn co https://c2bf.svn.sourceforge.net/svnr...
I have the following struct: ``` struct elem { int number; char character; }; struct item { struct elem element; }; ``` and the following function: ``` void init(struct item *wrapper) { assert(wrapper != NULL); wrapper->element = NULL; } ``` item->element = NULLyields aincompatible types in assignment. ...
In CNULLis generally defined as the following ``` #define NULL ((void*)0) ``` This means that it's a pointer value. In this case your attempting to assign a pointer (NULL) to a non-pointer valueitem::elementand getting the appropriate message. It seems like your intent is to haveelementbe a pointer here so try the...
I want to have a function in C language file which can return string as output and I want to access that function from Managed Code i.e C# and get that string as return value. Any help or links related to this would be great for me.
Is this a method in a common library, or a custom library? The more common ones can be found onpinvoke.net. If not, MSDN has an article onPlatform InvokingusingDllImportthat may be useful.
I have an idea to create scripting language which will make people to program easier doing a lot of macros, functions, simpler function names everything more simpler for simple person to work with. That code (custom scripting language) then should be translated to simple C language things. Like so: ``` Scripting: IO[...
Thanks to PyPy, it is possible to translate a subset of Python code into c. For further details, see the following reference :http://doc.pypy.org/en/latest/translation.html See also the following question, which is basically your question specifying Python as the scripting language :Use Cython as Python to C Convert...
This question already has answers here:Closed11 years ago. Possible Duplicate:How to find the kth largest element in an unsorted array of length n in O(n)? The number of elements can vary from 1 to 10 million .Which is the fastest selection algorithm available for this purpose? Please note I think data structures li...
Aselection algorithmcan run in O(N) time. The most general way is to make a pass through the array, keep the K largest numbers you've seen so far. Return the last element of that list. As @ChrisA points out in the commentsstd::nth_element(documentedhere) is the quickest way to use this approach. If you always want...
can we pass enum as an array or pointer. I heard this type of question somewhere in internet. so I want to check what is that mean. how can we do that? example?
Just like any other array: ``` #include <stdio.h> enum colour { WHITE, RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET, BLACK }; char *colour_names[] = { "WHITE", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "INDIGO", "VIOLET", "BLACK" }; void...
I need to develop a test program, which sends and recieves data from terminal to the serial port.In order to do that I want to create virtual device file and work with it. I did that by using command: mknod -m 666 ttyS32 c 4, 500 The device file was successfully created, however I can't write data to it. Both progra...
That's right. You can write to the serial device usingecho. Are you sure that the device (not the device file) exists and is properly handled by the driver?
This question already has answers here:Closed11 years ago. Possible Duplicate:How to understand complicated function declarations? Consider: ``` char (*(*x())[5])() ``` How do I dissect this expression? I think it is a function which return an array of size 5, whose members are pointers to function which receive ...
Search for "Right-left rule" In your case, it should be: ``` x : x is a x() : function *x() : returning pointer to (*x())[5] : a 5-element array of *(*x())[5] : pointer to (*(*x())[5])() : function char (*(*x())[5])() : returning char ```
Suppose I have a variable, that stores the callback. ``` void* (*function)(int, double); ``` Now I would like to create a function, that will return this callback. I do not want the user to access the callback directly but by a function. This doesn't work: ``` void* (*)(int, double) getCallback(); ``` My question ...
typedefthe callback type: ``` typedef void* (*pf)(int, double); pf getCallback(); ``` This will also make sure that there are no mistakes from manually typing the wrong signature and such.
I currently have a C Shell with a native browser (IE) Embedded Can i anyhow use WPF /WCF in this ? I am talking total Client Side not a launcher app ? Wanted something cool and Jazzy with respect to UI
A dotnet desktop application is always preferred for WPF and WCF. This can be done using C But it will be too much code and without any guarantee if the code will properly function or not. So best is to create the dotnet application rather than C Application.
I have a C program that detects keyboard events, but I need to know the best technique to implement an input buffer and a simplegetchfunction to retrieve the oldest character in the buffer.
One way is to use acircular buffer. You create a fixed sized array and have two indices, a read index and a write index. Each time a keyboard event fires, you place the value at the write index and increment. When thegetchfunction is called, you read from the read index and increment it. If either index goes over ...
I'm trying to use this function to compare two strings, case insensitively. ``` int strcasecmp(const char *x1, const char *x2); ``` I have the copy piece correct, yet the case sensitive portion is giving me some trouble as const is a constant, thus read only, making these fail: ``` *x1 = (tolower(*x1)); // toupper ...
You could use a temporary char variable: ``` char c1 = tolower(*x1); char c2 = tolower(*x2); if (c1 == c2) ... ```
In my codeopen()fails with a return code of -1 but somehowerrnois not getting set. ``` int fd; int errno=0; fd = open("/dev/tty0", O_RDWR | O_SYNC); printf("errno is %d and fd is %d",errno,fd); ``` output is ``` errno is 0 and fd is -1 ``` Why is errno not being set? How can i determine whyopen()fails?
int errno=0; The problem is you redeclarederrno, thereby shadowing the global symbol (which need not even be a plain variable). The effect is thatwhatopensets and what you're printing are different things. Instead you should include the standarderrno.h.
Code Snippet: ``` target_test : test.cc $(CXX) $(CPPFLAGS) $(CFLAGS) test.cc ``` I know thatCXXis a variable (containing the compiler command to call), but I was wondering where this variable comes from. The variable is not defined in the makefile and is not an environment variable. Can anyone explain where the...
Make has severalpredefined variablesamong which isCC. Initially, it is set atccwhich is a symlink to the installed C compiler: ``` $ readlink -f `which cc` /usr/bin/gcc-4.6 ``` Also: ``` $ readlink -f `which c++` /usr/bin/g++-4.6 ``` You can change it if you want. You can usemake -p -f /dev/nullto get a list of a...
This question already has answers here:Closed11 years ago. Possible Duplicate:Is there an interpreter for C? I want to practice C a bit and I would like to have something that allows to write and test C code quickly. I want to have an interpreter with UI where I can write my code and execute it. Are there any good ...
The closest solution to what you are looking for seems to be theC shell (CSH)orC Scripting Language (CSL). Alternatively, have an editor open where you will write your C sample, then have console window where you will execute your favourite C compiler. The idea is to have simple workflow like this: ``` $ gvim test.c...
This question's accepted answer shows how to set a bit in c:How do you set, clear, and toggle a single bit? But it is not really said what 'x' is. Is it counted from left to right or right to left ? Isn't that platform dependent anyway ?
The C standard doesn't say how you number the bits you shift. It says that a value will be twice as large for each position you shift it. The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 x 2E2, [...]. On most cur...
Why is that even if enter value 999999, it will always go to else statement? Can someone explain why and what is the correct way to do this? ``` #include <stdio.h> int main(int argc, char **args) { double dValue = 0; scanf("%d",&dValue); if(10000 < dValue){ printf("More than"); } else {...
If you're intending to read in the value as an integer (using"%d"), then you should declare it to be anint. If you're intending to read in the value as adouble, then you should instead use"%lf"as your scanf format specifier.
``` void foo(const gchar *a, ...) { do_something(); } ``` What does the...mean? Does it only work with glib?
It isvariable-length argument listwhich allows a function to have flexible number of arguments. It's part of the Standard. So it works everywhere that standard C is supported (or this feature itself is supported), not just glib.
I am new to C and im trying to work with Global variables i ran this program and all get as output is "Hey there" Which is the first part of the program. The second part doesn't get displayed. Here's the code. ``` char count[20]="Hey there"; char dig[7]="pooop"; main() { puts(count); return(0); } hey() { ...
You need to call the second functionhey()before you can get its output. E.g., inmain() ``` { puts(count); hey(); return 0; } ``` where exactly you put the call tohey()inmain()is up to you (it needs to be before thereturnstatement though).
When I took a class on ANSI-C in my university, I was taught a method to shorten a lot of repeating code. Basically, it's a declaration at the start using the # sign that you can use to assign a name and the code it should replace. Can anyone help me remember what this method was called, and it is possible to implemen...
You're probably thinking ofmacros. For example: ``` #define INCREMENT(x) x++ ``` However, macros are literally expanded to- meaning unless they're aggressively parenthesised, they can produce unexpected behaviour.
Consider these twoCfunctions with different headers but the same body differing only in how they return their results (via stack or pointer):T f1(int x)andvoid f2(int x, T *ret)wheresizeof(T) >= 16. Is there any performance penalty when callingf1over callingf2or the compiler likegcc -O2optimizes both calls into the si...
There would be a performance penalty from what I see. For f1, the function is going to have to create a object of type T, and then it's returning a copy of that since you didn't specify that it should be returned from reference or pointer (but then the function would have to allocate memory for it). But as for f2, yo...