Question:
In some C project, I have seen this code:

```
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
    (void)ud;
    (void)osize;
    /* some code not using `ud` or `osize` */
    return ptr;
}
```

Do the two casts to void serve any purpose?

Answer: It is there to avoid warnings from the compiler because some parameters are unused.


Question: Is it possible to make the checkboxes in a list view control with LVS_EX_CHECKBOXES style tri-state (having BS_3STATE button style)? I'm using WTL but I'm OK manually sending messages around.

Answer: Yes, you need an ImageList with 3 images of a unchecked, checked and indeterminate checkbox.  Call ListView_SetImageList() to assign the LVSIL_STATE image list.  Manipulate LVITEM.state to display the kind of checkbox you want.


Question:
I'm having trouble using bool as a type compiling with ndk-build:

```
bool test = true;
```

error:

48: error: 'bool' undeclared (first
  use in this function)

Any ideas?

Answer: boolis not a built-in type in C. You need to#include <stdbool.h>to get it.


Question:
Does anyone know of any C parser library for .NET?

(I'm intending to parse C code into some form of object graph, so I can convert it to a different language.)

Answer:
ANTLR can do what you'd like. It has a C preprocessor and ANSI C grammar.

https://github.com/antlr/grammars-v4


Question:
I'm looking for sample code on how to use the TMS3705 RFid transponder base station IC to communicate with the TMS37157 RFid device.
The TMS3705 datasheet is not very helpful - it only describes the physical interface.
Either sample code or a good description of how to construct/send a transmit packet and receive/parse a receive packet would be very helpful.

Answer: The TMS3705 is used in thePaLFI Evaluation kit TMS37157. You find the reference to theFAQ.


Question: Count amount of digits in a given number or input by the user.

Answer:
Independent of programming language:

floor(log10(x))+1

where x is your number (>0).

If you want to handle 0 and negative numbers, I'd suggest something like this:

x == 0 ? 1 : floor(log10(abs(x)))+1


Question:
I'm having trouble using bool as a type compiling with ndk-build:

```
bool test = true;
```

error:

48: error: 'bool' undeclared (first
  use in this function)

Any ideas?

Answer: boolis not a built-in type in C. You need to#include <stdbool.h>to get it.


Question:
Does anyone know of any C parser library for .NET?

(I'm intending to parse C code into some form of object graph, so I can convert it to a different language.)

Answer:
ANTLR can do what you'd like. It has a C preprocessor and ANSI C grammar.

https://github.com/antlr/grammars-v4


Question:
I'm looking for sample code on how to use the TMS3705 RFid transponder base station IC to communicate with the TMS37157 RFid device.
The TMS3705 datasheet is not very helpful - it only describes the physical interface.
Either sample code or a good description of how to construct/send a transmit packet and receive/parse a receive packet would be very helpful.

Answer: The TMS3705 is used in thePaLFI Evaluation kit TMS37157. You find the reference to theFAQ.


Question: Count amount of digits in a given number or input by the user.

Answer:
Independent of programming language:

floor(log10(x))+1

where x is your number (>0).

If you want to handle 0 and negative numbers, I'd suggest something like this:

x == 0 ? 1 : floor(log10(abs(x)))+1


Question:
This is a tricky C question asked in interview: Write a program that does nothing, not even taking up memory.

Is it possible to do so?

Answer: All programs use memory.  When you run the program, the OS will set up an address space for the program, copy its arguments into its process space, give it a process ID and a thread, give it some file descriptors for I/O, etc.  Even if your program immediately terminates you still use up this memory and CPU time.


Question: I want to create a tool like mini task manager. I want to show all the running processes, cpu and memory usage. Can anybody tell me related api's which I can use for this. Any link to related web page will be appreciated. (I want dump of all the statistics of running processes, cpu and memory.) Thanks in advance.

Answer:
To do that, you will need touse the tool help functions to get snapshotsof the system.

Hereis a code example.


Question:
Is it this kind of thing:

```
for(;;)
 {
   statements;
 }
```

Or is it this:

```
for(initialisation;condition;updation)
{
}
```

I am looking for answers with references to a variety of sources.

Answer: Your first case (forwith empty expressions) is aninfiniteloop and the second one (with empty body of theforstatement) is anemptyloop


Question: GCC has__builtin_prefetchto support prefetching. My question is how can I prefetch the data to a specific level of cache. For example, I only would like to prefetch the data toL2 cacheinstead of all the way toL1 cache.

Answer: __builtin_prefetchhas three arguments; the third one is the cache level. AFAICT, this has only effect on SSE, where it generates prefetchnta, prefetcht1, prefetcht2, prefetcht3, respectively.


Question:
I build the code, then when I try to run it, it executes and exits quickly .
I am pretty sure that there is a way in the project configuration , but I forgot how .

Answer:
You can always just usegetc()before the return. Enter a character and it will exit..

Or run the VSctrl+f5combination, or add a breakpoint if debugging.


Question: What is the use of padding struct in C?

Answer:
Some architectures will perform better if only aligned accesses are made, so putting 32-bit objects on 32-bit boundaries, and 64-bit objects on 64-bit boundaries can improve the speed of your application.

Some architectures are completely incapable of making unaligned accesses, and on those architectures not padding can be a real disaster.


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

Possible Duplicate:string to float conversion?

how can i convert a string to float in c with only Libc?

Answer: You can usestrtodorsscanfto do this.


Question: I want to create a tool like mini task manager. I want to show all the running processes, cpu and memory usage. Can anybody tell me related api's which I can use for this. Any link to related web page will be appreciated. (I want dump of all the statistics of running processes, cpu and memory.) Thanks in advance.

Answer:
To do that, you will need touse the tool help functions to get snapshotsof the system.

Hereis a code example.


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

Possible Duplicate:string to float conversion?

how can i convert a string to float in c with only Libc?

Answer: You can usestrtodorsscanfto do this.


Question: I'm looking for a simple C Wrapper of zlib, to decompress a byte array. Anyone knows one ?

Answer:
By wrapper function, you probably mean some simpler to use, more self-contained functions?

Zlib contains them. Have a look in themanualunder "Utility Functions".

You're probably look for:

ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
                                   const Bytef *source, uLong sourceLen));


Question:
How do I send UDP packet from aspecificinterface on Linux using C? Should I use bind? Is it possible to send UDP from the interface not having IP address?

Thanks.

Answer: Use bind. You cannot send UDP packets via an interface that does not have an IP address, because UDP uses the Internet Protocol and the Internet Protocol requires an IP address.


Question: I'm writing a C/CGI web application. Is there a library to parse a query string into something like aGHashTable? I could write my own but it certainly doesn't seem to be worth the effort to reinvent the wheel.

Answer: Theuriparserlibrary can parsequery stringsinto key-value pairs.


Question:
I want to learn C/C++ GUI Windows/Linux programming. Which IDE is more suitable? If I go with Visual Studio.NET, what are the pros and cons of it.

Any IDE that supports both Windows and Linux?

Answer:
TheQt Creator IDEworks for both Linux and Windows.

If you want a more versatile development environment, Qt can integrate with Eclipse.


Question:
In .NET land, there's the tremendously usefulSystem.Windows.Forms.CheckedListBoxclass.

What is the equivalent in Windows Common Controls land? (if any)

Answer:
Turn a list view into one with checkboxes. If you want it similar to a ListBox, only use 1 column.

```
ListView_SetExtendedListViewStyle (handle, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
```


Question: Is there a specific reason to use ldiv or div instead of '/' or '%' to divide/modulus two variables?

Answer:
Yes.  C99 §7.20.6.2/2 says:

Thediv,ldiv, andlldiv, functions  computenumer / denomandnumer %
  denomin a single operation.


Question: in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)

Answer: There is no static device name, you should usewaveOut*functions,hereis a nice example of using those APIs.


Question:
I want to define a function in C language which can take an unlimited number of arguments of  any datatype.
For example:printf(),scanf(), etc.

Any idea on this?

Answer:
To use variable number of arguments in C you need to include the header

```
#include <stdarg.h>
```

printf()in C is an example of function that takes variable number of arguments.

```
int printf(const char *fmt, ...)
```

More infohere


Question:
How can i get the last digit of an integer (or NSInteger) outputted to integer?

example:

```
int time = CFAbsoluteGetCurrent();
int lastDigit;
```

Answer:
Usemodulo:

```
int lastDigit = time % 10;
```


Question:
```
char program[3] = { 0x6a,  0x0a, 0xC3 }; //push 10; ret;
char (*p)(void) = program;
printf("char = %c \n", p());
```

This code crashes. Why?

The following code works ok:

```
char program[3] = { 0x90,  0x90, 0xC3 }; //nop; nop; ret
void (*p)(void) = program;
p();
```

Answer: Because you need to cleanup your stack by popping from it.  Read more on theretinstruction - it will load cs:ip with values from the stack!


Question: can any one provide me a link for B-tree code in C,have understood the algorithm but still have problems in coding it

Answer:
c++http://touc.org/btree.html

c (slightly fancier than normal)http://code.google.com/p/high-concurrency-btree/downloads/list


Question:
In .NET land, there's the tremendously usefulSystem.Windows.Forms.CheckedListBoxclass.

What is the equivalent in Windows Common Controls land? (if any)

Answer:
Turn a list view into one with checkboxes. If you want it similar to a ListBox, only use 1 column.

```
ListView_SetExtendedListViewStyle (handle, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
```


Question: Is there a specific reason to use ldiv or div instead of '/' or '%' to divide/modulus two variables?

Answer:
Yes.  C99 §7.20.6.2/2 says:

Thediv,ldiv, andlldiv, functions  computenumer / denomandnumer %
  denomin a single operation.


Question: in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)

Answer: There is no static device name, you should usewaveOut*functions,hereis a nice example of using those APIs.


Question:
I want to define a function in C language which can take an unlimited number of arguments of  any datatype.
For example:printf(),scanf(), etc.

Any idea on this?

Answer:
To use variable number of arguments in C you need to include the header

```
#include <stdarg.h>
```

printf()in C is an example of function that takes variable number of arguments.

```
int printf(const char *fmt, ...)
```

More infohere


Question:
How can i get the last digit of an integer (or NSInteger) outputted to integer?

example:

```
int time = CFAbsoluteGetCurrent();
int lastDigit;
```

Answer:
Usemodulo:

```
int lastDigit = time % 10;
```


Question:
```
char program[3] = { 0x6a,  0x0a, 0xC3 }; //push 10; ret;
char (*p)(void) = program;
printf("char = %c \n", p());
```

This code crashes. Why?

The following code works ok:

```
char program[3] = { 0x90,  0x90, 0xC3 }; //nop; nop; ret
void (*p)(void) = program;
p();
```

Answer: Because you need to cleanup your stack by popping from it.  Read more on theretinstruction - it will load cs:ip with values from the stack!


Question: in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)

Answer: There is no static device name, you should usewaveOut*functions,hereis a nice example of using those APIs.


Question:
I want to define a function in C language which can take an unlimited number of arguments of  any datatype.
For example:printf(),scanf(), etc.

Any idea on this?

Answer:
To use variable number of arguments in C you need to include the header

```
#include <stdarg.h>
```

printf()in C is an example of function that takes variable number of arguments.

```
int printf(const char *fmt, ...)
```

More infohere


Question:
How can i get the last digit of an integer (or NSInteger) outputted to integer?

example:

```
int time = CFAbsoluteGetCurrent();
int lastDigit;
```

Answer:
Usemodulo:

```
int lastDigit = time % 10;
```


Question:
```
char program[3] = { 0x6a,  0x0a, 0xC3 }; //push 10; ret;
char (*p)(void) = program;
printf("char = %c \n", p());
```

This code crashes. Why?

The following code works ok:

```
char program[3] = { 0x90,  0x90, 0xC3 }; //nop; nop; ret
void (*p)(void) = program;
p();
```

Answer: Because you need to cleanup your stack by popping from it.  Read more on theretinstruction - it will load cs:ip with values from the stack!


Question:
I'm writing a CGI program in C to get an uploaded file through HTTP multipart/form-data.

How is that Apache handles file uploads? How can I get the data?

Answer: You could use an established CGI library, such ascgic, which hascgiFormFileNamemethod for handling uploaded files.


Question: From a compiled file, can I see which compiler has been used to generate the file?

Answer: There's also the good old 'strings' utility. Dumps all ascii-ish looking strings it finds in the binary. Different compilers embed different amounts of information in the binaries they produce, but many will actually include obviously identifying strings.


Question:
Does anyone have an idea how to convert char* to string. Actually, I have a function which returns value as char*  and now i need to store/copy  std::string.
I have tried something like

char *sResult = (char*)malloc(1024);
std:string line;
line= line+ sResult

Thanks and regards,
Sam

Answer:
How about

```
std::string line(szResult);
```


Question:
For example I have a string<abc="xyz">

abc can change and so does the value xyz. I need a way to find out value which is between two double quotes. How do I do that in C?
Any standard lib function I can use? without doing explicit pointer dance?

Answer:
You have to browse the string.

Everything you need is there :http://www.cppreference.com/stdstring/index.html


Question: I want to decompile CHM file to HTML format . Is it possible using c or c++ ? Is there any c or c++ library to do this.

Answer: It is possible using C++. If you use Windows, you can do it using COM. An example you can findhere. This article is about C#, but it is done using COM interfaces and you can easily do the same in C++.


Question:
I wanna get string like 34,34;34,21;45,12;45,12(length is not certain.)
I wanna dynamic memory allocation with realloc but i can't do it.
How i can get like this characters to string??

it will be string={34,34,34,21,45,12,45,12}

Answer:
You will have to know the length beforehand, and when you know that your buffer is too small for data that is going to be newly entered, use:

```
realloc(ptr, newLength);
```


Question: I want to decompile CHM file to HTML format . Is it possible using c or c++ ? Is there any c or c++ library to do this.

Answer: It is possible using C++. If you use Windows, you can do it using COM. An example you can findhere. This article is about C#, but it is done using COM interfaces and you can easily do the same in C++.


Question:
What would be the best way to copy unsigned char array to another?

For example:

```
unsigned char q[1000];
unsigned char p[1000];

strcpy (q,&p);
```

The above code does not work, it gives me error saying "cannot convert parameter 1 from unsigned char [1000] to char *".

Answer:
As indicated by its name,strcpyworks on C string (which a unsigned char array is not).

You should considermemcpy.


Question: Ie, how to get keystrokes send directly to my program without waiting for the user to press enter.  Basicly I'm trying get something like curses'scbreak()call.  (But I can't use curses due a couple of bugs/misfeatures that I haven't been able to work around.)  This seems like something that should just be a trival escape sequence, but I haven't been able find anything.

Answer: Lookuptermiosand thetcsetattrfunction.


Question:
I have a pointer that's holding 100 bytes of data.
i would like to add 5 to every 2nd byte.

example:

```
1 2 3 4 5 6
```

will become:

```
1 7 3 9 5 11
```

Now i know i can do a for loop, is there a quicker way? something like memset that will increase the value of every 2nd byte ?

thanks

Answer: A loop would be the best way. memset() is efficient for setting a contiguous block of memory. Wouldn't be much help for you here.


Question:
From what Platform SDK?
Which version?
Where can be downloaded? link

Thanks.

Answer:
T_SafeVector.h is provided by Microsoft as part of what used to be called Platform SDK. Now Platform SDK has been superseded by the Windows SDK

http://msdn.microsoft.com/en-us/windows/bb980924

Windows SDK = Platform SDK + .NET Framework SDK


Question: I hadstruct point {(...)};defined. But with C90 it seems I have to do it with typedef. How do I do this correctly?typedef struct point {} point;?typedef struct {} point;?typedef struct point {};?

Answer:
You can do:

```
typedef struct Point { ... } MyPoint;
```

and then use both kinds of declarations:

```
struct Point p1;
MyPoint p2;
```


Question: I'm writing a Python module in C and I intend to mmap largeish blocks of memory (perhaps 500 MB). Is there anything about working in the same process space as the Python interpreter that I should be careful of?

Answer:
No, you're fine.
On 32-bit systems, you could run out of virtual memory, or with virtual memory fragmentation not have a single chunk big enough to map as many huge files as you want. But that pitfall isn't particular to CPython.


Question:
I'm sorry if this was covered before, but I can't find it anywhere on StackOverflow.

Basically I'm trying to run things that you usually run at a Windows command prompt:

msiexec /i file.msi /q

and other sort of commands from my C program. Is this possible?

Thanks.

Answer: In windows using the Win APIShellExecutewill give you best control of your child process. However the other two methods mentioned by Dave18 and Pablo work as well.


Question:
I'm getting errors while compiling with-ansi -pedanticon lines that have// Comment here. Why does this happen?

expected expression before '/' tokenstray '\347' in program

Example codeint someVariable = 0; // Some comment

I have many many errors of these, what is it?

Answer: C89 does not support C++-style comments.


Question:
What would be the best way to copy unsigned char array to another?

For example:

```
unsigned char q[1000];
unsigned char p[1000];

strcpy (q,&p);
```

The above code does not work, it gives me error saying "cannot convert parameter 1 from unsigned char [1000] to char *".

Answer:
As indicated by its name,strcpyworks on C string (which a unsigned char array is not).

You should considermemcpy.


Question: Ie, how to get keystrokes send directly to my program without waiting for the user to press enter.  Basicly I'm trying get something like curses'scbreak()call.  (But I can't use curses due a couple of bugs/misfeatures that I haven't been able to work around.)  This seems like something that should just be a trival escape sequence, but I haven't been able find anything.

Answer: Lookuptermiosand thetcsetattrfunction.


Question:
I have a pointer that's holding 100 bytes of data.
i would like to add 5 to every 2nd byte.

example:

```
1 2 3 4 5 6
```

will become:

```
1 7 3 9 5 11
```

Now i know i can do a for loop, is there a quicker way? something like memset that will increase the value of every 2nd byte ?

thanks

Answer: A loop would be the best way. memset() is efficient for setting a contiguous block of memory. Wouldn't be much help for you here.


Question:
e.g. quake engines have

```
typedef enum {qfalse, qtrue} qboolean;
```

When one does

```
static qboolean variable;
```

Is the variable's start-up value 0?

Answer:
static and global variables are cleared by default, if there is no value assigned at initialization.

In your examplevariablewill have the enum's equivalent of0, i.e.qfalse.


Question:
This question already has answers here:What are the best (portable) cross-platform arbitrary-precision math libraries? [closed](5 answers)Closed9 years ago.

I need the fastest library that is available for C++. My platform will be x86 and x86-64 which supports floating points.

Answer:
GMPLIB

GMP is a free library for arbitrary precision arithmetic, operating on signed ... C++ class based interface to all of the above.


Question: Which should I use to link for mysqlclient library? What is the difference between them? I can't seem to find the answer. Thanks.

Answer: Newer versions of the MySQL client distributions do not include the "_r" version. Some may have a symbolic link from libmyqslclient_r.a to libmyqslclient.a


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

Please let me know what this C inCprogramming and C++ programming is used for? I'm serious as this question was put in front of me in an interview.

Answer: Nothing at all. It was just the successor of B, which was a stripped-down version of BCPL.


Question: I would like to write a custom GlusterFS Translator for file encryption with AES. Besides this rather rare description:http://europe.gluster.org/community/documentation/index.php/GlusterFS_Contributors_FAQ, is there any other documentation on writing a custom Translator?

Answer: Maybe HekaFS is what you need, it already has a encryption translator.


Question: So I have G++ installed, I can eselycapture from main camera with OpenCV (at least 4 fps). But I also want to capture Live sound from mic. What are my options?

Answer: Take a look atQT for Maemo. It should handle the capturing part. Not sure about openCV though.


Question:
I'm having a hard time understanding what the WINAPI tag is with respect to c.

For example:

BOOL WINAPI CreateProcessA( ...);

What exactly is this WINAPI tag, does it have more formal name, and is it part of c or implementation specific?

Sorry if my question is a bit confusing.

Many Thanks!

Answer: It is thecalling convention, normally defined as__stdcallfor Windows.


Question: Is it possible to implement OS independent threading model of User Level Threads (ULT) in C/C++? In other words, can we break down a process logically into ULTs and dynamically make switches in between them?

Answer: Boost.Thread offers a fair amount of abstraction for cross-platform threading.


Question: Which should I use to link for mysqlclient library? What is the difference between them? I can't seem to find the answer. Thanks.

Answer: Newer versions of the MySQL client distributions do not include the "_r" version. Some may have a symbolic link from libmyqslclient_r.a to libmyqslclient.a


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

Please let me know what this C inCprogramming and C++ programming is used for? I'm serious as this question was put in front of me in an interview.

Answer: Nothing at all. It was just the successor of B, which was a stripped-down version of BCPL.


Question: I would like to write a custom GlusterFS Translator for file encryption with AES. Besides this rather rare description:http://europe.gluster.org/community/documentation/index.php/GlusterFS_Contributors_FAQ, is there any other documentation on writing a custom Translator?

Answer: Maybe HekaFS is what you need, it already has a encryption translator.


Question:
I need to find the path of where my program is running.
Using argv[0] doesn't seem to work because the program has to be run on the windows console, for example,C:\ >player parameter1 parameter2and I only get player on argv[0].

How can I accomplish this?

Answer: You can use Windows'GetModuleFileNamefunction to obtain the path of the executable by setting thehModuleparameter toNULL.


Question:
Is it possible?

```
typedef struct {
    listLink *next;
    listLink *prev;

    void *data;
} listLink;
```

Answer:
Yes, with this syntaxis

```
struct list {
    int   value;
    struct list  *next;
};
```

or

```
typedef struct list
{
      int value;
      struct list *next;
} list;
```


Question:
Is there any way to get all opened sockets usingc++? I know thelsofcommand and this is what I'm looking for, but how to use it in ac++application?

The idea is to get the FD of an opened socket by itsportnumber and thepid.

Answer: Just open the files in /proc/net, like /proc/net/tcp, /proc/net/udp, etc.  No need to slog through the lsof sources.  :)


Question:
i have to write an high efficiency sock reverse proxy in C/C++, so i was wondering, is there any library/framework to easily handle sockets, proxying, etc just to focus on the main part of the project (not the proxy itself :)) ?

Something like the ACE framework but possibly i little bit smaller and/or proxy oriented ...

Thanks

Answer: libeventis pretty good. ACE is horrible :)


Question:
I'm looking for a simple non-validating XML parser in either C or C++.

Several years back I found one that was just a single file solution but I can't find
it anymore.

I'm after some links and suggested ones that are very small and lightweight
ideally suited for an embedded platform.

Answer:
Expat

You can work with or without validation and in "streaming mode". It is very lightweight.


Question:
I'm looking for a simple non-validating XML parser in either C or C++.

Several years back I found one that was just a single file solution but I can't find
it anymore.

I'm after some links and suggested ones that are very small and lightweight
ideally suited for an embedded platform.

Answer:
Expat

You can work with or without validation and in "streaming mode". It is very lightweight.


Question:
if i have a variable from fgets

for example  fgets(question,200,stdin);
how do i determine the size of the variable question without all the trailing blank elemets?

Answer: Usestrlen(3). Was there a question aboutmalloc(3)too?


Question: Suppose there are two threads, the main thread and say thread B(created by main). If B acquired a mutex(say pthread_mutex)  and it has called pthread_exit without unlocking the lock. So what happens to the mutex? Does it become free?

Answer: nope.  The mutex remaines locked.  What actually happens to such a lock depends on its type,  You can read about thathereorhere


Question:
```
#define BS 1000
XDR *xdrs;
char buf1[BS];
xdrmem_create(xdrs,buf1,BS,XDR_ENCODE);
```

I followed what the text book said but whenever I ran my program, it has segmentation fault.
I think there is problem with xdrmem_create. Has anybody here been successful when using this function?

(I'm using Ubuntu 10.10)

Answer:
You didn't initialize the pointer.  Fix:

```
XDR stream;
xdrmem_create(&stream, buf1, BS, XDR_ENCODE);
```


Question: Suppose there are two threads, the main thread and say thread B(created by main). If B acquired a mutex(say pthread_mutex)  and it has called pthread_exit without unlocking the lock. So what happens to the mutex? Does it become free?

Answer: nope.  The mutex remaines locked.  What actually happens to such a lock depends on its type,  You can read about thathereorhere


Question:
```
#define BS 1000
XDR *xdrs;
char buf1[BS];
xdrmem_create(xdrs,buf1,BS,XDR_ENCODE);
```

I followed what the text book said but whenever I ran my program, it has segmentation fault.
I think there is problem with xdrmem_create. Has anybody here been successful when using this function?

(I'm using Ubuntu 10.10)

Answer:
You didn't initialize the pointer.  Fix:

```
XDR stream;
xdrmem_create(&stream, buf1, BS, XDR_ENCODE);
```


Question:
This is my code:

```
int a1[][3]={{1,2,3,4,5,6},{4,5,6,5}};

int (*q)[3];

q=a1;
```

qis a pointer to an array of 3 integers. Buta1does not comply withq's type. Yet the assignment works and no error comes.

Can anyone explain why?

Answer: The types do comply.a1is an array of length-3 arrays of ints.qis a pointer to a length-3 array of ints.  An array decays to a pointer in most circumstances; this is one of them, so everything's fine!


Question:
What does the following code fragment (in C) print?

```
int a = 033;
printf("%d", a + 1);
```

Answer:
033is anoctal integer literaland its value is8*3+3 = 27. Your code prints28.

An integer literal that starts with a0is octal. If it starts in0xit's hexadecimal.

By the way, for an example's sake

```
int x = 08; //error
```

is a compile-time error since8is not an octal digit.


Question: Is there any algorythm to sort an array of float numbers in one cycle?

Answer:
If you mean one pass, then no. Sorting generally requires either O(N log N). Single-pass implies O(N).

Radix sort takes O(N*k) with average key-length k. Even though it's linear time, it requires multiple passes. It is also not usually suitable for sorting floats.


Question:
I'am doing a program that deals with connecting to mysql server and accessing or writing data. I am wondering whether to do the connector part using connector for c or c++. I have heard that c connector is more stable than the c++ connector. Please do help me choose..
MySQL Connector/C or MySQL Connector/C++?

Answer: Go with the language you're the most comfortable with, and use the connector for that language.


Question:
I did the opposite by mistake and now i can't go back to the java enviorment.
anyoune knows how?
thanks.

Answer:
There should be a button in the top right corner for changing perspectives.

You can also get to it through theWindow > Open Perspectivemenu.


Question: So how to create a function to return nearest up so nearest to 9 9+ 1 to given int leaving no remainder when divided by 2 int?

Answer:
To round to the nearest int:

```
number+=(number & 1)
```


Question:
I'am doing a program that deals with connecting to mysql server and accessing or writing data. I am wondering whether to do the connector part using connector for c or c++. I have heard that c connector is more stable than the c++ connector. Please do help me choose..
MySQL Connector/C or MySQL Connector/C++?

Answer: Go with the language you're the most comfortable with, and use the connector for that language.


Question:
I did the opposite by mistake and now i can't go back to the java enviorment.
anyoune knows how?
thanks.

Answer:
There should be a button in the top right corner for changing perspectives.

You can also get to it through theWindow > Open Perspectivemenu.


Question:
I did the opposite by mistake and now i can't go back to the java enviorment.
anyoune knows how?
thanks.

Answer:
There should be a button in the top right corner for changing perspectives.

You can also get to it through theWindow > Open Perspectivemenu.


Question: So how to create a function to return nearest up so nearest to 9 9+ 1 to given int leaving no remainder when divided by 2 int?

Answer:
To round to the nearest int:

```
number+=(number & 1)
```


Question: Is there aplatform-independentway to measure time up to micro seconds using C standard library?

Answer: The precision of the measurement depends on the operating system, unfortunately.


Question:
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and  cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.

Diagram and program code in c is necessary.

Answer:
http://www.codeproject.com/KB/recipes/ReverseLinkedList.aspx

It's also on Google.


Question:
This is my code:

```
wchar_t wbuffer[512];
   wchar_t* wc = (wchar_t*) malloc(buffer_size);
   int buflen = 0;

// ... stuff

// inside the while loop
   wbuffer[buflen] = (wchar_t)wc;
```

what is wrong with this?

Answer:
Dereference wc within your loop.

```
wbuffer[buflen] = *wc;
```


Question:
Is there any way to find a unique hardware ID to a computer in C?

(Windows)

Answer:
How exactly would you define the "computer"?

The CPU?  What about the same CPU in a different MoBo?The MoBo?  What if it gets a new BIOS? a new CPU?The graphics card?  What if the machine has more than 1 GPU? and it gets upgraded?

Once you define exactly what you're asking, you'll be much closer to an answer


Question:
I need to modify trackers in torrent files using C, What type of encoding do they use?? When I just print characters in ascii they print gibberish.
Or is there a direct way of adding trackers to a torrent file using C?

Answer: Have you tried documenting yourself regarding .torrent file format ? TheWikipedia articleseems to be pretty complete on this question.


Question: I am reusing a legacy C library in an iOS app and in an Android app. I want to customize some macro definitions (e.g. for logging). Are there standard defines to check for (using #ifdef) whether the code is being compiled for iOS or Android/NDK?

Answer:
__ANDROID__orANDROIDfor Android (compilation with the NDK)
and__APPLE__on Apple platforms (iOS or OSX)


Question:
I'm desperately looking for some C sample source code that describes how to implement a HID client using Bluez. More specifically, I would like to know how to write an application that sends keyboard inputs over bluetooth to another Linux system. (Really, the fact that the receiver is running Linux/Bluez shouldn't matter.)

-Cheers


Question:
I'm searching for theomp.hfile for using it in eclipse. I failed to find it in openmp.org.

Where do I findomp.h?

thanks.

Answer:
Under Linux, you can find a file by

```
locate omp.h
```

Have you tried to simply use it with

```
#include <omp.h>
```

and add the openmp flag to your g++ compiler flag?

```
g++ -fopenmp sample.c
```


Question:
I was wondering if the WinAPI or something has a way to get the raw data from a USB device, or something that would lead me in the right direction for this sort of thing.

for example, for an midi device, this data might be the velocity, and which note was hit.

Thanks

Answer: Not directly but you can now useusblibon windows


Question:
I need to modify trackers in torrent files using C, What type of encoding do they use?? When I just print characters in ascii they print gibberish.
Or is there a direct way of adding trackers to a torrent file using C?

Answer: Have you tried documenting yourself regarding .torrent file format ? TheWikipedia articleseems to be pretty complete on this question.


Question: I am reusing a legacy C library in an iOS app and in an Android app. I want to customize some macro definitions (e.g. for logging). Are there standard defines to check for (using #ifdef) whether the code is being compiled for iOS or Android/NDK?

Answer:
__ANDROID__orANDROIDfor Android (compilation with the NDK)
and__APPLE__on Apple platforms (iOS or OSX)


Question:
I'm desperately looking for some C sample source code that describes how to implement a HID client using Bluez. More specifically, I would like to know how to write an application that sends keyboard inputs over bluetooth to another Linux system. (Really, the fact that the receiver is running Linux/Bluez shouldn't matter.)

-Cheers


Question:
I'm searching for theomp.hfile for using it in eclipse. I failed to find it in openmp.org.

Where do I findomp.h?

thanks.

Answer:
Under Linux, you can find a file by

```
locate omp.h
```

Have you tried to simply use it with

```
#include <omp.h>
```

and add the openmp flag to your g++ compiler flag?

```
g++ -fopenmp sample.c
```


Question:
I was wondering if the WinAPI or something has a way to get the raw data from a USB device, or something that would lead me in the right direction for this sort of thing.

for example, for an midi device, this data might be the velocity, and which note was hit.

Thanks

Answer: Not directly but you can now useusblibon windows


Question:
I may have missed something but I see here on header files all kinds of functions to move text around in C++ but not on the C API. How is it done?

EDIT: Pixmap fonts for example.

Answer:
TryglTranslatef()orglRasterPos2f().

Also, what documentation are you looking at?I'm not seeing any positioning functionality.


Question:
I have two C files. I want to declare a variable in one, then be able to access it from another C file. My definition of theexamplestring might not be perfect, but you get the idea.

```
//file1.c

char *hello="hello";
```

```
//file2.c

printf("%s",hello);
```

Answer:
```
// file1.h
#ifndef FILE1_H
#define FILE1_H
extern char* hello;

#endif

// file1.c
// as before

// file2.c
#include "file1.h"
// the rest as before
```


Question:
If I have

```
char input[50] = "xFFFF";
int a;
```

How can I store the numerical value of input in a?
the language is C.

Answer:
One way to do it might be:

```
if (sscanf(input, "x%x", &a) == 0) {
    /* matching failed */
}
```

If your input uses a real hex specifier (like "0xFFFF") you can just use %i:

```
if (sscanf(input, "%i", &a) == 0) {
    /* matching failed */
}
```


Question: I have a c program with say n number of for loops. How many processes and child processes will be running for this program and how?

Answer: A for loop does not fork a new process. N number of for loop should run in a single process.


Question: I have to call a c function declared in a lib file from c++. What instructions/attributes/configuration I have to set for this?

Answer:
Do you have a header file for the library? If so it should have

```
extern "C" {
blah blah
}
```

stuff in it to allow it to be used by C programs. If not, then you can put that around the include statement for the header in your own code. E.g.

```
extern "C" {
    #include "imported_c_library.h"
}
```


Question:
I need to intake a number like: 200939915

After doing this, which I know how, I need to remove the first number so it becomes: 00939915

What is the best way to do this?

Answer:
```
char *c = "200939915";
char *d = c + 1;
```


Question:
I need to intake a number like: 200939915

After doing this, which I know how, I need to remove the first number so it becomes: 00939915

What is the best way to do this?

Answer:
```
char *c = "200939915";
char *d = c + 1;
```


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

sem_t mutex;

int main (int argc, char * argv[])
{

sem_init (&mutex,0,1);

}
```

I'm getting:

```
/tmp/ccAMFxDX.o: In function `main':
programaservidor.c:(.text+0x86): undefined reference to `sem_init'
collect2: ld returned 1 exit status
```

Answer:
Per the sem_init() man page

Link with -lrt or -pthread.

As ingcc your_code.c -lpthread -o your_code


Question:
To use pthreads, I used as input a char* that was cast to void* as input. If it's later cast to (char*) it can be printed and used normally ( (char*)var ). However, if one does (char*)var[i], where 'i' will help us reference a character, it doesn't. Why?

e.g. MS says 'expression must be a pointer to a complete object type'.

Answer:
Because of operator precedence: the cast comes after the subscript operator.

You have to write((char*)var)[i];.


Question:
Is there any way to speed up getting an array size in C?

Typing outsizeof(array)/sizeof(int)every time gets old.  Do any C libraries have something like.lengthor is there some way I can definesizeof(array)/sizeof(int)as a shorter constant of some sort (possible also using dot notation)?

Answer:
You can usesizeof(array)/sizeof(*array)and make a macro.

```
#define length(array) (sizeof(array)/sizeof(*(array)))
```


Question: I have been looking through the Lua source code, and I think that is how it works.

Answer: Lua and C use a stack to exchange arguments. Many script languages use this way to communicate with C program.


Question: I am trying to debug a file that has had its symbols stripped. I have headers for the file, with offsets for each function, and was wondering if it was possible to create a DSYM file using these headers. I cannot set breakpoints on the offsets because the file is a plugin, so the functions are mapped to a different location in memory.

Answer: Simply put, it is not.


Question: I am working with graphics in C. I find thinking about the pixel locations terrible and I am in need of a tool where I can draw images and it gives me the pixel location of that point. Please guide me.

Answer: Paint that comes with Windows provides pixel locations in its status bar.


Question:
How to print the environment variables in a C program usingenviron.

```
extern char **environ
```

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

extern char **environ;
//...

int i = 0;
while(environ[i]) {
  printf("%s\n", environ[i++]); // prints in form of "variable=value"
}
```


Question:
Common programs like gcc, rm, cp etc. seem to follow a pattern in reporting their errors like this:

program: error

For instance:

```
$ gcc
gcc: no input files
```

Is there some standard function or macro I should call from within my own C programs to report errors in a standard fashion?

Answer: There are no macros (that I know of).  But, here's the relevantstandardfor formatting error output.


Question: I have a file called "main.c".  Whats the simplest Makefile I can have to compile this file into an executable that I can run like./blah?

Answer:
```
all:
     gcc -o blah main.c
```

You don't need makefile here, simple shell script is OK.


Question: I have been looking through the Lua source code, and I think that is how it works.

Answer: Lua and C use a stack to exchange arguments. Many script languages use this way to communicate with C program.


Question: I am trying to debug a file that has had its symbols stripped. I have headers for the file, with offsets for each function, and was wondering if it was possible to create a DSYM file using these headers. I cannot set breakpoints on the offsets because the file is a plugin, so the functions are mapped to a different location in memory.

Answer: Simply put, it is not.


Question: I am working with graphics in C. I find thinking about the pixel locations terrible and I am in need of a tool where I can draw images and it gives me the pixel location of that point. Please guide me.

Answer: Paint that comes with Windows provides pixel locations in its status bar.


Question:
How to print the environment variables in a C program usingenviron.

```
extern char **environ
```

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

extern char **environ;
//...

int i = 0;
while(environ[i]) {
  printf("%s\n", environ[i++]); // prints in form of "variable=value"
}
```


Question:
Common programs like gcc, rm, cp etc. seem to follow a pattern in reporting their errors like this:

program: error

For instance:

```
$ gcc
gcc: no input files
```

Is there some standard function or macro I should call from within my own C programs to report errors in a standard fashion?

Answer: There are no macros (that I know of).  But, here's the relevantstandardfor formatting error output.


Question: I saw this function in thelua.cfile calleddotty(). I have a feeling that it takes line-by-line input, is this correct?

Answer:
That's correct, it's basically theREPL.

That function technically works on a chunk-by-chunk basis. Theloadlinefunction does the actual line-by-line input, until it gets a complete chunk to execute.


Question:
ulimit -s shows the defaultstacksizelimit.

Is there a startup defaultheapsize ?

Answer:
no

in 32-bit Linux, every process see a continuous 4GB space.  most of it isn't mapped to real RAM, but gets mapped on usage.

in 64-bit it's similar but much bigger.


Question:
I am studying for an OS quiz and I did not understand what output

```
if(fork())
    fork()
```

will produce.  Can someone explain?

I didn't understand this line:

```
if(fork())
```

Edit:

What I meant with "output" is how many processes will be there if this code was executed.

Sorry I'm a bit dizzy after studying.

Answer: Here's a hint:if (fork())is just a short way of writingif (fork() != 0).


Question:
How do I get the output from the following:

```
lua_pushstring(L,"print(i)");
lua_call(L,0,0);
```

Answer:
If you want to run arbitrary Lua code from C, what you need to use isluaL_dostring, as in this question:C & Lua: luaL_dostring return value

Edit: please note that Lua's defaultprintfunction will still print its output straight to the console. You will need to redirect stdout in some way (probably to a pipe) if you want to capture its output.


Question: I am using Xcode (mac) and I want to import my own header file inside of a C project. How do I do this?

Answer: With your project open, go to theProjectmenu, chooseAdd to Project..., browse to the header file you want to add, on the next dialog click thecopy into destination group's folder(assuming the file is NOT within your project's path), then click theAddbutton. The file will now appear within your project.


Question:
In my programming project I want to parse command line attributes using flex/bison. My program is called like this:

```
./prog -a "(1, 2, 3)(4, 5)(6, 7, 8)" filename
```

Is it possible to parse this string using flex/bison without writing it to a file and parsing that file?

Answer: See this questionString input to flex lexer


Question:
I am aware thatfoo[bar]is equal to*(foo + bar), but what is*foo[bar]equal to, such as accessing*argv[2]? I am somewhat confused in understanding this, I assumed maybe something like*(*(foo) + bar)but am unsure..

I apologize if this is a simple answer.

Answer: *a[b]is equivalent to*(a[b])due to C and C++ precedence rules. so*a[b]is equivalent to**(a+b)


Question: Is it possible for a program written in C (or assembly) and is linked with c stdlib using gcc to print the address of its entry? (Since the _start symbol denotes the program entry actually i ask if its possible to print the address of that symbol from inside the main function without using parsing of ELF executable file.)?

Answer: I question why you need to do this, but have you tried usingdlsymfor your purposes?


Question:
I want to define a constant string containing non printable characters in C. For e.g - Let say I have a string

```
char str1[] ={0x01, 0x05, 0x0A, 0x15};
```

Now I want to define it like this

```
char *str2 = "<??>"
```

What should I write in place of<??>do define an string equivalent tostr1?

Answer: You can use"\x01\x05\x0a\x15"


Question: Where to search for free C/C++ libraries?

Answer:
trySourceforge

avoidGPL, as they aren't really free and are spreading like a virus through the rest of your project

useLGPL


Question:
Hey all, I need to compare a double inside an if statement. If the double has no value/is equal to zero, it should do nothing. Otherwise it should do something.

My if statement if (doubleNameHere > 0) doesn't work.

Obviously I'm missing something fundamental here, any ideas?

Answer: Sorry all, it turns out that it wasn't set to zero, it was equal to another blank double value. I started it at zero and it was fine.


Question: How would I load a chunk of Lua code as acharand run it using this function? If not, what other function can I use and how doeslua_load()work?

Answer:
UseluaL_dofileandluaL_dostringto load and run Lua code. Read their definitions inlauxlib.hto see how these are implemented in terms of lower-level primitives.
To learn howlua_loadworks, read the code ofluaL_loadfileandluaL_loadstring.


Question: If I define a function in filefunc1.c, and I want to call it from filecall.c. How can I accomplish this task?

Answer: You would put a declaration for the function in the filefunc1.h, and add#include "func1.h"incall.c.  Then you would compile or linkfunc1.candcall.ctogether (details depend on which C system).


Question:
How do I generate all possible permutations of a list of numbers in C?

As an example,[1, 8, 12]would generate

```
[1, 12, 8],
[12, 8, 1],
[12, 1, 8], ...
```

Answer: Have a look at thisJohnson-Trotter Algorithmand applet it is exactly what you want.


Question:
I'm confused in this program how the value of x=320 ...

```
#include<stdio.h>
 int a=5;
int main(){
    int x;
    x=~a+a&a+a<<a;
    printf("%d",x);
    return 0;
}
```

http://codepad.org/UBgkwdYl

hoping for quick and positive response..

Answer:
This is evaluated like this:

```
x = ((~a) + a) & ((a + a) << a);
```

You should review the C operator precedence tables.


Question: would it make any difference if i use c-style functions to search an array or cstring?

Answer:
In a character string (cstring), the NULL character at the end acts as a sentinel, to signify the end of the search.

If it's an array of characters without the terminating NULL character, then you had better know the length of the string, to avoid overflow.


Question:
XL Compiler of AIX seems to have the-qfuncsectoption which places each function in a seperate object control section with the effect that when the final executable is created it helps in removing unwanted functions.

Is there an equivalent option for the same in gcc? I am unable to find the same.

Answer:
```
-ffunction-sections
-fdata-sections
```

http://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/Optimize-Options.html


Question:
```
enum FileOpenFlags
{
    FileOpenFlags_Create = 1,
    FileOpenFlags_Truncate = 2,
};

FileOpenFlags flags = FileOpenFlags_Create | FileOpenFlags_Truncate;
```

Is it true the return type ofenum |is alsoenum??

Answer:
No, the above expression will have the typeint. However, sinceenums convert to and fromintwithout problems, it's then implicitly converted back toenumfor the store.

See alsothis comp.lang.c FAQ entry.


Question: I am usinglibcurlto create an http connection to anamfphpserver. Do I have to set the content type to any specific format? I noticed there is a option calledAMFPHP_CONTENT_TYPEin PHP cURL but I couldn't find a corresponding value inC.

Answer: Found it. I have to addContent-type: application/x-amfto thePOSTheader.


Question:
I'm interested in reviewing some of the functions included in the string library for c, but I can't find the source code (literally, i.e. functions and all) online and I have no idea where to find it.

Thanks.

EDIT:

thelink provided by pmgshows those functions divided into c files, so it's about what I needed. Thanks.

Answer: Take a look atredhat glibc. It appears to be somewhat current.


Question:
Can you tell me what is the meaning of " Java-class-file loader library in C"?

It's a homework assignment and I am not sure how I should approach it.

Update:I just found out a link ongithubwhich exactly defines the topic but I still need some help to figure out what exactly this means?

Answer: I suppose it's about a C library which provides an API for loading Java .class files. This should be possible usingJNI.


Question: On this link I came acrosshttp://lxr.linux.no/#linux+v2.6.36/include/linux/pci.h#L299integer declarationunsigned int    is_added:1;I have made C programs and declared integers in them but in the above I see use of:What sort of syntax is that?

Answer: I think you have come across abit-field:)


Question:
I was wondering if there are some recommendedread-eval-print loop (REPL)respectively for

(1) C++

(2) C

(3) Java

Thanks!

Answer:
C and C++

You can use CERN'scint.

Java

You can useBeanShell, or if you don't care so much about having Java syntax (e.g. your goal is just to make sure theclassesdo what you want), you can use Groovy, Scala, JRuby, or Jython.


Question:
I have an integer, retrieved from a file using fscanf.
How do I write this into a binary file as a two-byte integer in hex?

Answer:
This will write a short integer to a binary file.  The result is 2 bytes of binary data (Endianness dependent on the system).

```
int main(int argc, char* argv[])
{
   short i;
   FILE *fh;

   i = 1234;
   fh = fopen( argv[1], "wb" );
   fwrite( &i, sizeof( i ), 1, fh );
   fclose(fh);

}
```


Question:
What is the best (shortest) way to read the next non-blank (not space/newline/tab) character from a file in a C program?

I realize I could probably use gets followed by strtok, but it seems like there has to be something more concise.

If so, let me know; if not, let me know that too.

Thanks.

Answer:
```
char c;
fscanf(f, " %c", &c);
```

OR

```
int c;
while (isspace(c=fgetc(f)));
```


Question: I'm trying to make a Lua compiler for Mac OSX with an interface written in Objective-C and the Lua source code written in C.

Answer: You already are combining C and Objective C.  No extra effort is needed.


Question: How can I make a control using bitmaps which changes when I drag with the mouse (e.g. a rotating knob)? And this using the Win32 API?

Answer: Write code to recognize the WM_MOUSEWHEEL message in your control's window procedure.


Question:
I have

char aa[] = { "Hello, !" };

char bb[] = { "World" };

How to insert bb into aa the most efficiently with cstring ?

Answer: allocate big enough buffer (malloc/new[])copy the first part of the aa string into the buffer (strncpy/memcpy)copy the bb string (strcpy/memcpy)copy the rest of the aa string (strncpy/memcpy)


Question:
How could I make a line of code that would exit out of my program after input is given by the user for a specific word?

the psuedo-code of what I have is as follows:

take input;

compare (input) to exit word;

if input is same as exit word

exit the program <------- help here;

else

rest of program;

Answer: If the code is inside main, you can simply usereturnif somewhere else useexit


Question:
I need one server to receive ip requests from clients(there are not in the same intranet), and I can

route all the response packets to a special gateway server, and then I send the response packages to

clients after some processing. it is like VPN, but I want to do some development based one

opensource project, so i can control it myself.

any suggestion? thanks!

Answer: There isOpenVPNwhich is as the name already suggests open source.


Question: How in C can we read and makeDWORDvariables with a low and high word and low and high byte?

Answer:
WinAPI provides macros for the manipulations of these types, such as:

HIWORDLOWORDMAKELPARAM


Question: How would I get a string representation of a web page's source from URL in C?

Answer: If you just want to download it,libcurlis a pretty nifty library for fetching files from many different kinds of servers, including HTTP.


Question:
I know i can set an alarm to "go off" with a SIGALRM after a specified amount of time usingalram(numberOfSeconds)what i am looking to do is to raise the SIGALRM immediately.

Any help would be greatly appreciated.

Answer: raise(SIGALRM);


Question:
If I call:

```
./program hello world
```

then:

```
argc would be 3.
argv[0] would be "./program".
argv[1] would be "hello".
argv[2] would be "world".
```

What's the purpose of passing "./program" as an argument? In fact, it's not an argument at all!

Answer: You can make symbolic links to the same binary. Depending on what link you use, you will get different behaviour. Busybox is an example of this.


Question:
given a pointer to unsigned char value,*ptr.

How to copy its whole value to new char valuechar buff;in a correct way (malloc etc), without looping for each character? Any way to retreive the memory amount currently allocated for the pointer value?

Answer:
If you really have a single character:

```
char buff = (char)*ptr;
```

If you have a string which i assume as you are talking about looping over characters:

```
char *buff = strdup(ptr);
```


Question: How would I get a string representation of a web page's source from URL in C?

Answer: If you just want to download it,libcurlis a pretty nifty library for fetching files from many different kinds of servers, including HTTP.


Question:
I know i can set an alarm to "go off" with a SIGALRM after a specified amount of time usingalram(numberOfSeconds)what i am looking to do is to raise the SIGALRM immediately.

Any help would be greatly appreciated.

Answer: raise(SIGALRM);


Question:
If I call:

```
./program hello world
```

then:

```
argc would be 3.
argv[0] would be "./program".
argv[1] would be "hello".
argv[2] would be "world".
```

What's the purpose of passing "./program" as an argument? In fact, it's not an argument at all!

Answer: You can make symbolic links to the same binary. Depending on what link you use, you will get different behaviour. Busybox is an example of this.


Question:
given a pointer to unsigned char value,*ptr.

How to copy its whole value to new char valuechar buff;in a correct way (malloc etc), without looping for each character? Any way to retreive the memory amount currently allocated for the pointer value?

Answer:
If you really have a single character:

```
char buff = (char)*ptr;
```

If you have a string which i assume as you are talking about looping over characters:

```
char *buff = strdup(ptr);
```


Question:
I know i can set an alarm to "go off" with a SIGALRM after a specified amount of time usingalram(numberOfSeconds)what i am looking to do is to raise the SIGALRM immediately.

Any help would be greatly appreciated.

Answer: raise(SIGALRM);


Question:
If I call:

```
./program hello world
```

then:

```
argc would be 3.
argv[0] would be "./program".
argv[1] would be "hello".
argv[2] would be "world".
```

What's the purpose of passing "./program" as an argument? In fact, it's not an argument at all!

Answer: You can make symbolic links to the same binary. Depending on what link you use, you will get different behaviour. Busybox is an example of this.


Question:
given a pointer to unsigned char value,*ptr.

How to copy its whole value to new char valuechar buff;in a correct way (malloc etc), without looping for each character? Any way to retreive the memory amount currently allocated for the pointer value?

Answer:
If you really have a single character:

```
char buff = (char)*ptr;
```

If you have a string which i assume as you are talking about looping over characters:

```
char *buff = strdup(ptr);
```


Question:
```
int main()
{
        char *temp = "Paras";

        int i;
        i=0;

        temp[3]='F';

        for (i =0 ; i < 5 ; i++ )
                printf("%c\n", temp[i]);

        return 0;
}
```

Whytemp[3]='F';will cause segmentation fault sincetempis notconst?

Answer: You are not allowed to modify string literals.


Question:
What would be the fastest/shortest way to create a string of repeating characters.

For instance,n = 10, char = '*', resulting allocated string: **********

Answer:
Usememset.

```
int n = 10;
char c = '*';

char* buf = malloc(n+1);
memset(buf, c, n);
buf[n] = '\0';

free(buf);
```


Question:
I'm trying to get theCPU serialormotherboard serialusingCorPythonfor licensing purposes. Is it possible?

I'm usingLinux.

Answer: Under Linux, you could use "lshw -quiet -xml" and parse its output. You'll find plenty of system information here: cpuid, motherboard id and much more.


Question:
This question already has answers here:Copying a part of a string (substring) in C(13 answers)Closed9 years ago.

For example, I have this

```
char *buff = "this is a test string";
```

and want to get"test". How can I do that?

Answer:
```
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
```

Job done :)


Question:
```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &r1, &n, &r2, &m)
```

What's"ss"for here?

Answer:
The type specifier in your case is"ss". The specifiersis for a string. Since you are requestingtwostring parameters you need to supply twosasss:

```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &field1 &field1_length,
                                                       &field2, &field2_length)
```


Question: Is there any way to change anintfile descriptor to aFILEstruct pointer or/and changeFILE*to a file descriptor in C?

Answer:
The functionfdopen()returns a new (FILE *) associated with an open file descriptor.

The functionfileno()returns the file descriptor associated with an open FILE *.


Question:
I am using MSVS 2008.  I am writing an application in c, and would like to know whats the best way to determine hard disk information such as space available and total capacity.

Thanks

Answer:
The Win32 API reference is where you should be looking.

The call for free space isGetDiskFreeSpaceEx()


Question: Since a function in C returns only one value, all the time, how canfork(), which is also a function, return two values?

Answer:
The fork function returns 0 to the child process that was created and returns the childs ID to the parent process.

The two seperate processes are each returned a single value.

So think of it more as one return being called on eachthreadprocess.


Question: I am seeking for a C library that does approximate string matching.  Calculating Levenshtein distance for example.  My query strings will be ~512 bytes.  I know aboutFlamingobut it is C++.

Answer:
Not a library but simple function you findhere

A GPL Version


Question:
```
$ getconf BUFSIZ
getconf: Unrecognized variable 'BUFSIZ'
```

Is there a standard way to determine the value of BUFSIZ from a shell?  It's easy enough to write a simple C program to output the value, but I don't quite understand why getconf doesn't do it.

Answer: Because BUFSIZ is a somewhat-arbitary configuration parameter for the stdio library, and not a system configuration parameter


Question:
I'm trying to get theCPU serialormotherboard serialusingCorPythonfor licensing purposes. Is it possible?

I'm usingLinux.

Answer: Under Linux, you could use "lshw -quiet -xml" and parse its output. You'll find plenty of system information here: cpuid, motherboard id and much more.


Question:
This question already has answers here:Copying a part of a string (substring) in C(13 answers)Closed9 years ago.

For example, I have this

```
char *buff = "this is a test string";
```

and want to get"test". How can I do that?

Answer:
```
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
```

Job done :)


Question:
```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &r1, &n, &r2, &m)
```

What's"ss"for here?

Answer:
The type specifier in your case is"ss". The specifiersis for a string. Since you are requestingtwostring parameters you need to supply twosasss:

```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &field1 &field1_length,
                                                       &field2, &field2_length)
```


Question: Is there any way to change anintfile descriptor to aFILEstruct pointer or/and changeFILE*to a file descriptor in C?

Answer:
The functionfdopen()returns a new (FILE *) associated with an open file descriptor.

The functionfileno()returns the file descriptor associated with an open FILE *.


Question:
I am using MSVS 2008.  I am writing an application in c, and would like to know whats the best way to determine hard disk information such as space available and total capacity.

Thanks

Answer:
The Win32 API reference is where you should be looking.

The call for free space isGetDiskFreeSpaceEx()


Question: Since a function in C returns only one value, all the time, how canfork(), which is also a function, return two values?

Answer:
The fork function returns 0 to the child process that was created and returns the childs ID to the parent process.

The two seperate processes are each returned a single value.

So think of it more as one return being called on eachthreadprocess.


Question:
Why can you kind of cheat compiler this way:

```
const int a = 5;
*((int*)&a)=5;   // VC/armcc does not complain
```

when above is "abridged" equivalent of this:

```
const int *ptr2const = &a;
int *ptr = ptr2const;      // as expected error is raised here
*ptr = 5;
```

Answer: Casting is your way of telling the compiler "I know what I'm doing", so it doesn't complain.  Unfortunately, in this instance, you will invoke undefined behaviour.


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

Possible Duplicate:Reason for the Output

Hi,

Can you please explain me the output of this code snippet? The answer is "d"

```
void main()
{
short int a=5;
clrscr();
printf("%d"+1,a);
getch();
}
```

Thanks.

Answer: "%d" + 1is a pointer to"d", so in fact you are executingprintf( "d", a );.


Question:
In C/C++, the main function receives parameters which are of typechar*.

```
int main(int argc, char* argv[]){
  return 0;
}
```

argvis an array ofchar*, and points to strings. Where are these string located? Are they on the heap, stack, or somewhere else?

Answer: They are compiler magic, and implementation-dependent.


Question:
I have a struct like this:

```
struct A
{
  char x[];
};
```

What does it mean? When I do something like:

```
A a;
a.x = "hello";
```

gcc throws an error saying:

```
error: incompatible types in assignent of 'const char [6]' to 'char [0u]'
```

Answer:
This is a C99 "flexible array member".
See here for gcc specifics:http://www.delorie.com/gnu/docs/gcc/gcc_42.html


Question:
What are the Compiler Options & Other mechanism for reducing the static library size?

OS : VxWorks
Compiler : GCC
Language : C

Answer: Use-Osto optimise for smaller code size, and leave out-gand any other debug options.


Question:
i'm doing some code now and got some problem using restrict keyword.

```
typedef int* pt;

int foo(pt a, pt b)
{
 ... /* stuff */
}
```

What if I want to make a and b restricted? The code below failed:

```
typedef int* pt;

int foo(pt restrict a, pt restrict b)
{
 ... /* stuff */
}
```

Thanks in advance.

Answer: Make sure you're compiling it using the C99 flag for your compiler. Therestrictkeyword doesn't exist in C89 C.


Question:
Does anyone know a function/library that I could use to do general FTP functions in a FTP connection?

I'd rather have these in C, as that would be extremely easy to add to my current project.

Answer: libcurlis probably the best library you can use for that.


Question:
I am using c .
I have fd1 as a file descriptor, can I call like this twice?

```
main () {
....
shutdown(fd1, SHUT_WR);
....
shutdown(fd1, SHUT_WR);
....
}
```

I personally think it works because fd1 has not been really free yet. Just want somebody to confirm.

Answer: You should check the return value of the second call -shutdown(2)probably returns-1- and check the value oferrno(3).


Question:
I was looking at some c++ code, and I saw this:

```
int num = *(int *)number;
```

I had never seen this before?
it was in a function labeled as such:

```
void *customer(void *number){ }
```

What does that even do? Is there a different way to show this?

Thanks, this isn't homework btw I was just confused at what this does?

Answer: The (int *) part casts the variable number to a pointer to an int, then the * in front dereferences it to an int.


Question:
I'm looking for a runtime memory debugger, capable of showing memory usage (not just leaks) per function or line of C++ code on Linux.
I am trying to track down a spike in my program memory usage.
I have used Valgrind and Purify and I found that there are are no leaks. I expected that, as after that spike, the memory usage gets back to its expected level for my program.

Thanks.

Answer: You can use the massif tool from the valgrind pack of tools.


Question:
Does OpenSSL have any support for operations in the quadratic extension field (or, alternatively, operations with complex numbers) using the BN API?

If not, are there any other open source libraries that do?

Answer: You may want to look atPBC. This is a library for computing pairings on some elliptic curves, which implies using field extensions of various degrees, including quadratic extensions for some fields.


Question:
I am using c .
I have fd1 as a file descriptor, can I call like this twice?

```
main () {
....
shutdown(fd1, SHUT_WR);
....
shutdown(fd1, SHUT_WR);
....
}
```

I personally think it works because fd1 has not been really free yet. Just want somebody to confirm.

Answer: You should check the return value of the second call -shutdown(2)probably returns-1- and check the value oferrno(3).


Question:
I was looking at some c++ code, and I saw this:

```
int num = *(int *)number;
```

I had never seen this before?
it was in a function labeled as such:

```
void *customer(void *number){ }
```

What does that even do? Is there a different way to show this?

Thanks, this isn't homework btw I was just confused at what this does?

Answer: The (int *) part casts the variable number to a pointer to an int, then the * in front dereferences it to an int.


Question:
I'm looking for a runtime memory debugger, capable of showing memory usage (not just leaks) per function or line of C++ code on Linux.
I am trying to track down a spike in my program memory usage.
I have used Valgrind and Purify and I found that there are are no leaks. I expected that, as after that spike, the memory usage gets back to its expected level for my program.

Thanks.

Answer: You can use the massif tool from the valgrind pack of tools.


Question:
Does OpenSSL have any support for operations in the quadratic extension field (or, alternatively, operations with complex numbers) using the BN API?

If not, are there any other open source libraries that do?

Answer: You may want to look atPBC. This is a library for computing pairings on some elliptic curves, which implies using field extensions of various degrees, including quadratic extensions for some fields.


Question: What's the counter part of _wfopen? I found that there is fclose related to fopen, but it seems there is no _wfclose.

Answer: I would sayfclose(), since you don't actually need anything "wide" in order to close it.


Question:
Using only bitwise operators (|, &, ~, ^, >>, <<) and other basic operators like +, -, and !, is it possible to replace the "==" below?

```
int equal(int x, int y) {
    return x == y;
}
```

Answer:
Remember that anXORis the exactly same asNOT EQUALSandXNORis exactly the same asEQUALS. So, the following will give you exactly what you want:

```
return !(x ^ y);
```


Question:
I'm using a dsPic33F (16 bit microcontroller);

How to convertchar[]toint[]such that every two chars becomes an int using C++?and the inverse operation?

Answer:
```
int* intArray = new int[sizeOfByteArray];

for (int i=0; i<sizeOfByteArray; ++i)
   intArray[i] = byteArray[i];
```

Or

```
std::copy(byteArray, byteArray+sizeofByteArray, intArray);
```


Question:
Using C or a bat file, I'm trying to edit the file hosts file from c:\Windows\System32\drivers\etc but I can;t bc it is write protected.

Can you tell me what can i do?

Answer: The program modifying the host file needs to run as Administrator


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

int main(int argc, char **argv)
{
 int ret;

 ret = execve("/bin/bash", NULL, NULL);

 return 0;

}
```

i m confuse about why the null values are passsed in execve
please help.....

Answer: Those parameters correspond to the program's arguments and environment.  By passing NULL in for both, the caller is indicating that no arguments should be supplied to the program and no environment variables should be supplied either.


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

Possible Duplicate:Why there is not a comprehensive c archive network?

Like Python has a Cheeseshop and Perl has CPAN?
Google results have a lot of C++ results and I am looking for purely C libraries.

PS: Looking for *nix libraries

Answer: Yep. SourceForge, Codeplex, Github, and Google.  Also, your distro's packages, if you are on Linux.


Question: As the title implies: the scenario is a coder with a gdb and a user reporting a crash. Can he get from the user an easy to use memory dump which can be fed to gdb but also not make it hard for the user?

Answer:
You can set upProcess Dumperto produce a full dump on any exception or process exit, based on the name of the executable file.

I am assuming Windows due to the title, alter the tags if not.


Question:
I am trying to store every hex value from 0000 to fffe into a file.  How would I use fwrite or fprintf to place these values into a file?

At the moment, I have a while loop that prints all the numbers using printf (which is to the console screen), but I need them in a file.

Answer:
```
fprintf(fp, "%04x", your_number)
```


Question:
Does Google protocol buffers are binary-compatibly with C structures?
I mean can I read serialized files from C direct into structs without deserializing?
Orprotobuf-cis the only one solution?

Answer: Depending on the alignment, endianness and packing of structures on your platform, this may or may not work. You may be lucky with your particular target, but in general you should use proper serialise / deserialise routines.


Question: As the title implies: the scenario is a coder with a gdb and a user reporting a crash. Can he get from the user an easy to use memory dump which can be fed to gdb but also not make it hard for the user?

Answer:
You can set upProcess Dumperto produce a full dump on any exception or process exit, based on the name of the executable file.

I am assuming Windows due to the title, alter the tags if not.


Question:
I am trying to store every hex value from 0000 to fffe into a file.  How would I use fwrite or fprintf to place these values into a file?

At the moment, I have a while loop that prints all the numbers using printf (which is to the console screen), but I need them in a file.

Answer:
```
fprintf(fp, "%04x", your_number)
```


Question:
Does Google protocol buffers are binary-compatibly with C structures?
I mean can I read serialized files from C direct into structs without deserializing?
Orprotobuf-cis the only one solution?

Answer: Depending on the alignment, endianness and packing of structures on your platform, this may or may not work. You may be lucky with your particular target, but in general you should use proper serialise / deserialise routines.


Question:
I wanted to know what is the current standard C compiler being used by companies. I know of the following compilers and don't understand which one to use for learning purposes.

Turbo CBorland CGCCDJGPP

I am learning C right now and referring to the K&R book.

Can anyone please guide me to which compiler to use?

Answer: GCCwould be the standard, best supported and fastest open source compiler used by most (sane) people.


Question:
I have a header file for a game that declares a two-dimensional array for a board.

```
#ifndef GAME_H_
#define GAME_H_

static const int columns = 15;
static const int rows = 15;

int board[rows][columns];

#endif /* GAME_H_ */
```

I get an error:

error: variably modified 'board' at file scope

Answer:
C doesn't allowconstvariables as array bounds. Use an enum instead:

```
enum { columns = 15, rows = 15 };
```


Question:
Example:

```
var x, y, z;
//...
x > 100 ? y = x : z = x ;
```

Answer:
Yes it does work the same although operator precedence is always tricky so I would recommend parenthesis to avoid confusion.

tangentially related..You can also use||in JavaScript similar to the null coalescing operator??in C#


Question:
I wanted to know what is the current standard C compiler being used by companies. I know of the following compilers and don't understand which one to use for learning purposes.

Turbo CBorland CGCCDJGPP

I am learning C right now and referring to the K&R book.

Can anyone please guide me to which compiler to use?

Answer: GCCwould be the standard, best supported and fastest open source compiler used by most (sane) people.


Question:
I have a header file for a game that declares a two-dimensional array for a board.

```
#ifndef GAME_H_
#define GAME_H_

static const int columns = 15;
static const int rows = 15;

int board[rows][columns];

#endif /* GAME_H_ */
```

I get an error:

error: variably modified 'board' at file scope

Answer:
C doesn't allowconstvariables as array bounds. Use an enum instead:

```
enum { columns = 15, rows = 15 };
```


Question:
Example:

```
var x, y, z;
//...
x > 100 ? y = x : z = x ;
```

Answer:
Yes it does work the same although operator precedence is always tricky so I would recommend parenthesis to avoid confusion.

tangentially related..You can also use||in JavaScript similar to the null coalescing operator??in C#


Question: For jpeg,gif,png I use libgd. ( not ImageMagick - it's not possible ). May I resize bmp image using simple method/library ?

Answer: Most of the libraries that deal with image resizing represent the image as a bitmap (i.e. an uncompressed array of pixels) internally. So it wouldn't be very hard to read in a bitmap image from a file and put it in memory.


Question:
quick question

Can you use the free() function without having to prior call a malloc ??

ei.

```
void someFunc( void )
{
   char str[6] = {"Hello"};

   //some processing here ....

   free(str);
}
```

I get no compiling errors but Does this work or is it correct at all ?

Thank you,

Answer:
This is not at all correct:

You cannot free a static array such aschar str[6].free() should only be called on memory you allocated (or on NULL).


Question: I could find a C++ onehere, but no pure C one. Any pointers?

Answer:
C code for a red and black tree, licensed with the very generousMIT license.

(Backup at archive.org.)


Question: I have a file with various 'return BBQ;' statements. I'd like to change them all to 'exit(BBQ);\nreturn BBQ;' (with BBQ being an arbitrary value). Is this possible?

Answer:
Backreferences.

```
s/return \(BBQ\);/exit(\1);\nreturn \1;/
```


Question: Somebody can give me an example to do this. Suppose static variable scope is  limited to file only.That is private to that file.Like that some more examples i want to know. In other words HOW TO ACHIEVE DATA HIDING CONCEPT IN C-LANGUAGE WITH CURRENTLY AVAILABLE KEYWORDS(STRUCT,STATIC...ETC)

Answer:
This guy is one of the worlds authorities on embedded systems. He wrote this white paper on OOP in c.

http://www.state-machine.com/resources/cplus_3.0_manual.pdf


Question:
quick question

Can you use the free() function without having to prior call a malloc ??

ei.

```
void someFunc( void )
{
   char str[6] = {"Hello"};

   //some processing here ....

   free(str);
}
```

I get no compiling errors but Does this work or is it correct at all ?

Thank you,

Answer:
This is not at all correct:

You cannot free a static array such aschar str[6].free() should only be called on memory you allocated (or on NULL).


Question: So I need to get web camera fps rate in OpenCV. Which function can do such thing for?

Answer:
```
int cvGetCaptureProperty( CvCapture* capture, int property_id);
```

withproperty_id = CV_CAP_PROP_FPS


Question:
I have two bytes, 8 bit octets, which should be read as: [3 bits][4 bits][3 bits].

Example:

```
unsigned char octet1 = 0b11111111;  // binary values
unsigned char octet2 = 0b00000011;
```

As integers: [7][15][7].

Anybody can give me a hint where to start?

Answer:
In a kind ofpseudocode

```
octet1 = 0b11111111
octet2 = 0b00000011
word = octet1 | octet2<<8
n1 = word & 0b111
n2 = word>>3 & 0b1111
n3 = word>>7 & 0b111
```


Question:
I have two bytes, 8 bit octets, which should be read as: [3 bits][4 bits][3 bits].

Example:

```
unsigned char octet1 = 0b11111111;  // binary values
unsigned char octet2 = 0b00000011;
```

As integers: [7][15][7].

Anybody can give me a hint where to start?

Answer:
In a kind ofpseudocode

```
octet1 = 0b11111111
octet2 = 0b00000011
word = octet1 | octet2<<8
n1 = word & 0b111
n2 = word>>3 & 0b1111
n3 = word>>7 & 0b111
```


Question:
I use the Tiny C Compiler and I want to useGetUserNamefrom
the WinAPI. My problem is, I don't know how to link toadvapi32.dll

I get an error from tcc:

```
undefined symbol '_GetUserNameA@8'
```

Answer: I explained how to create a .def file from a dll and how to compile and link  with tcc here:Tiny C Compiler (TCC) and winsock?


Question:
```
#include<stdio.h>
void compute(int);
int cube(int);
int main( )
{
        compute(3);
}
void compute(int in)
{
        int res=0,i;
        for(i=1;i<=in;i++);
        {
                res=cube(i);
                printf("%d %d",res,i);
        }
}
int cube(int n)
{
        return (n*n*n);
}
```

~output :  64 4

How does it happen ?

Answer: Semicolon at the end of yourforline.


Question:
in php

```
$arr = array()
$arr[0] = "string 1";
$arr[1] = "string 2";
```

how about in c?

thanks

Answer:
You need to declare an array of pointers. Each element of the array is a pointer to the string. You need to copy the string in, and then release it when done.

```
char *strings[2];

strings[0] = strdup("Hello, world!");
printf("%s\n", strings[0]);
free(strings[0]);
```


Question:
For example:

```
console> please enter 3 digits: 1 2 3
```

I only know how to accept 1 digit usingscanf:

```
scanf("%d", &space);
```

Answer:
You can read in multiple numbers with scanf

```
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
```


Question:
I've been going through some C source code and I noticed the following:

```
void some_func (char *foo, struct bar *baz)
{
    (void)foo;
    (void)baz;
}
```

Why isvoidused here? I know(void)before an expression explicitly indicates that the value isthrown away; but can someone please explain me the rationale for such an use?

Answer: This code ensures that you won't get a compiler warning about foo and baz being unused.


Question:
```
int SDL_BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect);
```

Why are the srcrect and dstrect arguments not const? Are they modified in the function? At the moment I'm const-casting my Sprite class member variables to use BlitSurface... It seems silly.

Answer: Becausethey're modified.


Question:
What is a good C compiler for OSX or Windows XP or DOS? I would like to make a GUI shell for DOS.
Also what is a good pascal compiler for these platforms?

Answer: On Mac OS X, you should use the GNU Compiler Collection (GCC). You can install it by downloading and installing the freeXcode Developer Tools. On Windows, you can also install GCC (usingCygwin).


Question:
I have this code in C:

```
int main(){ char a[10]; _asm{ mov DWORD PTR[a],eax;}
```

This works well, but why do I actually need the

```
DWORD PTR
```

When the DWORD size is already stated by using eax? IAnd for destination, I dont need any size whe I have pointer, right? Thanks.

Answer: It is because your code is wrong.  Theavariable is an array, not a pointer.  Declare it char* and you don't need the override.  The code is nonsense of course.


Question:
How to convert lower case ASCII char into upper case using a bitmask (no -32 allowed)?

I'm not asking for solving my homework, only some hints.

Thanks

Answer: As you state "(no -32 allowed)", I guess you know that the difference between lower case characters and upper case characters is 32. Now convert 32 to its binary representation, there's only one bit set. After that, work out a way to use abit maskto switch the bit.


Question:
I have an integer matrix that should act like a buffer:

x = {{0, 0, 0, 0, 0}, {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}};

Now if I add a new row{3, 3, 3, 3, 3}, the new matrix should look like:

x = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}};

Is there a clever way of doing this without copying all elements around?

Answer: If your matrix is defined as anint **and you separately allocate each row, then you would only have to swap the row pointers.


Question:
I have a C file generated with f2c (Fortran to C translator) that contains the following C structure:

```
struct {
    real rez, pi, st;
} const_;
```

How can I declare thisconst_variable as an external in another .c file without modifying the one generated by f2c?

Answer:
In another file.

```
extern struct {
    real rez, pi, st;
} const_;
```


Question:
Given strings like the following:

```
sdfsd34
    sdfdsf1
```

I would like to extract:34, 1using c++ (STL but no boost), c.

thanks

Answer:
You’re searching for the functionstring.find_last_not_of:

```
string str = "sdfsd34";
size_t last_index = str.find_last_not_of("0123456789");
string result = str.substr(last_index + 1);
```


Question:
Can I use a socket library from TCC? I can't find any reference to winsock or sys/socket.h in the include directory.

If i remember correctly, winsock was part of the windows platform SDK (?) If so can I link that with TCC?

Answer:
According toTinycc-devel mailing list

you should give this a try:

```
tiny_impdef winsock.dll -o winsock.def
tcc yourcode.c  winsock.def -o yourcode.exe
```


Question:
I want to call a function of the business class after every 2 hours.
I m not getting any way to implement same in C/C++ without using a while loop.
My problem is that i cannot use while(1) as this does not retun back the control for further execution.

Any pointer in this regards wud be helpful....:)

thnaks

Answer: Boost.AsioprovidesTimers.


Question:
with other IDE, you can pass parameter to the program via the IDE
(it save times instead of typing hello.c parameter1 parameter2 in the shell)

Is there any way to pass parameters to the program trhough the Xcode IDE instead of just clicking on "RUN" then "CONSOLE" (which provide no arguments to the program)

Thanks

Answer:
Under "Executables" get info on your binary.

Go to the "Arguments" tab, and add them there.


Question: I want to create a route server to proxy some clients(they may not in the same intranet) to access internet. I need to assign unique ip to the client and get the ip when packets response，so I can do some monitor task. i want to know if I use PPPoE server to deal with this case, how to through NAT ? thanks!

Answer: You can't. NAT routes packets in theTransport layer, but PPPoE operates in theData Link layer; NAT can't evenseePPPoE packets.


Question:
When you see code like this in C, what's the order of assignment?

```
int i = 0, var1, var2;
```

I don't understand the syntax...

Answer:
Onlyiis assigned the value zero.

var1andvar2are uninitialized.


Question:
I am playing withlibnetfilter_queueand am looking for a good C library to work with packets captured by libnetfilter_queue. I really like thedpktlibrary for python and some similar library for C would be wonderful.

Any other workaround or example code for manipulating the packets are also welcome.

with regards,

raj

Answer: Netfilter's TPROXY target is available (even at *BSD) => setsockopt can be done from your python code without messing at C.


Question: Why are function arguments pushed on the stack in right to left order?

Answer: To enable the existence of functions with a variable number of arguments, like printf. The function can extract the first one or two arguments and then use their values to deduce the total number of arguments on the stack.


Question:
I am playing withlibnetfilter_queueand am looking for a good C library to work with packets captured by libnetfilter_queue. I really like thedpktlibrary for python and some similar library for C would be wonderful.

Any other workaround or example code for manipulating the packets are also welcome.

with regards,

raj

Answer: Netfilter's TPROXY target is available (even at *BSD) => setsockopt can be done from your python code without messing at C.


Question: Why are function arguments pushed on the stack in right to left order?

Answer: To enable the existence of functions with a variable number of arguments, like printf. The function can extract the first one or two arguments and then use their values to deduce the total number of arguments on the stack.


Question:
scanf("%s",str) won't do it. It will stop reading at the first space.
gets(str) doesn't work either when the string is large. Any ideas?

Answer: usefgetswith STDIN as the file stream.  Then you can specify the amount of data you want to read and where to put it.


Question:
```
const struct sockaddr FAR* name,
```

Answer:
It's an old extension from the era of segmented memory architectures. It basically means "this is a pointer that needs to be able to point at any address, not just things in the same segment as the code using it".

See more or on thewikipedia page.


Question:
There are many good packages for calculating the intersection of polygons. I have found the GPC library useful.

I would like to compute intersections of polyhedra (piecewise linear boundaries) in 3D. Are there any good libraries in C/C++ for this?

Answer: So far, I've foundCGAL, but I haven't tried it out yet.


Question: Can we anyhow change the size of the pointer from 2 bytes so it can occupy more than 2 bytes?

Answer:
Sure, compile for a 32 (or 64) bit platform :-)

The size of pointers is platform specific, it would be 2 bytes only on 16-bit platforms (which have not been widely used for more than a decade - nowadays all mainstream[update](desktop / laptop / server)[/update]platforms are at least 32 bits).


Question:
The question is&str[2], if I writestr+2then it would give the address and its logical but where did I used pointer notation in it?

Should I prefer writing&(*(str+2))?

Answer:
You can use either

```
&str[2]
```

or

```
(str + 2)
```

Both of these are equivalent.


Question:
what does this sybol means please?
"<<"
for example:
if (1 << var)

I want the name of the thing to study. Thank you.

Answer:
It shifts the bits in the integer 1varpositions to the left. So in effect it calculates 2 to the power ofvar.

Seethe article on bit shifts on wikipedia.


Question:
I am working on a C assignment for uni, and I've been coding in TextMate and compiling in the command line.

But TextMate wont (or cant) format C code, as it would for say, HTML, Ruby or PHP (using SHIFT + CTRL + F).

Is there a plugin or some other tool I can use to fix my indenting and curly braces for .c files?

Answer: I useastyle. It has a lot of options to customize according to your coding style, and I think it is included in the major linux distributions.


Question: For instance if I called WriteFile to the end of a file, and later I wanted to delete the written bytes, how could I do this? Do I have to read the file's contents into a buffer, re-create the file, and write the desired bytes, or is there an easier way?

Answer: Seekto the file position you want to truncate from (if you're not already there), then call the aptly-namedSetEndOfFile()function.


Question:
Is there a way to set the blending parameters so the whole scene renders in grayscale? (without using GLSL, only pipeline functions)

Thanks

Answer: No, all colors are separated. You need a pixel shader for that


Question:
I need to use natural cubic spline interpolation in an iPhone app.  Does anyone know of a class for Obj C or C that resembles this:http://www.ee.ucl.ac.uk/~mflanaga/java/CubicSpline.html

"performing an interpolation within a one dimensional array of data points, y = f(x), using a cubic spline."

Answer: Look at thisarticleThis is a sample for Curve Fitting. It uses Cubic Spline Interpolation, and Bezier Spline Curve.


Question: I have a C source file having comments in//(C++) style. I want to change all the comments to the old/* */(C) style. Is there a way to do this using an existing script?

Answer: A substitution with you favorite editor and a regular expression likes#//(.*)#/*\1 */#should do it...


Question: How do I cause a thread to respond topthread_cancel()if it is blocked on asem_wait()?

Answer: You can set a signal handler, let's says for SIGUSR1, for the thread that will be blocking then, from another thread, you callpthread_cancel(tid)andpthread_kill(tid, SIGUSR1). The thread will be canceled oncesem_wait()is interrupted by the signal.


Question:
Many times I see in open source code that a call to a C function is cast to void.

For example, in the source code forls(http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/ls/ls.c) I see the following.

```
(void) setlocale(LC_ALL, "");
```

Why is this good practice?

Answer: It explicitly means you ignore the return value, and did not just forget it.


Question:
I am looking for a automated finite state machine generator for C? I have seen a few over the internet but unable to decide which one to use. If anybody worked with any such tool then help me to find the right one.

Thanks,
Ravi Gupta

Answer: Ragelis fairly powerful.


Question:
I'm Interested in writing gedit-plugins in C. I've checkedGedit/NewMDIPluginHowTo...but haven't had any luck with it.

How can I get more information about writing gedit plugins in C?

Answer: If you're willing to use Python instead,hereis a tutorial for writing gedit plugins in Python.


Question:
I have#include<math.h>,
and I tried to use pow(x, y) and powf(x, y).
but it seems neither of them are under c99 standard.
and I use the commandgcc -std=c99 test.c -o testto compile.
what function there exists I can use?

Answer:
Forhistericalreasons, the math library is not bundled in with the rest of the Standard Library. You have to manually add it to the compilation with the-lmoption to gcc.

```
gcc -std=c99 test.c -o test -lm
```


Question:
I am looking for a automated finite state machine generator for C? I have seen a few over the internet but unable to decide which one to use. If anybody worked with any such tool then help me to find the right one.

Thanks,
Ravi Gupta

Answer: Ragelis fairly powerful.


Question:
I'm Interested in writing gedit-plugins in C. I've checkedGedit/NewMDIPluginHowTo...but haven't had any luck with it.

How can I get more information about writing gedit plugins in C?

Answer: If you're willing to use Python instead,hereis a tutorial for writing gedit plugins in Python.


Question:
I have#include<math.h>,
and I tried to use pow(x, y) and powf(x, y).
but it seems neither of them are under c99 standard.
and I use the commandgcc -std=c99 test.c -o testto compile.
what function there exists I can use?

Answer:
Forhistericalreasons, the math library is not bundled in with the rest of the Standard Library. You have to manually add it to the compilation with the-lmoption to gcc.

```
gcc -std=c99 test.c -o test -lm
```


Question:
I've downloaded Eclipse  C/C++ IDE . I need to run a simple c program in this(To print welcome).

While trying to run the program its popping up an error message  like"Launch failed: Binary not found" .

Need i install any compiler package. ?

Please help me to do this.

Answer: Yes, you have to install a compiler, Eclipse is only an IDE. You can get MinGWhere.


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

Possible Duplicate:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?

This is C code sample of a reference page.

```
signed int _exponent:8;
```

What's the meaning of the colon before '8' and '8' itself?

Answer: It's a bitfield. It's only valid in astructdefinition, and it means that the system will only use 8 bits for your integer.


Question:
I was trying to develop a chat application using C programmable sockets. I need to check whether the stdin buffer has some value in it to send the message to the client/server and receive it. But I don't know how to check the stdin buffer for values.
Please help.

Answer: You wantselect(2,3p).


Question:
```
struct stats
   {
       char top         : 1;
       char bottom      : 1;
       char side        : 2;
   } MyStat;
```

I have seen this format with integers but how does the above char bit field work and what does it represent?

Thank You.

Answer: Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.


Question:
```
struct stats
   {
       char top         : 1;
       char bottom      : 1;
       char side        : 2;
   } MyStat;
```

I have seen this format with integers but how does the above char bit field work and what does it represent?

Thank You.

Answer: Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.


Question:
there is someone that know if exist a XSD code generator for C source code?
I have a lot of xsd files and I need to generate C struct and relative function fromXml and toXml.
Thanks.

Answer: For C++ generation there ishttp://sourceforge.net/projects/xxsd2code/


Question:
This post is edited and the original post here is asking the implementation of _malloc_r which is not a good move to use.

My question now is there any other malloc implementation or alternative function for malloc and free functions?

Please advice.

Many thanks.

Answer: Give up on trying to have a reentrantmalloc. It's a bad idea. If you really need to allocate memory from signal handlers, usemmap, but even that is a bad design.


Question:
I have an array of double (size more than 60k entries), I have the frequency value. Now I want to create a sound from it using C/C++ which I can play on speaker. My OS is linux.

Thanks. I hope I am clear enough.

Answer:
http://www.linuxjournal.com/article/6735

This is a link to an article in Linux Journal about programming with the ALSA (Advance Linux Sound Architecture).  It contains some example code.


Question:
Do these two structs have the same memory layout? (C++)

```
struct A
{
   int x;
   char y;
   double z;
};

struct B
{
   A a;
};
```

Further can I access x, y, z members if I manually cast an object of this to anA?

```
struct C
{
   A a;
   int b;
};
```

Thanks in advance.

EDIT:

What if they wereclassesinstead ofstructs?

Answer: Yes and yes. The latter is commonly used for emulating OO inheritance in C.


Question:
Is it possible to get the list of #defines(both compile time and defined in the source code) used in a C program while execution.
Because  i am having a project having lot of C source files.

Is there any compile time option to get that?

Answer: GNUcpptakes various-doptions to output macro and define data. See their man pages for more details.


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

Possible Duplicate:C# driver development?

Why do we use C for device driver development rather than C#?

Answer: Because C# programs cannot run in kernel mode (Ring 0).