question
stringlengths
25
894
answer
stringlengths
4
863
What are the different types of Linked Lists which are commonly used? I know and have used the following: Singly Linked ListDoubly Linked ListCircular List What are the other kinds of lists that have been used by you or known to you?
Unrolled Linked List In computer programming, an unrolled linked list is a variation on the linked list which stores multiple elements in each node. It can drastically increase cache performance, while decreasing the memory overhead associated with storing list metadata such as references. It is related to the B-tree. - Wikipedia XOR Linked List XOR linked lists are a data structure used in computer programming. They take advantage of the bitwise exclusive disjunction (XOR) operation, here denoted by ⊕, to decrease storage requirements for doubly-linked lists. - Wikipedia
I've read that mysql_store_result() in the MySQL C API will allocate memory for each and every call to it; ``` mysql_store_result() reads the entire result of a query to the client, allocates a MYSQL_RES structure, and places the result into this structure. ``` It is really so? I'm asking because I'm about to call it many times in a server application. Allocating/Freeing is horrible for my purpose. Is there a way to provide a custom buffer to it? Maybe some "undocumented" API?
See this link about using mysql_use_result:http://dev.mysql.com/doc/refman/5.0/en/mysql-use-result.html i use "use_result" instead of "store_result" on all select queries.
Does your editor/ide highlight thata++;in this C/C++ code as part of a comment? ``` int a=1; //some comment \ a++; printf("%d\n",a); ``` And what about this? ``` int a=1; //some comment ??/ a++; printf("%d\n",a); ```
VC6, Visual Studio 2003, 2005, 2008, 2010 all do.
I'm looking to follow along withThe C Programming Language (Second Addition)on a machine running Vista. So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output. How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution,System("pause"), and a really ugly C solution,whileloopingfflush(stdout), but nothing nice and pretty.
I put agetchar()at the end of my programs as a simple "pause-method". Depending on your particular details, investigategetchar,getch, orgetc
Is there a version of fnmatch for Windows? I'm trying to have the same functionality (basically using *'s from the command line for the filename)in Cwithout having to call FindFirst() etc. Code is appreciated. EDIT: I need to accept wild cards from the command line for filenames, for example *.txt and be able to open each .txt file. As I said, I don't want to use if possible FindFirst, FindNext. Thanks
PathMatchSpecExwould be roughly equivalent, though it takes arguments in the opposite order.
Pardon if this question has been answered but I couldn't find it. I'm kinda confused aboutrecv()andrecvfrom(). Once the server binds the address (or accepts connection for TCP),recv()is called. Doesrecv()constantly check for messages that has been sent or does it wait until a message is received? If it does wait, how long is the wait time? Not sure if I'm making sense, but if someone could enlighten me, I'd be grateful.
If no messages are available at the socket andO_NONBLOCKis not set on the socket's file descriptor,recv() shall block until a message arrives.If no messages are available at the socket andO_NONBLOCKis set on the socket's file descriptor,recv() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK]. Source:http://www.opengroup.org/onlinepubs/009695399/functions/recv.html
I am writing C code for anAVRchip. The code is heavy oninterrupt service routines(ISRs) which wait on serial ports,ADCsand timers. The ISRs write to buffers which the main loop examines when it gets to them. I design the buffers so that ISRs can update them while the main loop is reading them. I want to verify that this works. I have unit tests to validate basic operation, but I'm not clear on how to test what happens if an interrupt fires while the main loop is reading a buffer. My unit tests are really basic--some code in amain()function. I run the tests on my Linux box.
Threads? Launch a high-priority thread which calls your ISR at some rate similar to the real thing. Then in your main, do the buffer read over and over again in a loop. Validate that the buffer read is not corrupted. (Maybe this is more of an integration test than a pure unit test.)
I write software for the disabled. One of the problems is difficulty tracking the mouse pointer. I want to have the mouse cursor glow (or similar effect. Maybe water like ripples around it) when the user needs to locate it. How is this done? I know it's possible because it's used in a variety of software.
You can create custom animated cursors "on the fly" by using CreateIconFromResource and painstakingly creating the cursor data structures yourself. I recently added some tests to the Wine project for creating cursors in this way, you can take a look at the structure of the cursor data by looking at this example for a three-frame cursor:http://source.winehq.org/source/dlls/user32/tests/cursoricon.c?v=wine-1.3.16#L222
For example, I'm supposed to convert "int" to "INT". But if there's the word "integer", I don't think it's supposed to turn into "INTeger". If I define"int" printf("INT");the substrings are matched though. Is there a way to prevent this from happening?
I believe the following captures what you want. ``` %{ #include <stdio.h> %} ws [\t\n ] %% {ws}int{ws} { printf ("%cINT%c", *yytext, yytext[4]); } . { printf ("%c", *yytext); } ``` To expand this beyond word boundaries ({ws}, in this case) you will need to either add modifiers towsor add more specifc checks.
When I copy code from another file, the formatting is messed up, like this: ``` fun() { for(...) { for(...) { if(...) { } } } } ``` How can I autoformat this code in vim?
Try the following keystrokes: ``` gg=G ``` Explanation:gggoes to the top of the file,=is a command to fix the indentation andGtells it to perform the operation to the end of the file.
``` int a = -534; unsigned int b = (unsigned int)a; printf("%d, %d", a, b); ``` prints-534, -534 Why is the typecast not taking place? I expected it to be-534, 534 If I modify the code to ``` int a = -534; unsigned int b = (unsigned int)a; if(a < b) printf("%d, %d", a, b); ``` its not printing anything... after allais less thanb??
Because you use%dfor printing. Use%ufor unsigned. Since printf is a vararg function, it cannot know the types of the parameters and must instead rely on the format specifiers. Because of this the type cast you do has no effect.
If I write a C program then it will not automatically get out of if else like .... ``` #include<stdio.h> int main () { int a, b, c, d; printf ("enter the value "); scanf("%d %d %d ",&a,&b,&c); d=a+b+c; if(d==180) printf("triangle is valid "); else printf("triangle is invalid "); return 0; } ``` then it will not terminate itself..... Can anyone help to figure out what the problem in this .....
It's the space at the end of the scanf format string. Remove that space and your program will terminate.
I am not able to understand the following statement from the file limits.h. What is the use of this statement and what does it accomplishes? ``` /* If we are not using GNU CC we have to define all the symbols ourself. Otherwise use gcc's definitions (see below). */ #if !defined __GNUC__ || __GNUC__ < 2 ```
It checks if your program is compiled by some other compiler than GCC, or some very old GCC version.
I'm developing a fairly simple C project for an embedded device. I'd like to employ xUnit testing. I've settled down with the Check framework (http://check.sourceforge.net/), but it seems it doesn't support function stubs. I remember using a very syntactically similar framework a few years ago that supported stubs, but i can't remember its name. So, can anyone suggest an xUnit framework for C that supports stubs? A way to imitate stubs while using Check library would be OK, too.
Cgreen supports mock functions, is this what you want? https://cgreen-devs.github.io/#_what_are_mock_functions
I am trying to control ftp client from C program (OS X). I did fork and execve - process is started ok. The problem is with pipes - I can send command to ftp client process and get feedback from it just fine (If i send "help\n" i get back help output) but what I never get in pipe is "ftp> " prompt. Any ideas? Ivan
Your ftp client is probably behaving differently if stdin/stdout is a terminal or something else (lots of program do, for a start the C library does buffering in a different way...) If you want to control that, search information about pseudo-terminals, that's a little too technical to be explained here. (And looks first at programs likeexpect, it's possible you won't have to write yours).
What happens inside memory if we try to free a pointer which is pointing to NULL? Is that ever valid? Why does it not show any warning/error messages?
From C99 section 7.20.3.2 : Thefreefunction Synopsis ``` 1 #include <stdlib.h> void free(void *ptr); ``` Description 2 The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.If ptr is a null pointer, no action occurs.
This question already has answers here:Closed13 years ago. Possible Duplicate:Why does tm_sec range from 0-60 instead of 0-59 in time.h? So when I looked up<time.h>for some info, I ran across this. I'm assuming the numbers in the square brackets are the ranges possible for each respective member of the structure. So why is there 0~61 possible range for seconds? Were there 62 seconds in each minute and I'm the only one who didn't know about it??? ``` int tm_sec seconds [0,61] // <-- this part is weird int tm_min minutes [0,59] int tm_hour hour [0,23] int tm_mday day of month [1,31] int tm_mon month of year [0,11] int tm_year years since 1900 int tm_wday day of week [0,6] (Sunday = 0) int tm_yday day of year [0,365] int tm_isdst daylight savings flag ```
Leap seconds.
I want to get a HTML and use like a file in C. Actually I can do that, but I have to save the file first on the disk and then use fopen("/file.html", "r");. What I would like to do is to extract the html directly from the URL and work with it. Hypothetically, fopen("http://www.google.com", "r"); I saw something about libcurl but I don't know if it will help me.
You can do something as simple as: ``` #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com"); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); } return 0; } ``` Source:Using cURL in C You can get the complete function documentations here:Using The libcurl C Interface ThisPDFlink will help you in using libcurl in VS
for C, is there a function that takes an int and doesn't execute next statement ? ``` printf("a"); wait(500); printf("b"); ``` b will be printed after 500ms after a is printed out. something of the sort. sorry for the stupid question but i wasn't sure how to go about searching for such function.
There is nothing like that in standard C. However, POSIX defines thesleep()function (which takes an argument in seconds),usleep()(which takes an argument in microseconds), andnanosleep()(nanosecond resolution). It is also possible to use theselect()function withNULLfor all three file descriptor sets to sleep for sub-second periods, on older systems which don't haveusleep()ornanosleep()(this is not so much a concern these days).
Is it just to test compile a simple program, with that header file #included in it? To better understand the compilation process I'm writing my own "configure", which tests for the existence of a few header and library files.
Yes, use the compiler to compile your simple test program. That's the best and easiest way to see if the compiler can find the header. If you hard code #include search paths you'll always have to modify and adapt for different compilers.
I am trying to make a simple twitter client in C. I'm new at this and not sure how to go about segregating meaningful stuff from the JSON string that I get from the API. For example, if I getthisas a response from the API, how do I extract out the value of "text" into a string (char*)? I guess I can work with the string at low level, but wouldn't that become too tedious every time I need to get a value from the JSON string?
For JSON in general,json.orghas a big list of parsers implemented in a ton of different languages. For C: JSON_checkerJSON parserjson-cM's JSON parserYAJLcJSONJanssonjsmn
I am looking for theCprogram for reverse the digits like below: If i enter: 123456 Then the result would be: 654321 Please help me.
Here is a simple solution to this complex problem: ``` #include <stdio.h> int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } } ``` A new version that outputs the newline: ``` #include <stdio.h> #include <stdlib.h> static void newline(void) { printf("\n"); } int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } else { atexit(newline); } } ```
How can I write to/generate a *.doc file programmatically using c or c++? Is there a (open source/cross platform) library to do this? If this is not possible, can write an *.odt file and then convert it to *.doc? Thanks in advance! EDIT: Anders Abel commented that *.rtf file type is an option, so any suggestions on this one are also accepted.
Joel has an interesing article about this topic:http://www.joelonsoftware.com/items/2008/02/19.html Basically he suggest either: Use MS Word via COM to create the document.Generate another format that MS Word will load, such as RTF. RTF has the advantage that it is a text format. So you can generate a template document with place holders, and then just run a substitution operation when you want to generate your documents.
Is there a simple library to benchmark the time it takes to execute a portion of C code? What I want is something like: ``` int main(){ benchmarkBegin(0); //Do work double elapsedMS = benchmarkEnd(0); benchmarkBegin(1) //Do some more work double elapsedMS2 = benchmarkEnd(1); double speedup = benchmarkSpeedup(elapsedMS, elapsedMS2); //Calculates relative speedup } ``` It would also be great if the library let you do many runs, averaging them and calculating the variance in timing!
Use the functionclock()defined intime.h: ``` startTime = (float)clock()/CLOCKS_PER_SEC; /* Do work */ endTime = (float)clock()/CLOCKS_PER_SEC; timeElapsed = endTime - startTime; ```
I have created a header file and a corresponding .c file full of functions I would like to use with a java program. I created a JNI header file using javah. I'm using gcc to compile my header file. How can I link my regular c object file with my JNI static library to get a static library that utilizes my C library? I'm using gcc to compile. Here's an example of what I'm asking: ``` lib.h lib.c JNITest.h JNITest.c (uses lib.h functions) ```
You might try looking at thishttp://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html
What I need to do is use the read function from unistd.h to read a file line by line. I have this at the moment: ``` n = read(fd, str, size); ``` However, this reads to the end of the file, or up to size number of bytes. Is there a way that I can make it read one line at a time, stopping at a newline? The lines are all of variable length. I am allowed only these two header files: ``` #include <unistd.h> #include <fcntl.h> ``` The point of the exercise is to read in a file line by line, and output each line as it's read in. Basically, to mimic the fgets() and fputs() functions.
You can read character by character into a buffer and check for the linebreak symbols (\r\nfor Windows and\nfor Unix systems).
Could you please explain to me theWINAPIword in theWinMain()function? In the simplest way.. ``` #include <windows.h> int -->WINAPI<-- WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, "Goodbye, cruel world!", "Note", MB_OK); return 0; } ``` Is it just some Windows funky mode? What does it do? Or rather what is this C++ feature I haven't encountered yet?
WINAPIis a macro that evaluates to__stdcall, a Microsoft-specific keyword that specifies a calling convention where the callee cleans the stack. The function's caller and callee need to agree on a calling convention to avoid corrupting the stack.
This question already has answers here:Closed13 years ago. Possible Duplicate:Why does tm_sec range from 0-60 instead of 0-59 in time.h? So when I looked up<time.h>for some info, I ran across this. I'm assuming the numbers in the square brackets are the ranges possible for each respective member of the structure. So why is there 0~61 possible range for seconds? Were there 62 seconds in each minute and I'm the only one who didn't know about it??? ``` int tm_sec seconds [0,61] // <-- this part is weird int tm_min minutes [0,59] int tm_hour hour [0,23] int tm_mday day of month [1,31] int tm_mon month of year [0,11] int tm_year years since 1900 int tm_wday day of week [0,6] (Sunday = 0) int tm_yday day of year [0,365] int tm_isdst daylight savings flag ```
Leap seconds.
I want to get a HTML and use like a file in C. Actually I can do that, but I have to save the file first on the disk and then use fopen("/file.html", "r");. What I would like to do is to extract the html directly from the URL and work with it. Hypothetically, fopen("http://www.google.com", "r"); I saw something about libcurl but I don't know if it will help me.
You can do something as simple as: ``` #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com"); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); } return 0; } ``` Source:Using cURL in C You can get the complete function documentations here:Using The libcurl C Interface ThisPDFlink will help you in using libcurl in VS
for C, is there a function that takes an int and doesn't execute next statement ? ``` printf("a"); wait(500); printf("b"); ``` b will be printed after 500ms after a is printed out. something of the sort. sorry for the stupid question but i wasn't sure how to go about searching for such function.
There is nothing like that in standard C. However, POSIX defines thesleep()function (which takes an argument in seconds),usleep()(which takes an argument in microseconds), andnanosleep()(nanosecond resolution). It is also possible to use theselect()function withNULLfor all three file descriptor sets to sleep for sub-second periods, on older systems which don't haveusleep()ornanosleep()(this is not so much a concern these days).
Is it just to test compile a simple program, with that header file #included in it? To better understand the compilation process I'm writing my own "configure", which tests for the existence of a few header and library files.
Yes, use the compiler to compile your simple test program. That's the best and easiest way to see if the compiler can find the header. If you hard code #include search paths you'll always have to modify and adapt for different compilers.
I am trying to make a simple twitter client in C. I'm new at this and not sure how to go about segregating meaningful stuff from the JSON string that I get from the API. For example, if I getthisas a response from the API, how do I extract out the value of "text" into a string (char*)? I guess I can work with the string at low level, but wouldn't that become too tedious every time I need to get a value from the JSON string?
For JSON in general,json.orghas a big list of parsers implemented in a ton of different languages. For C: JSON_checkerJSON parserjson-cM's JSON parserYAJLcJSONJanssonjsmn
I am looking for theCprogram for reverse the digits like below: If i enter: 123456 Then the result would be: 654321 Please help me.
Here is a simple solution to this complex problem: ``` #include <stdio.h> int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } } ``` A new version that outputs the newline: ``` #include <stdio.h> #include <stdlib.h> static void newline(void) { printf("\n"); } int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } else { atexit(newline); } } ```
How can I write to/generate a *.doc file programmatically using c or c++? Is there a (open source/cross platform) library to do this? If this is not possible, can write an *.odt file and then convert it to *.doc? Thanks in advance! EDIT: Anders Abel commented that *.rtf file type is an option, so any suggestions on this one are also accepted.
Joel has an interesing article about this topic:http://www.joelonsoftware.com/items/2008/02/19.html Basically he suggest either: Use MS Word via COM to create the document.Generate another format that MS Word will load, such as RTF. RTF has the advantage that it is a text format. So you can generate a template document with place holders, and then just run a substitution operation when you want to generate your documents.
Is there a simple library to benchmark the time it takes to execute a portion of C code? What I want is something like: ``` int main(){ benchmarkBegin(0); //Do work double elapsedMS = benchmarkEnd(0); benchmarkBegin(1) //Do some more work double elapsedMS2 = benchmarkEnd(1); double speedup = benchmarkSpeedup(elapsedMS, elapsedMS2); //Calculates relative speedup } ``` It would also be great if the library let you do many runs, averaging them and calculating the variance in timing!
Use the functionclock()defined intime.h: ``` startTime = (float)clock()/CLOCKS_PER_SEC; /* Do work */ endTime = (float)clock()/CLOCKS_PER_SEC; timeElapsed = endTime - startTime; ```
I have created a header file and a corresponding .c file full of functions I would like to use with a java program. I created a JNI header file using javah. I'm using gcc to compile my header file. How can I link my regular c object file with my JNI static library to get a static library that utilizes my C library? I'm using gcc to compile. Here's an example of what I'm asking: ``` lib.h lib.c JNITest.h JNITest.c (uses lib.h functions) ```
You might try looking at thishttp://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html
What I need to do is use the read function from unistd.h to read a file line by line. I have this at the moment: ``` n = read(fd, str, size); ``` However, this reads to the end of the file, or up to size number of bytes. Is there a way that I can make it read one line at a time, stopping at a newline? The lines are all of variable length. I am allowed only these two header files: ``` #include <unistd.h> #include <fcntl.h> ``` The point of the exercise is to read in a file line by line, and output each line as it's read in. Basically, to mimic the fgets() and fputs() functions.
You can read character by character into a buffer and check for the linebreak symbols (\r\nfor Windows and\nfor Unix systems).
I am looking for theCprogram for reverse the digits like below: If i enter: 123456 Then the result would be: 654321 Please help me.
Here is a simple solution to this complex problem: ``` #include <stdio.h> int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } } ``` A new version that outputs the newline: ``` #include <stdio.h> #include <stdlib.h> static void newline(void) { printf("\n"); } int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } else { atexit(newline); } } ```
How can I write to/generate a *.doc file programmatically using c or c++? Is there a (open source/cross platform) library to do this? If this is not possible, can write an *.odt file and then convert it to *.doc? Thanks in advance! EDIT: Anders Abel commented that *.rtf file type is an option, so any suggestions on this one are also accepted.
Joel has an interesing article about this topic:http://www.joelonsoftware.com/items/2008/02/19.html Basically he suggest either: Use MS Word via COM to create the document.Generate another format that MS Word will load, such as RTF. RTF has the advantage that it is a text format. So you can generate a template document with place holders, and then just run a substitution operation when you want to generate your documents.
Is there a simple library to benchmark the time it takes to execute a portion of C code? What I want is something like: ``` int main(){ benchmarkBegin(0); //Do work double elapsedMS = benchmarkEnd(0); benchmarkBegin(1) //Do some more work double elapsedMS2 = benchmarkEnd(1); double speedup = benchmarkSpeedup(elapsedMS, elapsedMS2); //Calculates relative speedup } ``` It would also be great if the library let you do many runs, averaging them and calculating the variance in timing!
Use the functionclock()defined intime.h: ``` startTime = (float)clock()/CLOCKS_PER_SEC; /* Do work */ endTime = (float)clock()/CLOCKS_PER_SEC; timeElapsed = endTime - startTime; ```
I have created a header file and a corresponding .c file full of functions I would like to use with a java program. I created a JNI header file using javah. I'm using gcc to compile my header file. How can I link my regular c object file with my JNI static library to get a static library that utilizes my C library? I'm using gcc to compile. Here's an example of what I'm asking: ``` lib.h lib.c JNITest.h JNITest.c (uses lib.h functions) ```
You might try looking at thishttp://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html
What I need to do is use the read function from unistd.h to read a file line by line. I have this at the moment: ``` n = read(fd, str, size); ``` However, this reads to the end of the file, or up to size number of bytes. Is there a way that I can make it read one line at a time, stopping at a newline? The lines are all of variable length. I am allowed only these two header files: ``` #include <unistd.h> #include <fcntl.h> ``` The point of the exercise is to read in a file line by line, and output each line as it's read in. Basically, to mimic the fgets() and fputs() functions.
You can read character by character into a buffer and check for the linebreak symbols (\r\nfor Windows and\nfor Unix systems).
Could you please explain to me theWINAPIword in theWinMain()function? In the simplest way.. ``` #include <windows.h> int -->WINAPI<-- WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, "Goodbye, cruel world!", "Note", MB_OK); return 0; } ``` Is it just some Windows funky mode? What does it do? Or rather what is this C++ feature I haven't encountered yet?
WINAPIis a macro that evaluates to__stdcall, a Microsoft-specific keyword that specifies a calling convention where the callee cleans the stack. The function's caller and callee need to agree on a calling convention to avoid corrupting the stack.
I have just started C very recently and I have been asked to answer some coding exercises in which the following piece of code appears: ``` typedef enum { false = 0, true = 1 } Bool; ``` Could someone please provide a brief and clear explanation to that? Thanks very much.
It's really doing two things; you can break it down something like this: ``` enum _bool { false = 0, true = 1 }; ``` And: ``` typedef enum _bool Bool; ``` This code creates a new enumeration type and then usestypedefto give it a convenient name. It would let you use a new 'type' calledBoolelsewhere in your code, and assign it the valuesfalseandtrue. Here's a simple use case: ``` Bool logical_not(Bool in) { if (in == true) return false; else return true; } ```
I am compiling under Linux (GCC 4.4.2) and Windows VS C++ Express Edition 2008 I am currently compiling under Windows XP Pro 32 bit, and have added this to my source code. ``` #if defined( WIN32 ) /* Do windows stuff here */ #endif ``` However, the code in the if statement is disabled (grayed out). However if I do the following: ``` #if defined( _MSC_VER ) /* Do windows stuff here */ #endif ``` The if statement code is enabled. I am just wondering, what should I be using. I have seen many programmers use WIN32. However, doesn't seem to work for me. Should I be using _MSC_VER instead? Many thanks for any advice,
There is noWIN32. If you've seen it being used elsewhere, it's either wrong or the code is explicitly defining that macro itself somewhere. You want_WIN32. Seehttps://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macrosfor a list of predefined macros in Microsoft's compiler.
I'm using the FNV hash as a hashing algorithm on my Hash Table implementation but I'm getting the warning in the question title on this line: ``` unsigned hash = 2166136261; ``` I don't understand why this is happening because when I do this: ``` printf("%u\n", UINT_MAX); printf("2166136261\n"); ``` I get this: ``` 4294967295 2166136261 ``` Which seems to be under the limits of my machine... Why do I get the warning and what are my options to get rid of it?
``` unsigned hash = 2166136261u; // note the u. ``` You need a suffixuto signify this is an unsigned number. Without theusuffix it will be a signed number. Since ``` 2166136261 > 2³¹ - 1 = INT_MAX, ``` this integer literal will be problematic.
I try to define a 64 bits width integer using C language on Ubnutu 9.10. 9223372036854775808 is 2^23 ``` long long max=9223372036854775808 long max=9223372036854775808 ``` When I compile it, the compiler gave the warning message: ``` binary.c:79:19: warning: integer constant is so large that it is unsigned binary.c: In function ‘bitReversal’: binary.c:79: warning: this decimal constant is unsigned only in ISO C90 binary.c:79: warning: integer constant is too large for ‘long’ type ``` Is the long type 64 bits width? Best Regards,
``` long long max=9223372036854775808LL; // Note the LL // long max=9223372036854775808L; // Note the L ``` Along longtype is at least 64 bit, alongtype is at least 32 bit. Actual width depends on the compiler and targeting platform. Useint64_tandint32_tto ensure the 64-/32-bit integer can fit into the variable.
Is there a "proper" way to clear the console window in C, besides usingsystem("cls")?
``` printf("\e[1;1H\e[2J"); ``` This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window's console, since it also supports ANSI escape sequences. ``` #include <unistd.h> void clearScreen() { const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J"; write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12); } ``` There are some otheralternatives, some of which don't move the cursor to {1,1}.
I'm working on a client-server application written in C. I want to broadcast a message to all the machines available on the local network. How can I do that using the usual socket system calls in C?
Just send the message to the broadcast address of your subnet, which for 192.168.0.0/24 is 192.168.0.255, or just broadcast to 255.255.255.255.
I m looking for a faster implementation or good a approximation of functions provided bycmath. I need to speed up the following functions pow(x,y)exp(z*pow(x,y)) wherez<0.xis from (-1.0,1.0) andyis from (0.0, 5.0)
Here are some approxmiations: Optimized pow Approximation for Java and C / C++. This approximation is very inaccurate, you have to try for yourself if it is good enough.Optimized Exponential Functions for Java. Quite good! I use it for a neural net. If the above approximation for pow is not good enough, you can still try to replace it with exponential functions, depending on your machine and compiler this might be faster: x^y = e^(y*ln(x))And the result:e^(z * x^y) = e^(z * e^(y*ln(x))) Another trick is when some parameters of the formula do not change often. So if e.g. x and y are mostly constant, you can precalculate x^y and reuse this.
Is there any way to get the source code by using object file in C? For example I have a source code simple.c cc simple.c Now I have a.out (object file). By this a.out whether can I get the source? code of simple.c
No. Turning a cow into hamburger is fairly easy. Turning hamburger into a living cow, somewhat more difficult.
I want to have a static array with arrays in it. I know you can make a normal array like this: ``` int test[] = {1,2,3,4}; ``` But I want to do something like this (Xcode gives me a bunch of warnings and stuff): ``` int test[] = {{1,2}, {3,4}}; ``` In python it would be: ``` arr = [[1,2], [3,4]]; ``` What's the proper way to do this?
To have a multidimensional array, you'd need two levels of arrays: ``` int test[][] = {{1,2}, {3,4}}; ``` However, thatwill not work, as you need to declare the size of the inner-most arrays except the last one: ``` int test[2][] = {{1,2}, {3,4}}; ``` Or if you need an even stricter type safety: ``` int test[2][2] = {{1,2}, {3,4}}; ```
I'm using the old good Mixer API right now, but it does not work as expected on Windows Vista & 7 in the normal, not in XP compatibility mode. It mutes the sound for the current app only, but I need a global (hardware) mute. How to rearch the goal? Is there any way to code this w/o COM interfaces and strange calls, in pure C/C++?
The audio stack was significantly rewritten for Vista. Per-application volume and mute control was indeed one of the new features. Strange calls will be required to use theIAudioEndpointVolume interface.
I want to convertWinMain'scmdLineargument toargcandargvso I can use the argument parsing function I wrote for console applications. This would be trivial except that I want to support "quotes" too. For example: test.exe test1 test2 "testing testing" should be ``` argv[0] = "test.exe"; argv[1] = "test1"; argv[2] = "test2"; argv[3] = "testing testing"; ``` I realize that cmdLine doesn't have the program name (the argv[0]); this doesn't matter I can use a dummy value. I was thinking of doing it with a regex,(("[^"]+")\s+)|(([^\s]+)\s*)I'm not sure how well it would work though.. Probably not very well? Is there any function to do that in the windows api? Thanks
If you are using Microsoft compiler, there are public symbols__argc,__argvand__wargvdefined instdlib.h. This also applies to MinGW that uses Microsoft runtime libraries.
This question already has answers here:Dividing 1/n always returns 0.0 [duplicate](3 answers)Closed5 years ago. I got this C code. ``` #include <stdio.h> int main(void) { int n, d, i; double t=0, k; scanf("%d %d", &n, &d); t = (1/100) * d; k = n / 3; printf("%.2lf\t%.2lf\n", t, k); return 0; } ``` I want to know why my variable 't' is always zero (in the printf function) ?
because in this expression ``` t = (1/100) * d; ``` 1 and 100 are integer values, integer division truncates, so this It's the same as this ``` t = (0) * d; ``` you need make that a float constant like this ``` t = (1.0/100.0) * d; ``` you may also want to do the same with this ``` k = n / 3.0; ```
After my system call has returned because it was interrupted by a signal, is there a way to determine exactly which signal type (i.e. child process termination) caused the interruption?
There's a number of facilities in Linux to deal with signals: waitpid(2)could be used to wait inline forSIGCHLDsigaction(2)could be used to setup handler functions to react to specific signals, theSA_RESTARTflag here affects whethercertainsystem calls areinterruptedorrestartedsigprocmask(2)could be used to block a number of signalssigwait(3)could be used to wait for number of signals inlineLatest kernels supportsignalfd(2), which is convenient when one needs to combine signal handling and non-blocking IO. Then there's the whole next level of complexity when we start talking about threads, though if you deal with signals explicitly you usually don't really carewhichsignal interrupted the system call.
I'm trying to play only part of a sound using FMOD, say frames 50000-100000 of a 200000 frame file. I have found a couple of ways to seek forward (i.e. to start playback at frame 50000) but I have not found a way to make sure the sound stops playing at 100000. Is there any way FMOD can natively do this without having to add lbsndfile or the like into the picture? I should also mention that I am using the streaming option. I have to assume that these sounds are arbitrarily large and cannot be comfortably/quickly loaded into memory.
You can use Channel::setDelay for sample accurate starting and stopping of sounds. Use FMOD_DELAYTYPE_DSPCLOCK_START to set the start time of the sound and FMOD_DELAYTYPE_DSPCLOCK_END to set the end time. Check out the docs for Channel::setDelay, FMOD_DELAYTYPE, System::getDSPClock.
I like to know how count the received values from. Im using an 4x4 keypad, and AVR studio as compiler for example if I press button "1" I receive a "1" but if I press button "1" again it should be an "11" and not a "2", int inputcounter;if (button = 00x1) { // what should i do instead of inputcounter++ to get "11" and not "2" } Thank you.
Based on the commentinstead of inputcounter++, it sounds like you are trying to use a numeric value. So you need to do: ``` inputcounter = (inputcounter * 10) + newvalue; ```
If 2 file descriptors were dupped to the same file (i.e.506andSTDOUT), will invokingclose(506)cleanup the object associated by both and renderSTDOUTunusable? Or does kernel implement reference counting for its files?
The kernel implements reference counting, so the kernel object is not closed until all the file handles pointing to it are closed.
What I need to do is unzip a file, (.gz or .z), read the first line and do some stuff according to the first line read. But the C standard library doesn't seem to offer a way to do this. Is the a platform-independent way to do it?
Use "zlib", the library that performs compression and decompression: http://www.zlib.net/ It's included in the base of all Unix distributions, and you can easily link your program against it for the windows version and ship the DLL.
How do I convert a binary string like "010011101" to an int, and how do I convert an int, like 5, to a string "101" in C?
Thestrtolfunction in the standard library takes a "base" parameter, which in this case would be 2. ``` int fromBinary(const char *s) { return (int) strtol(s, NULL, 2); } ``` (first C code I've written in about 8 years :-)
How to get the absolute path for a given relative path programmatically in Linux? Incase of Windows we have the_fullpath()API. In other words, I mean what is analogous API to_fullpathof Windows in Linux?
As Paul mentioned, userealpath(). Please note though, that since many file systems in Linux supporthard links, any given directory can have a number of different absolute paths.
this is very basic...but please help me if anybody know about this... Can an array be called as a const pointer?
Do you mean "can array be used where a const pointer is expected"? In that case, yes: ``` void f(const int* p) { ... } int ar[10]; f(ar); // this works, array is essentially a pointer ```
The pycups-1.9.48 library doesn't build on Mac OS 10.6 unless I remove this ifdef: ``` #ifdef __SVR4 /* * A rudimentary emulation of getline() for systems that dont support it * natively. Since this is used for PPD file reading, it assumes (possibly * falsely) that BUFSIZ is big enough. */ ssize_t getline(char **line, size_t *linelen, FILE *fp) { ... ``` I'm guessing __SVR4 gets defined somewhere in the SVR4 compilation environment so that the preprocessor knows it should include this homebrew getline implementation. What is this mechanism called? Googling for __SVR4 actually gets a lot of hits into source code and people discussing source code. And, more generally, is there an equivalent symbol for Snow Leopard so I can make this code compile without either learning autoconf or editing it by hand?
Seehttp://predef.sourceforge.net/index.php
According to my memory the following piece of code should compile fine on C++ but not in C. Only problem is how to test it? It compiled fine with g++ and also with gcc. I'm assuming that g++ is C++ compiler and gcc is C compiler. I've tried it with mingw under Windows. Am I correct? if not then how to compile it using C compiler. ``` int main() { const int i = 1; const int j = 2; const int k = 3; int array[i + j + k]; return 0; } ```
No, that will compile in C99, which has support forvariable length arrays. To get strict C89 behavior, try compiling with: ``` gcc -std=c89 -pedantic-errors ``` That gives: ``` error: ISO C90 forbids variable length array ‘array’ ``` c89 means use C89, pedantic-errors means error on non-C89 code.
I'm creating a c program that I intend to run on an ARM processor in the near timeframe. I want to measure the amount of memory I'm using with my global variables while ignoring the size of the stack/heap. Is there a way to either get gcc to dump this out at compile time or to retrieve this information from the compiled binary?
A great way to see where your memory is going is to look at the linker map. A linker map is a file that is generated by the linker and details all memory locations for the program. You can see memory allocation on a symbol by symbol basis for global variables as well as code. I've used linker maps in the past for projects which have tight memory requirements. They make it easy to identify problems areas like global memory buffers which take up alot of space. Add this option to the gcc command line to generate the linker map: -Wl,-Map=output.map
How to install new units (i mean includes ex: stdio.h) for my C, and how to download more?
put the header file on the same folder as your main source file, ex: /folder /-->main.c-->function.h -->function.c then on main.c include it by writing : ``` #include "function.h" ``` the quotes are used to include a header file that's on the same folder as your c source file u can also write your own and include them like above.
I’m taking a C++ class, and my teacher mentioned in passing that thetypenamekeyword existed in C++ (as opposed to using theclasskeyword in a template declaration), for backwards compatibility with “C templates.” This blew my mind. I’veneverseen or heard tell of anything like C++’s templates (except, perhaps, the preprocessor… and that’s not really the same thing at all) in ANSI C. So, did I miss somethinghugesomewhere, or is this a really esoteric extension bygccor something, or is my teacher way off-base?
I think your teacher is off base. SeeStan Lippman's post: Why C++ Supports both Class and Typename for Type Parametersfor the real reason why C++ supports both.
In beej's guide to networking there is a section of marshalling or packing data for Serialization where he describes various functions for packing and unpacking data (int,float,double ..etc). It is easier to use union(similar can be defined for float and double) as defined below and transmit integer.pack as packed version of integer.i, rather than pack and unpack functions. ``` union _integer{ char pack[4]; int i; }integer; ``` Can some one shed some light on why union is a bad choice?Is there any better method of packing data?
Different computers may lay the data out differently. The classic issue is endianess (in your example, whether pack[0] has the MSB or LSB). Using a union like this ties the data to the specific representation on the computer that generated it. If you want to see other ways to marshall data, check out theBoost serializationandGoogle protobuf.
I have been using ! (logical negation) in C and in other languages, I am curious does anyone know how to make your own ! function? or have a creative way of making one?
``` int my_negate(int x) { return x == 0 ? 1 : 0; } ```
This question already has answers here:Why can't I use sizeof in a preprocessor condition?(2 answers)Closed9 years ago. I have this: ``` #if sizeof(int) #error Can't use sizeof in a #if #endif ``` I get this compiler error: ``` missing binary operator before token "(" ``` Why can't I use the sizeof operator here?
Because sizeof() is calculated after the preprocessor is run, so the information is not available for#if. C compilers are logically split into two phases, even if most modern compilers don't separate them. First, the source is preprocessed. This involves working out and substituting all the preprocessor conditionals (#if, #define, replacing defined words with their replacements). The source is then passed, processed, to the compiler itself. The preprocessor is only minimally aware of the structure of C, it has no type knowledge, so it can't handle compiler-level constructs like sizeof().
Suppose I have a C function: ``` void myFunction(..., int nObs){ int myVec[nObs] ; ... } ``` Is myVec being dynamically allocated? nObs is not constant whenever myFunction is called. I ask because I am currently programming with this habit, and a friend was having errors with his program where the culprit is he didn't dynamically allocate his arrays. I want to know whether my habit of programming (initializing like in the above example) is a safe habit. Thanks.
To answer your question, it's not considered dynamic allocation because it's in the stack. Before this was allowed, you could on some platforms simulate the same variable length allocation on the stack with a functionalloca, butthatwas not portable. This is (if you program for C99).
When performing SQL statements such asUPDATE, andINSERT, the usual.fetch*()methods on theCursorinstance obviously don't apply to the number ofrows modified. In the event of executing one of the aforementioned statements, what is the correct way to obtain the corresponding row count in Python, and the corresponding API in the Sqlite3 C interface?
After calling yourCursor.execute*()methods with your UPDATE or INSERT statements you can useCursor.rowcountto see the # of rows affected by the execute call. If I had to guess I would say the python lib is callingint sqlite3_changes(sqlite3*)from the C API but I have not looked at the code so I can't say for sure.
I am using MSVS C++ Express 2008. Right now my intellisense only works for objects that have methods or arguments in a method. Is it possible to set it where it detects declared constants and varibles that are within scope. Thanks
It should work when you hover over a constant, or any variable for that matter. It should show you the definition. I'm not sure if there are any feature differences between the Express and "real" versions, but I don't believe so. Some things to try: Do a rebuild of the solution.Restart VS.There is a file in your solution root directory with an ".ncb" extension. Delete it and restart VS. This forces VS to rebuild the Intellisense database. Intellisense is notoriously flakey...
I want to write some portable (as possible) C code to look up DNS TXT records. I would also prefer not to have dependencies on libraries that don't ship with the machine. What is the best way to do this on Unix-like machines using standard libraries? I found some sample code that works using libresolv, but it's not reentrant (not thread safe) and is very ugly. Is there a better way? Also, what about Windows? If there were a way that worked there too that would be perfect.
you can useres_querywhich uses the standard libresolv. There's anexample herefrom clamav: ``` if((len = res_query(domain, C_IN, T_TXT, answer, PACKETSZ)) < 0) { mprintf("@Can't query %s\n", domain); return NULL; } ```
I have an IPaddress and subnet mask, both in unsigned long; how can I AND both of these and check whether my incoming ipaddress (ip2) belongs to the same subnet or not? like: ``` if (ip1 & subnet == ip2 & subnet) then same subnet. ```
Use parentheses - the precedence levels are confusing: ``` if ((ip1 & subnet) == (ip2 & subnet)) ... ``` The original code was effectively the same as: ``` if (ip1 & (subnet == ip2) & subnet) ... ```
I have a bash script in which i check the exit code of a last run command by using $? variable but now I am executing a C program (from that script) which returns 0 if the program gets executed successfully. Is there any way I can catch this return value of the C program from with in my bash script? I believe different commands like awk, sed etc are written in C. How do they use $? to store their exit codes in it? How can I make my C program to store its exit code in $?? I hope my question is clear.
There's no need to do anything - if your C program returns 0, that's what will be stored in the$?variable of the shell that executed it.
I have to write some code to retrieve network packets from an Ethernet card in Windows using ANSI C. Can anybody tell me where to get started?
The easiest way to do this is to use the PCAP library, there's a version for Windowshereand a basic examplehere
I have used Signals and slots in Qt and I want to implement same stuff in GTK+. I have 2 threads in which I need to pass data. I have done it using signals and slots in Qt but now I have to implement this same stuff in GTK+ and C. How should I do it?
Here's a general tutorial for the signal/event mechanism without threads. When using threads, you'll have to make sure to init the Gtk main loop for threads by callingg_thread_init()andgdk_threads_init().usegdk_threads_add_idle()oruseGDK_THREADS_ENTER()andGDK_THREADS_LEAVE()in the callback (= event handler). There are probably hundreds of tutorials for threading in Gdk out there, so I'll leave it at that.
How do I read input one string at a time to call another function in C. I thought this would work, but my output hangs: ``` #define BUFFMT "%255" #define LINE_LEN 256 #define START_COUNT 1 // filename is declared in the main file elsewhere. I know the file opens since I tried an //old method I use to read one line at time using fgets, but I didn't know how to do one //string at a time. Thanks. FILE *OpenFile(const char *fileName) { FILE *fptr; if ((fptr = fopen(fileName, "r")) == NULL) { fprintf(stderr, "Error opening file %s, exiting...", fileName); exit(EXIT_FAILURE); } return fptr; } LIST *CreateList(FILE *fp) { char buf[LINE_LEN]; while (scanf(BUFFMT"s", buf) != EOF) { printf("%s: \n", buf); } } ```
scanf()is going to read from the terminal, so it's going to hang waiting for you to type in your input. Usefscanf(fp, BUFFMT"s", buf)instead.
I am following a tutorial and one of the steps its asking is to go to my projects properties and click on c/c++ and add a path to "Additional Include Directories" property. I am using visual C++ Express Edition 2008. the tutorial is using the same thing. Is there away to get this or an alternative ?? This is my screen This is tutorials screen
You don't have the C++ compiler options until you're actually using the C++ compiler. In this case, you don't have a .cpp file. So just add one and the compiler options will appear.
I am trying to setupallegroto work withvisual studio express 2008. But I don't know the set of instructions. I want to to recognize theallegro library. I would like to get some help regarding the installation procedure.
TheAllegro wikihas instructions for configuring a Visual Studio Express 2008 project... withAllegro 4(stable version)withAllegro 5(development version) Here are some other excellent resources for Allegro-related development: Allegro.ccannotated manualAllegro.ccforumsMailing listsfor Allegro users and developers
I'm developing a Python module in C that parses a very efficient protocol which uses dynamic integer sizes. Integers sent using this protocol can range in size from the equivalent of C's 'short' to a 'long long.' The protocol has a byte that specifies the type of variable being sent (from short to long long), but I'm not sure how to deal with this in code. Right now, I'm setting up a void pointer and allocating memory in the size of the value being sent -- then using atoi, atol, and atoll to set that pointer. The problem is, I need to be able to access that value, and am unable to do so without it being cast later. What are some good ways to handle this issue?
Either always store it in along longlocally, or put it in astructcomposed of a flag for the size and aunionof all the possible types.
In the execve() man page it is said that argv is a list of string arguments which is ended by a null pointer. But what is the NP for? I mean, the number of arguments is stored in argc, so what's the point of the null pointer?
execvedoes not takeargcas a parameter, it manually counts the arguments you give asargvto determineargcitself. This is for compatibility withexeclwhich takes a variable number of arguments instead of anargvarray.
I get a segmentation fault afterfreeing a certain pointer: ``` free(studentDB->name); ``` I can get its value without any errors or warnings: ``` printf("[DBG] studentDB->name: %s\n", studentDB->name); ``` However, as I said, the program crashes when I try to free it. What are the most common causes for afreecommand leading to a segmentation fault?
If you didn'tmalloc()it, you can'tfree()it. Where doesstudentDB->namecome from?
Is there any way to decompile Linux .so?
There aredecompilers, but a decompiler might not emit code in the same language that the original program was written in. There are alsodisassemblers, which will reassemble the machine code into assembly. The Decompilation Wikimay be a good source of additional information.
I already know that I can trace memory leaks in my code withmtraceandvalgrindon Linux, both of which are unavailable for Windows. Which Windows program would you recommend to trace memory leaks? I'm an Eclipse user and I've been working with C for a month or two now, so I prefer a user-friendly solution over something more advanced.
Application Verifier will do this quite well,http://msdn.microsoft.com/en-us/library/ms220948.aspx
Here is the situation : Some process writes lines into a fifo file (created withmkfifo). At some point in my program, I want to read the last line in the fifo, and discard all the others. The procedure may block, only if there is less than one line in the fifo. I can't come up with a clean way to do this, any ideas ? EDIT : The writing process will never stop writing lines into the fifo, What I mean by the last line is the last by the time I read the fifo. It is not necessarily followed by a EOF.
If your main concern is that the read will block then open the FIFO as non-blocking. I assume you know what you are looking for in the stream and will simply discard everything before. You can also use something likeselect()to be informed when there is something to read off the pipe.
I'm trying to free up the memory I've allocated withmalloc, but thefreecommand doesn't seem to do its job properly according to Eclipse's debugger. How's this possible? Below is a screenshot of my debugger after it supposedly freed upseCurrent->student->year, which is clearly not the case.yearwas allocated usingmalloc. alt text http://img693.imageshack.us/img693/7840/codeo.png
free() does not normally change any values in your program - it just makes adjustments to the C runtime heap. This means that the values in the memory that was just freed are retained. However, attempts to access them from your code lead to undefined behaviour.
My friend said he thinks i may have made a mistake in my programme and wanted to see if i really did. He asked me to send him the binary opposed to the source. As i am new to this i am paranoid that he is doing someting to it? What can you do with the binary that would mean you wouldnt want the source? thank
Black-box testing. Having the source may skew your view on how the program may be behaving.
The question is simple "Say we have an integer1 <= n <= 12,How to usestrftimeto displayJanuaryfor '1',Februaryfor '2',Marchfor '3' and so on ... ?"
``` #include <stdio.h> #include <time.h> size_t monthName( char* buf, size_t size, int month) { struct tm t = {0}; t.tm_mon = month - 1; // turn month 1..12 to 0..11 as `struct tm` wants return strftime( buf, size, "%B", &t); } int main(int argc, char* argv[]) { char buf[10]; monthName( buf, sizeof( buf), 9); printf( "%s\n", buf); return 0; } ```
I am reading a book on game AI. One of the terms that is being used is to normalize a vector which is to turn a vector into a unit. To do so you must divide each dimensionx,yandzby its magnitude. We must turn vector into a unit before we do anything with it. Why? And could anyone give some scenarios where we must use a unit vector? Thanks!
You don't have to normalize vectors, but it makes a lot of equations a little simpler when you do. It could also make API's smaller: any form of standardization has the potential to reduce the number of functions necessary. Here's a simple example. Suppose you want to find the angle between two vectors u and v. If they are unit vectors, the angle is just arccos(uv). If they're not unit vectors, the angle is arccos(uv/(|u| |v|)). In that case, you end up computing the norms of u and v anyway.
I heard fopen supports UTF8 but i dont know how to convert an array of shorts to utf8 How do i create a file with unicode letters in it? I prefer to use only built in libraries (no boost which is not installed on the linux box). I do need to use fopen but its pretty simple to.
fopen(3)supports any valid byte sequence; the encoding is unimportant. Usenl_langinfo(3)withCODESETto get what charset you should use for the encoding, and libiconv or icu for the actual encoding.
Is there a way to do check for numerical equality in macros? I want to do something like ``` #define choice 3 #if choice == 3 .... #endif #if choice == 4 ... #endif ``` Does C macros have support for things like this?
Another way to write your code uses chained#elifdirectives: ``` #if choice == 3 ... #elif choice == 4 ... #else #error Unsupported choice setting #endif ``` Note that ifchoiceis not#defined, the compiler (preprocessor) treats it as having the value0.
If I declare a pointer to a struct in .h for example: ``` my_struct_t *ptr; ``` ... and then I checkif(ptr==NULL)in the code, without actually setting ptr to NULL or allocating memory for it, can I do that check to see if its equal to NULL? essentially what I'm asking is, by having ptr in the .h, does it get set to NULL automatically, or do I have to do that? Thanks, Hristo revisiont: this is done in C
From K&R2nd: In the absense of explicit initializations, external and static variables are guaranteed to be initialized to zero. So, yes. That appears to be in section A8.7 of the 1990 standard. Don't know where to look in the 1999 standard.
If Python was so fast as C, the latter would be present in python apps/libraries? Example: if Python was fast as C would PIL be written completely in Python?
To access "legacy" C libraries and OS facilities.
For a project at university I need to extend an existing C application, which shall in the end run on a wide variety of commercial and non-commercial unix systems (FreeBSD, Solaris, AIX, etc.). Which things do I have to consider when I want to write a C program which is most portable?
The best advice I can give, is to move to a different platform every day, testing as you go.This will make the platform differences stick out like a sore thumb, and teach you the portability issues at the same time. Saving the cross platform testing for the end, will lead to failure. That aside Integer sizes can vary.floating point numbers might be represented differently.integers can have different endianism.Compilation options can vary.include file names can vary.bit field implementations will vary. It is generally a good idea to set your compiler warning level up as high as possible, to see the sorts of things the compiler can complain about.
Nearly every (relatively) new book about c programming I've seen doesn't seem to adhere to the C99 standard, or they cover it in an extra chapter. Comming from a Java background, the C99 standard made the migration (well, still migrating ^^) much easier for me, and this probably applies to other languages, too. It seems like C99 hasn't reached most of the C developers yet. But why?
Short answer:compiler support is slow to get installed and c programmers are a conservative lot who change their behavior slowly.
Is there a one-liner that will free the memory that is being taken by all pointers you created usingmallocs? Or can this only be done manually byfreeing every pointer separately?
you could do that by creating some kind of "wrapper" around malloc. (warning that's only pseudo code showing the idea, there is no checking at all) ``` void* your_malloc(size_t size) { void* ptr = malloc(size); // add ptr to a list of allocated ptrs here return ptr; } void your_free(void *pointer) { for each pointer in your list { free( ptr_in_your_list ); } } ``` But it doesn't sound like a good idea and I would certainly not do that, at least for general purpose allocation / deallocation. You'd better allocate and free memory responsibly when it is no longer needed.
Consider a float value like1.82set by the user. How do I find the next highest .05 value? For the given example the next highest value is 1.85. Is there a simple way or does it take a complex algorithm? I tried to usefloorandceilingfunctions to come up with the distance from the float to the next highest and lowest Integers. But I'm not sure how to proceed once I have that info. Thanks.
Multiply by 20, use ceiling, divide by 20.