Question:
I'm programming in Windows right now, but portable code would be welcomed too.

What I'm using right now isfwrite(4), but this function needs a maximum number of elements to be written to the file. I can usestrlen(1)here but I'd like to know if there is any better way to do this.

Answer:
Usefputsinstead:

```
FILE * f = fopen( "myfile.txt", "w" );
fputs( "Hello world\n", f );
```


Question:
Is there a way to replace any keyword in a text file using POSIX calls, without re creating the file..
If yes Please tell me how to do it..

Thanks in advance..

Answer: If the text and the replacement are the same size then you can open it with moder+, seek, and then write. If their sizes are different then there is no way to replace without recreating.


Question:
Hi I'm working in a Linux environment and I have to link to a object file already compiled which offers me some services (services.o) and I know some of them, but I'd like to know which are all of the exported symbols of it.

Is there any way to accomplish this not having the sources? If so, how?

Thanks you very much.

Answer: Trynm-- this tool is there for just this purpose.


Question:
I have an array of data that represents PNG:

```
unsigned short systemFontTexture[] = {

...
0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089,
0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089,
0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089,
...

}
```

Can I create PNG file using this data?
If yes, then HOW?

Answer: Create a data providerto serve up the data, and thencreate an image with the data provider.


Question:
How can I detect when a removable disk drive is (dis)connected to the system? How to get the mount path (for Linux) and the drive letter (for windows)?

EDIT: Is there a way to detect the currently connected devices?

Answer: For Windows, the APIRegisterDeviceNotificationwill let you know when a USB device is added.  The information about the volume is given in theDEV_BROADCAST_VOLUME structure.  Thedbcv_unitmaskgives the drive letter.


Question:
I have an array of data that represents PNG:

```
unsigned short systemFontTexture[] = {

...
0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089,
0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089,
0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089,
...

}
```

Can I create PNG file using this data?
If yes, then HOW?

Answer: Create a data providerto serve up the data, and thencreate an image with the data provider.


Question:
```
int x[10],y[10];
x = y;
```

I am thinking of a simple hack, which would enable me to get this effect.

Answer:
You can wrap them instructs to use simple assignment:

```
struct foo { int a[10]; } x, y;
x = y;
```

But really, just usememcpy.


Question:
I've compiled my C program usinggcc 4.4.1using the flag-g, but when I try to step through one of my functions ingdb version 7.0, I get the message:

```
"Single stepping until exit from function _DictionaryTree_getNodeList,
which has no line number information."
```

Can someone tell me why this is happening?

Answer: Just guessing, but is _DictionaryTree_getNodeList in another file that wasn't compiled with -g?


Question:
I'm trying to learn how to use Lua with C, so by now I want to try running a script without loading it from a file, since I don't want to be bothered with messing up with files.
Can anybody tell me which functions do I need to call for executing a simple string or what ever?

Answer:
You can useluaL_dostringto execute a script from a string.

If you need help with the basics (creating a Lua state, etc.), read part IV ofProgramming in Lua.


Question:
I have the simplest of makefiles:

```
threads:
   gcc threads.c -o threads
```

but I get the error:

'make: Fatal error: Don't know how to make target'

Any ideas what I am doing wrong?  It's probably something simple - I made the makefile in emacs on the system which is trying to run it (Unix)

Answer: Do you have spaces instead of a tab on the second line there? Most common basic make mistake, I'd say.


Question:
Why sometimes C code gets wrapped with curly braces without declaring a variable in them?
e.g. (from FreeRTOS source code, file 'tasks.c'):portENTER_CRITICAL();
{
    xTicks = xTickCount;
}
portEXIT_CRITICAL();

Answer: This is just an inner scope. The benefit is that code shows your intent in that case. e.g. This scopeisthe critical section.


Question: How can I print the source of a webpage, specified in curl_easy_setopt, without html tags? So, printing only the text in the source?

Answer:
Curl/libcurl is just for fetching the HTML page. To extract information from it, you need other tools.

The most general solution is to use a HTML parser. A good one in C isHTMLparser from libxml.


Question: I want to see implementation of java.util.zip.CRC32. But within this class its using native c library functions for core implementation.How can I get the native source code. I can see the java.util.zip.CRC32 source code, but this doesn't have the actual implementation.

Answer:
You must ask SUN, I mean Oracle about having the source code...  :-/

You can try the source code for Java 6 at thisdownload page. CRC32 should not have changed much between Java 1.4 and 6.


Question:
Interesting little bug here:

```
if (host != NULL) {
    printf("hi");
} else {
    printf("FAIL");
}
return 0;
```

doesn't print anything at all, but:

```
if (host != NULL) {
    printf("hi");
} else {
    printf("FAIL");
}
fprintf(stdout, "\n%s\n", (char *)&additionalargs);
return 0;
```

prints

hiabc

Does anyone know why this is?

Answer: printf output to stdout is buffered. You might want to look atfflush


Question: I have a function that runs in C.  I would like for it to timeout, or at least be non blocking.  Is there a way to do that without running it as a thread?

Answer: select()(or one of its platform-specific equivalents) is what should be used if you don't know that there is input available from a blocking file or socket, and want to continue if there isn't.


Question: Is it possible to skin the GTK+ progress bar widget such that it shows a custom image (an AJAX style animated gif maybe)? If so how and if not, is there any other option/control which can achieve this effect?

Answer: Something likeGtkSpinner?


Question: Are there solutions in C or Objective-C to receive and play back SHOUTcast audio streams on the mac or iphone?

Answer:
Implement an M3U/PLS parser (which is just a text list of MP3 streams) and use the code here to play the MP3's

http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html


Question:
Python hasctypesto access libraries. In PHP you write extensions for everything. Popular extensions like the one for libgd are available almost everywhere.

Is there any extension which works like Python's ctypes, letting you access libraries without the need to write an PHP extension?

Answer: You're looking forffi.


Question:
In general i see the process'spidwhich is running in the background and start dbx on that process using the commanddbx -a <pid>

similarly how could i do it using gdb?

Answer:
In addition to the previous you can directly use

```
gdb -p <pid>
```


Question: I have a function that runs in C.  I would like for it to timeout, or at least be non blocking.  Is there a way to do that without running it as a thread?

Answer: select()(or one of its platform-specific equivalents) is what should be used if you don't know that there is input available from a blocking file or socket, and want to continue if there isn't.


Question: Is it possible to skin the GTK+ progress bar widget such that it shows a custom image (an AJAX style animated gif maybe)? If so how and if not, is there any other option/control which can achieve this effect?

Answer: Something likeGtkSpinner?


Question: Are there solutions in C or Objective-C to receive and play back SHOUTcast audio streams on the mac or iphone?

Answer:
Implement an M3U/PLS parser (which is just a text list of MP3 streams) and use the code here to play the MP3's

http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html


Question: Is there an option I can change in Eclipse to make sure that my code has got to be ANSI C-compliant before it can be compiled?

Answer: Project > Properties > C/C++ Build > Tool Settings > Miscellaneous > "Support ANSI programs"


Question: What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dstirbutions?

Answer: These are c library calls, and as such are in the libc library.


Question:
I perform some checks in my Window class constructor, and if they fail I want to display an error message and close the window.

I'm getting crashes when calling Close() from the constructor or from Window_Loaded.  Does that sounds normal or am I doing something wrong?  If this is normal, when should I call Close()?

Answer: It turns out you can call Close() in the constructor or on Window_Loaded - I was just doing something wrong later on in the destructor.


Question:
For example, say we have a union

```
typedef union {
unsigned long U32;
float f;
}U_U32_F;
```

When a variable of this union type is declared, is there a way to set an initial value?

```
U_U32_F u = 0xffffffff;   // Does not work...is there a correct syntax for this?
```

Answer:
Use an initializer list:

```
U_U32_F u = { 0xffffffff };
```

You can set other members than the first one via

```
U_U32_F u = { .f = 42.0 };
```


Question: Is there an option I can change in Eclipse to make sure that my code has got to be ANSI C-compliant before it can be compiled?

Answer: Project > Properties > C/C++ Build > Tool Settings > Miscellaneous > "Support ANSI programs"


Question: What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dstirbutions?

Answer: These are c library calls, and as such are in the libc library.


Question: I am working in Ansi C, windows platform. I want to attach mysql database to my c program. Kindly guide me how I can make it possible.

Answer: Hereis a working example which sets up a connection and performs a query.


Question:
Is the following code valid

```
int main(){
int * a = 0;
if ( !a ) {
    int b[500];
    a = b;
}

//do something with a,
//has the array a is
//pointing too gone out
//of scope and garbage
//or is it still fine?
}
```

Answer: No it is not, b has gone out of scope, accessing it (through the pointer) is undefined behavior.


Question:
This does work

```
LLIST *mylist[10] = {NULL};
```

But would if I wanted to do this I get errors:

```
int x=10;

LLIST *mylist[x] = {NULL};
```

xcan be any value I'm setting it to 10 for the time being.xis going to be used as a counter.

Answer:
Support for variable length arrays (which your second example uses) came in the C99 standard, which your compiler may not support.

For gcc, you should pass the-std=c99option when compiling.


Question: Can I somehow tell GStreamer to look for plugins in a specified directory?

Answer:
Use theGST_PLUGIN_PATHenvironment variable to point at the directory you want, or programatically just call:

```
GstRegistry *registry;
registry = gst_registry_get();
gst_registry_scan_path(registry, directory);
```


Question: I'm new to using C programming I was wondering if there is a function call that can be used to quickly determine the amount of rows in a text file.

Answer:
```
#include <stdio.h>
#include <stdint.h>

uint32_t CountRows(FILE* fp, uint8_t line_delimiter){
  uint32_t num_rows = 0;
  uint16_t chr = fgetc(fp);
  while(chr != EOF){
    if(chr == line_delimiter){
      num_rows++;
    }
    chr = fgetc(fp);
  }

  return num_rows;
}
```


Question:
What are the various mechanisms using which we can detect if a process execution is leading to memory fragmentation?

Are there any tools available for the same? Suggestion for tools which work with 'C' code and can run on Windows, Linux and VxWorks will be helpful.

Answer:
Just as a suggestion, you may want to try Valgrind.  I'm not certain it's what you're looking for, but it may come in handy.

http://valgrind.org/


Question:
I've got a menu in curses that I'd like to put multi-line descriptions onto.

My code puts the description fields on but they don't display if they don't fit on the line.

Curses is happy enough printing multi-line text as strings (not as menu descriptions)

Any ideas how to get multi-line descriptions working ?

Answer: I've given up on this and render my own scrollable list of items instead.


Question: What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?

Answer: _beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state.  Thestrtok()function would be an example.  That's been fixed, that state now gets dynamically initialized, at least since VS2005.  UsingCreateThread()no longer causes problems.


Question: I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?

Answer:
You need a temporary variable:

```
void*temp = array[4];
array[4]=array[1];
array[1] = temp;
```

Edit Fixed first line.


Question:
I've got a menu in curses that I'd like to put multi-line descriptions onto.

My code puts the description fields on but they don't display if they don't fit on the line.

Curses is happy enough printing multi-line text as strings (not as menu descriptions)

Any ideas how to get multi-line descriptions working ?

Answer: I've given up on this and render my own scrollable list of items instead.


Question: What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?

Answer: _beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state.  Thestrtok()function would be an example.  That's been fixed, that state now gets dynamically initialized, at least since VS2005.  UsingCreateThread()no longer causes problems.


Question: I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?

Answer:
You need a temporary variable:

```
void*temp = array[4];
array[4]=array[1];
array[1] = temp;
```

Edit Fixed first line.


Question:
I want to send a file in C++ over network (for a chat program)
what should I do?

Answer:
Take a look athttp://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/examples.html. The Iostreams example should give you the first good step. Asio is a portable network library of the boost project. Boost is available for most platforms available today.

You can stream in the file and stream out it into the TCP stream.


Question: How to split a string into tokens by'&'in C?

Answer:
strtok / strtok_r

```
char *token;
char *state;

for (token = strtok_r(input, "&", &state);
     token != NULL;
     token = strtok_r(NULL, "&", &state))
{
    ...
}
```


Question:
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse:

Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.

Answer: If you are okay with the GPL license, you wantGNU getopt.


Question:
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse:

Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.

Answer: If you are okay with the GPL license, you wantGNU getopt.


Question: How would I go about taking a number like123456and having it print as1 2 3 4 5 6?

Answer:
The simplest way of doing this (though not the fastest) would probably be to firstsprintfthe number to a string buffer, and then loop through the bufferprintf-ing one character and one space at a time.

There's no built-in way of doing this within the standardprintfformatting.


Question:
I know in C++, you're able to peek at the next character by using:in.peek();.

How would I go about this when trying to "peek" at the next character of a file in C?

Answer:
fgetc+ungetc.  Maybe something like this:

```
int fpeek(FILE *stream)
{
    int c;

    c = fgetc(stream);
    ungetc(c, stream);

    return c;
}
```


Question:
Are there any portable open source libraries that support sample-based synthesis and encapsulate producing and mixing simple PCMs?

I really need something minimalistic and decoupled from operating system audio output mechanisms.

Answer: csoundhas aC apiand can handle PCM.ffmpegcan also convert lots of popular formats in PCM.


Question:
here is a code sample

```
void something()
{
   char c[100];
   scanf("%s",c);
   char c2[100]=c;
}
```

my problem is when i do this assignment an error says that i can't assign

```
char * "c"  to char[] "c2";
```

how can i achieve this assignment?

Answer:
You'll have to usestrcpy()(or similar):

```
...
char c2[100];
strcpy(c2, c);
```

You can't assign arrays using the=operator.


Question:
Does anyone know how to save gdb settings (like "set print pretty on" or "set print elements 0", both fromhere)? I don't want to set my configuration every time that I will use gdb :/

I searched in google and SO, but I found nothing.

Answer: Add any commands you want to auto run in the.gdbinitfile in your home directory.


Question: How can I lock a file for a specified period of time (10 seconds) using the C language in Ubuntu Linux ?

Answer:
It works like this:

```
#include <io.h>
#include <sys/file.h>
...
int f = open ("filename", O_RDONLY);
if (f < 0)
       error();
if (flock (f, LOCK_EX))
       error();
sleep (10);

if (flock (f, LOCK_UN))
       error();
...
```


Question:
I am trying to add a new IP address to a local network adapter in Windows using the Windows API. Are there functions to do this in the Windows API, and if so, what are they?

I am not trying to create virtual network adapters, but simply trying to assign multiple IP addresses to the same adapter.

Answer: Take a look atAddIPAddressandDeleteIPAddress.


Question:
A function returns an aray of integers and I want it to pass to another function which searches for some pattern. But the second function expects a string.

Example:

```
int IArray = {1, 2, 3};
// should be coverted into "123"
```

Is there a direct function available?  If not, how do I convert the array of integers into a string?

Answer:
There is no direct function to do that.

You'll have to usesprintf.


Question:
In C language, how to get struct's start address from its member's address?

```
struct type1 {
    //...
    int member1;
    //...
};
struct type1 obj1;
```

Andptr1is the address of membermember1inobj1, how to definemacro#define start_add(ptr1, type1, member1)to get obj1'sstart address?

Answer:
You can do this usingoffsetof:

```
#define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1)))
```


Question:
I'm currently trying to patch theTotem Youtube plug-inand I'd like to determine the best quality available for the current played video (&fmt parameter). It's possible inJavaScriptbut the plug-in is developped in C.

Is that possible?

Answer:
Are you playing the videos in the YouTube video player?

If so, you can query the quality levels through theActionScriptor JavaScript API,
seehttp://code.google.com/apis/youtube/js_api_reference.html#Playback_quality.


Question:
Why does the following code compile?

```
#include <stdio.h>

int main(void) {
    getchar;
}
```

Answer:
Because function names are aliases to function pointers to those functions, which are themselves values much like integers..  This is semantically very similar to

```
#include <stdio.h>

int main(void) {
    42;
}
```

It is valid but pointless.


Question:
```
short sho1, sho2;
printf("Enter two shorts.\n");
scanf("%hd %hd", &sho1, &sho2);
printf("%hd^%hd is %hd.\n", sho1, sho2, sho1^sho2);
```

When I enter '2 2', I get this output:

2^2 is 0.

How come? I'm using the MinGW GCC compiler in Eclipse, in case that's of any importance.

Answer: ^is not the mathematical power operator in C, it's thebitwise exclusive-OR operator.  You probably want thepow function, which takes two doubles.


Question: Why does each .h file starts with #ifndef #define #endif? We can certainly compile the program without those directives.

Answer: It's a so-called "include guard". The purpose is to prevent the file from having to be parsed multiple times if it is included multiple times.


Question:
I recently came across this line in a code  -

```
fprintf(logfile,"   |-IP Version        : %dn",(unsigned int)iph->version);
```

Is "%dn" here a format string ? If so , what does it signify ?

Answer: It sounds a bit like someone wanted to write%d\nto terminate the line with a linefeed, but the backslash got lost somewhere. The format code, in any case, ends with the "d".


Question:
In C language, how to get struct's start address from its member's address?

```
struct type1 {
    //...
    int member1;
    //...
};
struct type1 obj1;
```

Andptr1is the address of membermember1inobj1, how to definemacro#define start_add(ptr1, type1, member1)to get obj1'sstart address?

Answer:
You can do this usingoffsetof:

```
#define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1)))
```


Question:
I'm currently trying to patch theTotem Youtube plug-inand I'd like to determine the best quality available for the current played video (&fmt parameter). It's possible inJavaScriptbut the plug-in is developped in C.

Is that possible?

Answer:
Are you playing the videos in the YouTube video player?

If so, you can query the quality levels through theActionScriptor JavaScript API,
seehttp://code.google.com/apis/youtube/js_api_reference.html#Playback_quality.


Question:
When reading/writing a file in my application, I want to exit(1) if the file is not closed correctly. On Windows it works well, but on Linux this error appears:

```
‘exit’ was not declared in this scope
```

How can I solve that?

Thanks.

Answer: If this is in C, did you#include <stdlib.h>?


Question:
I can't figure out how to display something (like hello world) in every 3 seconds.
I'm writing in only C programming with gcc compiler in linux.
We can stop it by Ctrl+c.
I just want simplest and easiest way to manipulate thet code with my project.

Thank you so much in advance!

Answer:
```
while(1) {
    printf("something\n");
    Sleep(3000); //this function counts in milliseconds, so this is what 3 seconds looks like.
}
```


Question:
Came across this conditional in some uncommented Objective-C code:

```
if (w & (w - 1))
{
    i = 1;
    while (i < w)
    {
        i *= 2;
    }
    w = i;
}
```

Wherewis asize_tgreater than1.

Update:Added the code contained by the conditional for context.

Answer: It tests whether more than one bit is set inw, i.e. whether it's not an exact power of two. Seehere.


Question:
When reading/writing a file in my application, I want to exit(1) if the file is not closed correctly. On Windows it works well, but on Linux this error appears:

```
‘exit’ was not declared in this scope
```

How can I solve that?

Thanks.

Answer: If this is in C, did you#include <stdlib.h>?


Question:
I can't figure out how to display something (like hello world) in every 3 seconds.
I'm writing in only C programming with gcc compiler in linux.
We can stop it by Ctrl+c.
I just want simplest and easiest way to manipulate thet code with my project.

Thank you so much in advance!

Answer:
```
while(1) {
    printf("something\n");
    Sleep(3000); //this function counts in milliseconds, so this is what 3 seconds looks like.
}
```


Question:
```
int *i;
*i=123;
```

Answer:
Yes. There is no allocated memory to place the value123.

Like initializing a variable likeintis not guaranteed to be0, anint*isn't guaranteed to be a safe address.

It also could potentially lead to data corruption.


Question: I have installed visual studio 2008 and i want to create some simple applications using C language. I do this by creating c++ console applications but i want the compiler to work for C not C++. Any way to accomplish this or i need another compiler if i want to deal with C?

Answer: Use .c file extension instead of .cpp, those files will be compiled as C-only code by default in a C/C++ Visual Studio project.


Question:
I am using GCC, what switches do I need to add to link with Xlib? After searching, all I could find was-lX11, but that gave meld: library not found for -lX11

I am using a mac (10.6), but I would not like anything that is Mac specific.

Answer:
You can usually usepkg-configto determine the flags you need to pass:

```
gcc my-program.c $(pkg-config --cflags --libs x11) -o my-program
```


Question:
```
int *i;
*i=123;
```

Answer:
Yes. There is no allocated memory to place the value123.

Like initializing a variable likeintis not guaranteed to be0, anint*isn't guaranteed to be a safe address.

It also could potentially lead to data corruption.


Question: I have installed visual studio 2008 and i want to create some simple applications using C language. I do this by creating c++ console applications but i want the compiler to work for C not C++. Any way to accomplish this or i need another compiler if i want to deal with C?

Answer: Use .c file extension instead of .cpp, those files will be compiled as C-only code by default in a C/C++ Visual Studio project.


Question:
I am using GCC, what switches do I need to add to link with Xlib? After searching, all I could find was-lX11, but that gave meld: library not found for -lX11

I am using a mac (10.6), but I would not like anything that is Mac specific.

Answer:
You can usually usepkg-configto determine the flags you need to pass:

```
gcc my-program.c $(pkg-config --cflags --libs x11) -o my-program
```


Question:
linux gcc 4.4.1 C99

I am wondering what is the best way to test the performance of a C program.

I have some functions that I have implemented. However, I could have used a different design for each function.

Basically, I should want to test to see which design gives better performance.

Many thanks,

Answer: Take a look atthis poston code profilers.


Question:
I want to create a thread in C so that the thread automatically call after two seconds. I am using Visual Studio and Windows platform for development.

How do I get started?

Answer: You are going to need to use OS specific libraries to do threading.  On Posix, you will want to look intopthreads(and specificallypthread_create).  On Windows, you'll wantCreateThreador _beginthreadex.


Question:
I am reading a file with fgetc, so each time it reads a character, the cursor positio gets changed.

Is it possible to know, after each read, the "coordinates" of the cursor on the file in terms of column and line number?

Thanks

Answer:
You can useftell

It does not give you the position in terms of row and column but gives the current position in the stream from the start.


Question: As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?

Answer: Take a look at theC10Kpage for a great overview and comparison of I/O frameworks and strategies.


Question:
I mean i want the input to be invisible like inputing password when i log in Linux.
How can I implement it both in C under linux and windows.
thanx

Answer:
There is no single solution that will work across platforms.

For Linux you can use thegetpass() function.

For windows you can try_getch().


Question:
What is the result of the following line:

```
int* ptr;
printf("%x, %x\n", ptr, &ptr);
```

I know thatptris an address in a memory, but what is&ptr?

Answer: &ptr would be the address for the memory location that ptr is held in. Essentially it is a pointer to a pointer.


Question:
I'm trying to enumerate some operators, my code line is :

```
enum operations{+=4,-,%,<,>}
```

when i'm trying to compile this line , gcc says : expected identifier before ‘+’ token

So, how can I enumerate these operators. Can we use some escape characters for them ?

Answer:
Your best bet is something like this:

```
enum Operations
{
  Plus=4,
  Minus,
  Mod,
  LessThan,
  MoreThan
}
```


Question: How to inform the server if a client is interrupted, and then close the socket?

Answer:
If the other end of a socket is closed, your end will be marked as readable and return0fromread- this is the "end of file" indication.

If you try towriteto such a socket, you will recieve theSIGPIPEsignal, and thewritewill return error with errno set toEPIPE("Broken Pipe").  You must be prepared to handle this event, because the other end can close the socket atanytime.


Question:
I am reading a file with fgetc, so each time it reads a character, the cursor positio gets changed.

Is it possible to know, after each read, the "coordinates" of the cursor on the file in terms of column and line number?

Thanks

Answer:
You can useftell

It does not give you the position in terms of row and column but gives the current position in the stream from the start.


Question: As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?

Answer: Take a look at theC10Kpage for a great overview and comparison of I/O frameworks and strategies.


Question:
I mean i want the input to be invisible like inputing password when i log in Linux.
How can I implement it both in C under linux and windows.
thanx

Answer:
There is no single solution that will work across platforms.

For Linux you can use thegetpass() function.

For windows you can try_getch().


Question:
What is the result of the following line:

```
int* ptr;
printf("%x, %x\n", ptr, &ptr);
```

I know thatptris an address in a memory, but what is&ptr?

Answer: &ptr would be the address for the memory location that ptr is held in. Essentially it is a pointer to a pointer.


Question:
Is it possible to compile C code into a Visual C++ dll? I'm looking at using some C code with a .Net project and trying to determine whether this is even an option.

Thanks,
Becky

Answer:
yes. If you want to get rid ofname manglinguse"extern "C" { /*...*/ }construct.

Also, refer FAQ :How to mix C and C++


Question:
```
#ifndef NULL
#define NULL NULL
#endif
```

This code compiles in gcc with no warnings/errors.  Can someone explain what the preprocessor is doing here?

Answer: Anywhere the compiler sees the text "NULL" it will replace it with the text "NULL". It's like doing a search-and-replace in your code for "NULL" and replacing with "NULL". Not illegal, just weird :)


Question:
Managed to create a simple bootloader... and with VESA 2.0 I managed to change the resolution to 1024x768x32, also managed to setup a Linear Frame Buffer... Where can I find tutorials for using the frame buffer? Like lets say to display a picture before it finishes to load?

So far I saw one sample on how to "draw" an ipod...called CdPod

Answer: If you have the address of the linear framebuffer all you need to do is to copy the raw image data to it's location.


Question: Is it necessary to code RTOS in C language always? Why can't that be coded in java or some other technology..?? Is that because of the absence of pointer concept in java?

Answer:
Garbage collection is the big reason against Java being Real Time. JIT is another, but it could be overcome.

In general though, C being effectively portable assembly gives very predicable run-time performance, and that's essential for reliable real-time execution.


Question:
I am writing a C project. Now I just doubt one function in the whole project may be take the most of computational complexity. If I can make sure about this, I can further improve this function with a more clear target.

Or, is there any tools for this usage?? I mean to find the most "expensive" function in the whole program or project??

Any advices?  Thanks!

Answer: The gprof profiler comes with theGCCcompiler suite. Theres a manual for ithere.


Question:
I have a binary search tree created in C. The problem is I can't find a efficient way to delete all the nodes with e.g., id>5.

When I traverse the tree, if I delete a node, the recursion is getting error, because the structure is not the same.

Is there any way, instead of using a helping stack to keep the data before delete them from the tree?

Answer: Did you try postorder?Delete the node after its children.


Question: I need to prevent application's memory pages from being swapped out of RAM on Windows. Is there a WinAPI function equivalent of POSIXmlockall()to achieve that?

Answer: Yes, VirtualLock().  There's a limit on how many pages you can lock, you can't hog RAM.  Details are in theMSDN article.


Question: I'm currently exploring interfacing C and R (using R's .Call for speed). I've only used C for trivial integer computation and text processing applications, and I've never had to worry about issues with float variables, underflow, etc. What tests can I write for functions to ensure numerical accuracy?

Answer:
For a great overview of possible edge cases, see thisWikipedia article.

Then for unit tests seeThe pitfalls of verifying floating-point computations.


Question:
Any idea what this means? Not sure of the language.

(void *) 0x00

Answer:
In C, it means a NULL pointer, i.e., a pointer that points to no relevant data.

Trying to access this data raises a Segmentation Fault, at least on Unix/Linux.


Question:
I need to work out if a massive integer (I mean 20 digits...) is prime.

I'm trying to use the brute-force method, but (of course) I need to use doubles to contain the original number. However, the modulo operator (%) is an integer operator - thus it is useless to me!

Answer: That's not possible, a double only has 15 significant digits.  Look for an implementation of aBigInt class.C specific is discussedhere.


Question:
I have a binary search tree created in C. The problem is I can't find a efficient way to delete all the nodes with e.g., id>5.

When I traverse the tree, if I delete a node, the recursion is getting error, because the structure is not the same.

Is there any way, instead of using a helping stack to keep the data before delete them from the tree?

Answer: Did you try postorder?Delete the node after its children.


Question: I need to prevent application's memory pages from being swapped out of RAM on Windows. Is there a WinAPI function equivalent of POSIXmlockall()to achieve that?

Answer: Yes, VirtualLock().  There's a limit on how many pages you can lock, you can't hog RAM.  Details are in theMSDN article.


Question: I'm currently exploring interfacing C and R (using R's .Call for speed). I've only used C for trivial integer computation and text processing applications, and I've never had to worry about issues with float variables, underflow, etc. What tests can I write for functions to ensure numerical accuracy?

Answer:
For a great overview of possible edge cases, see thisWikipedia article.

Then for unit tests seeThe pitfalls of verifying floating-point computations.


Question:
Any idea what this means? Not sure of the language.

(void *) 0x00

Answer:
In C, it means a NULL pointer, i.e., a pointer that points to no relevant data.

Trying to access this data raises a Segmentation Fault, at least on Unix/Linux.


Question:
I need to work out if a massive integer (I mean 20 digits...) is prime.

I'm trying to use the brute-force method, but (of course) I need to use doubles to contain the original number. However, the modulo operator (%) is an integer operator - thus it is useless to me!

Answer: That's not possible, a double only has 15 significant digits.  Look for an implementation of aBigInt class.C specific is discussedhere.


Question:
I'm looking for a nice and efficient implementation of Xiaolin Wu's anti-aliased line drawing algorithm in C, does anyone have this code they could share with me?

Thanks

Answer:
Wikipedia haspseudo code.

Google has many examples likethis oneorthis one. And your question reminded me this nice article onantialiasing.

EDIT: It's time to discoverHugo Helias's websiteif you don't know it already.


Question:
gcc 4.4.1

I am maintaining someone's code and I have come across something that I don't understand.

```
#define RES_API(name, func) name##_##func
```

Can anyone explain?

Many thanks,

Answer: The##is a concatenation operator.  UsingRES_API(name1, func1)in your code would be replaced withname1_func1.  More informationhere.


Question:
I'm looking to build a Morse decoder (and eventually a coder) in C.  I'd like to use the audio port as input, and sample the incoming voltage on the port.

How do I go about reading the voltage on a microphone audio port in Windows using C?

Answer:
The simplist way is to use thewaveInfunctions provided by the Win32 API.

You can readRecording and Playing Sound with the Waveform Audio Interfacefor an overview, or just dive into theAPI documentation.


Question: How would I P/Invoke a C function which returns a union'ed struct?

Answer:
You would need to use aStructLayoutof explicit and theFieldOffsetattribute.

An example of usage:

```
<StructLayout(LayoutKind.Explicit, Size:=4)> _
   Public Structure DWord
      <FieldOffset(0)> Public Value As Int32
      <FieldOffset(0)> Public High As Int16
      <FieldOffset(2)> Public Low As Int16
   End Structure
```


Question:
See question. Also any links to example code or example code on how to validate an xml file against multiple schemas would be helpful.

EDT: Sorry forgot to mention that this is for LINUX

Answer: libxml2is portable, pure C andimplements XML Schema. It is also open-source (MIT license) and has an active developer community.


Question:
say you have a source file namedsum.cthat looks like this:

```
#include "sum.h"

int sum(int x, int y) {
    return x+y;
}
```

What's the point of including method's header in it's own definition file? Aren't you supposed to include it only in source files that call thesumfunction?

Answer: This way you avoid possible problems if the definitions in the header and in the source files differ.


Question: I would like someone to give a working example ofSetWindowPoson how to make a window "topmost" (be on top and stay there) using either C/C++/C#. Thanks in advance!

Answer:
C/C++:

```
// This doesn't size or move the window, just makes it top-most.
SetWindowPos( hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
```


Question: Is the there a way to forceanotherwindow to be on top?Notthe application's window, butanotherone, already running on the system. (Windows, C/C++/C#)

Answer:
```
SetWindowPos(that_window_handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
```

BringWindowToTopmoves the window to the top of the Z-order (for now) but doesnotmake it a topmost window.


Question: It looks like g_strncasecmp is deprecated, so I am looking for another function to do the same thing.

Answer:
From the docs athttp://library.gnome.org/devel/glib/stable/glib-String-Utility-Functions.html#g-strncasecmp

"There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8."


Question: I creates program in c/c++ in turbo c . but i am facing problem is that i am not able to make it full screen in windows vista. please tell me how to do it?

Answer:
Why are you still living in the Turbo era? Switch on to some better compiler.

gcc and MSVC++ Professional Edition are better ones.

On windows use IDEs like DevCpp or Code::Blocks, both support MinGw port of gcc.


Question: It looks like g_strncasecmp is deprecated, so I am looking for another function to do the same thing.

Answer:
From the docs athttp://library.gnome.org/devel/glib/stable/glib-String-Utility-Functions.html#g-strncasecmp

"There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8."


Question: I creates program in c/c++ in turbo c . but i am facing problem is that i am not able to make it full screen in windows vista. please tell me how to do it?

Answer:
Why are you still living in the Turbo era? Switch on to some better compiler.

gcc and MSVC++ Professional Edition are better ones.

On windows use IDEs like DevCpp or Code::Blocks, both support MinGw port of gcc.


Question: It looks like g_strncasecmp is deprecated, so I am looking for another function to do the same thing.

Answer:
From the docs athttp://library.gnome.org/devel/glib/stable/glib-String-Utility-Functions.html#g-strncasecmp

"There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8."


Question: I creates program in c/c++ in turbo c . but i am facing problem is that i am not able to make it full screen in windows vista. please tell me how to do it?

Answer:
Why are you still living in the Turbo era? Switch on to some better compiler.

gcc and MSVC++ Professional Edition are better ones.

On windows use IDEs like DevCpp or Code::Blocks, both support MinGw port of gcc.


Question:
I have the string:"foo$bar@baz"

I'm looking to write a C program which will extra all three sub-strings ("foo","bar"and"baz") and put each into it's own string.

P.S. Don't worry, this isnothomework.

Answer: What you are looking for isstrtok. It allows for you to set the delimiters as well.