Question:
I saw this function in some code and I can't find documentation on google about it. Can someone explain what it does and are there any alternatives to this ?

Thanks.

Answer:
Seehttp://msdn.microsoft.com/en-us/library/tsbaswba%28VS.80%29.aspx: it is a generic name forsscanf_s.

EDIT: which is conveniently documentedhere._stscanf_sis in TCHAR.H on Windows platforms. You can probably get away with usingsscanf_sorswscanf_s.


Question:
I'm working with a lexer that acceptsFILE*objects to read data from. I'd like to be able to pass it POSIX file descriptors (i.e. stuff you get fromopen, pipes, etc.).

How can I turn a POSIX file descriptor into aFILE*?

Answer: On any POSIX-compliant system, you usefdopen().


Question:
I want to use a byte variableito execute a bit of code 256 times. The line below loops indefinitely, is there a tidy alternative that would work?

```
for (i = 0; i < 255; i++){
```

Hopefully without using:

a 16 bit variable, (or any extra bits at all)nested loopswhile(1)break;statements

Thanks

Answer:
```
i = 0;
do {
  f(i);
} while(i++!=255);
```


Question: I am debugging some code and there is l_pid = 0 always for setting file locks.. It seems odd to me.. Is this correct?Documentation doesnt say about 0 zero value ..

Answer: l_pidis only meaningful when getting the lock status withF_GETLK; when setting a lock, if it succeeds then you know what pid owns it.  :)  (And the buffer is returned unmodified it it fails.)


Question:
I saw this function in some code and I can't find documentation on google about it. Can someone explain what it does and are there any alternatives to this ?

Thanks.

Answer:
Seehttp://msdn.microsoft.com/en-us/library/tsbaswba%28VS.80%29.aspx: it is a generic name forsscanf_s.

EDIT: which is conveniently documentedhere._stscanf_sis in TCHAR.H on Windows platforms. You can probably get away with usingsscanf_sorswscanf_s.


Question:
I'm working with a lexer that acceptsFILE*objects to read data from. I'd like to be able to pass it POSIX file descriptors (i.e. stuff you get fromopen, pipes, etc.).

How can I turn a POSIX file descriptor into aFILE*?

Answer: On any POSIX-compliant system, you usefdopen().


Question:
I want to use a byte variableito execute a bit of code 256 times. The line below loops indefinitely, is there a tidy alternative that would work?

```
for (i = 0; i < 255; i++){
```

Hopefully without using:

a 16 bit variable, (or any extra bits at all)nested loopswhile(1)break;statements

Thanks

Answer:
```
i = 0;
do {
  f(i);
} while(i++!=255);
```


Question: I am debugging some code and there is l_pid = 0 always for setting file locks.. It seems odd to me.. Is this correct?Documentation doesnt say about 0 zero value ..

Answer: l_pidis only meaningful when getting the lock status withF_GETLK; when setting a lock, if it succeeds then you know what pid owns it.  :)  (And the buffer is returned unmodified it it fails.)


Question:
I found a C source in these files with.wextensions.  It seems like a mix of TeX code
and C Programming Language.Thisis an example of these sources.

How can I compile?

PS: Excuse me for the silly question but I didn't found any documentation

Answer: Use Knuth's CWEB, a literate-programming tool.  You can download it fromhere.


Question:
Dcraw contains a following algorithm to process image colors:https://gist.github.com/1047302.Is it a formal (named) image processing algorithm?

If not, what should I read to understand reasoning behind it?

Answer: It's not processing an image.  It's generating a lookup table (curve[]) used to performgamma correction.


Question:
I am developing a C application using ncurses library in linux. my program cant distinguish between Alt  and Esc keypresses. both return 27!
can you help me how I can distinguish between the two?
thank you

Answer: You need to incorporate a short delay after the^[in order to see if there are further characters incoming. If not, thenEschas been pressed.


Question:
Do these two statements compile equivalently: n % 2 == 0 and n & 1 == 0 ?

if not, is one more efficient?

Answer: No, they do not always give the same result.  The C standard allows for ones' complement implementations, in which case they will give a different result for negativen.


Question:
how can I get the user name that auth by pam_ldap in C/c++?
I found "pam_get_user" API, but how can I get the pam_handle_t for this function?

Thanks
Dma

Answer:
You get the handle by calling:

```
int pam_start(const char *service_name, const char *user,
              const struct pam_conv *pam_conversation, pam_handle_t **pamh);
```

pamh- is an output parameter in above api.

Check more detailshere.


Question:
When declaring an enum as shown below, do all C compilers set the default values asx=0,y=1, andz=2on both Linux and Windows systems?

```
typedef enum {
    x,
    y,
    z
} someName;
```

Answer: Yes.  Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.


Question:
I know it is a little bit off topic but I believe I can get the answer anyway here. What does "psz" stand for inpszBufferor the similar variable in C/C++ system library? I saw a lot of variables prefixed with "psz" and it looks like a pattern.

Thanks!

Answer: This isHungarian notation.psznormally stands for "(p)ointer to (s)tring, (z)ero-terminated".


Question:
When declaring an enum as shown below, do all C compilers set the default values asx=0,y=1, andz=2on both Linux and Windows systems?

```
typedef enum {
    x,
    y,
    z
} someName;
```

Answer: Yes.  Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.


Question:
I know it is a little bit off topic but I believe I can get the answer anyway here. What does "psz" stand for inpszBufferor the similar variable in C/C++ system library? I saw a lot of variables prefixed with "psz" and it looks like a pattern.

Thanks!

Answer: This isHungarian notation.psznormally stands for "(p)ointer to (s)tring, (z)ero-terminated".


Question:
When declaring an enum as shown below, do all C compilers set the default values asx=0,y=1, andz=2on both Linux and Windows systems?

```
typedef enum {
    x,
    y,
    z
} someName;
```

Answer: Yes.  Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.


Question:
I know it is a little bit off topic but I believe I can get the answer anyway here. What does "psz" stand for inpszBufferor the similar variable in C/C++ system library? I saw a lot of variables prefixed with "psz" and it looks like a pattern.

Thanks!

Answer: This isHungarian notation.psznormally stands for "(p)ointer to (s)tring, (z)ero-terminated".


Question:
How can I remove the dot at the end of a line in C? This is my current code but it eliminates all dots, even in the middle of the word.

```
char *pc;
  pc = strtok(acData, " .\n");
```

Answer:
If your strings are of this format:word word word.Thenpc[strlen(pc) - 1]corresponds to\0andpc[strlen(pc) - 2]to the., so by doingpc[strlen(pc) - 2] = '\0';it will remove the..

If your strings contain\nthen you should dopc[strlen(pc) - 3] = '\0';.


Question: For a 32 bit integer, how do I set say k low order bits in C?

Answer:
Assuming you want to set theklowest bits of a 32-bit integerx, I believe this will work:

```
if( k > 0 ) {
    x |= (0xffffffffu >> (32-k))
}
```


Question:
How do I change the location where .obj, .exe files are generated in visual studio?
I want these files to always be in a folder on the desktop

Answer: In the project properties, under Configuration Properties, you can set the Output directory and the intermediate directory.


Question:
In21.6.7.1,21represents the some segment,6represents some lane inside that segment and so on and so forth. The individual values need to be extracted.

One way to represent this is string, any other way which is better and more convenient than string?

Answer: A structure with a four fields? An array of 4 elements, can also be an option.


Question: I'm using C.  How can I print the values of a member of an instance of a structure? Is it possible? At least is it possible in case of a structure declared as global variable (not a dynamically allocated one)?

Answer:
```
set print objects on
p structVar
p *pointerToStructVar
```

Or, more explicitly:

```
p structVar.member
p pointerToStructVar->member
```


Question:
Sorry about this basic question, but why0x11is17in decimal(print(%d, 0x11)=17?

I search information about the way to convert from hex to dec, but it doesn't talk about this sort of numbers.

Answer: Just like "11" in base ten means "1 ten" and "1 one", "11" in base 16 (i.e. hex) means "1 sixteen" and "1 one" - or 17 in base 10.


Question:
In21.6.7.1,21represents the some segment,6represents some lane inside that segment and so on and so forth. The individual values need to be extracted.

One way to represent this is string, any other way which is better and more convenient than string?

Answer: A structure with a four fields? An array of 4 elements, can also be an option.


Question: I'm using C.  How can I print the values of a member of an instance of a structure? Is it possible? At least is it possible in case of a structure declared as global variable (not a dynamically allocated one)?

Answer:
```
set print objects on
p structVar
p *pointerToStructVar
```

Or, more explicitly:

```
p structVar.member
p pointerToStructVar->member
```


Question:
Sorry about this basic question, but why0x11is17in decimal(print(%d, 0x11)=17?

I search information about the way to convert from hex to dec, but it doesn't talk about this sort of numbers.

Answer: Just like "11" in base ten means "1 ten" and "1 one", "11" in base 16 (i.e. hex) means "1 sixteen" and "1 one" - or 17 in base 10.


Question: I have.libfile compiled from C code. How I know if this self-contained static library or just an import lib and DLL will be needed at runtime? Is there somedumpbinoption I'm missing?

Answer:
Use the lib command. If it's static, lib will show you a pile of .obj files inside. Not so if it's an implib.

```
lib /list foo.lib
```

will do it.

Also see:

https://learn.microsoft.com/en-us/cpp/build/reference/managing-a-library


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:In C arrays why is this true? a[5] == 5[a]

```
int a[5]={1,2,3,4,5};
int i=4;
printf("%d",i[a]);
```

Why do a[i] and i[a] refer to same location in the array?

Answer:
This is because array subscript iscommutative(it's an addition), the order can be swapped :

```
a[i] = *(a + i)
i[a] = *(i + a)

*(a + i) = *(i + a)
a[i] = i[a]
```


Question: I have installed mingW to use gcc, platform windows 7. I am trying to locate the standard C library libc.a in mingW folder. no luck.. is it stored in some other name?

Answer: MinGW does not build against glibc, it builds against msvcrt. As such, it uses libmsvcrtXX.a instead.


Question: I am doing a GTK C program on Windows and I want to prevent the user from being able to select/highlight any rows in the tree view. Can anyone point me in the right direction?

Answer:
The "gtk_tree_selection_set_select_function ()" seems to be exactly what you want.

http://developer.gnome.org/gtk/2.24/GtkTreeSelection.html#gtk-tree-selection-set-select-function


Question:
I am wondering how to add the new line before closing the file.

I have tried usingfputsandputsand frpints something likeputs("/n");etc
but it doesnt work.

Thanks & regards,
SamPrat

Answer:
a very simple way, no error checking:

```
FILE * file = fopen(fname, "a");
fwrite("\n", strlen("\n"), 1, file);
fclose(file);
```


Question:
I am working on a project which involves stereo-vision. I am using c and openncv right now. I want to make a 3D plot of points based on their calculated position. Can someone tell how to do it in c or opencv?

platform: XP, visualstudio 2005

Answer: You need a 3D rendering engine like OpenGL or DirectX. You can use any of them in VS2005 and WindowsXP.


Question: was wondering if an Equivalent of PHP'sstripslashes()in C existed?

Answer: No, because this is not a problem that is usually encountered in C. If you want the same functionality then you will need to write it yourself, or find some library that provides it.


Question:
Hi I am trying to use C to parse xml, but all the examples I can find are using a file to get the xml, I have the xml already loaded into a variable and I want libxml2 to take the xml from there instead of a file.... but I can't figure out how!

Any help would be appreciated thanks

Answer: Have a look atthis example:usingXmlReadMemory


Question: I have an old piece of software that uses gtkembedmoz, and I need to update it to run on ubuntu lucid, which does not provide that library. What API replaces the functionality that it provides?

Answer: You should useWebkitGTKthese days for embedding a web browser into a GTK program.


Question:
Just want to know whether the casts in the example below are redundant.

uint16_t basic_units = 4587U;

uint8_t int_val =  (uint8_t) (((uint16_t ) (basic_units * 5U)) / 1000U);

Answer: Theuint8_tcast is redundant. Theuint16_tcast may have the (un)intended consequence of truncating an intermediate value in the calculation ifbasic_units * 5Uwould overflow a normaluint16_tbefore being divided by 1000.


Question:
i wanted an UDisks script to list all the usb devices that are mounted on my system , which
must have ability to detect LVM devices.

Perl / C / Shell any is fine

Many thanks.

P.S: Hal is deprecated on my Gentoo and removed

Answer: loads of info about udisks herehttp://igurublog.wordpress.com/2011/01/26/a-custom-udisks-automounter/


Question:
I want to combine both the for loops into single for loop. How can i do that?

I want to loop through a to z, and A to Z, like so:

```
char ch;
for (ch = 'A' ; ch <= 'Z' ; ch++ )
{
}
for (ch = 'a' ; ch <= 'z' ; ch++ )
{
}
```

but using a single loop.

Answer:
```
for (char ch = 'A' ; ch <= 'z' ; ch == 'Z' ? ch = 'a' : ++ch )
{
}
```

Should work -- though please, please, don't inflict this on your fellow developers.


Question:
i like to get float value with first two decimal value in C language.

my input is

```
Float f;
f=2.3678;
```

i like to get output like this

```
2.36
```

Answer:
Include themath.hheader file and do this:

```
float f;
f = 2.3678;
f = floor(f * 100) / 100;
// f = 2.36
```


Question:
I have
char* data;
which has a buffer dumped into it. I want to view the content of this char*. I do not know the size of this pointer data so How do I print it?! Thank you

Answer:
Assuming thechar*isNUL-terminated, useprintf("%s\n",data);.

If the data are notNUL-terminated, this may cause a segmentation fault.

If your data have some format other than ASCII characters, you're going to need to write some code to print it.


Question:
Is it a guarantee thatstateafter this code will beLX_DONE?

```
enum lx_state { LX_START, LX_MIDDLE, LX_DONE };

enum lx_state state = LX_START;
++state;
++state;
```

Answer:
Yes, the C standard says, in 6.7.2.2/3,

Each subsequent enumerator with no =
  defines its enumeration constant as the value of the constant expression obtained by
  adding 1 to the value of the previous enumeration constant


Question:
Just want to know whether the casts in the example below are redundant.

uint16_t basic_units = 4587U;

uint8_t int_val =  (uint8_t) (((uint16_t ) (basic_units * 5U)) / 1000U);

Answer: Theuint8_tcast is redundant. Theuint16_tcast may have the (un)intended consequence of truncating an intermediate value in the calculation ifbasic_units * 5Uwould overflow a normaluint16_tbefore being divided by 1000.


Question:
i wanted an UDisks script to list all the usb devices that are mounted on my system , which
must have ability to detect LVM devices.

Perl / C / Shell any is fine

Many thanks.

P.S: Hal is deprecated on my Gentoo and removed

Answer: loads of info about udisks herehttp://igurublog.wordpress.com/2011/01/26/a-custom-udisks-automounter/


Question:
I want to combine both the for loops into single for loop. How can i do that?

I want to loop through a to z, and A to Z, like so:

```
char ch;
for (ch = 'A' ; ch <= 'Z' ; ch++ )
{
}
for (ch = 'a' ; ch <= 'z' ; ch++ )
{
}
```

but using a single loop.

Answer:
```
for (char ch = 'A' ; ch <= 'z' ; ch == 'Z' ? ch = 'a' : ++ch )
{
}
```

Should work -- though please, please, don't inflict this on your fellow developers.


Question:
Is it possible to call C or C++ code from a Java Code, i can re-write the code in Java, but need to reuse the existing code..

Thanks

Answer: Yes, it's possible using theJava Native Interface.


Question: What is the portable way to check whethermallocfailed to allocate non-zero memory block?

Answer: According to theSingle Unix Specification,mallocwill returnNULLand seterrnowhen it fails.


Question: GNU Emacs is easily extended with Emacs Lisp. In some cases you may hit a performance wall even after byte compiling. In this situation it would be useful to be able to write C functions that you could call from Emacs Lisp code. Is this possible? How do you do it? Is there example code?

Answer: Isthis (Writing Emacs Primitives)what you are looking for?


Question:
Is there is an equivalent in C or Objective-C to do the following (taken from Java)

```
Integer.toHexString(some_int)
```

Answer:
For 32 bit Integers:

```
char buffer[enough_space_for_the_largest_string..];
sprintf (buffer, "%08x", YourNumber);
```


Question:
I am looking for a good library (preferably in C/C++) that can calculate the intersections between a line segment (ray) and a trimesh.

Thanks in advance for any answers!

Answer: CGALis probably overkill, but I suggest it just for reference. Thedocumentationis somewhat intimidating, butthis chaptercould be of interest for you.


Question: I'm looking for classes like "File, Socket, String" wrapping the C (or C++) standard library functions and throwing exceptions in case of errors.

Answer:
Maybe the question wasn't clear,
btw i've found this library is exactly what i was looking for:commonc++.

Edit:Better alternative still maintained.


Question:
How to swap the following two hexadecimal numbers in c language? Eg:

input :0xabcdoutput:0xcdab

Answer:
You can use something along the lines of:

```
#include <stdio.h>
int main (void) {
    unsigned int from = 0xabcd;
    unsigned int to = ((from & 0xff) << 8) | (from >> 8);
    printf ("%04x\n", to);
    return 0;
}
```

This swaps the two bytes around, giving you an output ofcdab.


Question: I'm looking for classes like "File, Socket, String" wrapping the C (or C++) standard library functions and throwing exceptions in case of errors.

Answer:
Maybe the question wasn't clear,
btw i've found this library is exactly what i was looking for:commonc++.

Edit:Better alternative still maintained.


Question:
How to swap the following two hexadecimal numbers in c language? Eg:

input :0xabcdoutput:0xcdab

Answer:
You can use something along the lines of:

```
#include <stdio.h>
int main (void) {
    unsigned int from = 0xabcd;
    unsigned int to = ((from & 0xff) << 8) | (from >> 8);
    printf ("%04x\n", to);
    return 0;
}
```

This swaps the two bytes around, giving you an output ofcdab.


Question:
I want to create a message server using epoll. Several devices will connect to the server and exchange simple text messages. I don't have that much experience with this and I will be very appreciated if you guys can provide me any references or tutorials related to this.

I would like to work with C. Thanks in advance.

Lee

Answer: I would suggest you start by taking a lookhere, and keepingthisclose as a reference.


Question:
Is it safe when therequest_token.size()is larger thanLEN?

```
char dst[LEN];
memcpy(dst, request_token.c_str(), request_token.size());
```

Answer: No, it's not safe; you'll cause a buffer overflow. The reason is,memcpyhas no way to know the size of your target buffer, other than the size you pass in the third argument.


Question:
Is detecting tabs same as detecting the spaces? i.e. for detecting a space, I would just compare the space character with its ascii number.

For a tab do I have to search for '\t' character in the file or there is some other way?

Answer:
```
if('\t' == myChar)
```

This would work, and would be better than checking against 9 since 9 may not be a guaranteed value across all architectures.


Question: I would like to add arp bindings into/proc/net/arpinC. Writing into file is not allowed, so trying to do it some other way. Any suggestions? I already know about net-tools, but havent tryed yet

Answer: You will need to use thenetlink protocolorlibnetlink. I would recommend looking at the source for thearpcommand to see exactly how it does it.


Question: I want to integrate a c language compiler in to java application to compile c sources without file creation (Like Java Compiler Api). Is there any c compiler that has entirely written in java?

Answer:
You can check this link from Google CodeC compiler written in Java

and say congratz to the developer :) -it's not me :p-

Another option is this one:JCPP


Question:
When using GLib 1.2'sGHashTablewith theg_hash_table_foreach()method, is it safe to remove items using theg_hash_table_remove()method?

I know that Glib 2.0 provides theg_hash_table_foreach_steal()method, but we're stuck with 1.2 for our build at work.

Answer: Well it's not allowed in the current API, so I'd be really surprised if that functionality was there in 1.2.


Question:
Consider the following OpenMP for loop:

```
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < n; ++i)
{
    //do something with i
}
```

Is it guaranteed that each OpenMP thread sees its i values in ascending order?

Answer: The order in which threads run is not guaranteed;the order in which a thread processes its own chunk is guaranteed.


Question:
If I Make A Program In C Without Including Windows.h Header File Will It Run On Linux.
I Am Making It In Code Blocks On Windows.

Answer:
If you only use the Standard C Library you'll be fine. if you go includingio.handconio.hand other junk like that, then you won't be fine.

Obviously I am assuming you are not expecting a windows PE to run on linux (without WINE) or a linux ELF to run on windows (you have to recompile like @sehe suggests).


Question:
Can somebody verify whether the functiongtk_combo_box_text_append()is available from 2.24 or 3?  I was playing with it last night and I got undefined reference error to the specific function.

By the way, I did the test on Slackware64 13.37 on which I checked the version of gtk+2 is 2.24.4.

Answer: According todocumentationthere is no such function in 2.24. There is functiongtk_combo_box_text_append_textin both 2.24 and 3.


Question:
Is this code (simplified from a real project) correct? Will the message always print?

```
char *cp = NULL;
char **cpp = &cp;
if(*cpp == NULL) {
    printf("I believe this will this always print. Does it?\n");
}
```

Thanks!

Answer:
There is nothing wrong with the code you have shown. Yourchar **pointer is pointing to a valid variable, thus it's always proper to dereference it.

P.S. Yes, it will always print.


Question:
I want to create pkcs7 signed envelop having S/MIME format and also want to read it. The file extension ispk7.

How to do it with the OpenSSL library?

Answer:
TheSMIME_read_PKCS7()andSMIME_write_PKCS7()functions can be used to convert an SMIME message into a PKCS7 structure and vice-versa.

You can usePKCS7_sign()/PKCS7_encrypt()to create PKCS7 structures, andPKCS7_verify()/PKCS7_decrypt()to consume them.


Question: I am using gnu tool chain. How can I, at run time, find caller of a function? i.e for example function B() gets called by many functions using function pointers. Now, whenever B gets called, I want to print the callers name. I need this for debugging a certain issue.

Answer: If you're using GNU, you can use thebacktracefunctions. There's an example of the use on that man page.


Question: How can I print all global variables/local variables? Is that possible in gdb?

Answer:
Typeinfo variablesto list "All global and static variable names" (huge list.

Typeinfo localsto list "Local variables of current stack frame" (names and values), including static variables in that function.

Typeinfo argsto list "Arguments of the current stack frame" (names and values).


Question:
Can somebody verify whether the functiongtk_combo_box_text_append()is available from 2.24 or 3?  I was playing with it last night and I got undefined reference error to the specific function.

By the way, I did the test on Slackware64 13.37 on which I checked the version of gtk+2 is 2.24.4.

Answer: According todocumentationthere is no such function in 2.24. There is functiongtk_combo_box_text_append_textin both 2.24 and 3.


Question:
Is this code (simplified from a real project) correct? Will the message always print?

```
char *cp = NULL;
char **cpp = &cp;
if(*cpp == NULL) {
    printf("I believe this will this always print. Does it?\n");
}
```

Thanks!

Answer:
There is nothing wrong with the code you have shown. Yourchar **pointer is pointing to a valid variable, thus it's always proper to dereference it.

P.S. Yes, it will always print.


Question:
I want to create pkcs7 signed envelop having S/MIME format and also want to read it. The file extension ispk7.

How to do it with the OpenSSL library?

Answer:
TheSMIME_read_PKCS7()andSMIME_write_PKCS7()functions can be used to convert an SMIME message into a PKCS7 structure and vice-versa.

You can usePKCS7_sign()/PKCS7_encrypt()to create PKCS7 structures, andPKCS7_verify()/PKCS7_decrypt()to consume them.


Question: I am using gnu tool chain. How can I, at run time, find caller of a function? i.e for example function B() gets called by many functions using function pointers. Now, whenever B gets called, I want to print the callers name. I need this for debugging a certain issue.

Answer: If you're using GNU, you can use thebacktracefunctions. There's an example of the use on that man page.


Question: Is there a way or an API to install a font on the PC for every user, without logging off or restarting the PC?

Answer:
See the MSDN document,Font Installation and Deletion, for full details. In summary:

Copy the font file to the fonts directory (%windir%\fonts).CallAddFontResource()to ensure the font is immediately available.Broadcast theWM_FONTCHANGEmessage.

Thanks to @Alex K for cleaning this up and adding the fine detail.


Question:
I have a struct :

```
struct ABC
{
   int size;
   int arr[15];
};
```

I know I cannot make 'int size' as 'const int size' so how can I keep the size member from being modified accidently/intentionally.Is there a way around in C?

Thanks.

Answer:
It can be const:

```
struct ABC
{
   const int size;
   int arr[15];
};

int main() {
    struct ABC a = {3, {1,2,3} };   // ok
    a.size = 42;    // error
}
```


Question:
This seems ambiguous to me:

```
*p1->p2
    *(p1->p2) or (*p1)->p2

*p1.a
    *(p1.a) or (*p1).a
```

How does the compiler interpret such expressions?

Answer:
It's all down tooperator precedence.  Both->and.have higher precedence than*(in this context), so the two expressions are equivalent to:

```
*(p1->p2)
*(p1.a)
```


Question:
This seems ambiguous to me:

```
*p1->p2
    *(p1->p2) or (*p1)->p2

*p1.a
    *(p1.a) or (*p1).a
```

How does the compiler interpret such expressions?

Answer:
It's all down tooperator precedence.  Both->and.have higher precedence than*(in this context), so the two expressions are equivalent to:

```
*(p1->p2)
*(p1.a)
```


Question:
```
#include <stdio.h>

int main()
{
   int i = 10;
   printf("%d\n", ++(-i)); // <-- Error Here
}
```

What is wrong with++(-i)? Please clarify.

Answer: -igenerates a temporary and you can't apply++on a temporary(generated as a result of an rvalue expression). Pre increment++requires its operand to be an lvalue,-iisn't an lvalue so you get the error.


Question: I'm writing code for a primality testing function that handles long long int's.Do I have to use special operators for such large numbers?Is there any documentation concerning large number manipulation in C?I'm using the gnu standard library.Thanks.

Answer: No, you don't need to do anything special. You handle along long intjust the same way as you would handle aint. Just beware of overflows, as with every native integer type.


Question:
```
#include <stdio.h>

int main()
{
   int i = 10;
   printf("%d\n", ++(-i)); // <-- Error Here
}
```

What is wrong with++(-i)? Please clarify.

Answer: -igenerates a temporary and you can't apply++on a temporary(generated as a result of an rvalue expression). Pre increment++requires its operand to be an lvalue,-iisn't an lvalue so you get the error.


Question: I'm writing code for a primality testing function that handles long long int's.Do I have to use special operators for such large numbers?Is there any documentation concerning large number manipulation in C?I'm using the gnu standard library.Thanks.

Answer: No, you don't need to do anything special. You handle along long intjust the same way as you would handle aint. Just beware of overflows, as with every native integer type.


Question: I don't want to resize the entire image structure, but the images I am working with are too large to easily view with cvShowImage.  Is there a way to resize their view within the window created by cvShowImage?

Answer: No there isn't, you will have to create a new image structure and use cvResize.


Question:
Is there any method inCcan find a text within another text?

For example,text = "abaHello",textneedtoSearch = "Hello";.

If thetextcontains"Hello",return true, else return false.

Answer: Usestrstr, seehttp://pubs.opengroup.org/onlinepubs/9699919799/functions/strstr.html


Question: Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?

Answer: It depends on the compiler. Visual C++ 9 can do that - unusedstaticfunctions are removed at compilation phase (there's even aC4505 warningfor that), unused functions with external linkage can be removed at link phasedepending on linker settings.


Question:
```
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```

It doesn't look like ascii nor multibyte,what's that?

Answer: These areoctalcharacter escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value.\377for instance is the hexadecimal valueffor decimal255which would be thisÿin ASCII but most likely has a very different meaning in this context.


Question:
```
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```

It doesn't look like ascii nor multibyte,what's that?

Answer: These areoctalcharacter escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value.\377for instance is the hexadecimal valueffor decimal255which would be thisÿin ASCII but most likely has a very different meaning in this context.


Question:
consider the following two code:

```
void PrintLetter(char *src)
{
 while(*src != '\0')
 {
   printf("%c",*src);
   src++;
 }
}
```

and

```
void PrintLetter(char *src)
{
 int i;
 for(i=0;src[i];i++)
  printf("%c",src[i]);
}
```

Is there any performance difference between the two?

Answer: None whatsoever. The compiler will perform its optimizations regardless of the form you are writing. The underlying assembly code is the same.


Question: I'm learning C/C++ right now and I am reading about file operations. Suppose a program A is working with an external file (say, a text file) and another another program B is, say, trying to move the file (or worse, delete it). Is it possible to tell the OS to inform the program B that the file is in use, even though it was not created by program A?

Answer: What you're trying to do is calledfile locking. Search for "file locking in C".


Question:
```
typedef struct {
    float *numbers;
    float val1;
    float val2;
} Values;
Values val[16];
```

How can one allocate memory for numbers in the struct?

Answer:
If you want to allocate the space for one float in the first element of your struct, you would do it like this:

```
#include <stdlib.h>

/* ... */

val[0].numbers = malloc(1 * sizeof(float)); /* "1 * " for clarity... */
```

If that's what you meant.


Question:
are there any specifics when developing a device driver (kernel-mode) on Windows 7 32 bit or Windows 7 64 bit? Can I develop on some platform and prepare builds to run on the other one?
Thank you.

Answer: You need theWindows Driver Kit. Yes, you should be able to cross-compile.


Question: What is the cleanest way to pass data from device driver to windows service and back?

Answer:
This is normally achieved usingDevice Input and Output Control (IOCTL).

You can define your own private control code and then send information in both directions. The function is called from user mode, i.e. the service in your case.


Question:
C++ can use c functions byextern "C",

can c use c++ functions somehow?

Answer: Not really. You can write a "C-compatible" function in C++, that is to say outside of any class or namespace and whose prototype does not use classes or references. If declaredextern "C"then you could call such a function from C. The function could then go on to make use of whatever C++ features were useful for it.


Question:
```
typedef struct {
    float *numbers;
    float val1;
    float val2;
} Values;
Values val[16];
```

How can one allocate memory for numbers in the struct?

Answer:
If you want to allocate the space for one float in the first element of your struct, you would do it like this:

```
#include <stdlib.h>

/* ... */

val[0].numbers = malloc(1 * sizeof(float)); /* "1 * " for clarity... */
```

If that's what you meant.


Question:
are there any specifics when developing a device driver (kernel-mode) on Windows 7 32 bit or Windows 7 64 bit? Can I develop on some platform and prepare builds to run on the other one?
Thank you.

Answer: You need theWindows Driver Kit. Yes, you should be able to cross-compile.


Question: What is the cleanest way to pass data from device driver to windows service and back?

Answer:
This is normally achieved usingDevice Input and Output Control (IOCTL).

You can define your own private control code and then send information in both directions. The function is called from user mode, i.e. the service in your case.


Question:
what's the meaning ofVOID()

There are the following C code, but what's it's meaning?

```
VOID(pthread_mutex_init(&tina_mutex,MY_MUTEX_INIT_FAST));
```

Answer:
Looks like a preprocessor macro. Your editor should be able to find what it is. Or try

```
gcc -E source.c > source2.c
```

It runs the preprocessor only and replaces macros with what they really evaluate to.


Question:
When I want to pass a "char (*c)[10];" as a parameter,
what argument should I define in my function definition?

I mean, if I have a function:

```
void foo(*****) { ... }
```

I want to passchar (*c)[10];to it, so what do I write in place of*****?

Answer:
This should work fine:

```
void foo(char (*c)[10]);
```


Question:
for example,

```
int a;
```

Here there is aspacebetween 'int' and 'a'but what can be the separators other than whitespace?

Answer:
You can use a paren:

```
int main() {
    int(a);
    a = 42;
}
```

but please don't.


Question:
I used to usefflush(stdin). I read that this is not a good way to get rid of the extra characters and that it is better to use fgets like this:

```
fgets(buffer,maxsize,stdin);
```

In cases that I want to dispose of those extra chars...what kind of buffer should I use? Could I redirect in some kind of "buffer of no return"? Or do I have to use a finite size array?

Thanks in advance.


Question:
what's the meaning ofVOID()

There are the following C code, but what's it's meaning?

```
VOID(pthread_mutex_init(&tina_mutex,MY_MUTEX_INIT_FAST));
```

Answer:
Looks like a preprocessor macro. Your editor should be able to find what it is. Or try

```
gcc -E source.c > source2.c
```

It runs the preprocessor only and replaces macros with what they really evaluate to.


Question:
```
i=n;

while (i>=1) {

  --x=x+1;

  --i=i/2;

}
```

What is the running time of this code?

A O(N^2)B O(N^3)C O(N^4)D O (LOG N)E O(2^N)

I believe it is the option D

This is for revision. Not homework

Answer:
This will never terminate as the while condition is

```
i>=i
```

However, assuming you wanted to type

```
i>=1
```

The answer will be log(n).


Question:
Here's all .h files I've included so far,but non have the definition ofbool:

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
#include <event.h>
```

Which file does definebool?

Answer: It's part ofC99and defined inPOSIX definition stdbool.h.


Question:
I came across a piece of codevoid *p = &&abc;. What is the significance of&&here?
I know about rvalue references but I think&&used in this context is different. What does&&indicate invoid *p = &&abc;?

Answer:
&&is gcc's extensionto get the address of the label defined in the current function.

void *p = &&abcis illegal in standard C99 and C++.

Thiscompiles with g++.


Question: How can I create my own virus signature of a .exe or .lib file? I started my reading certain bytes to the file and then just storing them in another file and manually adding this to a virus scanner. Will this work? thanks

Answer: There are many different ways to create a signature of a file, one of the simplest, and easiest, is to take a hashing function, like SHA1, and run it against the whole file.


Question:
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question

How does (exactly) utility like UNIXfilecommand guess the file type?

Are there any source-codes?

Answer:
It uses various heuristics, mainly signatures which are described in a configuration file.

```
man -s 5 magic
```

will gives the file format.


Question: suppose I have a Unicode codepoint c (auint32). Is there a way to print this integer to console (as a wide character) without usinglocale.horwchar.h? Thanks.

Answer:
You can try to use

```
printf("%lc", c);
```

though you really need to make sure thatcis awint_t(which requireswchar.h) rather than auint32_t, even though the two are most likely the same type...


Question:
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question

How does (exactly) utility like UNIXfilecommand guess the file type?

Are there any source-codes?

Answer:
It uses various heuristics, mainly signatures which are described in a configuration file.

```
man -s 5 magic
```

will gives the file format.


Question: suppose I have a Unicode codepoint c (auint32). Is there a way to print this integer to console (as a wide character) without usinglocale.horwchar.h? Thanks.

Answer:
You can try to use

```
printf("%lc", c);
```

though you really need to make sure thatcis awint_t(which requireswchar.h) rather than auint32_t, even though the two are most likely the same type...


Question:
The question is quite simple: How to read a .pgm image file into a 2D double array in C. I do not have a .pgm buffer in memory. I would like to read it from the disk into memory.

Would really appreciate if I could get a code snippet. Thank You.

Answer:
You probably won't get someone writing you all the code, but here are some useful links that might point you in the right direction:

pgm.cpgm.hPGM Format Specificationhttp://www.cplusplus.com/forum/general/2393/


Question: Is there a tool around that will list all the global variables in a C program? More specifically, is there a simple commandline tool that will do this, i.e. not a heavyweight IDE, CASE, graphical toolkit system etc., but just something that can be run likefoo *.c?

Answer:
```
ctags -R -x --sort=yes --c-kinds=v --file-scope=no file "c:\my sources" > c:\ctagop.txt
```


Question:
The question is quite simple: How to read a .pgm image file into a 2D double array in C. I do not have a .pgm buffer in memory. I would like to read it from the disk into memory.

Would really appreciate if I could get a code snippet. Thank You.

Answer:
You probably won't get someone writing you all the code, but here are some useful links that might point you in the right direction:

pgm.cpgm.hPGM Format Specificationhttp://www.cplusplus.com/forum/general/2393/


Question: Is there a tool around that will list all the global variables in a C program? More specifically, is there a simple commandline tool that will do this, i.e. not a heavyweight IDE, CASE, graphical toolkit system etc., but just something that can be run likefoo *.c?

Answer:
```
ctags -R -x --sort=yes --c-kinds=v --file-scope=no file "c:\my sources" > c:\ctagop.txt
```


Question:
When I printf a char with %c format and the char is unprintable like '\0' then there is no column of printout.  Same if I use %1c.  Or %1.1c. Is there a way to force printf to output a column for '\0'?

I'm doing some large printf's and I want columns to match up.

Answer:
There is nothing you can do for printf. But you can useisprintto filter the arguments of printf

```
printf("%c", (isprint(c) ? c : ' ' ));
```


Question:
Suppose i create a thread that ,in some point, calls a function foo().
If i call pthread_exit() from within foo, will that have as a result termination
of the thread that called foo?

thanks,
Nikos

Answer: Of course. Otherwise what's the point of pthread_exit in the first place.http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_exit.3.html"The pthread_exit() function shall terminate the calling thread"


Question: In C, if my application ends unexpectedly can I call a function before that happens? I'm writing a flag into a database (processRunning = 1) that prevents other applications from starting a similar process. When the application ends it would not change that flag back.

Answer: look into theatexitAPI of the C standard library.


Question:
```
#include<stdio.h>
void f(int a)
{
printf("%d", a);
}
#define f(a) {}

int main()
{
 /* call f : function */
}
```

How to callf(the function)? Writingf(3)doesn't work because it is replaced by{}

Answer:
Does(f)(3);work?

The C preprocessor doesn't expand the macrofinside( ).


Question:
```
if ( sscanf( line, "%[^ ] %[^ ] %[^ ]", method, url, protocol ) != 3 )...
```

That format above is very strange,what's it doing?

Answer: That line is attempting to read 3 strings that do not contain a space separated by spaces into method, url, protocol and if it fails to read 3 it will then enter the if block.


Question:
```
if ( fgets( line, sizeof(line), stdin ) == (char*) 0 )...
```

I don't understand what this line does,anyone knows?

Answer:
That's a rather odd way of writing a test for the return of a null pointer which indicates an error infgets().

I'd write it like this:

```
if (!fgets(line, sizeof(line), stdin))
```


Question:
I'm currently working on a code that uses SDL to display video and as i'm working through ssh, i'm looking for something like a text driver (just need to avoid seing the video because it's so slow).

So what I need is a simple way to avoid screen init and all that stuff that keep my framerate below 15fps :)

Does anyone know something that might help me?

Answer:
I'm not sure if that's what you want. But try:

```
export SDL_VIDEODRIVER=dummy
```


Question: Is there any where to convert a openFILE*returned fromfopento aHANDLEthat is used in the Windows API functions? If so, how?

Answer:
(HANDLE)_get_osfhandle(_fileno( file ) )

Good luck on 64-bit systems if you're using Visual C++ 2008 or earlier, though, because the return type islongon those. :(


Question:
I'm currently working on a code that uses SDL to display video and as i'm working through ssh, i'm looking for something like a text driver (just need to avoid seing the video because it's so slow).

So what I need is a simple way to avoid screen init and all that stuff that keep my framerate below 15fps :)

Does anyone know something that might help me?

Answer:
I'm not sure if that's what you want. But try:

```
export SDL_VIDEODRIVER=dummy
```


Question: Is there any where to convert a openFILE*returned fromfopento aHANDLEthat is used in the Windows API functions? If so, how?

Answer:
(HANDLE)_get_osfhandle(_fileno( file ) )

Good luck on 64-bit systems if you're using Visual C++ 2008 or earlier, though, because the return type islongon those. :(


Question:
I'm looking for a measure performance tool for C (I'm using MinGW windows toolchain) that gives me some results like:

Occupied memory by a variable;Cycles to run the program/a function;Spent time on a function.

Thanks

Answer:
Google Perftools is multi-platform:http://code.google.com/p/google-perftools/

GCC has profiling as well:How to use profile guided optimizations in g++?


Question: I wonder there are any tools or online tools which one can construct tree just giving datas. ex ; after giving datas, I want get a picture like ;google picture

Answer: Look intoGraphviz, and its descriptive languageDOT.


Question:
I want to make GUI for my application. It should work on multiple platforms. I want most of the code to be portable for all the OS (unix, windows, MAC).

GTK and GLib looks as a good solution. I want to use native APIs too

How to do this all??

Answer: Qtmay be good for that.


Question:
Say I have the following code:

```
struct test* t1;
t1 = get_t(1);
```

... whereget_tis:

```
struct test* get_t(int);
```

How can I refactor the above code and put it in a function? Something like the following:

```
void r1(?* t, ?* (fn*)(int)) {
    t = fn(1);
}

/* ... */

struct test* t1;
r1(t1, &get_t);
```

Answer: usevoid *param, a pointer to anything ... commonly used in glib asgpointer


Question:
How can I know in a C program, on which physical processor and core my code is running?
I'm using Linux and gcc 4.4.3.

Answer:
sched_getcpu()

call returns virtual CPU number. Mapping of virtual CPU to real CPU info is in /proc/cpuinfo.

If your system supports VDSO, thensched_getcpu()is relatively fast.

CPU number can be also obtained usingCPUIDinstruction, but it is slower thansched_getcpu().


Question:
Is there a way to communicate with Mac OS X clipboard in language C (without Obj-C/Cocoa) ?

Thanks.

Answer: The easiest way might be to call the command line programspbcopyandpbpaste.


Question:
I have to draw several thousands of pixels per frame for a falling sand animation, up to now I drawed them with Sprite.Draw (and a 1x1 Texture), but this only worked for resolutions 256x256 or lower. So is there an faster alternative to draw individual pixels?

(Shaders will not work for my problem, since the logic is applied according to the pixels state)

Answer: You could try drawing points. I foundthisbut it is only for DirectX 9.


Question:
I am using the UNIXalarmsystem call to deliver a signal to the currently running process on a schedule.

The man page describes the argument to this function as being in units of seconds. I would like to have precision in milliseconds.

Is there an alternative system call on UNIX (or Linux specifically) that will allow this?

Answer: Take a look atsetitimer() or the more modern (and more flexible)timer_setitime() APIs.


Question:
I want to find the length of this :

```
char *s[]={"s","a","b"};
```

it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives me wrong answers..
How can i find it?

Answer:
You are making an array ofchar*and not ofchar. That's whystrlenwon't work. Use

```
sizeof(s) / sizeof(char*) //should give 3
```

If you want a single string use

```
char s[] = "sab";
```


Question:
I want to find the length of this :

```
char *s[]={"s","a","b"};
```

it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives me wrong answers..
How can i find it?

Answer:
You are making an array ofchar*and not ofchar. That's whystrlenwon't work. Use

```
sizeof(s) / sizeof(char*) //should give 3
```

If you want a single string use

```
char s[] = "sab";
```


Question:
I want to find the length of this :

```
char *s[]={"s","a","b"};
```

it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives me wrong answers..
How can i find it?

Answer:
You are making an array ofchar*and not ofchar. That's whystrlenwon't work. Use

```
sizeof(s) / sizeof(char*) //should give 3
```

If you want a single string use

```
char s[] = "sab";
```


Question:
I have a variable , Float64 min;
I want to display it only upto 1 place of decimal. Right now, I get 6 places if I use %f. How do I get only upto 1 place?

Answer:
Use:

```
printf("%.1f", min);
```

See any reference such asthisfor details.


Question:
I am usingsscanfin a simple little project. However, I can't see any obvious way to find where in the input string thatsscanfdecided it found all of its data and stopped processing.

Is there a way to do this?

Answer:
I think %n is what you are looking for.

Example:

```
sscanf("123", "%d%n", &i, &count);
```

This will store 3 in `count'.


Question:
I have an iPad app that outputs a PDF file that needs to be uploaded to a remote server. What are my options here? Is there a sFTP or FTP implementation for iOS that would help me achieve this? Can it be done using other protocol?

Thanks!

Answer:
FTP Client Wrapper in Objective-C for iPhone

ConnectionKit(might not be iOS compatible)


Question:
```
void TestPrint(char* format, ...)
{
    va_list argList;

    va_start(argList, format);
    printf(format, argList);
    va_end(argList);
}

int main()
{
    TestPrint("Test print %s %d\n", "string", 55);
    return 0;
}
```

I need to get:

```
Test print string 55
```

Actually, I get garbage output. What is wrong in this code?

Answer: Usevprintf()instead.


Question: In K&R it says that declaring a function prototype such asvoid foo();with an empty parameter list turns off function parameter type checking.  Is this only forfooor for all functions?

Answer: That only applies to the function in question, not globally.


Question:
I have a structure :

```
struct vertex
    {
     double a; double b;
    }

    struct polygon
    {
     int numofVertex;
     vertex v[10];
    }
```

How to send this nested structure in MPI using MPI_Send?

Answer:
Since your structure does not contain any pointers, it's easily possible.

```
MPI_Send(ptr_to_your_struct, sizeof(struct polygon), MPI_BYTES, ...);
```


Question: I google it, which says it's line printer. I don't think it make any sense...

Answer: Thelis for list and thepis for path.  Check out all the othervariants, e.g. execl, execlp, execle, execv, execvp.


Question:
Does C supports an equivalent of the triple-slash,XML Documentation Commentsthat Visual Studio uses to provide helpful tooltips for my code in C#, or am U just spoiled by being able to use them in C#?

If it's not supported in C, are there other options?

Answer:
C does not have any equivalent of XML documentation comments or JavaDoc.

Trydoxygen.


Question: hi there i can compare people birthday in format YYYY-MM-DD with string (strcmp) functions. but i need compare todays date with person's birthday to display if his/her birthday is in 7 days or not_?. i searched "time.h" library but couldn't managed it. i appreciated if you can help.

Answer: I would usedifftimeon thetime_tvalues and compare against the number of seconds in a week...


Question: hi there i can compare people birthday in format YYYY-MM-DD with string (strcmp) functions. but i need compare todays date with person's birthday to display if his/her birthday is in 7 days or not_?. i searched "time.h" library but couldn't managed it. i appreciated if you can help.

Answer: I would usedifftimeon thetime_tvalues and compare against the number of seconds in a week...


Question:
What exactly does the below statement do?

```
const char *string
*string - '0'
```

Thanks!

Answer: It subtracts the value of the character'0'from the character pointed to bystring, turning it into a numerical value. So for example the character'9'will be turned into the integer9.


Question:
I have a sample problem withw=1,y=7,z=0,x = ~(w && y) | y;and the solution isx = -1, but I can't figure out why?

Here is my thought process:(w && y) = (1 && 7) = 1~11 in bits is0000 0001~1 in bits is1111 1110

Not sure what to do from here.

Answer:
The last step is a bitwise OR so you get:

```
1111 1110 | 0000 0111 = 1111 1111
```

which is -1.


Question: Is there a way to find the parameters passes to the kernel (/proc/cmdline) at boot time without reading any files in proc? I might have a process that needs to read the boot parameters before /proc is mounted.

Answer:
It seems the kernel passes anything on the boot line as a arg to init- unless there is a ' = ' or a ' . '

Passing Linux boot opts to Init


Question:
```
main()
{
  char *x="girl";
  int n,i;
   n=strlen(x);
  *x=x[n];
  for(i=0;i<n;i++)
  {
   printf("%s \n",x);
    x++;
  }
}
```

What is the output?Please explain the output.......................o/p is :

```
irl
rl
l
```

Answer: The output is undefined behaviour. You modified a string literal.


Question: Where i can find documentation about registers which assembly must preserve when a C function is called?

Answer: What you want is your system's C Application Binary Interface. Google for "C ABI" and your architecture, and you'll find it. For example,hereis one for sparc andhereis the relevant bit for AVRs.


Question: Are there existing algorithm visualization tool for C programs? like visualizing an execution of a C program through animated execution stack.

Answer: I recommenddddfor fancy GUI debugging visualizations. It visualizes all the data structures and makes pretty graphs and gives you access to your regular debugger.


Question: Where i can find documentation about registers which assembly must preserve when a C function is called?

Answer: What you want is your system's C Application Binary Interface. Google for "C ABI" and your architecture, and you'll find it. For example,hereis one for sparc andhereis the relevant bit for AVRs.


Question: Are there existing algorithm visualization tool for C programs? like visualizing an execution of a C program through animated execution stack.

Answer: I recommenddddfor fancy GUI debugging visualizations. It visualizes all the data structures and makes pretty graphs and gives you access to your regular debugger.


Question:
I am new to C and I have this code:

```
f = fopen( argv[1], "rb" );
fseek( f, 64, SEEK_SET );
fpos_t pos;
fgetpos (f, &pos);
printf("%x", pos);
```

However, this returns 40, even though it's supposed to be returning 64. What am i doing wrong?

Answer: You are outputting 64 in hex format,"%x". Since 64=0x40, the mystery is solved!


Question:
The below fails to compile:

```
typedef int arr[10];
int main(void) {
    return sizeof arr;
}

sizeof.c:3: error: expected expression before ‘arr’
```

but if I change it to

```
sizeof(arr);
```

everything is fine. Why?

Answer:
According to 6.5.3, there are two forms forsizeofas the following:

```
sizeof unary-expression
sizeof ( type-name )
```

Sincearrin your code is atype-name, it has to be parenthesized.


Question:
We're running a Linux server with Microsoft SQL Server for the database.  Are there any good (preferably open source) c libraries that we could use other than FreeTDS?

Thank you

Answer: Not really. Sybase has some client libraries, but they only work for older versions of MS SQL Server (since it is a derivative of Sybase SQL Server).


Question: Can anyone recommend a good library I could use on Linux to watermark videos? I want to overlay a watermark at several different positions in my videos, fade them in randomly and with different colors and opacity.

Answer: Have you triedffmpeg? That's a very good tool for video related stuff. Also for watermarking you can try thislink.


Question:
I am wondering if there is an equivalent to C's fputc in PHP?
I am trying to do the following C code in PHP:

```
fputc(0x10, fp);
```

more information on fputc:http://en.wikipedia.org/wiki/C_file_input/output#Writing_to_a_stream_using_fputc

Thanks

Answer:
You can write the character code directly to the file:

```
fputs($fp, "\x10");
// or
fputs($fp, chr(16));
// or
fputs($fp, chr(hexdec(10));
```


Question:
Let's say I've got that:

```
char *p = NULL;
```

I'm sure this one would be a problem as I'd be dereferencing aNULLpointer:

```
*p = 16;
```

On the other hand, I think this one would be OK for I'd be getting the address of *p which is notNULLitself:

```
char **pp = &p;
```

Am I right in both cases?

Answer: Yes you are. Although the value of p is NULL, it still has a valid address, so you may pass its reference.


Question:
I'm having a problem with using the automatic formatting in Eclipse CDT. For the most part it works great but it seems to insist on putting the semicolons after macro calls on a separate line.

Is this a bug or did I mischeck a combination of formatting settings which lead to this?

Answer: The problem has been fixed in later versions of Eclipse CDT. Just try to download later version of Eclipse.


Question: I hope that this makes sense.... is there a way to get xCode to use the makefile system for building C programs??

Answer: Yes - set up an "external build system" project.


Question:
is it possible in java to have a C like syntax for this:

```
int counter = 10;
            while(counter){
                    System.out.println(counter--);
            }
```

In C it is working very well to count until the counter is 0... do i really have to write

```
int counter = 10;
            while(counter!=0){
                    System.out.println(counter--);
            }
```

?

Answer: No, java requires abooleanin awhilecondition.


Question: Does anyone know, how can we verify whether an allocated space is successfully freed? In the manual page, it says that "free() returns no value".

Answer:
There are three possible cases:

```
free( NULL );     // does nothing, so always works
free( malloc(42) );  // does something, always works
free( 666 );      // undefined behaviour - returned value would be meaningless
```

So there is no case where testingfree()has a point.


Question:
Hi i would like to convert 0x49 and 0x83 from C++ to C#.

May i know what does this 0x49 represent in c# character?
Also, what does  83 represent in character?

I have searching through google but found no answer for this. I would appreciate it there is a chart outthere list out all the ASCII code representing the characters meaning.

Answer: Have a lookhere. But ascii is ascii.. there are no differences between C++ and C#


Question:
I am trying to make a calculator in C or Objective-C that accepts a string along the lines of

```
8/2+4(3*9)^2
```

and returns the answer 2920. I would prefer not to use a generator like Lex or Yacc, so I want to code it from the ground up. How should I go about doing this? Other than the Dragon book, are there any recommended texts that cover this subject matter?

Answer: Dave DeLong'sDDMathParserclass may save you a lot of time and trouble.


Question:
If I have a an array ofints, how could I directly edit eachint?

```
int i = arr + 1; // Getting the integer in pos 1
```

iis just a copy, correct? If I seti = 4, thenarr + 1would still be1.

Would this work?

```
int *i = &(arr + 1);
*i = 4;
```

Answer:
You should use the array operators:

```
int i = arr[1];
arr[1] = 4;
```


Question:
Hi i would like to convert 0x49 and 0x83 from C++ to C#.

May i know what does this 0x49 represent in c# character?
Also, what does  83 represent in character?

I have searching through google but found no answer for this. I would appreciate it there is a chart outthere list out all the ASCII code representing the characters meaning.

Answer: Have a lookhere. But ascii is ascii.. there are no differences between C++ and C#


Question:
I am trying to make a calculator in C or Objective-C that accepts a string along the lines of

```
8/2+4(3*9)^2
```

and returns the answer 2920. I would prefer not to use a generator like Lex or Yacc, so I want to code it from the ground up. How should I go about doing this? Other than the Dragon book, are there any recommended texts that cover this subject matter?

Answer: Dave DeLong'sDDMathParserclass may save you a lot of time and trouble.


Question:
If I have a an array ofints, how could I directly edit eachint?

```
int i = arr + 1; // Getting the integer in pos 1
```

iis just a copy, correct? If I seti = 4, thenarr + 1would still be1.

Would this work?

```
int *i = &(arr + 1);
*i = 4;
```

Answer:
You should use the array operators:

```
int i = arr[1];
arr[1] = 4;
```


Question:
Can anyone give me an example code for a tool window (with pixel dimensions) for the Win32 API?

Thanks

Answer:
Tool windows are just windows with the WS_EX_TOOLWINDOW extended style:

```
hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, 100, 100, 500, 400, NULL, NULL, hInstance, NULL);
```

Note you need to use CreateWindow*Ex* to use extended styles. The above is a 500x400 window at 100,100 on the screen.


Question:
I need to parse a document in C language.  I was about to use the strtok function but I don't know if it's the best method or if just a token system is enough (searching for \n, space etc).

The structure of each line of the document is : element \n element "x".

thanks :-)

Answer: Token system if fine,strtokis just an implementation of that. However, you're better off with usingstrtok_rwhich does not keep any internal state outside control of your program.


Question: How can I add a new libc function and also call it from C programs? The new function is a not a wrapper to any kernel level system calls. Its function will be done in user space.

Answer: Put it in its own library file and link it with-llibrary_name_here. The only things that belong in libc are already there (along with plenty of things that don't belong there).


Question:
For the following piece of code:

```
#include<stdlib.h>
#include<stdio.h>

int main()
{
    int x;
    x = rand()%100;
    printf("The Random Number is: %i", x);

return 0;
}
```

It always seems to print the random number as 83. Why is this?

Answer:
Mostrandom number generatorsare repeatable. You need to seed the generator before using it which you typically do using the system time.

```
#include <time.h>
srand(time(NULL));
```


Question:
I'm trying to clear all stored cookies in Libcurl (version 7.21.6) but
nothing really seems to work.

What command should I use?
I'm using the C-binding version.

Thanks.

Answer:
You can't "clear" a cookie file (on disk) with libcurl. Just remove it from the file system with a normal system function such as unlink() or zero it with truncate().

You can clear all cookies libcurl knows about in memory with CURLOPT_COOKIELIST "ALL".


Question:
I have following code,

```
char * segbase_char = (char*)segbase;
```

As debugged in gdb, it prints

```
segbase_char = 0x80e2da8
segbase = 0xb7ffd000
```

Any ideas?

Answer: It is possible that optimisation has resulted in code being moved around, such that the load ofsegbase_charhas been delayed.  Try compiling with a lower level of optimisation enabled.


Question:
How to Create NodeJS equivalent for the below simple C code?

```
int main(int argc, char *argv[]) {
    if (fork()) {
        printf("I'm parent %d", getpid());
        printf("From parent : %d", 1+1);
    } else {
        printf("I'm child %d", getpid());
        printf("From child : %d", 10+20);
    }

    return 0;
}
```

Answer: Check outChild Processesin theNodeJS docs. Then check outForeveras an example of how to use them.


Question:
I wrote some simple program

```
int main(){
              printf("hello word!");
              return 0;
}
```

I compiled it usinggcc -o hello hello.c(no errors)
but when I run itin terminalusing./helloI see nothing, why? thanks in advance

Answer:
Could be the missing newline, so that the output is mangled with the next prompt.

Try:

```
printf("hello world\n");
```

this version also uses a more conventional message.


Question:
when i use read system call, the buffer that i provide in the second argument, where the data
from reading are supposed to get stored, gets overwritten right!?

thanks,
Nikos

Answer: Yes, that is the point ofread(), to fill (=overwrite) the buffer with the content read from the file.


Question: Can a CFMutableArrayRef store simple integer values? Or must I wrap them like with NSMutableArray (which is basically the same beast at runtime)?

Answer: CFMutableArrayand its toll-free bridged siblingNSMutableArraywill only allow a pointer value to be stored inside of it.


Question: 1)can we define a void pointer?such asvoid * pointer;is it allowed in C?   what is a void pointer?2) I always hear about Global Variable, but I do not know how to define Global Variable, I mean where to define a Global Variable? in the beginning of a file or what?

Answer: Yes. A void pointer is a pointer to memory where we have not specified what type is at that memory location.Define them outside of any function or class.


Question:
How to Create NodeJS equivalent for the below simple C code?

```
int main(int argc, char *argv[]) {
    if (fork()) {
        printf("I'm parent %d", getpid());
        printf("From parent : %d", 1+1);
    } else {
        printf("I'm child %d", getpid());
        printf("From child : %d", 10+20);
    }

    return 0;
}
```

Answer: Check outChild Processesin theNodeJS docs. Then check outForeveras an example of how to use them.


Question:
I wrote some simple program

```
int main(){
              printf("hello word!");
              return 0;
}
```

I compiled it usinggcc -o hello hello.c(no errors)
but when I run itin terminalusing./helloI see nothing, why? thanks in advance

Answer:
Could be the missing newline, so that the output is mangled with the next prompt.

Try:

```
printf("hello world\n");
```

this version also uses a more conventional message.


Question:
when i use read system call, the buffer that i provide in the second argument, where the data
from reading are supposed to get stored, gets overwritten right!?

thanks,
Nikos

Answer: Yes, that is the point ofread(), to fill (=overwrite) the buffer with the content read from the file.


Question: Can a CFMutableArrayRef store simple integer values? Or must I wrap them like with NSMutableArray (which is basically the same beast at runtime)?

Answer: CFMutableArrayand its toll-free bridged siblingNSMutableArraywill only allow a pointer value to be stored inside of it.


Question: Can a CFMutableArrayRef store simple integer values? Or must I wrap them like with NSMutableArray (which is basically the same beast at runtime)?

Answer: CFMutableArrayand its toll-free bridged siblingNSMutableArraywill only allow a pointer value to be stored inside of it.


Question:
I'm learning C, but I do not understand this:

```
#define square(x) x*x
a = square(2+3) //a = 11
```

When this is run, why doesaend up being11?

Answer:
It expands to2+3*2+3, which is equivalent to2+(3*2)+3. Use parentheses to fix it:

```
#define square(x) ((x)*(x))
```

Now try it withsquare(x++)and you'll run into more problems (undefined behavior). Avoid doing this as a macro if you can.


Question: what_if_var[0].price(type ischar [10]) has the value of "$15555.665". Is there is anyway to remove "$" from the value (like "15555.665") and convert the value into double?

Answer:
If you always know that the'$'is going to be the first character, you could just try:

```
double num = strtod (what_if_var[0].price + 1, NULL);
```


Question:
Almost every c/c++ open source project I see ships with it aconfigurefile.

But in our own c/c++ project I haven't seen this file so far,

when is it needed?

Answer:
I think you are speaking about configure script which is used, whenautotoolsare used to build the project.

The main purpose of theconfigurefile is to generateMakefilesappropriate to your system configuration and to check various preconditions (installed libs, for example).


Question:
I have a hex value stored in a two byte array:

```
unsigned char hex[2] = {0x02, 0x00};
```

How can I convert this to a decimal value?

Answer:
You can use (bitwise operation)

int b = (hex[0] << 8) | hex[1];

or (simple math)

int b = (hex[0] * 0x100) + hex[1];


Question:
How does 1.000(base2) x 2^-1 + (-0.111(base2) x 2^-1) = .001(base2) x 2^-1?
To add binary numbers don't you simply just add? I'm not seeing how the addition works..

Answer:
I'm not sure what you mean when you ask "don't you simply just add?", but the math is correct. It is basically in base-2 scientific notation.

```
1.000(base2) x 2^-1 = 0.100(base2)
-0.111(base2) x 2^-1 = -0.0111(base2)

0.100 + (-0.0111) = 0.0001

0.0001 = 0.001(base2) x 2^-1
```


Question:
i'm practicing c and looking to use visual studio. but can I write console C programs and debug it step by step? (i use debug for understading algorithms step by step)

thank you.

Answer:
Yes, you can. Start off with the c++ version (if you are using Express), it supports c as well.

Visual Studio has a very good debugger and will allow you to step through your code.


Question:
How can I make it so my window never gets any smaller than x,y? Which WINAPI function can do this?

Thanks

Answer: You reply toWM_GETMINMAXINFOand fill in the structure with your limits.


Question:
I want to find the size of file on disk on linux OS .
I know command to do so:
du -s -h

Is there any way to find it using c/c++ code ?

Answer:
Yes, use thestat(2)system call:

```
#include <sys/stat.h>
...
struct stat statbuf;

if (stat("file.dat", &statbuf) == -1) {
  /* check the value of errno */
}

printf("%9jd", (intmax_t) statbuf.st_size);
```


Question:
I am reading a file of integers. I want to save integers from each line to a new array. For this I want to detect a new line of a file. If anybody knows this please help.

The file to be read is as follows

```
1 2 4 5 6
7 3 2 5
8 3
9 7 6 2
```

Answer: Why not usefgets()to get one line at a time from the file?  You can then usesscanf()instead offscanf()to extract the integers.


Question:
I have a hex value stored in a two byte array:

```
unsigned char hex[2] = {0x02, 0x00};
```

How can I convert this to a decimal value?

Answer:
You can use (bitwise operation)

int b = (hex[0] << 8) | hex[1];

or (simple math)

int b = (hex[0] * 0x100) + hex[1];


Question:
I have a check in my program to see if the user supplies the right amount of command line arguments. If they do not, I print a usage message and then exit the program.

However I'm not sure if I should exit with EXIT_SUCCESS or EXIT_FAILURE - it appears that they both have some merit in terms of their english meaning. Is there an important distinction? What should I do?

Answer: I personally useEXIT_FAILURE, since it's not a normal usage of your program.


Question: On my Linux box it shows up as^A,CTRL-Awhen ivithe file. While writing a C program, how should i reference it? How can i find out a numeric value of it?

Answer: Control characters are 0x40 less than their character.Ais65, so^Ais1.


Question:
After havingdownloadeda Linux Man Page Viewer, I am  not seeing the actual man page when hovering over a function.

Should i enable it somehow? Is where a menu item i should be using?

Please advise

Answer:
Looks like it requiresCDT5.0.1 and depending on the version of Eclipse you have installed it may not be included.

What Eclipse package do you have installed?


Question:
The readln reads until the end of line (enter pressed) with spaces and everything,

I would like something like that but for ansi c (not c++ and need to be for linux and windows)

I know that I can make a function that reads every char until the enter pressed but If there is anything cooler it would be great =D

Thanks!

Answer: Fromherethere is fgets that does this.


Question: I would like to store 4 char (4 bytes) into an unsigned int.

Answer:
You need to shift the bits of each char over, then OR combine them into the int:

```
unsigned int final = 0;
final |= ( data[0] << 24 );
final |= ( data[1] << 16 );
final |= ( data[2] <<  8 );
final |= ( data[3]       );
```

That uses an array of chars, but it's the same principle no matter how the data is coming in. (I think I got the shifts right)


Question:
how to count number of occurrences of 1 in a 8 bit string. such as 10110001.
bit string is taken from user. like 10110001
what type of array should be used to store this bit string in c?

Answer:
Short and simple. Usestd::bitset(C++)

```
#include <iostream>
#include <bitset>

int main()
{
  std::bitset<8> mybitstring;
  std::cin >> mybitstring;
  std::cout << mybitstring.count(); // returns the number of set bits
}
```

Online Test at Ideone


Question:
The matrix X is:

```
aa bb cc
dd ee ff
gg hh ii
```

and can be indexed as X[0][1]

my question is how to represent a string matrix in C?

I know char ***matrix, but I don't know the details

Answer:
A string is represented in C as an array of chars, so actually this is a three-dimensional matrix:

```
char string_matrix[ROWS][COLUMNS][STRING_LENGTH]
```

or

```
char*** string_matrix
```


Question: How can I write afor/whileloop inside a#definedirective in C?

Answer:
You're probably looking for\to continue a macro definition across several lines:

```
#define LOOP(start, end)                  \
  for (int i = (start); i < (end); i++) { \
    printf("%d\n", i);                    \
  }
```


Question:
How can I compile my C source files without needing to put amainfunction within them?

I get an error for the.cfiles that have no main function and don't want to have to add the main function just for compilation.

Answer:
On GCC, the-cswitch is what you want.

-cmeans "compile, don't link", and you get aname.ooutput file.


Question:
The matrix X is:

```
aa bb cc
dd ee ff
gg hh ii
```

and can be indexed as X[0][1]

my question is how to represent a string matrix in C?

I know char ***matrix, but I don't know the details

Answer:
A string is represented in C as an array of chars, so actually this is a three-dimensional matrix:

```
char string_matrix[ROWS][COLUMNS][STRING_LENGTH]
```

or

```
char*** string_matrix
```


Question: How can I write afor/whileloop inside a#definedirective in C?

Answer:
You're probably looking for\to continue a macro definition across several lines:

```
#define LOOP(start, end)                  \
  for (int i = (start); i < (end); i++) { \
    printf("%d\n", i);                    \
  }
```


Question:
OK, I have read about CreateFile, ReadFile and WriteFile and I know how to use these. But I could not find any tutorial or guide with an example to use them properly.
How do I handle files?
I want to learn about:

Read strings from file.Write strings to file.

How does one do that?

Answer:
Here is an example:

http://www.gamedev.net/page/resources/_/reference/programming/platform-specific/windows/file-io-in-visual-c-r707


Question: What does it mean to say that a function (e.g. modular multiplication,sine) is implemented in hardware as opposed to software?

Answer:
Implemented in hardware means the electrical circuit (through logical gates and so) can perform the operation.

For example, in the ALU the processor is physically able to add one byte to another.

Implemented in software are operations that usually are very complex combinations of basic implemented in hardware functions.


Question:
AFAIK, neither C99 nor C++ standards are aware of shared libraries. Why is that?

EDIT: What is a good practice of writing shared libs without duplicating Linux/Windows versions?

Thanks.

Answer:
Because a shared library is a feature of the OS.

Nothing to do with any particular language.


Question:
Very quick question. I want to copy & paste textual data into the source code from the separate file usingincludedirective.

Is it legal?

```
struct Record; // collection of data fields

Record rec = { #include "some_big_record.txt" };

int numbers[] = { #include "some_long_sequence_of_numbers.txt" };
```

It works on my box (GCC), but is it portable?

Answer:
This is portable:

```
Record rec = {
#include "some_big_record.txt"
};
```


Question:
How to detect at compile time if I'm using gcc or icc?

(I was quite puzzled to find out that icc defines__GNUC__-- and even__GNUC_MINOR__and__GNUC_PATCHLEVEL__! why?)

Answer:
We use

```
#ifdef __INTEL_COMPILER
```

to spliticcoff, assuminggccas a default.


Question:
I'm a new in both C and Python. These days, I'm learning to embed Python in C. As I am calling Python functions from C, I'd like to know, how can we pass a C structure to Python?

thanks alot in advance!

Answer: The cleanest thing to do is probably tocreate a new typeand implementtp_getattr, either returning the appropriate member of the struct or raising an exception depending on the argument passed.


Question: I want to read a string through keyboard to avoid buffer overflow. When i usedfgets(text,30,stdin), it reads but it also reads '\n' character. But i don't want to read '\n' character.

Answer:
```
char s[30];
scanf("%30[^\n]", s);
```

a little explain:

%30[^\n]

30which means read at most 30 chars,[^\n]which means read any char except '\n'.


Question: In my programfprintf()returns -1, which indicates an error. How can I find out what actual error was?

Answer:
```
#include <errno.h>
#include <string.h>

...
rc = fprintf(...)
if (rc < 0)
    printf("errno=%d, err_msg=\"%s\"\n", errno,strerror(errno))
```


Question:
Why 2[a] can be compiled if only declare int a[3] in C.

```
1  #include <stdio.h>
 2
 3  int main(int argc, char **argv)
 4  {
 5      int a[3] = {1, 2, 3};
 6      printf("a[2] is: %d\n", a[2]);
 7      printf("2[a] is: %d\n", 2[a]);
 8
 9      return 0;
10  }
```

And the output both 3, how to explain it?

Answer: Becausea[2]is just syntactic sugar for*(a+2), which is the same as*(2+a)or2[a].


Question:
Very quick question. I want to copy & paste textual data into the source code from the separate file usingincludedirective.

Is it legal?

```
struct Record; // collection of data fields

Record rec = { #include "some_big_record.txt" };

int numbers[] = { #include "some_long_sequence_of_numbers.txt" };
```

It works on my box (GCC), but is it portable?

Answer:
This is portable:

```
Record rec = {
#include "some_big_record.txt"
};
```


Question:
How to detect at compile time if I'm using gcc or icc?

(I was quite puzzled to find out that icc defines__GNUC__-- and even__GNUC_MINOR__and__GNUC_PATCHLEVEL__! why?)

Answer:
We use

```
#ifdef __INTEL_COMPILER
```

to spliticcoff, assuminggccas a default.


Question: In my programfprintf()returns -1, which indicates an error. How can I find out what actual error was?

Answer:
```
#include <errno.h>
#include <string.h>

...
rc = fprintf(...)
if (rc < 0)
    printf("errno=%d, err_msg=\"%s\"\n", errno,strerror(errno))
```


Question:
This question already has answers here:Closed12 years ago.

Possible Duplicate:Parsing XML in Pure C

Which is the best XML Library for C?

Features I am looking out for are

1) Good Support in the form of tutorials and active mailing list.
2) Easy to develop.
3)Portabilityfor Windows, Linux, Mac.
4) I need to do parsing, validating and writing of simple XML Files.

Answer: Libxml2should do the trick.


Question: I need a method in C that the random number between decimal 65-90 [a-z] and decimal 97-122 [A-Z] returns. If I call the method the method must be a different number give back what he has previously given How can I do this in C ?

Answer:
```
#include <stdlib.h>

char rand_az_AZ() {
    char val = rand() % 52;
    if (val < 26) {
        val += 'a';
    } else {
        val -= 26;
        val += 'A';
    }
    return val;
}
```


Question:
```
mov     r8, FlushCounts[r14]
```

Can some one explain me what the FlushCounts[r14] is used for ? Does this mean r14 = &FlushCounts and r8 = FlushCounts ? Why is it done like this ?

Answer: This means copy 64 bits from addressFlushCount + r14to r8. Offset inr14register is in bytes.


Question: Are there any reference guides or tutorials for writing a MIPS assembler?

Answer: If you are looking to actually write an assembler you need to know the format of the executable of the platform you are writing for (ex.ELF), then you need to use theMIPS instruction setas a reference to determine the correct machine code for your .TEXT section. Good luck!


Question: I need a method in C that the random number between decimal 65-90 [a-z] and decimal 97-122 [A-Z] returns. If I call the method the method must be a different number give back what he has previously given How can I do this in C ?

Answer:
```
#include <stdlib.h>

char rand_az_AZ() {
    char val = rand() % 52;
    if (val < 26) {
        val += 'a';
    } else {
        val -= 26;
        val += 'A';
    }
    return val;
}
```


Question:
```
mov     r8, FlushCounts[r14]
```

Can some one explain me what the FlushCounts[r14] is used for ? Does this mean r14 = &FlushCounts and r8 = FlushCounts ? Why is it done like this ?

Answer: This means copy 64 bits from addressFlushCount + r14to r8. Offset inr14register is in bytes.


Question: Are there any reference guides or tutorials for writing a MIPS assembler?

Answer: If you are looking to actually write an assembler you need to know the format of the executable of the platform you are writing for (ex.ELF), then you need to use theMIPS instruction setas a reference to determine the correct machine code for your .TEXT section. Good luck!


Question: How do you write anNaNfloating-point literal in C?

Answer:
In C99's<math.h>

7.12  Mathematics <math.h>

```
[#5] The macro

           NAN

   is defined if and only if the implementation supports  quiet
   NaNs   for  the  float  type.   It  expands  to  a  constant
   expression of type float representing a quiet NaN.           |
```


Question:
If I usegetHostByName()I only get "127.0.0.1", because it is written on /etc/host, but this is not useful to me.

However, with the following java code I actually get what I want:

```
NetworkInterface.getByName(("eth0")).getInetAddresses().nextElement().getHostAddress()
```

I think that there is a way to get the same ip address also from C?

Answer: Check outgetifaddrs.


Question:
I'm trying to capture the fields in a table but I need to get that data even if the table is empty.

sqlite3_table_column_metadataisn't an option (it wasnt compiled into my version of SQLite3).

Is there is a trick to obtain that info?

Answer:
```
PRAGMA table_info(table_name);
```

returns a list of column names

heres a link:

http://www.sqlite.org/pragma.html#pragma_table_info


Question:
If I usegetHostByName()I only get "127.0.0.1", because it is written on /etc/host, but this is not useful to me.

However, with the following java code I actually get what I want:

```
NetworkInterface.getByName(("eth0")).getInetAddresses().nextElement().getHostAddress()
```

I think that there is a way to get the same ip address also from C?

Answer: Check outgetifaddrs.


Question:
I'm trying to capture the fields in a table but I need to get that data even if the table is empty.

sqlite3_table_column_metadataisn't an option (it wasnt compiled into my version of SQLite3).

Is there is a trick to obtain that info?

Answer:
```
PRAGMA table_info(table_name);
```

returns a list of column names

heres a link:

http://www.sqlite.org/pragma.html#pragma_table_info


Question:
I want to input words from a file which are delimited by anything that isn't a letter. Is there an easy way to do this in C similar to using the \W predefined character classes in Java?

How should I approach this?

Thanks.

Answer: Character classes in general and \W specifically really aren't related to Java at all.  They're just part of regular expression support, which is available for many languages, including GNU C.  SeeGNU C library Regular Expressions.


Question:
What does the following declaration mean?

```
unsigned char (*pArray[10][10]);
```

Answer:
Declaration

```
unsigned char (*pArray[10][10]);
```

is exactly equivalent to

```
unsigned char *pArray[10][10];
```

The parentheses are entirely redundant and have no effect at all. This is a 2D 10x10 array ofunsigned char *pointers.


Question:
I want to declare a new integer in the heap,

```
int *intPtr = (int*) malloc(sizeof(int));
```

How do I change the value of the space in the heap, to which*intPtrpoints to?
Thanks

Answer:
DereferenceintPtr:

```
*intPtr = 0;
```


Question:
Let's say I have sometypedef struct {int b;} some_t;and a pointerato such a struct. Then why is

```
(*a).b = 5;
```

not the same as

```
some_t c = *a;
c.b = 5;
```

?

Answer:
In the second,cis acopyof*a, andc.bis a copy of(*a).b.

c.b = 5modifies the copy, not the original.


Question:
This function aims to get the start address of the stack:

```
unsigned long find_start(void){
        __asm__("movq %rsp, %eax");
}
```

When I compile it,getting an error:

```
Error: suffix or operands invalid for `movq'
```

Answer:
movqis an instruction that expects 64-bit operands.rspis a 64-bit register, whileeaxis a 32-bit register.

Perhaps tryrax?


Question: What exactly is the difference between the two?

Answer:
fprintfdoes formatted output. That is, it reads and interprets a
format string that you supply and writes to the output stream the
results.

fputssimply writes the string you supply it to the indicated output
stream.

fputs()doesn't have to parse the input string to figure out that all you want to do is print a string.fprintf()allows you to format at the time of outputting.


Question:
I want to write regular expression library in C/C++.
What is the good starting point , any books or articles.

I know there are may libraries are available , but I want to write my own version.

Answer:
A good starting point is to use existing implementations and criticize them.

Pay attention to data structures and design decisions you don't like.Avoid them when you write your version.


Question:
I have a function that takes in two strings, and I want to, let's say compare the 2nd letter of each string to the other.
How do I fix this statement:

```
if (strncmp(str1 + 1, str2 + 1) != 0) {
...
```

I get an error stating that passing the argument makes a pointer from an integer without a cast.

Answer:
```
if (str1[1] == str2[1]) {
    /* Do something */
}
```


Question: How do I conver an RGB component (0-255) to a floating point number in which 255 would be 1.0f and 0 would be 0.0f?

Answer:
What's wrong with dividing?

```
unsigned char red = 45;
float percentage = red/255.0f;
```


Question:
Why does this Compile:

```
int main()
{
    {}
}
```

But this does not:

```
{}

int main()
{
}
```

Answer:
First case, you're defining a block inside a function, which is allowed (it limits visibility).
Second case, you're defining an anonymous block, which is not allowed (it needs to be predeceded by a function definition, otherwise, the compiler will never know when it will have to execute it)


Question:
Is there any difference betweenuintandunsigned int?

I'm looking in this site, but all questions refer to C# or C++.
I'd like an answer about the C language.

If it is relevant, note that I'm using GCC under Linux.

Answer: uintisn't a standard type -unsigned intis.


Question:
For example,

```
struct node {
  struct node *left, *right;
};
#define LEFT(X) (X->left)
#define RIGHT(X) (X->right)
```

I would like to forbid macro call like this without changing the existing macro interface.

```
LEFT(n) = ...
```

Any idea?

Answer:
Try this:

```
#define LEFT(X) ((X)->left+0)
#define RIGHT(X) ((X)->right+0)
```


Question:
Hi
How can I convert pdf to txt with qt ?
if there isn't way to do this , Is there any library for c++ that convert pdf files to txt files ?
thanks.My os is windows7 and my ide is visual studio 2008

Answer:
Foxit sells their PDF code as a library. I use it, and it's great.

http://www.foxitsoftware.com/pdf/sdk/dll/

You may know them for their very popular free Acrobat Reader alternative.


Question:
I am getting this exception with posix_memalign. Any idea as to why we get it?

Thanks in advance.

Answer: Interrupted system calls are usually the result of a system call being interrupted.  In other words, the process is receiving a signal while the call is executing.


Question: Is it guaranteed that a function registered with atexit will ALWAYS be called upon normal program termination? (I encounterd a scenario in FreeBSD where a function that I register with atexit never gets called, even when the program terminates normally).

Answer: No.  First, the function will not be called ifatexitreturns a non-0 value.  Secondly, it won't be called if a function registered before it doesn't return normally.


Question: For example,system("sh /mydir/some-script.sh &")

Answer:
```
system("sh /mydir/some-script.sh &")
```

executes

```
/bin/sh -c 'sh /mydir/some-script.sh &'
```

systemwill return as soon as outer shell returns, which will be immediately after it launches the inner shell. Neither shell will wait forsome-script.shto finish.

```
$ cat some-script.sh
sleep 1
echo foo

$ /bin/sh -c 'sh some-script.sh &' ; echo bar ; sleep 2
bar
foo
```


Question:
I have the following code:

```
int **ptr = (int **)malloc(sizeof(int*)*N);
for(int i=0;i<N;i++)
     ptr[i]=(int*)malloc(sizeof(int)*N));
```

How can I freeptrusingfree? Should I loop overptrand freeptr[i]or should I just do

```
free(ptr)
```

andptrwill be freed?

Answer:
Just the opposite of allocation:

```
for(int i = 0; i < N; i++)
    free(ptr[i]);
free(ptr);
```


Question:
I'm looking for the reference/documentation of thedos.hAPI.
(especially for an openwatcom specific version).

Where to get the documentation?

Answer: One reasonable starting point would probably be thelibrary documentationat OpenWatcom.


Question:
I get a warning

warning: comparison between pointer and integer

on the line containingiffrom the next piece of code:

```
char cwd[1024];

if (getcwd(cwd, sizeof(cwd)) != (char*)NULL)
    printf("%s\n",cwd);
else
    error_print("error in pwd");
```

how and what do I need to fix?

Answer:
Do you include unistd.h? If not, the error appears because your C compiler is assuming getcwd returns int.

The fix? Include unistd.h


Question: Is there any CSS parser for C/C++ with CSS3 support? I found a few but they all don't support CSS3 yet.

Answer: If you need CSS3 support before any libraries support it, you could try a non-validating solution such ashtmlcxx.


Question:
I am trying to find the syntax that will let me redirect standard input output toward a named pipe after using the mkfifo() function and creating a child process using fork.

Which man page should I be looking at for the syntax?

Thanks,
Aaron

Answer:
Do you referredthis

gives you idea about the syntax.


Question:
When i make some opensource project, there is one error: make: flex: Command not found

I want to know what is the flex ?

Answer: Flexis the Fast Lexical analyzer generator.


Question:
is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program.

Thanks

Answer:
You can use theclockfunction in<time.h>along with the macroCLOCKS_PER_SEC:

```
clock_t start = clock() ;
do_some_work() ;
clock_t end = clock() ;
double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;
```

Nowelapsed_timeholds the time it took to calldo_some_work, in fractional seconds.


Question:
When i make some opensource project, there is one error: make: flex: Command not found

I want to know what is the flex ?

Answer: Flexis the Fast Lexical analyzer generator.


Question:
is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program.

Thanks

Answer:
You can use theclockfunction in<time.h>along with the macroCLOCKS_PER_SEC:

```
clock_t start = clock() ;
do_some_work() ;
clock_t end = clock() ;
double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;
```

Nowelapsed_timeholds the time it took to calldo_some_work, in fractional seconds.


Question: I'm using libltdl in my C code to dynamically load libtool made shared object files. Apparently a reference count is internally kept for each module handle returned by libtool's version of dlopen. Is there any way to access this reference count?

Answer:
```
const lt_dlinfo *info;
info = lt_dlgetinfo(myhandle);
printf("refcount is %d\n", info->ref_count);
```


Question:
how can i write my own module in C ?
is it possible ?

Answer:
Yes, it is possible. Here's an old article that I used when I wrote my first extension:

http://web.archive.org/web/20110222035803/http://devzone.zend.com/article/1021

Things may have changed since then, so you may want to search for similar tutorials for additional references.

Oh, and this should be useful:

http://www.php.net/manual/en/internals2.php


Question: I would like to, in C code, create more than one terminal processes. As in, I want to runfooin a terminal process, and then in a separate terminal process, I want to runbar. Is this possible? Could I do it withsystem(char *)?

Answer: This sounds like a job forposix_spawn(). Here is anexample. Definitely donotcallsystem()to launch new processes.


Question:
For example, I want to run:

```
ssh root@127.0.0.1 -p 2222
```

in C (viasystem) command. But right after I run that, it asks for input:

```
root@127.0.0.1's password:
```

Then I'm expected to type in the password. How can I do this in C code? Could I please get some code on how I could simulate key presses? Or is there a better way to do this?

Answer: There are better ways to do this, such askey-based SSH authentication.


Question: I would like to, in C code, create more than one terminal processes. As in, I want to runfooin a terminal process, and then in a separate terminal process, I want to runbar. Is this possible? Could I do it withsystem(char *)?

Answer: This sounds like a job forposix_spawn(). Here is anexample. Definitely donotcallsystem()to launch new processes.


Question:
For example, I want to run:

```
ssh root@127.0.0.1 -p 2222
```

in C (viasystem) command. But right after I run that, it asks for input:

```
root@127.0.0.1's password:
```

Then I'm expected to type in the password. How can I do this in C code? Could I please get some code on how I could simulate key presses? Or is there a better way to do this?

Answer: There are better ways to do this, such askey-based SSH authentication.


Question:
I am wondering, how to check if I am opening file which exists with fopen? I want to diplay some message, when user selects file with bad name. Is must be some simple checking, but I am not able to solve it.

Thanks

Answer:
in your param list:

```
FILE pFile ;
```

then:

```
pFile = fopen ("myfile.txt","r");

if (pFile == NULL)
printf("No Such File !! ");
```


Question:
in my program I will use two parameters. It could look like this:

```
./myApp -status 7 -file abc.txt
```

My question is how to make conditions like "if(parameter_status==7)" and how to get to abc.txt from -file in my main?

Thanks

Answer: Use the GNU C Library getopt() call. An example of how to use it is atwww.gnu.org.


Question: I find little things like this throughout the C programming language; something that is very easy to provide, has very little chance of breaking old code, and has an obvious way to standardize it.  Is minimalism the reason?

Answer: Because they're trivial to compute if you have the "standard" trig functions?


Question: I find little things like this throughout the C programming language; something that is very easy to provide, has very little chance of breaking old code, and has an obvious way to standardize it.  Is minimalism the reason?

Answer: Because they're trivial to compute if you have the "standard" trig functions?


Question:
How do I write a function for this in C language?

y = 20 ln (x + 3) ?

How do I write the ln function?

Answer:
```
#include <math.h>

double fun(double x)
{
    return 20 * log( x + 3 );  //base-e logarithm!
}

//usage
double y = fun(30);
```

For base-10 logarithm, uselog10().


Question:
As all we know: the sequence of evalutation is determined by the priority and associativity.
For this example,the associativity determined that a+b,then the result plus c. This is what ANSI C compliant compiler do(leave out the optimization).But will it be evaluated like foregoing manner in the title? In what compiler? In K&R C?

Answer:
Let me throw this at you:

Operator Precedence vs Order of Evaluation


Question: If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?

Answer: See theGNU Make Debugger


Question: Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.

Answer:
float *mat2d = malloc( rows * cols * sizeof( float
  ));

to access a value from the matrix use this adressing scheme:

float val = mat2d[ x + y * cols ];


Question: If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?

Answer: See theGNU Make Debugger


Question: Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.

Answer:
float *mat2d = malloc( rows * cols * sizeof( float
  ));

to access a value from the matrix use this adressing scheme:

float val = mat2d[ x + y * cols ];


Question:
I seem to be able to compile code that callswsprintfwith theMinGWgccif I have these includes (in this order):

```
#include <stdarg.h>
#include <wingdi.h>
#include <winuser.h>
```

But I feel like there might be some "cleaner" way to do this. Perhaps with only a single header inclusion. I arrived at this list by searching header files for missing symbols and then including headers one-by-one.

Answer: Include<Windows.h>


Question:
```
enum protocol {
    ascii_prot = 3, /* arbitrary value. */
    binary_prot,
    negotiating_prot = 4 /* Discovering the protocol */
};
```

Bothbinary_protandnegotiating_protequals to4?

Answer: Yes.


Question:
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0?

```
int r = arc4random() % (9);
    NSLog(@"Random Number: %d",r);
```

Answer: int r = (arc4random() % 8) + 1