question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Closed12 years ago. Possible Duplicate:Why there is not a comprehensive c archive network? Like Python has a Cheeseshop and Perl has CPAN? Google results have a lot of C++ results and I am looking for purely C libraries. PS: Looking for *nix libraries
Yep. SourceForge, Codeplex, Github, and Google. Also, your distro's packages, if you are on Linux.
whysizeof("")is equivalent to 1 andsizeof(NULL)is equivalent to 4 in c-language ?
A string literal is anarrayof characters* (with static storage), which contains all the characters in the literal along with a terminator. The size of an array is the size of the element multiplied by the number of elements in the array. The literal""is an array that consists of onecharwith the value0. The type ischar[1], andsizeof(char)is always one; thereforesizeof(char[1])is always one. In C,NULLis implementation-defined, and is often((void*)0). The size of avoid*,on your particular implementation, is 4. It may be a different number depending on the platform you run on.NULLmay also expand to an integer of some type of the value 0, and you'd get the size of that instead. *A literal is not a pointer, arrays are not pointers, pointers do not play a role in this part of the question.
How safe would be to do something like: ``` if (flag_val != NULL && strcmp (val, flag_val) == 0) { // something } else { // something else } ``` Knowing that sometimesflag_valwill beNULLand sometimes not. I know it will check first ifflag_val != NULL, if it evaluates false, it shouldn't check the second condition right? Thanks
Correct, if flag_val is NULL then the && operator will short-circuit. As long as flag_val can't be changed by some other thread, this is safe code.
I am usingstrtok().But i want to print corresponding delimiters also as we do usingStringTokenizerin Java.Is there any function which provides this functionality(printing delimiters) ?
Based on OP's comments, tokenization is not what is actually desired. You want to usestrstr(), notstrtok(). That will tell you if the string is present, and then you can usestrcpy()andstrcat()as appropriate. Please note, the "n" versions of these methods, i.e.strncpyandstrncat, are safer -- less likely to crash due to buffer overrun.
I want to obtain the "base" property from a gtkstyle, which is a GdkColor type, but I just can manage to get it. I know I can use gtk_style_get_style_property() ``` void gtk_style_get_style_property (GtkStyle *style,GType widget_type, const gchar *property_name, GValue *value); ``` but what am I supposed to put in "widget_type" and how a can get a gdkcolor type from "value"?
You must pass theGTypeof a widget class (e.g.GTK_TYPE_LABEL,GTK_TYPE_BUTTON, etc.) inwidget_type. To get aGdkColorfrom aGValue, callg_value_get_boxed(): ``` GdkColor *color = (GdkColor *) g_value_get_boxed(value); ```
So, I'm trying to calculate a certain value to a rather large precision. The expression in C is: ``` long double t = 2.0L+.2L*(sp)+s.missRate*50L; ``` my result is:11.575345 But the 'real' result is:11.575345222971968 I'm using long doubles, which are the largest primitive type AFAIK. I shouldn't have to use any precision libraries to do this. So, what C type has this kind of precision?
The result is probably precise enough, but you are printing it rounded to 6 digits after the decimal point. Increase your printing precision, like this: ``` long double var; printf("%.20Lf\n", var); //20 digits after the radix ```
As the title implies: the scenario is a coder with a gdb and a user reporting a crash. Can he get from the user an easy to use memory dump which can be fed to gdb but also not make it hard for the user?
You can set upProcess Dumperto produce a full dump on any exception or process exit, based on the name of the executable file. I am assuming Windows due to the title, alter the tags if not.
I am working on a program and need to implement a double-entry accounting system. It would seem to me that there should be some open source project or code base out there already with most all of the basic accounting functions already written, but Google didn't turn anything up. I don't want to re-invent the wheel, so is anyone aware if there is already a package out there that implements double-entry accounting in C, C++, or Objective-C? Thank you! (Frank) Note: I am looking for a double-entry module to plug in to my existing application (it is a property management system) and I'm not re-writing a package like GNUCash. Sorry if I didn't state that clearly.
GnuCash -http://www.gnucash.org/
I am trying to store every hex value from 0000 to fffe into a file. How would I use fwrite or fprintf to place these values into a file? At the moment, I have a while loop that prints all the numbers using printf (which is to the console screen), but I need them in a file.
``` fprintf(fp, "%04x", your_number) ```
this is my .h file: ``` struct _MyString; typedef struct _MyString MyString; ``` i would like to declare its members in the .c file. i tried: ``` typedef struct MyString{ char * _str;// pointer to the matrix unsigned long _strLength; }MyString; ``` but it doesn't work. how do i declare the struct's memebers in the .c file? thank you
You need only 1 typedef. Keep the one you already have in the .h file and delete all others. Now, the struct name isstruct _MyString. That is what you should define in the .c file, notstruct MyString: notice the absence of the '_'. So .h file ``` struct _MyString; typedef struct _MyString MyString; ``` .c file ``` #include "file.h" struct _MyString { char * _str;// pointer to the matrix unsigned long _strLength; }; ```
The code, derived from "The C Programming Language, Second Edition": ``` #include <stdio.h> main() { long nc; nc = 0; while(getchar() != EOF) ++nc; printf("%s: %ld\n", "number of characters", nc); } ``` Why doesn't the "printf" statement execute after pressing the "enter" key (EOF)?
The enter key isnotEOF. Depending on your system, it will send a carriage return (0x0D or'\r'), a line feed (0x0A or'\n'), or both. On Linux (and probably Unix), EOF can be sent by Ctrl+D. On Windows it should be Ctrl+Z (but you might need to press enter afterwards).
Does Google protocol buffers are binary-compatibly with C structures? I mean can I read serialized files from C direct into structs without deserializing? Orprotobuf-cis the only one solution?
Depending on the alignment, endianness and packing of structures on your platform, this may or may not work. You may be lucky with your particular target, but in general you should use proper serialise / deserialise routines.
How safe would be to do something like: ``` if (flag_val != NULL && strcmp (val, flag_val) == 0) { // something } else { // something else } ``` Knowing that sometimesflag_valwill beNULLand sometimes not. I know it will check first ifflag_val != NULL, if it evaluates false, it shouldn't check the second condition right? Thanks
Correct, if flag_val is NULL then the && operator will short-circuit. As long as flag_val can't be changed by some other thread, this is safe code.
I am usingstrtok().But i want to print corresponding delimiters also as we do usingStringTokenizerin Java.Is there any function which provides this functionality(printing delimiters) ?
Based on OP's comments, tokenization is not what is actually desired. You want to usestrstr(), notstrtok(). That will tell you if the string is present, and then you can usestrcpy()andstrcat()as appropriate. Please note, the "n" versions of these methods, i.e.strncpyandstrncat, are safer -- less likely to crash due to buffer overrun.
I want to obtain the "base" property from a gtkstyle, which is a GdkColor type, but I just can manage to get it. I know I can use gtk_style_get_style_property() ``` void gtk_style_get_style_property (GtkStyle *style,GType widget_type, const gchar *property_name, GValue *value); ``` but what am I supposed to put in "widget_type" and how a can get a gdkcolor type from "value"?
You must pass theGTypeof a widget class (e.g.GTK_TYPE_LABEL,GTK_TYPE_BUTTON, etc.) inwidget_type. To get aGdkColorfrom aGValue, callg_value_get_boxed(): ``` GdkColor *color = (GdkColor *) g_value_get_boxed(value); ```
So, I'm trying to calculate a certain value to a rather large precision. The expression in C is: ``` long double t = 2.0L+.2L*(sp)+s.missRate*50L; ``` my result is:11.575345 But the 'real' result is:11.575345222971968 I'm using long doubles, which are the largest primitive type AFAIK. I shouldn't have to use any precision libraries to do this. So, what C type has this kind of precision?
The result is probably precise enough, but you are printing it rounded to 6 digits after the decimal point. Increase your printing precision, like this: ``` long double var; printf("%.20Lf\n", var); //20 digits after the radix ```
As the title implies: the scenario is a coder with a gdb and a user reporting a crash. Can he get from the user an easy to use memory dump which can be fed to gdb but also not make it hard for the user?
You can set upProcess Dumperto produce a full dump on any exception or process exit, based on the name of the executable file. I am assuming Windows due to the title, alter the tags if not.
I am working on a program and need to implement a double-entry accounting system. It would seem to me that there should be some open source project or code base out there already with most all of the basic accounting functions already written, but Google didn't turn anything up. I don't want to re-invent the wheel, so is anyone aware if there is already a package out there that implements double-entry accounting in C, C++, or Objective-C? Thank you! (Frank) Note: I am looking for a double-entry module to plug in to my existing application (it is a property management system) and I'm not re-writing a package like GNUCash. Sorry if I didn't state that clearly.
GnuCash -http://www.gnucash.org/
I am trying to store every hex value from 0000 to fffe into a file. How would I use fwrite or fprintf to place these values into a file? At the moment, I have a while loop that prints all the numbers using printf (which is to the console screen), but I need them in a file.
``` fprintf(fp, "%04x", your_number) ```
this is my .h file: ``` struct _MyString; typedef struct _MyString MyString; ``` i would like to declare its members in the .c file. i tried: ``` typedef struct MyString{ char * _str;// pointer to the matrix unsigned long _strLength; }MyString; ``` but it doesn't work. how do i declare the struct's memebers in the .c file? thank you
You need only 1 typedef. Keep the one you already have in the .h file and delete all others. Now, the struct name isstruct _MyString. That is what you should define in the .c file, notstruct MyString: notice the absence of the '_'. So .h file ``` struct _MyString; typedef struct _MyString MyString; ``` .c file ``` #include "file.h" struct _MyString { char * _str;// pointer to the matrix unsigned long _strLength; }; ```
The code, derived from "The C Programming Language, Second Edition": ``` #include <stdio.h> main() { long nc; nc = 0; while(getchar() != EOF) ++nc; printf("%s: %ld\n", "number of characters", nc); } ``` Why doesn't the "printf" statement execute after pressing the "enter" key (EOF)?
The enter key isnotEOF. Depending on your system, it will send a carriage return (0x0D or'\r'), a line feed (0x0A or'\n'), or both. On Linux (and probably Unix), EOF can be sent by Ctrl+D. On Windows it should be Ctrl+Z (but you might need to press enter afterwards).
Does Google protocol buffers are binary-compatibly with C structures? I mean can I read serialized files from C direct into structs without deserializing? Orprotobuf-cis the only one solution?
Depending on the alignment, endianness and packing of structures on your platform, this may or may not work. You may be lucky with your particular target, but in general you should use proper serialise / deserialise routines.
Is it possible todynamicallyload foreign C library (dll) and call its functions in Go? I know there iscgowhich is used to statically bind to C functions, but I'm interested in dynamic way.
Short answer: no. (at least not with gc, gccgo is gcc linkable however, so it might be possible) Medium answer: However, you can statically bind, say, libffi or libdl and then useitto dynamically load other libraries. Long answer: You can write go packages in C and ASM using the go toolchains C compiler and assembler (see src/pkg/runtime for example). So you could write a FFI in either C or ASM as a go package. Edit: From the comments below (also CW now) Alternatively, it can be done using thesyscallandunsafepackages (easily in windows, but I imagine it would be harder in linux and not far off from the third solution above). http://code.google.com/p/go/wiki/CallingWindowsDLLs
I know that for 1-dimensional arrays, I can do... ``` void g(int x[]) {} void f(int a, int b) { int x[a]; g(x); } ``` But with code such as... ``` void f(int a, int b) { int x[a][b][4]; g(x); } ``` What would the type signature of g(x) look like?
``` void g(int x[][b][4]) // b must be known in advance {} ``` Otherwise explicitly passb For example: ``` void g(int b,int x[][b][4]){ } int main() { int a=4,b=6; int x[a][b][4]; g(b,x); return 0; } ```
My code is this (main.c): ``` #include <inttypes.h> #include <stdio.h> int main(int argc, char **argv) { uint64_t n; n = UINT64_MAX; printf("%" PRIX64 " %" PRIu64 "\n", n, n); return 0; } ``` The output of the program is this: ``` FFFFFFFFFFFFFFFF 18446744073709551615 ``` But I am looking for this: ``` 10000000000000000 18446744073709551615 ``` I am using GCC (gcc -std=c99 main.c): gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 Looking for an answer in google gave me this:http://bytes.com/topic/c/answers/565055-convert-64-integer-hex-octet-string Now, I am lost. What am I doing wrong?
the value ofUINT64_MAXshould be0xffffffffffffffffas that is the value of 64-bits all set. I don't understand why you expect0x10000000000000000(which requires65-bits to represent). Also18446744073709551615in decimal is equal to0xffffffffffffffff, so printf is doing the right thing.
Recently I encountered this puzzle : ``` int main(){ int arr[7]; int b,c,d,a; a=4; printf("%d",arr[?]); return 0; } ``` The question is toReplace "?" with a integer so that output is 4.I am not sure but I don't think this is solvable in a standard way ?! (Not invoking Undefined Behavior or depending on implementation) If NO, then I am very interested in knowing how ? Edit:This task is taken fromhere, I tried to solve with 10, but sadly it's not the answer the problem setter wants.However, Isolvedit using some pretested implementation dependent mumbo-jumbo,but I really have no explanation for how it really works! Here is the answer :SPOILER,You are welcome to explain it
In most implementations,arr[10](or 7) will be 4, since the locals will be laid out sequentially. However, this is neither defined nor standard, andmust notbe relied on.
I wanted to know what is the current standard C compiler being used by companies. I know of the following compilers and don't understand which one to use for learning purposes. Turbo CBorland CGCCDJGPP I am learning C right now and referring to the K&R book. Can anyone please guide me to which compiler to use?
GCCwould be the standard, best supported and fastest open source compiler used by most (sane) people.
Where can I find working code of object detection (part of computer vision) written in OpenCL or CUDA? Greatly appreciate in advance.
There are lots of demos and papers at nvidia'sCuda Zone. Search for "detection". For example: Fast Human Detection with Cascaded Ensembles (476d306d-6a77-4749-8210-8b7b19ebd420)Detection and Tracking of Human Subjects (608510ce-a512-41c8-b32a-b55cb524284d)GPU-Based Road Sign Detection Using Particle Swarm Optimization (76dcd879-098a-41f2-ab03-38c43d2a042e)
I discovered something strange in gcc and hoping to get some input whether its a feature or quirk.Essentially I have a function defined in func.c as ``` void f(int a, int b, FILE* f) { ... ... } ``` There is no corresponding header file. But gcc doesn't give any warning when I call f(a,b) and gdb shows me that f is called with three parameters? Why is this the case?. What is the semantics for filling up the third argument.
Iff()doesn't have a declaration anywhere and is not defined in the current compilation unit, the compiler assumes thatf()returnsintand can take any number of arguments. I know this is odd, but in the old days this was possibly a way to reduce the number of header files that have to be included, and hence faster compilation.
guys I'm trying to compile my program in c but I'm getting this error (conflicting types for allocArray)? Here is my code: #include <stdio.h> #include <stdlib.h> int number(int); char *allocArray(int); int main () { printf("Enter a number: "); int userNumber; scanf("%d", &userNumber); int m= number(userNumber); printf("\nThe number is %d", m); printf("\n"); printf("*****************************************************\n"); printf("The array is %s", alloArray(5)); } int number(int n) { int num = n; return num; } char *alloArray(int num) { char *addr; addr = (char *) malloc(num); //addr = char[num]; return addr; }
You've misspeltallocArrayasalloArray(twice, in fact).
Why can I do ``` char identifier[4] = {'A', 'B', 'C', 'D'}; ``` and not ``` char identifier[4]; &identifier = {'A', 'B', 'C', 'D'}; // syntax error : '{' ``` ? And why can I do ``` char identifier[4] = "ABCD"; // ABCD\0, aren't that 5 characters?? ``` and not ``` char identifier[4]; &identifier = "ABCD"; // 'char (*)[4]' differs in levels of indirection from 'char [5]' ``` ? Is this a joke??
You can only initialize the array when you declare it. As forchar identifier[4] = "ABCD", this is indeed possible but the syntax is used to deliberately omit the trailing NUL character. Dochar identifier[] = "ABCD"to let the compiler count the characters and add the NUL ('\0') for you.
A fairly simple question (I hope). Given a struct in C (the layout of which is known at compile time), is there a way (via macro, or other) that I can access the byte position of a named field in the struct? Support for unions would be a bonus. The compiler is VC++ 2008. Assume that#pragma pack(1)is used. Cheers
You're looking foroffsetof. It should be instddef.h, but in case you don't have that, a sample implementation (fromwikipedia): ``` #define offsetof(st, m) \ ((size_t) ( (char *)&((st *)(0))->m - (char *)0 )) ``` For a union, the offset of every field is0.
I have a header file for a game that declares a two-dimensional array for a board. ``` #ifndef GAME_H_ #define GAME_H_ static const int columns = 15; static const int rows = 15; int board[rows][columns]; #endif /* GAME_H_ */ ``` I get an error: error: variably modified 'board' at file scope
C doesn't allowconstvariables as array bounds. Use an enum instead: ``` enum { columns = 15, rows = 15 }; ```
Example: ``` var x, y, z; //... x > 100 ? y = x : z = x ; ```
Yes it does work the same although operator precedence is always tricky so I would recommend parenthesis to avoid confusion. tangentially related..You can also use||in JavaScript similar to the null coalescing operator??in C#
I am researching a project in which I need to playback simultaneously a multi-track audio source. ( >30 mono channels ) The audio on all channels needs to start simultaneously and be sustained for hours of playback. What is the best audio API to use for this? WDM and ASIO have come up in my searches. I will be using aMOTU PCI Audio interfaceto get this many channels. The channels show up as normal audio channels in the host PC.
ASIO is definitely the way to go about this. It will keep everything in sync properly, with low latency, and is the defacto industry standard way to do it. Any pro audio interfaces supports ASIO, and for interfaces that don't,there is a wrapperthat is capable of syncing multiple devices.
I wanted to know what is the current standard C compiler being used by companies. I know of the following compilers and don't understand which one to use for learning purposes. Turbo CBorland CGCCDJGPP I am learning C right now and referring to the K&R book. Can anyone please guide me to which compiler to use?
GCCwould be the standard, best supported and fastest open source compiler used by most (sane) people.
Where can I find working code of object detection (part of computer vision) written in OpenCL or CUDA? Greatly appreciate in advance.
There are lots of demos and papers at nvidia'sCuda Zone. Search for "detection". For example: Fast Human Detection with Cascaded Ensembles (476d306d-6a77-4749-8210-8b7b19ebd420)Detection and Tracking of Human Subjects (608510ce-a512-41c8-b32a-b55cb524284d)GPU-Based Road Sign Detection Using Particle Swarm Optimization (76dcd879-098a-41f2-ab03-38c43d2a042e)
I discovered something strange in gcc and hoping to get some input whether its a feature or quirk.Essentially I have a function defined in func.c as ``` void f(int a, int b, FILE* f) { ... ... } ``` There is no corresponding header file. But gcc doesn't give any warning when I call f(a,b) and gdb shows me that f is called with three parameters? Why is this the case?. What is the semantics for filling up the third argument.
Iff()doesn't have a declaration anywhere and is not defined in the current compilation unit, the compiler assumes thatf()returnsintand can take any number of arguments. I know this is odd, but in the old days this was possibly a way to reduce the number of header files that have to be included, and hence faster compilation.
guys I'm trying to compile my program in c but I'm getting this error (conflicting types for allocArray)? Here is my code: #include <stdio.h> #include <stdlib.h> int number(int); char *allocArray(int); int main () { printf("Enter a number: "); int userNumber; scanf("%d", &userNumber); int m= number(userNumber); printf("\nThe number is %d", m); printf("\n"); printf("*****************************************************\n"); printf("The array is %s", alloArray(5)); } int number(int n) { int num = n; return num; } char *alloArray(int num) { char *addr; addr = (char *) malloc(num); //addr = char[num]; return addr; }
You've misspeltallocArrayasalloArray(twice, in fact).
Why can I do ``` char identifier[4] = {'A', 'B', 'C', 'D'}; ``` and not ``` char identifier[4]; &identifier = {'A', 'B', 'C', 'D'}; // syntax error : '{' ``` ? And why can I do ``` char identifier[4] = "ABCD"; // ABCD\0, aren't that 5 characters?? ``` and not ``` char identifier[4]; &identifier = "ABCD"; // 'char (*)[4]' differs in levels of indirection from 'char [5]' ``` ? Is this a joke??
You can only initialize the array when you declare it. As forchar identifier[4] = "ABCD", this is indeed possible but the syntax is used to deliberately omit the trailing NUL character. Dochar identifier[] = "ABCD"to let the compiler count the characters and add the NUL ('\0') for you.
A fairly simple question (I hope). Given a struct in C (the layout of which is known at compile time), is there a way (via macro, or other) that I can access the byte position of a named field in the struct? Support for unions would be a bonus. The compiler is VC++ 2008. Assume that#pragma pack(1)is used. Cheers
You're looking foroffsetof. It should be instddef.h, but in case you don't have that, a sample implementation (fromwikipedia): ``` #define offsetof(st, m) \ ((size_t) ( (char *)&((st *)(0))->m - (char *)0 )) ``` For a union, the offset of every field is0.
I have a header file for a game that declares a two-dimensional array for a board. ``` #ifndef GAME_H_ #define GAME_H_ static const int columns = 15; static const int rows = 15; int board[rows][columns]; #endif /* GAME_H_ */ ``` I get an error: error: variably modified 'board' at file scope
C doesn't allowconstvariables as array bounds. Use an enum instead: ``` enum { columns = 15, rows = 15 }; ```
Example: ``` var x, y, z; //... x > 100 ? y = x : z = x ; ```
Yes it does work the same although operator precedence is always tricky so I would recommend parenthesis to avoid confusion. tangentially related..You can also use||in JavaScript similar to the null coalescing operator??in C#
I am researching a project in which I need to playback simultaneously a multi-track audio source. ( >30 mono channels ) The audio on all channels needs to start simultaneously and be sustained for hours of playback. What is the best audio API to use for this? WDM and ASIO have come up in my searches. I will be using aMOTU PCI Audio interfaceto get this many channels. The channels show up as normal audio channels in the host PC.
ASIO is definitely the way to go about this. It will keep everything in sync properly, with low latency, and is the defacto industry standard way to do it. Any pro audio interfaces supports ASIO, and for interfaces that don't,there is a wrapperthat is capable of syncing multiple devices.
For jpeg,gif,png I use libgd. ( not ImageMagick - it's not possible ). May I resize bmp image using simple method/library ?
Most of the libraries that deal with image resizing represent the image as a bitmap (i.e. an uncompressed array of pixels) internally. So it wouldn't be very hard to read in a bitmap image from a file and put it in memory.
If I have a file containing ``` manual /lib/plymouth/themes/default.plymouth /lib/plymouth/themes/spinfinity/spinfinity.plymouth 10 /lib/plymouth/themes/ubuntu-logo/ubuntu-logo.plymouth 100 ``` and then I open it inamode, then do ``` fprintf(f, "/el/derpito.plymouth\n100\n"); ``` why is the file now containing this? ``` manual /lib/plymouth/themes/default.plymouth /lib/plymouth/themes/spinfinity/spinfinity.plymouth 10 /lib/plymouth/themes/ubuntu-logo/ubuntu-logo.plymouth 100 /el/derpito.plymouth 100 ``` I'd expect the file to be this instead: ``` manual /lib/plymouth/themes/default.plymouth /lib/plymouth/themes/spinfinity/spinfinity.plymouth 10 /lib/plymouth/themes/ubuntu-logo/ubuntu-logo.plymouth 100 /el/derpito.plymouth 100 ```
Perhaps there is a lonely \n or \cr stuck at the end of the file before you make the write. I wuld open it with a hex editor and see.
If the syntax ofexternis ``` extern <type> <name>; ``` how do Iexternif I have an unnamed, single use struct: ``` struct { char **plymouthThemes; char *plymouthTheme; } global; ``` I've tried ``` extern global; ``` without any type, and it doesn't work. Or, do I have to name the struct?
You need to name your struct and put it in a .h file or included the definition by hand in every source file that uses global. Like this ``` ///glob.h struct GlobalStruct { ///char** ... /// }; ///glob.cpp #include "glob.h" struct GlobalStruct global; ///someOtherFile.cpp #include "glob.h" extern struct GlobalStruct global; ```
quick question Can you use the free() function without having to prior call a malloc ?? ei. ``` void someFunc( void ) { char str[6] = {"Hello"}; //some processing here .... free(str); } ``` I get no compiling errors but Does this work or is it correct at all ? Thank you,
This is not at all correct: You cannot free a static array such aschar str[6].free() should only be called on memory you allocated (or on NULL).
I created a small application which makes some settings. I want to start this application before a user logs into windows. Unfortunately i didn't find any solution for this problem, so i thought i could create a scheduled task. Unfortunately i didn't find any solution neither for this. So my question is, that could somebody help me? I would appropritiate any help, idees, or examples. Basicly my question is, how can i start an application before a user logs into windows? It is necessary to mention that i need to this on Windows XP!
Look intoMSDNfor Task Scheduler API. Creating a Task Using NewWorkItem Exampleseems to be what you are describing here.
As I know that in C, we can use function pointer and this is called during run-time (1). By definition from wikipedia: Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all ... So my question is, why C is not a dynamic language providing the feature in (1) ?
Because the function in your function pointer is still compiled at compile time. You cannot add a new function or modify a function "on the fly" at runtime.
I need a toolkit to implement SOAP requests and responses in a C production application. I've looked into gSOAP (no support), Apache Axis (not fully implemented according to their site). Has anyone been able to implement SOAP responses/requests over HTTP or TCP/IP?
Ever triedlibsoup? The libsoup library contains an HTTP implementation and a set of API for constructing and consuming SOAP messages. It also allows for secure authentication, so you can use web services to access private accounts over a secure connection. Using libsoup makes it easy to use web services without manually parsing and interpreting the messages sent through This is their main page ->libsoup
Is this loop busy waiting, I would think the wait call takes care of that. If it is, how can it be fixed to not busy wait? ``` id = fork(); for (i = 0; i < 20; i++) { switch (id) { case 0: /* do stuff with child */ exit(0); default: { if (children>=3) { int s; wait(&s); children--; } children++; id = fork(); } } } ```
waitwill cause the kernel to select other jobs that are not marked as blocked, so this isn't a case of busy-waiting. Also isn't switch a bit excessive for a fork(), why not use a simple if statement?
I implement a file's struct in my program but for some arrays in the struct I don't know the size. The size of the array is stored in another variable but it's unknown before the struct is filled in. ``` struct Vertex { float x; float y; float z; }; struct myFile { ulong nVertices; Vertex vertices[nVertices]; }; ``` That gives an error: "error C2065: 'nVertices' : undeclared identifier".
You should store a pointer in your struct: ``` Vertex *vertices; ``` Then allocate the memory at runtime: ``` myFile f; f.vertices = malloc(nVertices * sizeof(Vertex)); if (f.vertices == 0) handle_out_of_memory(); f.nVertices = nVertices; ``` Remember to free the memory when done: ``` free(f.vertices); ```
I could find a C++ onehere, but no pure C one. Any pointers?
C code for a red and black tree, licensed with the very generousMIT license. (Backup at archive.org.)
How can the exit code of the main thread be retrieved, after having run ShellExecuteEx() in asychronous mode? The process exit code can simply be retrieved as follows: ``` SHELLEXECUTEINFO execInfo; execInfo.cbSize = sizeof(SHELLEXECUTEINFO); execInfo.fMask = SEE_MASK_NOASYNC; ShellExecuteEx(&execInfo); /* Get process exit code. */ DWORD processExitCode; GetExitCodeProcess(execInfo.hProcess, &processExitCode); ``` But how can the exit code of the main thread be retrieved? What should be passed to GetExitCodeThread()?
The exit code of the main thread is equal to the exit code of the process IMHO.
I have a file with various 'return BBQ;' statements. I'd like to change them all to 'exit(BBQ);\nreturn BBQ;' (with BBQ being an arbitrary value). Is this possible?
Backreferences. ``` s/return \(BBQ\);/exit(\1);\nreturn \1;/ ```
to compile C programs and run it, I use ":make" but I would like to run the compiled program too if the compile is a success. I wrote ``` au FileType c setlocal makeprg=g++\ %\ \&\&\ ./a.out ``` in vimrc, that works, but I have a vim error when there's some mistakes in my code, so vim don't put the cursor on the good line. I get this error : E40: Can't open errorfile /tmp/vEtUQQ2/0 Is there a workaround, a fix or another way to achieve this ?
You could create a target in your makefile to run the program (say 'run'): ``` .PHONY : run run : $(PROG) # assuming $(PROG) is the name of your program ./$(PROG) ``` ...and then in vim you would do: ``` :make run ```
I have a question, which I was unable to Google because I really don't know the proper terminology for it, if concept exists that is. My question is this; Imagine having a while loop in C, which does 1 inline assembly instruction ``` __asm { mov eax, ebp }; ``` Then we would print it's output with printf, respectively. But would it be possible to determine when "time" has reached exactly 1 second? I'm doing some research on ASLR, and I want to see if there is a fixed timespan between each randomization by seeing if the randomization occures exactly X seconds apart from each other. Hope you understand, and thanks for reading/helping.
The address space does not get randomized after the process is started.
I'm looking for a Library that allows me to generate an Image via pixel information, in this style(dummyfunction): ``` /* coord_x = X coordinate coord_y = Y coordinate red = red part of RGB green = green part of RGB blue = blue part of RGB */ setPixel(int coord_x, int coord_y, int red, int green, int blue) ``` Is there such a Function? I've searched libpng, but it doesn't appear to allow to set pixels manually (might be wrong, though)... Prefered formats for output would be PNG, GIF would be acceptable, JPG will probably not work (due to compression and lack of transparency as in PNG and GIF).
a strong and powerful library is Imagick: Use MagickWand to convert, compose, and edit images from the C language. There is also the low-level MagickCore library for wizard-level developers. http://www.imagemagick.org/script/api.php?ImageMagick=2m69higs264080492m8ttkndb5#c
This question already has answers here:Closed12 years ago. Possible Duplicate:remove duplicate elements in an array in O(n) in C/C++ How can I remove duplicate elements from an array? Before ``` array [ ] = {1,2,3,4,5,1,2,4,9,0,0} ``` After ``` array [ ] = {0,1,2,3,4,5,9} ```
Sort the array using your favorite sorting algorithm.Walk through the array and eliminate duplicates - if a value is the same one as the previous one, keep going forward until you get a new value and then copy it back.
Somebody can give me an example to do this. Suppose static variable scope is limited to file only.That is private to that file.Like that some more examples i want to know. In other words HOW TO ACHIEVE DATA HIDING CONCEPT IN C-LANGUAGE WITH CURRENTLY AVAILABLE KEYWORDS(STRUCT,STATIC...ETC)
This guy is one of the worlds authorities on embedded systems. He wrote this white paper on OOP in c. http://www.state-machine.com/resources/cplus_3.0_manual.pdf
quick question Can you use the free() function without having to prior call a malloc ?? ei. ``` void someFunc( void ) { char str[6] = {"Hello"}; //some processing here .... free(str); } ``` I get no compiling errors but Does this work or is it correct at all ? Thank you,
This is not at all correct: You cannot free a static array such aschar str[6].free() should only be called on memory you allocated (or on NULL).
I created a small application which makes some settings. I want to start this application before a user logs into windows. Unfortunately i didn't find any solution for this problem, so i thought i could create a scheduled task. Unfortunately i didn't find any solution neither for this. So my question is, that could somebody help me? I would appropritiate any help, idees, or examples. Basicly my question is, how can i start an application before a user logs into windows? It is necessary to mention that i need to this on Windows XP!
Look intoMSDNfor Task Scheduler API. Creating a Task Using NewWorkItem Exampleseems to be what you are describing here.
As I know that in C, we can use function pointer and this is called during run-time (1). By definition from wikipedia: Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all ... So my question is, why C is not a dynamic language providing the feature in (1) ?
Because the function in your function pointer is still compiled at compile time. You cannot add a new function or modify a function "on the fly" at runtime.
to compile C programs and run it, I use ":make" but I would like to run the compiled program too if the compile is a success. I wrote ``` au FileType c setlocal makeprg=g++\ %\ \&\&\ ./a.out ``` in vimrc, that works, but I have a vim error when there's some mistakes in my code, so vim don't put the cursor on the good line. I get this error : E40: Can't open errorfile /tmp/vEtUQQ2/0 Is there a workaround, a fix or another way to achieve this ?
You could create a target in your makefile to run the program (say 'run'): ``` .PHONY : run run : $(PROG) # assuming $(PROG) is the name of your program ./$(PROG) ``` ...and then in vim you would do: ``` :make run ```
I have tried \a \7 the windows.h beep function etc etc and nothing works. Does newer hardware not have this functionality built in? (Console Program)
Newer hardware is required to have a beep for people with disabilities, but Windows 7 moved theBeep()into the actual Windows Audio Subsystem (so make sure your speakers are turned on). Larry Osterman explains it all on his blog:https://learn.microsoft.com/en-us/archive/blogs/larryosterman/whats-up-with-the-beep-driver-in-windows-7
I'm interested in writing a python binding or wrapper for an existing command line utility that I use on Linux, so that I can access its features in my python programs. Is there a standard approach to doing this that someone could point me to? At the moment, I have wrapped the command line executable in a subprocess.Popen call, which works but feels quite brittle, and I'd like to make the integration between the two sides much more stable so that it works in places other than my own computer!
If you must use a command line interface, then subprocess.Popen is your best bet. Remember that you can use shell=True to let it pick the path variables, you can use os.path.join to use OS-dependent path separators etc. If, however, your command line utility has shared libraries, look at ctypes, which allows you to connect directly to those libraries and expose functionality directly.
So I need to get web camera fps rate in OpenCV. Which function can do such thing for?
``` int cvGetCaptureProperty( CvCapture* capture, int property_id); ``` withproperty_id = CV_CAP_PROP_FPS
In Assembler i can use the MUL command and get a 64 bit Result EAX:EDX, how can i do the same in C ?http://siyobik.info/index.php?module=x86&id=210 My approach to use a uint64_t and shift the Result don't work^^ Thank you for your help (= Me
Any decent compiler willjust do itwhen asked. For example using VC++ 2010, the following code: ``` unsigned long long result ; unsigned long a = 0x12345678 ; unsigned long b = 0x87654321 ; result = (unsigned long long)a * b ; ``` generates the following assembler: ``` mov eax,dword ptr [b] mov ecx,dword ptr [a] mul eax,ecx mov dword ptr [result],eax mov dword ptr [a],edx ```
How to print ( with printf ) complex number? For example, if I have this code: ``` #include <stdio.h> #include <complex.h> int main(void) { double complex dc1 = 3 + 2*I; double complex dc2 = 4 + 5*I; double complex result; result = dc1 + dc2; printf(" ??? \n", result); return 0; } ``` ..what conversion specifiers ( or something else ) should I use instead "???"
``` printf("%f + i%f\n", creal(result), cimag(result)); ``` I don't believe there's a specific format specifier for the C99 complex type.
This question already has answers here:Closed12 years ago. Possible Duplicate:What do people find difficult about C pointers? New to c programming (Actually new to programming in general). Well, I just can't get familiar with c pointers. maybe, I can use them in some situations, but really am stuck tounderstandit. Anyone been in such a situation? Any suggestions?
I would start at theIntroduction to pointers. The link is to a very simple, concise, and easy to follow tutorial/e-learning site. The next chapter goes more in depth. I think you'll find the information helpful in getting a better understanding of how pointers work. That site discusses things that can confuse people easily. Such as the following syntax differences: ``` 1 int *pnPtr; // a pointer to an integer value 2 double *pdPtr; // a pointer to a double value 3 4 int* pnPtr2; // also valid syntax 5 int * pnPtr3; // also valid syntax ```
I have two bytes, 8 bit octets, which should be read as: [3 bits][4 bits][3 bits]. Example: ``` unsigned char octet1 = 0b11111111; // binary values unsigned char octet2 = 0b00000011; ``` As integers: [7][15][7]. Anybody can give me a hint where to start?
In a kind ofpseudocode ``` octet1 = 0b11111111 octet2 = 0b00000011 word = octet1 | octet2<<8 n1 = word & 0b111 n2 = word>>3 & 0b1111 n3 = word>>7 & 0b111 ```
gcc 4.4.4 c89 I have the following in my state.c file: ``` enum State { IDLE_ST, START_ST, RUNNING_ST, STOPPED_ST, }; State g_current_state = State.IDLE_ST; ``` I get the following error when I try and compile. ``` error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘g_current_state’ ``` Is there some with declaring a variable of type enum in global scope? Many thanks for any suggestions,
There are two ways to do this in straight C. Either use the fullenumname everywhere: ``` enum State { IDLE_ST, START_ST, RUNNING_ST, STOPPED_ST, }; enum State g_current_state = IDLE_ST; ``` or (this is my preference)typedefit: ``` typedef enum { IDLE_ST, START_ST, RUNNING_ST, STOPPED_ST, } State; State g_current_state = IDLE_ST; ``` I prefer the second one since it makes the type look like a first class one likeint.
If I have a 4 byte address stored in char address[4] and the contents are: ``` address[0] = '\x80'; address[1] = '\xAB'; address[2] = '\x0A'; address[3] = '\x1C'; // all together: 80 AB 0A 1C ``` I want to convert it to a character array that looks like "128.171.10.28", since 80 in hex is 128, AB in hex is 171 and so on. How can I do this?
``` char saddr[16]; sprintf(saddr, "%d.%d.%d.%d", (unsigned char)address[0], (unsigned char)address[1], (unsigned char)address[2], (unsigned char)address[3]); ``` or ``` char saddr[16]; unsigned char *addr = (unsigned char*)address; sprintf(saddr, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]); ``` or, as pointed out by dreamlax: ``` char saddr[16]; sprintf(saddr, "%hhu.%hhu.%hhu.%hhu", address[0], address[1], address[2], address[3]); ```
This question already has answers here:self referential struct definition?(9 answers)Closed6 years ago. ``` struct node{ struct node next; int id; } ``` gives "field next has incomplete type error ". what is wrong with this struct ?
When creating a self-referential data type, you need to use pointers to get around problems of circularity: ``` struct node; struct node { struct node * next; int id; } ``` ...should work, but take care to allocate memory correctly when using it. Why a pointer? Consider this: the point of astructdefinition is so that the compiler can figure out how much memory to allocate and what parts to access when you saynode.id. If yournodestruct contains anothernodestruct, how much memory should the compiler allocate for a givennode? By using a pointer you get around this, because the compiler knows how much space to allocate for a pointer.
I'm working on this project that uses proxy server and curl in c and i cant find a good tutorial that teaches me how to. Can you please help me?? i need an example code that shows the use of a proxy server to connect to google.com. maybe using the CURLOPT_PROXY option.. Thanks in advance.
Well all you do is yournormal curlretrieval, but just set the proxy server option. ``` curl_easy_setopt(handle, CURLOPT_PROXY, "127.0.0.1:96666"); ``` EDIT ``` /* create headers */ struct curl_slist *headers=NULL; headers = curl_slist_append(headers, "Content-Type: text/xml"); /* pass our list of custom made headers */ curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers); ```
I have a function that takes as one of its parameters "void* buffer". In this function, I need to write to that memory location. However, doing something like ``` *buffer = "Hello\0Hi\0"; ``` doesn't work because I can't dereference a void* pointer. How do I puta stringdata into that memory location? Note that I need to copy data, not necessarily a string, as it may contain the null character. Updatedto reflect that strcpy is not enough
If you string "may contain the null character," then it isn't really a C string. If you need to copy a certain number of bytes from one memory location to another, regardless of the contents, you can usememcpy. You can get the size of the string literal usingsizeof(this size includes the final, implicit null terminator).
This question already has answers here:Closed12 years ago. Possible Duplicate:What do people find difficult about C pointers? New to c programming (Actually new to programming in general). Well, I just can't get familiar with c pointers. maybe, I can use them in some situations, but really am stuck tounderstandit. Anyone been in such a situation? Any suggestions?
I would start at theIntroduction to pointers. The link is to a very simple, concise, and easy to follow tutorial/e-learning site. The next chapter goes more in depth. I think you'll find the information helpful in getting a better understanding of how pointers work. That site discusses things that can confuse people easily. Such as the following syntax differences: ``` 1 int *pnPtr; // a pointer to an integer value 2 double *pdPtr; // a pointer to a double value 3 4 int* pnPtr2; // also valid syntax 5 int * pnPtr3; // also valid syntax ```
I have two bytes, 8 bit octets, which should be read as: [3 bits][4 bits][3 bits]. Example: ``` unsigned char octet1 = 0b11111111; // binary values unsigned char octet2 = 0b00000011; ``` As integers: [7][15][7]. Anybody can give me a hint where to start?
In a kind ofpseudocode ``` octet1 = 0b11111111 octet2 = 0b00000011 word = octet1 | octet2<<8 n1 = word & 0b111 n2 = word>>3 & 0b1111 n3 = word>>7 & 0b111 ```
gcc 4.4.4 c89 I have the following in my state.c file: ``` enum State { IDLE_ST, START_ST, RUNNING_ST, STOPPED_ST, }; State g_current_state = State.IDLE_ST; ``` I get the following error when I try and compile. ``` error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘g_current_state’ ``` Is there some with declaring a variable of type enum in global scope? Many thanks for any suggestions,
There are two ways to do this in straight C. Either use the fullenumname everywhere: ``` enum State { IDLE_ST, START_ST, RUNNING_ST, STOPPED_ST, }; enum State g_current_state = IDLE_ST; ``` or (this is my preference)typedefit: ``` typedef enum { IDLE_ST, START_ST, RUNNING_ST, STOPPED_ST, } State; State g_current_state = IDLE_ST; ``` I prefer the second one since it makes the type look like a first class one likeint.
If I have a 4 byte address stored in char address[4] and the contents are: ``` address[0] = '\x80'; address[1] = '\xAB'; address[2] = '\x0A'; address[3] = '\x1C'; // all together: 80 AB 0A 1C ``` I want to convert it to a character array that looks like "128.171.10.28", since 80 in hex is 128, AB in hex is 171 and so on. How can I do this?
``` char saddr[16]; sprintf(saddr, "%d.%d.%d.%d", (unsigned char)address[0], (unsigned char)address[1], (unsigned char)address[2], (unsigned char)address[3]); ``` or ``` char saddr[16]; unsigned char *addr = (unsigned char*)address; sprintf(saddr, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]); ``` or, as pointed out by dreamlax: ``` char saddr[16]; sprintf(saddr, "%hhu.%hhu.%hhu.%hhu", address[0], address[1], address[2], address[3]); ```
This question already has answers here:self referential struct definition?(9 answers)Closed6 years ago. ``` struct node{ struct node next; int id; } ``` gives "field next has incomplete type error ". what is wrong with this struct ?
When creating a self-referential data type, you need to use pointers to get around problems of circularity: ``` struct node; struct node { struct node * next; int id; } ``` ...should work, but take care to allocate memory correctly when using it. Why a pointer? Consider this: the point of astructdefinition is so that the compiler can figure out how much memory to allocate and what parts to access when you saynode.id. If yournodestruct contains anothernodestruct, how much memory should the compiler allocate for a givennode? By using a pointer you get around this, because the compiler knows how much space to allocate for a pointer.
I'm working on this project that uses proxy server and curl in c and i cant find a good tutorial that teaches me how to. Can you please help me?? i need an example code that shows the use of a proxy server to connect to google.com. maybe using the CURLOPT_PROXY option.. Thanks in advance.
Well all you do is yournormal curlretrieval, but just set the proxy server option. ``` curl_easy_setopt(handle, CURLOPT_PROXY, "127.0.0.1:96666"); ``` EDIT ``` /* create headers */ struct curl_slist *headers=NULL; headers = curl_slist_append(headers, "Content-Type: text/xml"); /* pass our list of custom made headers */ curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers); ```
I have a function that takes as one of its parameters "void* buffer". In this function, I need to write to that memory location. However, doing something like ``` *buffer = "Hello\0Hi\0"; ``` doesn't work because I can't dereference a void* pointer. How do I puta stringdata into that memory location? Note that I need to copy data, not necessarily a string, as it may contain the null character. Updatedto reflect that strcpy is not enough
If you string "may contain the null character," then it isn't really a C string. If you need to copy a certain number of bytes from one memory location to another, regardless of the contents, you can usememcpy. You can get the size of the string literal usingsizeof(this size includes the final, implicit null terminator).
I use the Tiny C Compiler and I want to useGetUserNamefrom the WinAPI. My problem is, I don't know how to link toadvapi32.dll I get an error from tcc: ``` undefined symbol '_GetUserNameA@8' ```
I explained how to create a .def file from a dll and how to compile and link with tcc here:Tiny C Compiler (TCC) and winsock?
I have a function sayformula(f), where f is a TERM and TERM is a structure pointer. This function prints a formula likeforall([U,V],implies(U,V)].These U and V are variable. I need to pass the values in these variable and have to generate the forumula according the combination of the values of the variable.Suppose the values of the U and V are 2 and 2 then it has to generate the 4 formulas likeforall([a_1,b_1]implies(a_1,b_1),forall([a_1,b_2]implies(a_1,b_2))and so on... Can anybody please help me how to generate it?
Presuming that yourTERMstructure has U and V as integer members: ``` void formula(TERM* term) { int x = 0; int y = 0; for (x; x < (*term).U; ++x) for (y; y < (*term).J; ++y) printf("forall([a_%d,b_%d] implies(a_%d, b_%d))\n", x, y, x, y); } ``` Is this what you're looking for?
``` #include<stdio.h> void compute(int); int cube(int); int main( ) { compute(3); } void compute(int in) { int res=0,i; for(i=1;i<=in;i++); { res=cube(i); printf("%d %d",res,i); } } int cube(int n) { return (n*n*n); } ``` ~output : 64 4 How does it happen ?
Semicolon at the end of yourforline.
I am using the latest gcc with Netbeans on Windows. Why doesn'tlong doublework? Is theprintfspecifier%lfwrong? Code: ``` #include <stdio.h> int main(void) { float aboat = 32000.0; double abet = 5.32e-5; long double dip = 5.32e-5; printf("%f can be written %e\n", aboat, aboat); printf("%f can be written %e\n", abet, abet); printf("%lf can be written %le\n", dip, dip); return 0; } ``` Output: ``` 32000.000000 can be written 3.200000e+004 0.000053 can be written 5.320000e-005 -1950228512509697500000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000.000000 can be written 2.725000e+002 Press [Enter] to close the terminal ... ```
Yes -- forlong double, you need to use%Lf(i.e., upper-case 'L').
programming in C with the X11 library, is there a way to get notified if a new window has appeared? I foundXSetAfterFunctionbut its intended for debugging purposes only ... Thanks for your help! Heinrich @edit: This code solves my problem ``` int main() { Display* display = XOpenDisplay(":2"); XSetWindowAttributes attributes; attributes.event_mask = SubstructureNotifyMask | StructureNotifyMask; XChangeWindowAttributes(display, 0x100, CWEventMask, &attributes); while (true) { XEvent event; XNextEvent(display, &event); std::cout << "Event occured" << std::endl; } return 0; } ```
From memory, you can use XChangeWindowAttributes to listen to events from the root window, then act on XMapEvent (or XCreateWindowEvent or whateverEvent depending on your definition of "a new window has appeared").
I am working on logger using C language on QNX platform using Momnetics to print time in following format 2010-11-02 14:45:15.000 I able to get date, hour, minutes, and seconds using ``` time(&timeSpec); struct tm gmt; int iSysTimeSec = timeSpec; gmtime_r((time_t *)&iSysTimeSec, &gmt); sprintf(&MsgStamp[0], SYS_MSG_STAMP_PRINTF_FORMAT, gmt.tm_year+1900, gmt.tm_mon + 1, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec, iSysTimeMs ); ``` Question is how do i get milliseconds granularity using QNX Momentics. I tried to get granulaity for milliseconds using QNX specific int iSysTimeMs = ( (ClockCycles () * 1000) / SYSPAGE_ENTRY(qtime)->cycles_per_sec ) % 1000; but i want to do this POSIX way so that it is portable. How do we do this? Thanks! Venkata
In QNX6 You can use the clock_gettime to have the max granularity allowed by system. ``` struct timespec start; clock_gettime( CLOCK_REALTIME, &start); ```
I need to convert an int to a 2 byte hex value to store in a char array, in C. How can I do this?
If you're allowed to use library functions: ``` int x = SOME_INTEGER; char res[5]; /* two bytes of hex = 4 characters, plus NULL terminator */ if (x <= 0xFFFF) { sprintf(&res[0], "%04x", x); } ``` Your integer may contain more than four hex digits worth of data, hence the check first. If you're not allowed to use library functions, divide it down into nybbles manually: ``` #define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i) int x = SOME_INTEGER; char res[5]; if (x <= 0xFFFF) { res[0] = TO_HEX(((x & 0xF000) >> 12)); res[1] = TO_HEX(((x & 0x0F00) >> 8)); res[2] = TO_HEX(((x & 0x00F0) >> 4)); res[3] = TO_HEX((x & 0x000F)); res[4] = '\0'; } ```
I am trying different kinds of parallelization using OpenMP. As a result I have several lines of#pragma omp parallel forin my code which I (un-)comment alternating. Is there a way to make these lines conditional with something like the following, not working code? ``` define OMPflag 1 #if OMPFlag pragma omp parallel for for ... ```
C99 has the_Pragmakeyword that allows you to place what otherwise would be#pragmainside macros. Something like ``` #define OMP_PARA_INTERNAL _Pragma("omp parallel for") #if [your favorite condition] #define OMP_FOR OMP_PARA_INTERNAL for #else #define OMP_FOR for #endif ``` and then in your code ``` OMP_FOR (unsigned i; i < n; ++i) { ... } ```
``` char * myFunction () { char sub_str[10][20]; return sub_str; } void main () { char *str; str = myFunction(); } ``` error:return from incompatible pointer type thanks
A string array in C can be used either withchar**or withchar*[]. However, you cannot return values stored on the stack, as in your function. If you want to return the string array, you have to reserve it dynamically: ``` char** myFunction() { char ** sub_str = malloc(10 * sizeof(char*)); for (int i =0 ; i < 10; ++i) sub_str[i] = malloc(20 * sizeof(char)); /* Fill the sub_str strings */ return sub_str; } ``` Then, main can get the string array like this: ``` char** str = myFunction(); printf("%s", str[0]); /* Prints the first string. */ ``` EDIT: Since we allocatedsub_str, we now return amemory addressthat can be accessed in the main
There is integer variable, voltage in millivolts. ``` signed int voltage_mv = 134; //134mV ``` I have 2-segment display and I want to display hundredths of volts. How can I convert milivolts to hundredths volts in one operation? Without IF statement, without function? ``` 134 => 13 135 => 14 ```
How about simple rounding: ``` int millivoltToDisplay (int millivolts) { return (millivolts+5)/10; } ``` (written as a function for clarity)
in php ``` $arr = array() $arr[0] = "string 1"; $arr[1] = "string 2"; ``` how about in c? thanks
You need to declare an array of pointers. Each element of the array is a pointer to the string. You need to copy the string in, and then release it when done. ``` char *strings[2]; strings[0] = strdup("Hello, world!"); printf("%s\n", strings[0]); free(strings[0]); ```
For example: ``` console> please enter 3 digits: 1 2 3 ``` I only know how to accept 1 digit usingscanf: ``` scanf("%d", &space); ```
You can read in multiple numbers with scanf ``` int a, b, c; scanf("%d %d %d", &a, &b, &c); ```
I've been going through some C source code and I noticed the following: ``` void some_func (char *foo, struct bar *baz) { (void)foo; (void)baz; } ``` Why isvoidused here? I know(void)before an expression explicitly indicates that the value isthrown away; but can someone please explain me the rationale for such an use?
This code ensures that you won't get a compiler warning about foo and baz being unused.
``` int SDL_BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect); ``` Why are the srcrect and dstrect arguments not const? Are they modified in the function? At the moment I'm const-casting my Sprite class member variables to use BlitSurface... It seems silly.
Becausethey're modified.
Is there anywhere on the web where i can get an idea of what the various programming language syntax take in terms of processor (Core i7 and Core 2) cycles? At university i learnt the ARM assembly language and we could map the number of cycles taken to do a subtraction operator etc. I just wondered if its possible to do this with a higher level language on the Core i7 or Core 2?
No. That's completely dependent on the compiler you use, and what optimization settings you use, etc. You can use your favorite compiler and settings to generate assembly code, and from the assembly code you can make these kinds of predictions. However, remember that on modern architectures things like memory latency and register renaming have large effects on speed, and these effects are not obvious even from inspection of the assembly code.
What is a good C compiler for OSX or Windows XP or DOS? I would like to make a GUI shell for DOS. Also what is a good pascal compiler for these platforms?
On Mac OS X, you should use the GNU Compiler Collection (GCC). You can install it by downloading and installing the freeXcode Developer Tools. On Windows, you can also install GCC (usingCygwin).