Question:
The below code snippet is used to convert a string to lower case.

```
int main()
{
    unsigned char s[] = "AbS.d_";

    tolower(s);
    printf("%s\n", s);

    return 0;
}
```

I am getting theoutputas:

```
AbS.d_
```

Why the string is not being converted?

Answer:
tolowertakes int and return lowered int.

This should work:

```
int i=0;
for(i=0; s[i]; i++)
{
    s[i]=tolower(s[i]);
}
```


Question:
I am currently working on a embedded C project and I "inherited" some old code containing statements such as:

```
rxStruct = rxStruct;
```

where rxStruct is a variable.

What could be the use of such statements?

Answer: Without further information, one use of such a statement is to prevent an unused parameter compiler warning ifrxStructis passed in as a parameter and then otherwise not used.


Question:
The below code snippet is used to convert a string to lower case.

```
int main()
{
    unsigned char s[] = "AbS.d_";

    tolower(s);
    printf("%s\n", s);

    return 0;
}
```

I am getting theoutputas:

```
AbS.d_
```

Why the string is not being converted?

Answer:
tolowertakes int and return lowered int.

This should work:

```
int i=0;
for(i=0; s[i]; i++)
{
    s[i]=tolower(s[i]);
}
```


Question:
I am currently working on a embedded C project and I "inherited" some old code containing statements such as:

```
rxStruct = rxStruct;
```

where rxStruct is a variable.

What could be the use of such statements?

Answer: Without further information, one use of such a statement is to prevent an unused parameter compiler warning ifrxStructis passed in as a parameter and then otherwise not used.


Question:
I defined a static struct in C like this:

```
typedef static struct {
    int a;
    int b;
} Hello;
```

Do I need to initiate the struct before I use it? How to access the variable inside of it?

Answer:
You need to define the struct first, then instantiate it in a static variable

```
typedef struct {
  int a;
  int b;
} Hello;

static Hello hello;
```

Then you can access your data like this :

```
hello.a = 42;
```


Question:
I don't know what the compilar is doing with++*p;

Can anyone explain me pictorically what is going on inside the memory in this code?

```
int main()
{
    int arr[]={1,2,3,4};
    int *p;
    p=arr;
    ++*p;
    printf("%d",*p);
}
```

Answer:
The answer should be 2

The reason is ++*p is is actually incrementing the first member in the array by 1.


Question:
I defined a static struct in C like this:

```
typedef static struct {
    int a;
    int b;
} Hello;
```

Do I need to initiate the struct before I use it? How to access the variable inside of it?

Answer:
You need to define the struct first, then instantiate it in a static variable

```
typedef struct {
  int a;
  int b;
} Hello;

static Hello hello;
```

Then you can access your data like this :

```
hello.a = 42;
```


Question:
I don't know what the compilar is doing with++*p;

Can anyone explain me pictorically what is going on inside the memory in this code?

```
int main()
{
    int arr[]={1,2,3,4};
    int *p;
    p=arr;
    ++*p;
    printf("%d",*p);
}
```

Answer:
The answer should be 2

The reason is ++*p is is actually incrementing the first member in the array by 1.


Question: How should i create my own Events (This includes the code to bind the necessary callback) in c/C++ programming? It is directly available in Java.

Answer: There aren't built-in events in C++, but if you don't want to reimplement your own classes, tryboost signals.


Question: How should i create my own Events (This includes the code to bind the necessary callback) in c/C++ programming? It is directly available in Java.

Answer: There aren't built-in events in C++, but if you don't want to reimplement your own classes, tryboost signals.


Question:
```
bool somemethod(int number){
    return true;
}
```

I keep getting this error message when I try to compile code with this method

```
/Users/user/Desktop/test.c:14: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘somemethod’
```

Answer: Thing isboolisn't a true keyword in C. Includestdbool.hif you need it - this should work with C99 implementations.


Question: I just wanted to know that there is any free stack usage analyzer for C, something likehttp://www.absint.com/stackanalyzer/index.htm

Answer:
I think that gprof is a good tool.

http://www.cs.utah.edu/dept/old/texinfo/as/gprof.html


Question:
When I try to compile (on windows xp, with visual c++ 6.0) a c (NOT A C++) program which has the winusb.h header file, I get problems with c++ annotations (__in) like:

```
__in  HANDLE DeviceHandle,
```

What do I need to get this compiled in c?

Thanks alot in advance!

Answer:
Just ignore it (and the similar annoations):

```
#define __in
#define __out
#define __in_opt
```


Question: Functions likememPartInfoGet()requirePART_ID, in the manual it states thatmalloc()uses free lists of system memory partition. Is there a way to getstruct mem_part* PART_IDthat identifies with the system partition? To be able to use those functions?

Answer: memSysPartIdis what I was looking for.


Question:
Given this macro:

```
#define SOME_MACRO(ret, f, args) \
    typedef ret (*some_func_##f) args; \
    static some_func_##f my_func_##f = NULL;
```

Please let me know the equivalent for:

```
SOME_MACRO(void,  myFunctionName, (int a));
```

Thanks.

Answer:
You can use the-Eflag of gcc to see how the macro is expanded:

```
typedef void (*some_func_myFunctionName) (int a); static some_func_myFunctionName my_func_myFunctionName = ((void *)0);;
```


Question:
I have a question about enum variable in c++:

```
type enmu {
   DAY1 = 1,
   DAY2,
   DAY3,
   DAY4
} DAYS;

void main() {
   DAYS days;
}
```

then what is the default value of days?

Answer:
It's uninitialized andundefined behaviorto read the value.

Just like saying

```
int x;
```

xdoesn't have a value until you initialize it.


Question:
How to return 1000 variables from a function in C?This is an interview question asked which I was unable to answer.

I guess with the help of pointers we can do that. I am new to pointers and C can anyone give me solution to solve this problem either using pointers or different approach?

Answer:
Pack them all in a structure and return the structure.

```
struct YourStructure
{
    int a1;
    int b2;

    int z1000;
};

YouStructure doSomething();
```


Question:
I saw this code inthis .c file.

```
struct node {
  Item data;
  struct node *next;
};

struct stack_type {
  struct node *top;
};
```

What are the benefits of creating two structs when one would do?

Answer: It may make the code clearer to distinguish between the whole stack and a single node.


Question:
We have

```
int main(int argc, char** argv, char** envc)
```

for the ordinary. but I want to know if there is any other argument main can have instead of these. And if there is any, what does it point to?

Answer:
Well, heres the breakdown:

argc-- C standardargv-- C standardenv-- Works on most UNIX and MS Win, but not standardapple-- Other information passed as forth argument by Mac OSX and Darwin


Question:
Suppose a program has memory leaks.

1) When a process dies (normally or segmentation fault), are those leaked memory freed?

2) What aboutother resourcesa process holds?

Answer: With most modern operating systems (linux, windows from around NT 3.5), yes.


Question:
How do you initialize special ASCII chars, for example EOT (0x04), ENQ(0x05)?

```
char CHAR1 = '\EOT';
char CHAR2 = '\ENQ';
```

Is this correct?

Answer:
You can put character code into the variable:

```
char CHAR1 = 4;
char CHAR2 = 5;
```

You can also use escape sequences which you'll findhere.


Question:
I saw this code inthis .c file.

```
struct node {
  Item data;
  struct node *next;
};

struct stack_type {
  struct node *top;
};
```

What are the benefits of creating two structs when one would do?

Answer: It may make the code clearer to distinguish between the whole stack and a single node.


Question:
We have

```
int main(int argc, char** argv, char** envc)
```

for the ordinary. but I want to know if there is any other argument main can have instead of these. And if there is any, what does it point to?

Answer:
Well, heres the breakdown:

argc-- C standardargv-- C standardenv-- Works on most UNIX and MS Win, but not standardapple-- Other information passed as forth argument by Mac OSX and Darwin


Question:
Suppose a program has memory leaks.

1) When a process dies (normally or segmentation fault), are those leaked memory freed?

2) What aboutother resourcesa process holds?

Answer: With most modern operating systems (linux, windows from around NT 3.5), yes.


Question:
How do you initialize special ASCII chars, for example EOT (0x04), ENQ(0x05)?

```
char CHAR1 = '\EOT';
char CHAR2 = '\ENQ';
```

Is this correct?

Answer:
You can put character code into the variable:

```
char CHAR1 = 4;
char CHAR2 = 5;
```

You can also use escape sequences which you'll findhere.


Question:
Suppose a program has memory leaks.

1) When a process dies (normally or segmentation fault), are those leaked memory freed?

2) What aboutother resourcesa process holds?

Answer: With most modern operating systems (linux, windows from around NT 3.5), yes.


Question:
How do you initialize special ASCII chars, for example EOT (0x04), ENQ(0x05)?

```
char CHAR1 = '\EOT';
char CHAR2 = '\ENQ';
```

Is this correct?

Answer:
You can put character code into the variable:

```
char CHAR1 = 4;
char CHAR2 = 5;
```

You can also use escape sequences which you'll findhere.


Question:
Saw this in an answer to another question:

```
char (*arrs)[rowSize] = malloc(bytesPerTable);
```

What is arrs? / why are there parentheses / what is the description of this declaration?

Answer:
What is arrs ? what is the description of this declaration?

It's a pointer to an array ofrowSizechars, vastly different from a pointer to achar.

why are there parentheses

Because without them it would be an array of pointers tochar.


Question:
When I do something like:

```
./foo -uxw --bar something
```

Does the shell automatically parse these commands, or does each program have to do the parsing itself?

Answer: Each program parses its arguments. You'll probably want to look intogetoptfor that so the answer becomes:each program usually relies ongetoptto parse arguments.


Question:
Here's what I have:

```
#define STRING "string 1"

string string2 = STRING + "string3";
```

This is wrong. What is the solution? Is the problem thatstring2must be constant or what else, and why?

Answer:
```
#define STRING "string 1"

std::string string2 = STRING "string3";
```

Concatenation of adjacent string litterals isn't a feature of the preprocessor, it is a feature of the C/C++


Question:
I have a C program.

```
int main ()
{
    if (getchar()!=EOF)
        puts("Got a character");
    else
        puts("EOF");
}
```

What should I type into the stdin on the terminal to produce an EOF?

Answer: In Windows,Control+Zis the typical keyboard shortcut to mean "end of file", in Linux and Unix it's typicallyControl+D.


Question: Do I just usefree()function to free the pointer, or some specific API?

Answer: Sincereadahead()populates the page cache, memory is handled by the kernel. You don't do anything.


Question:
How do I initialize a new line char in C?

For example, to initialize char A:

```
char letter = 'A';
```

How to initialize new line? Like this maybe:

```
char newLine = '0x0A'?
```

Answer:
Use an escape character like this:

```
char letter = '\n';
```


Question: Do I just usefree()function to free the pointer, or some specific API?

Answer: Sincereadahead()populates the page cache, memory is handled by the kernel. You don't do anything.


Question:
How do I initialize a new line char in C?

For example, to initialize char A:

```
char letter = 'A';
```

How to initialize new line? Like this maybe:

```
char newLine = '0x0A'?
```

Answer:
Use an escape character like this:

```
char letter = '\n';
```


Question:
Is there a way to dynamically load compiled c-code in a linux-kernel-module at run-time?
I am looking for something likedlopenfromlibdl.

Answer: Yes. Move the code into another modules and then create a dependency to that other module in yours.


Question:
```
struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
                 __be32 daddr, __be16 dport, int dif)
```

Here is declaration of function, that converts connection attributes tostruct sock.
As I googled, first argument should be&init_net. But what should be last argument?

Answer: Thedifargument is the device interface.


Question:
There must be something I'm misunderstanding, why does this not return 10?

```
int main() {

    float i = 0;
    func(i);
    printf("%f", i);

    return 0;
}

void func(float i) {

    int j;
    for (j = 0; j < 5; j++) {

         i += 2;
    }
}
```

Answer: Primitive types (like floats) are "passed by value", func() is really modifying a copy of i.


Question: Does autotools comes out of box for all the major unix systems? I am looking for something that can compile the code without installing any additional software and platform independent(UNIX flavors and Architecture).

Answer:
If you use autotools correctly, the end result is a scriptconfigureso that

```
configure
 make
 make install
```

works -- and yes, the very point of autotools is that this should work just about everywhere.


Question: I'm dealing with win32 api subclass. My issue is I don't know my subclass procedure is running on a dialog or a "normal window". Can anyone tell me how can I determine current window is a dialog or a normal window?

Answer: Check the name of the window class. There is no formal documented way of determining this other than that.


Question:
Is there a way to dynamically load compiled c-code in a linux-kernel-module at run-time?
I am looking for something likedlopenfromlibdl.

Answer: Yes. Move the code into another modules and then create a dependency to that other module in yours.


Question:
```
struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
                 __be32 daddr, __be16 dport, int dif)
```

Here is declaration of function, that converts connection attributes tostruct sock.
As I googled, first argument should be&init_net. But what should be last argument?

Answer: Thedifargument is the device interface.


Question:
There must be something I'm misunderstanding, why does this not return 10?

```
int main() {

    float i = 0;
    func(i);
    printf("%f", i);

    return 0;
}

void func(float i) {

    int j;
    for (j = 0; j < 5; j++) {

         i += 2;
    }
}
```

Answer: Primitive types (like floats) are "passed by value", func() is really modifying a copy of i.


Question: How can I get the PID of the user process which triggered my Kernel module'sfile_operation.readroutine (i.e., which process is reading/dev/mydev) ?

Answer: When your read function is executing, it's doing so in the context of the process that issued the system call. You should thus pe able to usecurrent, i.e.current->pid.


Question:
Is it possible to do these things from a nativeCorC++-compiled program (gcc):

Callclangand compile givenCcode of a function, passed asconst char *.Obtain a pointer and run it in the LLVM virtual machine.Acquire the result in the native program and continue.

How?

Answer:
For a minimalistic example, seeClang interpreter.

Clingis bit more practical example of such an approach.


Question:
How does the initialization happen in cases 2, 3, 4, 5 below. 1 will contain garbage.

```
char x[16];
char x[16] = {0};
char x[16] = {0, };
char x[16] = {1};
char x[16] = {1, };
```

Answer: If you use the brace initializer syntax with arrays, any additional elements not mentioned in the initializer list are initialized with zeros.


Question: I have to create an array of char pointers each of them of size 10000000 using the best and optimized way to do this in C.

Answer:
I think this will do (haven't checked for nulls though):

```
int i;
int num_arrays;
char **huge_char_array;
num_arrays = 10; //number of arrays you want.
huge_char_array = (char **)malloc(sizeof(char *) * num_arrays);
for(i = 0; i < num_arrays; i++)
{
    huge_char_array[i] = (char *)malloc(sizeof(char) * 10000000);
}
```


Question:
May be it is one of the simplest things for C programmers but I really can't get it.

```
unsigned char Value[4];
unsigned long ulVer = 00010001;
unsigned long uSize = sizeof(ulVer);
memcpy(Value, &ulVer, uSize);
memcpy(&ulVer, Value, uSize);
printf("%d",ulVer);
```

Why ulVer is 4097, not 10001 ?

Answer:
00010001;  is an octal constant because it starts with 0.
You need to write 10001 if that's what you want in decimal.


Question:
May be it is one of the simplest things for C programmers but I really can't get it.

```
unsigned char Value[4];
unsigned long ulVer = 00010001;
unsigned long uSize = sizeof(ulVer);
memcpy(Value, &ulVer, uSize);
memcpy(&ulVer, Value, uSize);
printf("%d",ulVer);
```

Why ulVer is 4097, not 10001 ?

Answer:
00010001;  is an octal constant because it starts with 0.
You need to write 10001 if that's what you want in decimal.


Question: This is just a quick question. As I understand it, code from a static library is included directly, at compile time, into a .exe... so if I have some Library code running in a program, is it correct to say that the current directory as far as that code is concerned is the same as that of the .exe's, regardless of where the .lib is?

Answer: It doesn't matter where the lib is, even if it is dynamically linked.


Question:
In some C-source file I've seen comments in the format:

```
/**
 *  @bla bla bla
 *  bla bla..
 */
```

Someone told me that if I comment my.c/.hfiles properly, then with a certain tool I can autogenerate man pages from those files automatically.

Does anybody know if this is possible? (How to do, which software should I use, etc.)

Answer: It looks like you are searching fordoxygen


Question:
dois a keyword in C and all I have seen is that it is only used withwhile. So my question is candobe used alone withoutwhile.

If yes how?

Answer:
No. It cannot.

To be more precise, this is what theC standardhas to say:

6.8.5 Iteration statementsSyntaxiteration-statement:while ( expression ) statementdo statement while ( expression ) ;for ( expressionopt ; expressionopt ; expressionopt ) statementfor ( declaration expressionopt ; expressionopt ) statement


Question: should we useperrorinside signal handler because they have a user space buffer likeprintfand other stdio functions?

Answer: perroris not listed in the table of async-signal-safe functions (e.g.,section 2.4.3 Signal Actions) so it is not safe to call from a signal handler that may be invoked in response to a signal interrupting a non-async-signal-safe function.


Question:
How do I printf integers? When I use:

```
int n = GetInt();

printf("%n \n", n);
```

I get the error that there was an unused variable and I can't compile it.

Answer:
A signed integer uses%d(or%i).

See alsoman 3 printf(on Unix-like systems) for the whole list of modifiers.


Question:
For example, in a linux-machine there are so many process.
Each one is able to use a syscall, but usually few are used.
Well, there is a tool or a manner to show when a syscall is used and which is the process associated?

Answer:
You can use various tools, likestrace,ltraceand many other, although I'm not sure you want to trace all processes at the same time.

Normally you'd attach to one process of interest and follow its system calls.


Question:
I would like to declare an array in kernel module and to access it within a userspace app. how can I do it?

How do I memory map it for using via userspace so it can be used by a user?

Answer: You will most likely need to implement a character device. Then in your instance ofstruct file_operationsimplement themmap function.


Question:
Following is line of code in c.

```
i++=i++;
```

Output:Error Lvalue required.So what does this error indicate?

Answer:
The result ofi++is not a lvalue and the standard requires the left operand of the assignment operator to be a lvalue.

Even if it was allowed your program would invoke undefined behavior as you are trying to modify the same object twice between two sequence points.


Question:
For example, in a linux-machine there are so many process.
Each one is able to use a syscall, but usually few are used.
Well, there is a tool or a manner to show when a syscall is used and which is the process associated?

Answer:
You can use various tools, likestrace,ltraceand many other, although I'm not sure you want to trace all processes at the same time.

Normally you'd attach to one process of interest and follow its system calls.


Question:
I would like to declare an array in kernel module and to access it within a userspace app. how can I do it?

How do I memory map it for using via userspace so it can be used by a user?

Answer: You will most likely need to implement a character device. Then in your instance ofstruct file_operationsimplement themmap function.


Question:
Following is line of code in c.

```
i++=i++;
```

Output:Error Lvalue required.So what does this error indicate?

Answer:
The result ofi++is not a lvalue and the standard requires the left operand of the assignment operator to be a lvalue.

Even if it was allowed your program would invoke undefined behavior as you are trying to modify the same object twice between two sequence points.


Question:
There is a way to monitor directories for changes like FileSystemWatcher but in C?

NOTE: I (have to) use gcc.

Answer: SeeFindFirstChangeNotificationorReadDirectoryChangesW.


Question:
There is a way to monitor directories for changes like FileSystemWatcher but in C?

NOTE: I (have to) use gcc.

Answer: SeeFindFirstChangeNotificationorReadDirectoryChangesW.


Question:
I would like to create a group in Windows, and I've found the next reference but I don't know if I'm on the right path:

http://msdn.microsoft.com/en-us/library/aa374177.aspx

Answer: No. The right way is using aNet* functions family.In your case to create a new windows user group you have to use aNetGroupAddfunction.


Question: Can someone please explain why I should use strstr or string find() ? Which one is faster, at where ?

Answer: In C++ you should use std::string::find(), in C you should use strstr(). The difference in performance should not be significant.


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

int main()
{
int i;
string A[]={"Ahmet", "Mehmet", "Bulent", "Fuat"};

for(i=0;i<=3;i++){
printf("%s",A[i]);
}
return 0;
}
```

How can i see my array's elements as output?

Compiler says "'string' undeclared".

Answer:
This way:

```
char *A[] = {"Ahmet", "Mehmet", "Bülent", "Fuat"};
```

Ais an array of pointers tochar.


Question:
In C/C++

How can I read from serial port, without removing the info I have already read from the buffer?

I want to do something like the Peek function of arduino (http://arduino.cc/en/Serial/Peek) in a linux machine.

Answer: The serial port is accessed as though it is a file using a file descriptor so afgetc ungetcmethod should work.


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

Possible Duplicate:C -> sizeof string is always 8

If I dosizeof("HELLO");I get 6, which is expected, however if I have:

```
void printLength(char *s) {
    sizeof(s);
}
```

When passing "Hello" to to this functionsizeofreturns 8.

Why is this?

Answer: What you are getting is size ofchar *. To get it's actual length, usestrlen.


Question: I am compiling code withclangwith -O4 optimization. However, I want to disable inlining of functions. I have my own LLVM pass that injects some code to the generated code. After my pass, I want to enable the inlining of functions. How can I do that.

Answer:
You can use opt whichsaysit can run passes in any order.

```
clang -c main.cpp -O0 -emit-llvm | opt -load yourplugin -yourpass -inline
```


Question:
I have fixed an error in my code, but every time I callndk-buildthe same error is STILL there. I have calledndk-build cleanfifteen times at least, but I have had no luck. I have gone into my project and deleted my.o files. What should I do?

Notice the spelling ofinitilized/initialized:

Answer: In Eclipse, menuWindow->project->Clean.


Question:
Could someone help me by telling what is the Visual C equivalent of fseeko, fseeko64; ftello, ftello64?

Thanks :)

Answer:
There are no functions that returns/use off_t, if you need a 64bit position you can use:
_fseeki64
_ftelli64


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

Possible Duplicate:C -> sizeof string is always 8

If I dosizeof("HELLO");I get 6, which is expected, however if I have:

```
void printLength(char *s) {
    sizeof(s);
}
```

When passing "Hello" to to this functionsizeofreturns 8.

Why is this?

Answer: What you are getting is size ofchar *. To get it's actual length, usestrlen.


Question: I am compiling code withclangwith -O4 optimization. However, I want to disable inlining of functions. I have my own LLVM pass that injects some code to the generated code. After my pass, I want to enable the inlining of functions. How can I do that.

Answer:
You can use opt whichsaysit can run passes in any order.

```
clang -c main.cpp -O0 -emit-llvm | opt -load yourplugin -yourpass -inline
```


Question:
I have fixed an error in my code, but every time I callndk-buildthe same error is STILL there. I have calledndk-build cleanfifteen times at least, but I have had no luck. I have gone into my project and deleted my.o files. What should I do?

Notice the spelling ofinitilized/initialized:

Answer: In Eclipse, menuWindow->project->Clean.


Question:
Could someone help me by telling what is the Visual C equivalent of fseeko, fseeko64; ftello, ftello64?

Thanks :)

Answer:
There are no functions that returns/use off_t, if you need a 64bit position you can use:
_fseeki64
_ftelli64


Question:
I have a C program which contains#include <dos.h>header. It shows a compile time error. I know that thedos.hheader file is not valid in Linux.

Is there any other equivalent header fordos.hin Linux?

Answer: dos.h header file is interface to the DOS operating system. They are not portable to operating systems other than DOS (means not works in Linux). Which functionality in dos.h you are going to use?


Question: Is there a canonical way to check the size of a file in Windows?  Googling brings me bothFindFirstFileandGetFileSizeExbut no clear winner. And must GetLastError always be called too?

Answer: If you just want the size, theGetFileSizeExis the clear winner. Yes,FindFirstFilewill do the job too, but it's really intended for other purposes, and unless you need to do those other things, its use is likely to mislead or confuse the reader.


Question: Is there a canonical way to check the size of a file in Windows?  Googling brings me bothFindFirstFileandGetFileSizeExbut no clear winner. And must GetLastError always be called too?

Answer: If you just want the size, theGetFileSizeExis the clear winner. Yes,FindFirstFilewill do the job too, but it's really intended for other purposes, and unless you need to do those other things, its use is likely to mislead or confuse the reader.


Question: In C, when is it preferrable to use one over the other?

Answer:
It is really a matter of style and of coding conventions, since in Cp[i]isdefinedto be the same as*(p+i)wherepis a pointer andian integral index. AFAIK you could even writei[p]but that is ugly.

This is not always true in C++ (which gives you the power of definingoperator []etc...).

I personally dislike hand-coding&p[i]and preferp+iin that case.


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

Possible Duplicate:how to printf uint64_t?

I want to printu_int64_tin C.
I want to know the format specifier for this?
I am a C user, I want to do aprintf().

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

uint64_t t = 42;
printf("%" PRIu64 "\n", t);
```


Question:
I try to use CFLocaleCopyCurrent under OSX 10.5.8 but I get weird error:

```
#include <CoreFoundation/CoreFoundation.h>

int main(int argc, char **argv){
    setlocale(LC_ALL, "");
    CFLocaleRef loc = CFLocaleCopyCurrent();
    return 0;
}

Undefined symbols:
"_CFLocaleCopyCurrent", referenced from: _main in ccn51XwH.o
```

Answer: try/usr/bin/gcc -framework Foundation test.c


Question: I want to share memory between two processes. One way I know is tommapa shared file. However, I don't want to use a shared file, I want an anonymous mapping in the memory. How can I do that.

Answer: shm_openis your friend. You can unmap the shared region by usingshm_unlink.


Question:
I try to use CFLocaleCopyCurrent under OSX 10.5.8 but I get weird error:

```
#include <CoreFoundation/CoreFoundation.h>

int main(int argc, char **argv){
    setlocale(LC_ALL, "");
    CFLocaleRef loc = CFLocaleCopyCurrent();
    return 0;
}

Undefined symbols:
"_CFLocaleCopyCurrent", referenced from: _main in ccn51XwH.o
```

Answer: try/usr/bin/gcc -framework Foundation test.c


Question: I want to share memory between two processes. One way I know is tommapa shared file. However, I don't want to use a shared file, I want an anonymous mapping in the memory. How can I do that.

Answer: shm_openis your friend. You can unmap the shared region by usingshm_unlink.


Question:
```
#include<stdio.h>
int main(){
 char a[3];
 char *b=NULL;
 a[0]=0;
 a[1]=1;
 a[2]=2;
 b = a;
 printf("%c",b);
 b++;
 printf("%c",b);
 b++;
 printf("%c",b);
 return 0;
}
```

I tried to print the values 0,1,2 by incrementing the pointer by 1. please help

Answer:
b is a pointer in itself, you have to dereference it to get the actual values:

```
printf("%d", *b);
b++;
printf("%d", *b);
b++;
```

etc.


Question:
Anybody knows where is a list of the AVERROR meanings? Something like

```
-1: reason A
-2: reason B
```

and so forth?

Answer:
You can useav_strerror()to get a string representation of the error code.

If you simply want to look it up, you can refer to the docs forlibavutil/error.candlibavutil/error.h.


Question:
I have the following issues when trying to compile thelibtheoraplayerdemo (av_player demo).

If someone can help me out with some errors from libtheoraplayer (), I would be really grateful.

Answer:
If you are familiar with linux then check the vlc source code it is free
but it is C  code.

it may be help to you.

Thanks.


Question:
The problem is that the same code that compiles well on Windows, is unable to compile onUbuntu. Every time I get this error:

cc1: warnings being treated as errors

Now, it's big code base and I don't like fix all the warnings.

Is there a way I can compile successfully in spite of the warnings?

Answer: Sure, find where-Werroris set and remove that flag. Then warnings will be only warnings.


Question:
I have the following issues when trying to compile thelibtheoraplayerdemo (av_player demo).

If someone can help me out with some errors from libtheoraplayer (), I would be really grateful.

Answer:
If you are familiar with linux then check the vlc source code it is free
but it is C  code.

it may be help to you.

Thanks.


Question:
The problem is that the same code that compiles well on Windows, is unable to compile onUbuntu. Every time I get this error:

cc1: warnings being treated as errors

Now, it's big code base and I don't like fix all the warnings.

Is there a way I can compile successfully in spite of the warnings?

Answer: Sure, find where-Werroris set and remove that flag. Then warnings will be only warnings.


Question:
I am writing a c++ application and trying to cross compile for arm:
    sudo apt-get install gcc-4.4-arm-linux-gnueabi

However in the /usr/arm-linux-gnueabi/include directory I find no c++ directory. Can someone tell me where to find it?

Answer:
Install C++ compiler:

```
sudo apt-get install g++-4.4-arm-linux-gnueabi
```


Question:
I know that its possible to call functions in the native code from the java code, but what about vice-versa?

Is it possible for me to call a Java function from the native C code?

Answer: Yes! You are interested in theJava Native Interface.


Question:
```
int main(void)
{
  int x;
  float y;

  x=10;
  y=4.0;

  printf("%d\n",x/y);

  return 0;
}
```

I compiled this code using a gcc compiler and when run I get 0 as output.Why is this code giving output as 0 instead of 2?

Answer:
IT's not the division, it's the print format.

Change:

```
printf("%d\n",x/y);
```

to:

```
printf("%f\n",x/y);
```


Question:
in C# I would just do:

```
private long[] myMethodName()
{
    //etc
}
```

What is the equivalent in C?

This gives an error:

```
long[] readSeqFile(char *fileName)
```

Answer:
Typically for C you would pass a pointer and length

```
// returns number of elements written
size_t myMethodName(long* dest, size_t len)
{
    //etc
}
```


Question:
Given the below declaration for pcap callback:

```
void my_callback(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
```

How to ascertain the total number of bytes present in the packet? I need that value so that I can pass it to crc32() function.

Answer: according tothis referencethe information about the size of the packet is in thepcap_pkthdr's structure


Question:
I am creating a decompiler from IL (Compiled C#\VB code). Is there any way to create reference in C?

Edit:I want something faster than pointer like stack. Is there a thing like that?

Answer: A reference is just a syntactically sugar-coated pointer–a pointer will do just fine.


Question:
I thought the result would be(2**32 - 1)

```
#include <stdio.h>
int main(){
  unsigned int a = 0xffffffff;
  printf("the size of int a %d\n",a);
  return 0;
}
```

but it gives me-1, any idea?

Answer:
You're using the wrong format string.%dis a signed decimal int. You should use%u.

printfhas no knowledge of the types of variables you pass it. It's up to you to choose the right format strings.


Question:
I want to define a macro accepting either 1 or 2 parameters. Both the parameters should be different type. How to use ellipsis and read the arguments passed?

Below is the sample:

```
void test(char *var2)
{
 printf("%s\n",var2);
}

#define PRINT_STRING(...) ( if (!var1) test(var2) )

int main(int argc, _TCHAR argv[]) {

PRINT_STRING(TRUE);
PRINT_STRING(FALSE,"Hello, World!");
return 0;
}
```

Answer: This is known as aVariadic macro.


Question: A certain parameter has3possible values, and there arensuch parameters with 3 values each. Need to create scenarios by randomly changing them and save each scenario as a text file, without any duplicated scenarios.

Answer: Count from 0 to 3n-1, and convert your number to an n-digit base-3 number (including leading zeros). Each digit in the result represents the value for one parameter.


Question: There is the well-knownJoint Strike Fighter(JSF) standard for C++. Is there a similar standard for C which promotes the use of C programmers' quality when coding for mission-critical platform?

Answer:
There isMISRA Cby the Motor Industry Software Reliability Association:

MISRA-C:2004,Guidelines for the use of the C language in critical systems


Question: I need to convert a char * string of 3 characters ("123") to a float with two decimal places(1.23).

Answer:
You can use atoi, which will convert ASCII to Integer.  Then convert that int to a float.

```
int num = atoi(string);
float f = num/100.0f;
printf ("%.2f", f);
```


Question: I need to convert a char * string of 3 characters ("123") to a float with two decimal places(1.23).

Answer:
You can use atoi, which will convert ASCII to Integer.  Then convert that int to a float.

```
int num = atoi(string);
float f = num/100.0f;
printf ("%.2f", f);
```


Question: I want to have a function in C language file which can return string as output and I want to access that function from Managed Code i.e C# and get that string as return value. Any help or links related to this would be great for me.

Answer: Is this a method in a common library, or a custom library? The more common ones can be found onpinvoke.net. If not, MSDN has an article onPlatform InvokingusingDllImportthat may be useful.


Question:
```
void foo(const gchar *a, ...)
{
    do_something();
}
```

What does the...mean?

Does it only work with glib?

Answer: It isvariable-length argument listwhich allows a function to have flexible number of arguments. It's part of the Standard. So it works everywhere that standard C is supported (or this feature itself is supported), not just glib.


Question: For large files or other files that are not necessarily text, how can i compress them and what are the most efficient methods to check for data corruption? any tutorials on these kinds of algorithms would be greatly appreciated.

Answer:
For compression, LZO should be helpful. Easy to use and library easily available.
For data corruption check, CRC cahttp://cppgm.blogspot.in/2008/10/calculation-of-crc.html


Question: How I can convert Java Object into C struct? I know that I can translate the data with XML but I need more quick and easy way to do this? What are the possible solutions?

Answer:
Data serialisation is the buzz word here.

For a quiet impressive list of techniques you might like to read here:http://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats


Question:
Maybe I am misunderstanding the use of theP99library but what advantages does it provide over C11 (mainly concerned about multithreading) if anything more than being an emulator.

Speed?
Efficiency?

Or just backwards compat?

Answer: The main advantage it provides over C11 is that it works with C99 compilers.  C11 support doesn't really exist yet.  It also provides many features that aren't in C11.


Question: For large files or other files that are not necessarily text, how can i compress them and what are the most efficient methods to check for data corruption? any tutorials on these kinds of algorithms would be greatly appreciated.

Answer:
For compression, LZO should be helpful. Easy to use and library easily available.
For data corruption check, CRC cahttp://cppgm.blogspot.in/2008/10/calculation-of-crc.html


Question: How I can convert Java Object into C struct? I know that I can translate the data with XML but I need more quick and easy way to do this? What are the possible solutions?

Answer:
Data serialisation is the buzz word here.

For a quiet impressive list of techniques you might like to read here:http://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats


Question:
I have an embedded board (beagleboard-xm) that runs ubuntu 12.04, I would like to read one GPIO input if it is logic 1 or 0. How can I implementcat /sys/class/gpio/gpio139/valuein C? (valuefile stores 0 or 1)I open the file by:

```
FILE *fp;
fp = fopen("/sys/class/gpio/gpio139/value", "rb");
```

what do I need to do next?

Answer:
If you want to read one character, try this:

```
int value = fgetc(fp);
/* error checking */
value = value - '0';
```


Question:
I'm using Qt creator 2.4. I need to use a string sayhi"world"in my code. I have tried to useQstringandstd::stringand I know/is the escape sequence character but the IDE doesn't understand it as an escape sequence and gives errors when I write:

```
"hi/"world/""
```

I can use any string format that can be converted intoQstring. Any ideas what I'm doing wrong?

Answer:
Use it like this:

```
QString output = "Hi \"world\"!";
```


Question: What's the best practice for exiting C code on discovery of an error back to R? Package guidance says don't useexit(), which makes sense (as you kill everything), but how do you exit to R and indicate an error has occurred. Obviously you could have an error flag in the return vector, but is there a better way?

Answer: You're looking forerror().  It's described inSection 6.2ofWriting R Extensions... and you should listen to your subconscious more often. ;-)


Question: I know that there is a flag that can be used in makefile to include a header file in all the files which are being compiled, just like there is a -D flag to include a define. What flag is exactly for including header files. I don't remember know.

Answer:
In your compile command, you can use the-includeoption:

```
gcc -o main -include hello.h main.cpp
```


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

Possible Duplicate:Left shifting with a negative shift count

On a 16-bit compiler, why does32<<-3or32>>-1result in 0?
what is the major reason for such a behaviour

Answer:
From K&R:

The shift operators << and >> perform left and right shifts of their
left operand by the number of bit positions given by the right operand,
which must be non-negative


Question: I wrote a process explorer using C with GUI interface. I want to add a graph to show the CPU status. Which library or functions can help me to do that?

Answer: You can useCairo, it's a simple 2D graphics library written in C.


Question:
can anyone suggest a openCV method which extract connected components in a 8bit single  channel frame? is it cvBlobs suitable for this?
In addition to this i want to use it in C code.

Answer: It seems thatcvFindContoursfunction can help you.


Question: I've written several very helpful excel add-ins using VBA.  I'm using Excel for Mac 2011 Version 14.2.2 (120421).  I'd like to sell the add-ins via a web site.  Can I write the add-ins in Xcode or do I have to use C#?

Answer:
FromMicrosoft Support:

In Office 2011 for Mac, there is no concept of add-ins. So using Excel Add-In is not possible...

You'll need to use VBA or AppleScript to emulate the same behavior.


Question:
can anyone suggest a openCV method which extract connected components in a 8bit single  channel frame? is it cvBlobs suitable for this?
In addition to this i want to use it in C code.

Answer: It seems thatcvFindContoursfunction can help you.


Question:
The following C code returns a "segmentation fault" error. I do not understand why it does not return the value 20. What is my error?

```
#include <stdio.h>

int main()
{
    int* n;
    *n = 20;

    printf("%i\n",*n);

    return 0;

}
```

Answer:
You haven't allocated memory ton, so

```
*n = 20;
```

attempts to write unspecified memory.

Try

```
#include <stdlib.h>

int *n = malloc(sizeof *n);
/* use n */
free(n);
```


Question:
I am trying out a C/C++ program, I want to know how much memory i am using due to heap and some other data structures. So how can I find out the amount of memory used by my various data structures?

I think that malloc operator should be overridden but I am not sure about the same.I am working on Linux and on Netbeans 7.1.

Answer:
You can use memory profilers for c++ like Valgrind as recommended in similar questions.
seethis

For netbeans IDE look atthis.


Question:
The following C code returns a "segmentation fault" error. I do not understand why it does not return the value 20. What is my error?

```
#include <stdio.h>

int main()
{
    int* n;
    *n = 20;

    printf("%i\n",*n);

    return 0;

}
```

Answer:
You haven't allocated memory ton, so

```
*n = 20;
```

attempts to write unspecified memory.

Try

```
#include <stdlib.h>

int *n = malloc(sizeof *n);
/* use n */
free(n);
```


Question:
My scenario is as follows:(C++)

In char a[10],   the array a[] has elements (numbers) like '1','2','3' etc....

Say a[0] = '1';a[1] = '2';a[2] = '3';

Now a[] is storing 3 characters '1', '2' and '3'.I want to store this into an int as 123 (An integer 123).

How to achieve this in C++ ?

Answer:
a[3] = 0is a must. If your string isn't null-terminated, most methods won't work.

After that, it's a simplenumber = atoi(a)


Question: pthread_self()is to get your own thread id. It doesn't seem like you can get the thread id of the thread which spawned you unless it was given to you during spawning. Or is there a way?

Answer: No, all threads are equal in POSIX threads, there is no hierarchy. Even the thread that executesmainhas no special role and can be terminated without effecting the others.


Question:
in Linux kernel source code, I find below code:

```
h++;
    pending >>= 1;
```

It is part of__do_softirq(void). But what does ">>=" mean? Why isn't it ">>" as I remember?
Thanks!

Answer:
It simply does

```
pending = pending >>1;
```

In short it divides by 2 an unsigned int.

That's the same construct than+=,/=, etc.

It's not justpending >>1as you remember because that wouldn't store the result of the shift operation in the variable.


Question:
Using (I think) Visual basic / studio I want to make a bar to go at the top of my screen which would display a webpage.

Before I start trying to code it, is this concept possible (that the bar would dock at the top of the screen and other windows would change to fit around it.)

Thanks - Ryan

Answer: Sure, you would probably need to create it as a Windows Shell plugin.


Question:
How do I compile and executeRedis ziplist.cas individual executable ?

I want to execute ziplist.c main function ONLY.

Answer:
You can use the following command:

```
gcc -std=c99 -O2 -DZIPLIST_TEST_MAIN ziplist.c zmalloc.c util.c sds.c adlist.c
```

Note: it will use the default system allocator.


Question: pthread_self()is to get your own thread id. It doesn't seem like you can get the thread id of the thread which spawned you unless it was given to you during spawning. Or is there a way?

Answer: No, all threads are equal in POSIX threads, there is no hierarchy. Even the thread that executesmainhas no special role and can be terminated without effecting the others.


Question:
in Linux kernel source code, I find below code:

```
h++;
    pending >>= 1;
```

It is part of__do_softirq(void). But what does ">>=" mean? Why isn't it ">>" as I remember?
Thanks!

Answer:
It simply does

```
pending = pending >>1;
```

In short it divides by 2 an unsigned int.

That's the same construct than+=,/=, etc.

It's not justpending >>1as you remember because that wouldn't store the result of the shift operation in the variable.


Question:
Using (I think) Visual basic / studio I want to make a bar to go at the top of my screen which would display a webpage.

Before I start trying to code it, is this concept possible (that the bar would dock at the top of the screen and other windows would change to fit around it.)

Thanks - Ryan

Answer: Sure, you would probably need to create it as a Windows Shell plugin.


Question:
How do I compile and executeRedis ziplist.cas individual executable ?

I want to execute ziplist.c main function ONLY.

Answer:
You can use the following command:

```
gcc -std=c99 -O2 -DZIPLIST_TEST_MAIN ziplist.c zmalloc.c util.c sds.c adlist.c
```

Note: it will use the default system allocator.


Question:
I am using the GCC compiler but I want the to code the actually run after compilation. Is there a flag I can use for this? Right now I am just doing

```
gcc code.c
```

There is no code.exe being generated...

Answer: The file created by default is called a.out.  If you want to name it code.exe, the correct line should begcc -o code.exe code.c


Question:
I've an array of fixed size inC. There I might have any number (less than the array size) of useful element. Now I need only my useful element. So I'm thinking of using anend of arraymarker for integer array. First of all

a) Is this possible?

b) If possible, How?

Answer:
I would take a slightly different approach

```
struct IntArray
{
  int data[N];
  int size; // <-- use this to keep track of the size.
}
```


Question:
I am using the GCC compiler but I want the to code the actually run after compilation. Is there a flag I can use for this? Right now I am just doing

```
gcc code.c
```

There is no code.exe being generated...

Answer: The file created by default is called a.out.  If you want to name it code.exe, the correct line should begcc -o code.exe code.c


Question:
I've an array of fixed size inC. There I might have any number (less than the array size) of useful element. Now I need only my useful element. So I'm thinking of using anend of arraymarker for integer array. First of all

a) Is this possible?

b) If possible, How?

Answer:
I would take a slightly different approach

```
struct IntArray
{
  int data[N];
  int size; // <-- use this to keep track of the size.
}
```


Question:
I've an array of fixed size inC. There I might have any number (less than the array size) of useful element. Now I need only my useful element. So I'm thinking of using anend of arraymarker for integer array. First of all

a) Is this possible?

b) If possible, How?

Answer:
I would take a slightly different approach

```
struct IntArray
{
  int data[N];
  int size; // <-- use this to keep track of the size.
}
```


Question:
I am doing a CBIR system as an assignment.There are 100 .bmp files,but they have different size,how to re-size them to a same size?
Thanks.

Answer: Have a look at theCImg Library, it's quite easy to use. You can load your bitmap file then use one of theresizefunction.


Question:
I am confused about the evaluation time ofsizeofoperator.When does the sizeof operator get evaluated?

Does its evaluation time (compile-time or runtime) depend on the language (C? C++?)?

Can we usesizeofin case of objects created at runtime in C++?

Answer:
In almost all cases,sizeofis evaluated based on static type information (at compile-time, basically).

One exception (the only one, I think) is in the case of C99's variable-length arrays (VLAs).


Question:
Does the stack of a thread/process make seperate copy of static function/method or is it shared.if it is shared where it is kept/stored and how does the mechanism works in C.

Rgds,
Softy

Answer:
Static function is used to limit the scope of the function within file. As it is a function(code) it goes to text(code) segment.

You can understand in details from following article

http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory


Question:
Does the stack of a thread/process make seperate copy of static function/method or is it shared.if it is shared where it is kept/stored and how does the mechanism works in C.

Rgds,
Softy

Answer:
Static function is used to limit the scope of the function within file. As it is a function(code) it goes to text(code) segment.

You can understand in details from following article

http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory


Question:
How do I do the opposite of this:

```
while((*i2s) & (1<<19))
    usleep(10);
```

I want to keep sleeping while the 19th bit is 0.

Answer:
```
while(((*i2s) & (1<<19)) == 0)
    usleep(10);
```

of course.


Question: I'm sure others have already asked this, but is it possible to insert an element into the next available index of an array without using a for-loop to find that index first? Almost like a list.add() function but for arrays in C.

Answer: no, you will have to loop through the array.


Question:
Commands like sftp work in a way that it's not possible to pipe in user input (ex:password etc...)

Q1: How does sftp achieve this?
Q2: How do programs like expect get around this restriction?

Answer: Requires TTY to be connected for input.expect et al. allocate PTTYs to get around this.


Question:
I want to create a HTTP request from a specific port using C on a Linux machine.  There islibcurlbut I'm not sure if you can specify the interface.  Is it possible ?

Many thanks :).

Answer: Yes it is. Look into the optionsCURLOPT_INTERFACEandCURLOPT_LOCALPORT.


Question:
I can embed hexadecimal values in Python-Strings like this:\xe5abcdefghijklmnoqrstuvqxy\xfdz!\x18\xfejk

Is this possible with C?

Answer:
Yes, using the same notation.

```
printf("\x41\x42\x43\n");
```


Question:
I  have to multiply 2 large integer numbers, every one is 80+ digits.

What is the general approach for such kind of tasks?

Answer: You will have to use a large integer library.  There are some open source ones listed on Wikipedia's Arbitrary Precision arithmetic pagehere


Question:
```
char imei_temp[14] = {0, };

strcpy(imei_temp, "00000000000000");
```

According to my understanding this is valid code.

But Klocwork is saying Buffer overflow, array index of 'imei_temp' may be out of bounds. Array 'imei_temp' of size 14 may use index value(s) 0..14

Answer: It's a buffer overflow because your buffer is 14 bytes, but you are writing 15 bytes to it:  14 ascii "0"'s, and a null byte at the end.


Question:
I can embed hexadecimal values in Python-Strings like this:\xe5abcdefghijklmnoqrstuvqxy\xfdz!\x18\xfejk

Is this possible with C?

Answer:
Yes, using the same notation.

```
printf("\x41\x42\x43\n");
```


Question:
I  have to multiply 2 large integer numbers, every one is 80+ digits.

What is the general approach for such kind of tasks?

Answer: You will have to use a large integer library.  There are some open source ones listed on Wikipedia's Arbitrary Precision arithmetic pagehere


Question:
```
char imei_temp[14] = {0, };

strcpy(imei_temp, "00000000000000");
```

According to my understanding this is valid code.

But Klocwork is saying Buffer overflow, array index of 'imei_temp' may be out of bounds. Array 'imei_temp' of size 14 may use index value(s) 0..14

Answer: It's a buffer overflow because your buffer is 14 bytes, but you are writing 15 bytes to it:  14 ascii "0"'s, and a null byte at the end.


Question: I'm doing a project with a lot of calculation and i got an idea is throw pieces of work to GPU, but i wonder whether could we retrieve results from GLSL, if it is posible, how?

Answer:
GLSL does not provide outputs besides what is placed in the frame buffer.

To program a GPU and get results more conveniently, useCUDA(NVidia only) orOpenCL(cross-platform).


Question:
If I omit the operators from statement, something like this:while(foo)will the compiler turn it inwhile(foo != NULL || *foo != '\0' || foo != 0)orwhile(!foo)or something like this?

how to it is really done?

Answer:
while (condition)just checks forconditionbeing non-zero.

Therefore these two are equivalent:

```
while (foo)
while (foo != 0)
```


Question:
I have an array with a size that I dont know(mostly a size of a 10),
that most of it has 1's and 2's, but sometimes 3's and 4's...
I cant buble sort, because the order is importhan, but other then that, I can do everything

Thanks :)

Answer:
Iterate over the array until you hit your break condition.

While iterating (use thefororwhileloop), remember the highest value so far and compare against current.


Question: There is a file of 1 GB contains a single string of characters. As the string is very large it can't be loaded completely to memory. What is the best way to reverse this string?

Answer:
load blocks into memory, iterate through them in reverse while writing them out in order. pseudocode:

```
load_block(buffer, 4mb, end of file); // Load a 4mb block from the end
for (i = 4mb; i>=0; i--) {
    write(buffer[i],1); // Write it out in reverse
}
```


Question: i'm writing an app that needs a calculation support (Fun project). However, is there a way to enter input data to the interactive console in BC from C#, and then read the data from the console with C#? I have tried to use dllexport in the c source, but the code is confusing me.

Answer: The usual way to interact with prewritten console applications in c# is to useProcess.Startand then redirectStandardInputandStandardOutput.


Question:
Is there any control that can be used for drawing a diagram like this in winapi32 controles?

in not do you have any idea how can I draw one?

(something like this!)

Answer:
You will find third party chart control for the Windows APIs -http://www.gigasoft.com/graphinglibrary.htmlhttp://www.codeproject.com/Articles/14330/Custom-Control-Graph-and-Process-Bar

Or you can draw the line graph yourself using the GDI functionsLineToandMoveTo.


Question: i'm writing an app that needs a calculation support (Fun project). However, is there a way to enter input data to the interactive console in BC from C#, and then read the data from the console with C#? I have tried to use dllexport in the c source, but the code is confusing me.

Answer: The usual way to interact with prewritten console applications in c# is to useProcess.Startand then redirectStandardInputandStandardOutput.


Question:
Is there any control that can be used for drawing a diagram like this in winapi32 controles?

in not do you have any idea how can I draw one?

(something like this!)

Answer:
You will find third party chart control for the Windows APIs -http://www.gigasoft.com/graphinglibrary.htmlhttp://www.codeproject.com/Articles/14330/Custom-Control-Graph-and-Process-Bar

Or you can draw the line graph yourself using the GDI functionsLineToandMoveTo.


Question: Is there a function or any other way to calculate in C the logarithm of basex, wherexis an integer variable of my program?

Answer:
C doesn't provide functions to compute logarithms of any bases other thaneor10.

So just use math:

```
logarithm of x base b = log(x)/log(b)
```

If you'll be doing the logarithms over the same base repeatedly, you can precompute1/log(b).I wouldn't rely on the compiler being able to do this optimization for you.


Question:
Is there any way to clear parser buffers before callingYYACCEPTinyacc.

If i do not clear buffer it causes some problems when i callyyparsefor the second time.

Also note that I am using some global variables, so cannot use reentrant parser.

Thanks in advance !!

Answer: There sure is. Seethis sectionof the flex manual. Specifically, callYY_FLUSH_BUFFERbefore callingyyparse.


Question:
Will a thread stop if I send it SIGTSTP signal?  Or in other words will it behave like process on SIGTSTP and SIGCONT?

Thanks in advance.

Answer:
From `man 3p pthread_kill:

Note  that pthread_kill() only causes the signal to be handled in the context of the given thread;the signal action (termination or stopping) affects the process as a
         whole.

So I'd say that you will stop the whole process, not just the thread.


Question:
Doesa && (b = 5/a)assign5/atob(for nonzeroa)?

My friend says it doesn't, but I'm confused why it wouldn't.

Answer:
Your friend is wrong. For nonzeroa, the statementa && (b = 5/a)will assign the value5/atob.

Ifa == 0, then the conditional will short circuit and the assignment will not occur.


Question:
I would like to store all paths to headers in separate file. I'm going to generate file with paths dynamically, to avoid re-creating Makefile whenever paths change.
Is that possible?

Answer:
Yes, you can generate the file, let's call itpaths.inc, so it looks like, for example:

```
INCLUDEPATH=path1:path2
```

and then include the file in your mainMakefile

```
include paths.inc
```

and use the variable defined in it:${INCLUDEPATH}


Question:
What is the linux API to query the status of a thread, like thetop -Hcommand can do? I do not need portability, it just has to work on modern x86[_64] linux.

I do not want to only know if the thread is alive or terminated. I need to know if it's sleeping also.

Answer:
As far as I knowtopreads its information from/proc, on Linux at least.

Update: Fortop's sources you might like to read here:Procps - The /proc file system utilities


Question: The download page for cmake only shows a 32 bit installer for windows. Any idea how to install it on 64 windows systems.

Answer:
There is really no reason for a 64bit native CMake.  CMake is only building theconfiguration, so you can use it to build configurations for 64bit software, even with the 32bit version.

That being said, if you truly want a 64bit native version, you could always download the source and compile it.  There is no 64bit installer, however.


Question:
I have an array which is sorted in descending order, with no duplicates. Can I perform binary search on it using bsearch function in libc ? To do this, do I need to alter the compare function that I am passing to it ?

Thanks

Answer: Yes, you can usebsearch.  You will need to make sure yourcomparefunction agrees with the sort order of your array.  In your case that might mean logically inverting the normal ascending/equal/descending order.


Question: How can one tell, given avoid *pointer, what is the size of a block allocated on this given address (previously allocated usingmalloc; in Linux and Windows)? I hope both systems surely store this kind of information somewhere. That is, alternative ofmalloc_sizewhich exists on OSX/Darwin. Using gcc/mingw if it helps.

Answer: On Windows, things that use the MS CRT can use_msize, on Linux you could trymalloc_usable_size...


Question:
Under Windows I use MultiByteToWideChar(CP_ACP, ...) and WideCharToMultiByte(CP_UTF8, ...) for the conversion.

How do I do the same thing under OS X and Linux? I tried mbstowcs/wcstombs but the resulting char* is not UTF-8.

Answer: Look intoiconv(3). that's the api you want. You'll need-liconv.


Question:
if possible then how to return more than one value.
It can not be because of return is done through Accumulator in controller or CPU.

Is this is the correct reason?

Answer:
Because that's how the language is defined.  There is no fundamental reason; other languages can return multiple values (e.g. Matlab).

As a "workaround", you can return a struct that contains multiple fields.


Question: According to K&R C section 1.6, acharis a type of integer. So why do we need%c. And why can't we use%dfor everything?

Answer:
Because%dwill print the numeric character code of thechar:

```
printf("%d", 'a');
```

prints97(on an ASCII system), while

```
printf("%c", 'a');
```

printsa.


Question: What is the difference between_m256iand_m256dand_m256? andWhat is the difference between_m128iand_m128dand_m128?

Answer: Rule of thumb: anisuffix is used for allintegervector types,dis fordouble precisionfloating point vector types, and when there is no suffix it's forsingle precisionfloating point vector types.


Question:
Using Eclipse, working with (ANSI) C language, is there any way to view the values that pointers are pointing on from debug?

Thanks

Answer: I haven't used Eclipse in years, but isn't there a "watch" window, where you can add variables to watch? In that case you should be able to just put*pointerin there.


Question:
Under Windows I use MultiByteToWideChar(CP_ACP, ...) and WideCharToMultiByte(CP_UTF8, ...) for the conversion.

How do I do the same thing under OS X and Linux? I tried mbstowcs/wcstombs but the resulting char* is not UTF-8.

Answer: Look intoiconv(3). that's the api you want. You'll need-liconv.


Question:
if possible then how to return more than one value.
It can not be because of return is done through Accumulator in controller or CPU.

Is this is the correct reason?

Answer:
Because that's how the language is defined.  There is no fundamental reason; other languages can return multiple values (e.g. Matlab).

As a "workaround", you can return a struct that contains multiple fields.


Question: According to K&R C section 1.6, acharis a type of integer. So why do we need%c. And why can't we use%dfor everything?

Answer:
Because%dwill print the numeric character code of thechar:

```
printf("%d", 'a');
```

prints97(on an ASCII system), while

```
printf("%c", 'a');
```

printsa.


Question: What is the difference between_m256iand_m256dand_m256? andWhat is the difference between_m128iand_m128dand_m128?

Answer: Rule of thumb: anisuffix is used for allintegervector types,dis fordouble precisionfloating point vector types, and when there is no suffix it's forsingle precisionfloating point vector types.


Question:
Using Eclipse, working with (ANSI) C language, is there any way to view the values that pointers are pointing on from debug?

Thanks

Answer: I haven't used Eclipse in years, but isn't there a "watch" window, where you can add variables to watch? In that case you should be able to just put*pointerin there.


Question:
How can I dump all the global variables and the address offsets in my executable?

This is on os x, app developed with xcode compiled with gcc.

Thank you

Answer:
If Compiled to Mach-O

Either useotoolor thecctools.

If Compiled to ELF

You should be able to do this withobjdumpand/orreadelf.

I don't have a *nix system at hand here, butobjdump -s -j .datashould be getting you rather close enough.


Question:
Is there any way to know / warn if a global variable is uninitialized with gcc ?

I got it for local/ atomic variables “-Wuninitialized”

Answer: No!Global and static variables are initialized implicitly if your code doesn't do it explicitly as mandated by the C standard.In short, global and static variables are never left uninitialized.


Question: I understand how to create astructon the heap usingmalloc. Was looking for some documentation regarding creating astructin C on the stack but all docs. seem to talk about struct creation on heap only.

Answer:
The same way you declare any variable on the stack:

```
struct my_struct {...};

int main(int argc, char **argv)
{
    struct my_struct my_variable;     // Declare struct on stack
    .
    .
    .
}
```


Question:
Suppose I have the following structs:

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

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

how to check ifbis of typeBor ifbis of the typeA?

Answer: Do you mean at runtime, given avoid *that points to one or the other? Unfortunately, this is not possible; C doesn't have any kind of runtime type information mechanism.


Question: How can I get the current total allocated memory so far (in a Linux process inC/C++ (gcc))?

Answer: Try parsing/proc/self/mapsor/proc/$PID/maps. Look for a line marked[heap].


Question:
When I sendWM_SETREDRAWto disable redraw for a window, how do I "restore" the previous state when I'm done?

What's the proper way to send this message?

Answer: You can'trestore the previous state, as there is no way to access the current state. There is noWM_GETREDRAW. Once you are done you sendWM_SETREDRAWagain withTRUEas an argument this time, and if anyone else had set redraw toFALSEon an outer scope then well.. that's bad for them..


Question:
I have a number like this:int num = 36729;and I want to get the number of digits that compose the number (in this case 5 digits).

How can I do this?

Answer:
Use this formula:

```
if(num)
  return floor(log10(abs((double) num)) + 1);

return 1;
```


Question: Indouble (*foo)[2]what does the[2]represent? And how would I convert an array as such to an array of float* in C?

Answer:
```
double (*foo)[2]
```

foois a pointer to an array of twodoubleelements.

For example:

```
double bla[2];
double (*foo)[2] = &bla;
```


Question:
I have an array of int and i have to initialize this array with the value -1. For now i use this loop:

```
int i;
int myArray[10];

for(i = 0; i < 10; i++)
    myArray[i] = -1;
```

There are faster ways?

Answer:
The quickest way I know for the value-1(or0) ismemset:

```
int v[10];
memset(v, -1, 10 * sizeof(int));
```

Anyway you can optimize the loop in this way:

```
int i;
for(i = 10; i--;)
    v[i] = -1;
```


Question:
I have to write a C program to convert XML file to WBXML format, without using external conversion library. Is it possible?

I have created the XML file in C and now want to convert it into WBXML file.

Answer:
You want to know if it is possible? - Yes.

You want to know how? - check the implementation of one of theexternal libraries. I'm sure you can get an idea if you browse the source code.


Question: I often see something likeattributein error messages. What is this? Are there any similar things like thisattribute? Can anyone give me a detailed explanation?

Answer:
It is aGCC extensionwhich allows a developer to attach characteristics to function declarations to allow the compiler to perform more error checking.

Detailed Explanation also foundhereandhere. A set of GCC extensions for C can be foundhere.


Question:
How do I get the key codes so I can process arrow, pageUp, pageDown, etc, keys using simple C or C++?

I can get the regular keys, I do not know how to get these special keys.

Answer: Ncurses should be able to handle that. There is lots of tutorials out there


Question: When I attach gdb to a process that uses many source files, such as PHP, sometimes I want to set a breakpoint on line x of file y. How do I specify the file for gdb?

Answer:
It's as simple as:

```
b filename.c:XYZ
```

Seethe documentationfor more info.


Question:
How do I get the key codes so I can process arrow, pageUp, pageDown, etc, keys using simple C or C++?

I can get the regular keys, I do not know how to get these special keys.

Answer: Ncurses should be able to handle that. There is lots of tutorials out there


Question:
someone please tell me which one of the following is more fast and why ??

```
int add(int a, int b){
     return a+b;
}
```

OR

```
void add(int a, int *b){
     *b = a+(*b);
}
```

Answer: Chances are functions areinlinedand both result in the same generated code.


Question:
What kind of API or algorithm is normally used to generate session ids? For something like an online game?
Thanks

Answer:
You can useUUID-v4. Implementations are available in pretty much any language. Here is one for C++:

http://sourceforge.net/projects/ooid/


Question:
I saw the following code in CCTL (~line 330)https://github.com/jobytaffey/cctl/blob/master/cctl/main.c

```
switch(page)
{
   // ...
   ack:
      cons_putc(0);
}
```

What is theack:section for?  It looks like same asdefault:to me.  I can't find it in the SDCC docs either.

Is this something in C spec?

Thank you

Answer: It's not a C keyword; it's just a label.  Note the correspondinggotostatements.


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

Possible Duplicate:Why do these two pointer subtractions give different results?

```
char arr[] = "stackoverflow";
char *p1 = arr;
char *p2 = arr + 3;
printf("%d",  (int*)p2 - (int*)p1);
```

it's answer is 0..Can you explain why is it so ?

Answer: Becausep2 - p1is<  sizeof (int). So(int *) p2 - (int *) p1 == 0, the number ofintelements between the two pointers.


Question:
Do I need to include a library?
Can anyone please elaborate in it?

I know is used to get the process id of the current task where is being called from

But I want to printk something with current->pid

printk("My current process id/pid is %d\n", current->pid);

...and is giving me an error

error: dereferencing pointer to incomplete type

Answer: You're looking for#include <linux/sched.h>. That's wheretask_structis declared.


Question: I'm writing code that depends on whether or not a header file is included.  If the file is included, I want certain added functionality.  Is there any way to do this, perhaps with an #if?  Using C btw

Answer:
Just#definea symbol in that header and use#ifdeflater on.

```
header.h
#define HAVE_IPV6

some_file.c
#ifdef HAVE_IPV6
/* code */
#endif
```


Question:
I saw the following code in CCTL (~line 330)https://github.com/jobytaffey/cctl/blob/master/cctl/main.c

```
switch(page)
{
   // ...
   ack:
      cons_putc(0);
}
```

What is theack:section for?  It looks like same asdefault:to me.  I can't find it in the SDCC docs either.

Is this something in C spec?

Thank you

Answer: It's not a C keyword; it's just a label.  Note the correspondinggotostatements.


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

Possible Duplicate:Why do these two pointer subtractions give different results?

```
char arr[] = "stackoverflow";
char *p1 = arr;
char *p2 = arr + 3;
printf("%d",  (int*)p2 - (int*)p1);
```

it's answer is 0..Can you explain why is it so ?

Answer: Becausep2 - p1is<  sizeof (int). So(int *) p2 - (int *) p1 == 0, the number ofintelements between the two pointers.


Question:
Do I need to include a library?
Can anyone please elaborate in it?

I know is used to get the process id of the current task where is being called from

But I want to printk something with current->pid

printk("My current process id/pid is %d\n", current->pid);

...and is giving me an error

error: dereferencing pointer to incomplete type

Answer: You're looking for#include <linux/sched.h>. That's wheretask_structis declared.


Question: I'm writing code that depends on whether or not a header file is included.  If the file is included, I want certain added functionality.  Is there any way to do this, perhaps with an #if?  Using C btw

Answer:
Just#definea symbol in that header and use#ifdeflater on.

```
header.h
#define HAVE_IPV6

some_file.c
#ifdef HAVE_IPV6
/* code */
#endif
```


Question: I have a call likeclock_gettime(CLOCK_REALTIME), does it handle leap seconds? If not, what changes are required? Working on Solaris.

Answer:
If your Unix system is synchronized with NTP, chances are that it handles leap seconds.

See this article for more information:NTP Leap Second.


Question:
I have very simple xml

```
<root>
    <node>some value</node>
</root>
```

How can I get the serialized HTML fragment, using libxml and C. I mean same as you can get usingouterHTMLin JS (document.getElementsByTagName("node")[0].outerHTML).

Answer: You have to usexmlNodeDump. Or if you want to print node out to file/stdout, then usexmlElemDump


Question: As the title said, I have a task that I need to read data from excel files. I'm wondering how to implement it in pure C, not C++ or C#. Btw, I need to write and test the program in Linux but others may use the code in Windows, which means my code has to be OS independent. Thank you.

Answer: Check outhttp://xlslib.sourceforge.net/


Question:
If I use macros in my C code, such as

```
#define var 10
```

then where exactly are the stored in the space allocated to the process by the kernel?
In heap or BSS or global data? Or is it just a text replacement for var in one of the compiler passes?

Answer:
Yes.the last one

just a text replacement

It is performed by a preprocessing pass.
Some good details can be foundhere


Question:
Is the stack allocated at runtime or compile time?Example:

```
void main()
{
    int x;
    scanf("%d", &x);
    int arr[x];
}
```

Answer: Stack isallocatedat runtime; layout of each stack frame, however, is decided at compile time, except for variable-size arrays.


Question:
When I want to work with big and small digits how must I sum / compare values in C?

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

int main(void) {
    if (1.0 + (1/pow (10,50)) == 1.0)
        printf("true");
    else
        printf("false");
    return 0;
}
```

how to make it to return false?

Answer: You can't make it return false with standard C types.  You'll need to use a high-precision floating point library.


Question: I'm curious because the man page of connect(2) is pretty short and it takes a struct sockaddr* which is normally cast anyways..

Answer: sockaddr_inandin_addraren't even similar. There's no way that would work. There different because more than an address is usually needed. For example, a port number is needed to establish connect a IP socket.


Question:
DigiFlow is used for image processing for fluid dynamics experiments -DigiFlow website. There is a console within the program which is used for writing macros.

Some example code:

```
function do_this(variable) {variable += 2};
    output := do_this(5);
```

(output = 7 after running this.)

Answer: From assignment and function declaration I'd say it looks like Google'sgo language. Pascal might be another choice.


Question:
This question already has an answer here:Closed11 years ago.

Possible Duplicate:What is the C Equivalent of Python's pack(“<I”, 0)

How can I replicate the code in Python:

```
from struct import pack
string = pack("<I", 0x11111111)
print string
```

in C? From what I understand \x11 is a nonprintable character so...?

Answer:
```
const char *string = "\x11\x11\x11\x11";
puts(string);
```


Question:
This question already has an answer here:Closed11 years ago.

Possible Duplicate:What is the C Equivalent of Python's pack(“<I”, 0)

How can I replicate the code in Python:

```
from struct import pack
string = pack("<I", 0x11111111)
print string
```

in C? From what I understand \x11 is a nonprintable character so...?

Answer:
```
const char *string = "\x11\x11\x11\x11";
puts(string);
```


Question:
Given:

```
int a[N];
int *p;
```

why doesa-pwork yeta+pdoes not with error: "invalid operands to binary +".

Answer:
Thedifferencebetween two pointers is meaningful, i.e. it is the number of elements between the two pointers (provided that they both lie within the same array).

Addingtwo pointers makes no sense though (how would you interpret it ?).


Question: I have a repository. I don't want to checkout the whole repository but just one folder inside it. I don't remember the folder names, so I want to see them. Is there a command in svn which can show all the folder names in the root directory of the repository.

Answer: Have you triedsvn ls http://repo.url/here?


Question:
Given:

```
int a[N];
int *p;
```

why doesa-pwork yeta+pdoes not with error: "invalid operands to binary +".

Answer:
Thedifferencebetween two pointers is meaningful, i.e. it is the number of elements between the two pointers (provided that they both lie within the same array).

Addingtwo pointers makes no sense though (how would you interpret it ?).


Question: I have a repository. I don't want to checkout the whole repository but just one folder inside it. I don't remember the folder names, so I want to see them. Is there a command in svn which can show all the folder names in the root directory of the repository.

Answer: Have you triedsvn ls http://repo.url/here?


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.Closed11 years ago.

What is the meaning of "f" in C's printf?

Answer: Thefinprintfstands forformatted, its used for printing with formatted output.


Question: How could I go about writing a Haskell library to provide input functionality similar to that provided by SDL or GLFW? Specifically, how would I go about grabbing device events (e.g. mouse, keyboard, joystick) and system events (e.g. quit, resize, window move, focus).

Answer: Make FFI bindings to the primitives provided by the platform (or library) you're building on.Use these primitives to implement higher level abstractions.


Question: I want creat a C program for Unix that can porcess the Regular Expression,like a simple Perl interpreter. Do I have to personally write an regexp engine?

Answer:
http://www.gnu.org/software/libc/manual/html_node/Regular-Expressions.html

You might like to look for a library with it already coded. C uses librarys to allow you to include other peoples code into your work. I assume there are many regular expression librarys for you to use already to go!


Question: Embarrassingly basic question.sudo apt-get install libmemcached6- where do the .h's and .o's or .so's live in a typical install on a Linux machine (Ubuntu)?  And, how do I make sure g++ can pick them up?

Answer: They go to /usr/include and /usr/lib. If you use the -l option (for the libraries) it should find them from these standard places. If you include using<file.h>it should also get it from the right place.


Question: There is a function I have written in C that I would like to use in the debugger to send commands to a javascript engine. Since this function is not used directly in code the linker strips this symbol. Is there a way to mark a particular function to not be stripped?

Answer:
Found it!

http://disanji.net/iOS_Doc/#documentation/DeveloperTools/Conceptual/XcodeBuildSystem/500-Linking/bs_linking.html

declaration should have

```
__attribute__((used))
```


Question: There is a function I have written in C that I would like to use in the debugger to send commands to a javascript engine. Since this function is not used directly in code the linker strips this symbol. Is there a way to mark a particular function to not be stripped?

Answer:
Found it!

http://disanji.net/iOS_Doc/#documentation/DeveloperTools/Conceptual/XcodeBuildSystem/500-Linking/bs_linking.html

declaration should have

```
__attribute__((used))
```


Question:
Namely code similar to this, making the printout undefined.

```
int a=41; a++ & printf("%d\n", a);
```

I don't know what exactly this operation is called.

Answer: The problem is that it is not specified which is evaluated first, theprintfor thea++, and since one has a side effect on the other (you either readathen write it then read it again, or read it then read it then write it), you get undefined behaviour.


Question:
Namely code similar to this, making the printout undefined.

```
int a=41; a++ & printf("%d\n", a);
```

I don't know what exactly this operation is called.

Answer: The problem is that it is not specified which is evaluated first, theprintfor thea++, and since one has a side effect on the other (you either readathen write it then read it again, or read it then read it then write it), you get undefined behaviour.


Question:
Namely code similar to this, making the printout undefined.

```
int a=41; a++ & printf("%d\n", a);
```

I don't know what exactly this operation is called.

Answer: The problem is that it is not specified which is evaluated first, theprintfor thea++, and since one has a side effect on the other (you either readathen write it then read it again, or read it then read it then write it), you get undefined behaviour.


Question: I'm looking for a cross-platform(works at UNIX-like and Windows) library to handling operating system date. Is there it for C programmers? or C++ if really have no for C. Thanks in advance!

Answer: Perhaps you should tryBoost.Date_Time.


Question:
please find thecodefor the service created to detect my USB device.

The problem in the above code is that the logfile is getting updated only after the service is stopped.

My intension is to update the log file once the device is detected.. But it happens only after the service is stopped. how to achieve what i intend to?

please guide me..

Answer:
To avoid losing log entries, you need to flush thefwrites .

fflush(your file handle )


Question:
please find thecodefor the service created to detect my USB device.

The problem in the above code is that the logfile is getting updated only after the service is stopped.

My intension is to update the log file once the device is detected.. But it happens only after the service is stopped. how to achieve what i intend to?

please guide me..

Answer:
To avoid losing log entries, you need to flush thefwrites .

fflush(your file handle )


Question: Does calloc allocate return  contiguous memory location? If yes, what would it do if it is not available?

Answer:
Does calloc allocate returns contiguous memory location?

Yes.1

what would it do if it is not available?

ReturnNULL.

See section 7.20.3.1 of the C99 standard.

1. So far as the C program is concerned.  In a virtual memory system, the underlying physical memory used may not be contiguous.


Question:
I'm reading through some code for an Arduino example and I came across this line:

uint16_t pulses[100][2];

It appears that this is defining a 100x2 array -- is that correct?

Answer: You are correct. It defines a 100x2 array of unsigned 16 bit integers.


Question:
How to get the id of a specific edge with two of its vertex?

Example:

egde id=4 with vertex 2 and 3, using id 2 and 3 vertex how to get the id=4 of that edge?

Answer: igraph_get_eidis the function you are looking for.


Question:
How to get the id of a specific edge with two of its vertex?

Example:

egde id=4 with vertex 2 and 3, using id 2 and 3 vertex how to get the id=4 of that edge?

Answer: igraph_get_eidis the function you are looking for.


Question:
I know that in h264 we can detect a NAL Unit by the bit pattern0x000001.

Is there an equivalent method to detect a slice header in a NAL Unit? How does one handle multi-slice NAL units?

Currently I'm using parsing code for h264 and get the slice header in a respective structure.

Answer:
The slice header syntax is discussed on page 36 (section 7.3.3) of theH.264 standard.

It might be worth having a look at thereference software.


Question:
I have the following C statement:

```
int res = x & (x ^ y);
```

Is there a way to do the same thing, but usingxandyonly one time each?

For example:

```
x | (~x & y) == x | y
```

Answer:
Yes, by expanding the xor (a ^ b == (a & ~b) | (~a & b)), and then simplifying the result, one gets:

```
res = x & ~y;
```


Question:
I need a library to list files in archives  and to extract archive files. The library should support archive types as much as possible. Do you have any suggestion ?

Any help would be appreciated.

Answer: This sounds like you are looking for libarchivehttp://libarchive.github.com/


Question:
I have the following C statement:

```
int res = x & (x ^ y);
```

Is there a way to do the same thing, but usingxandyonly one time each?

For example:

```
x | (~x & y) == x | y
```

Answer:
Yes, by expanding the xor (a ^ b == (a & ~b) | (~a & b)), and then simplifying the result, one gets:

```
res = x & ~y;
```


Question:
I have the following C statement:

```
int res = x & (x ^ y);
```

Is there a way to do the same thing, but usingxandyonly one time each?

For example:

```
x | (~x & y) == x | y
```

Answer:
Yes, by expanding the xor (a ^ b == (a & ~b) | (~a & b)), and then simplifying the result, one gets:

```
res = x & ~y;
```


Question:
I need a library to list files in archives  and to extract archive files. The library should support archive types as much as possible. Do you have any suggestion ?

Any help would be appreciated.

Answer: This sounds like you are looking for libarchivehttp://libarchive.github.com/


Question:
I came across the below declaration ; what will be the scope of this MACRO ?

```
typedef struct Hdr_s {
#define MACRO1   1
#define MACRO2       2
#define MACRO3   3
unsigned char  Flag;
unsigned char  Offset;
unsigned short cpy_len_offset;
unsigned char  cpy_offset;
}Hdr_t;
```

Answer: A macro definition remains for the whole remainder of the compilation, and macros aren't scoped.


Question: I needed to execute a loop and a condition in every second or in the interval of a few milliseconds. What can I do to achieve this?

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

usleepfor POSIX platform (hight precision sleep)


Question:
Is it possible to hack the Chrome (more precisely the Webkit's), through an extension, in order to use my own media server instead of Google's one?

It's needed to make realtime voice interactive app and I'm looking to an alternatives instead of doing this in flash or a Java Applet.

Answer: I found (for my projects) that usingVideoIO.swfandRTMPLiteis far easier and more portable solution.


Question:
I knowgetppidretrieves the parent pid of the underlying program, but how can you tell this out of that program? I can't find anything useful in/proc/[pid], or is there any useful API that i can use?

UPDATE

I mean , i'm inspecting these procress with another process , so getppid won't work here

Answer: It is the fourth field in /proc/[pid]/stat. It is documented in the man pageproc(5).


Question:
I know some difference between char* and char[].char x[] = "xxxx"Is an array of chars;char *y = "xxxx"is a pointer to the literal (const) string;
Andx[4]=='\0', and*(y+4) == '\0'too.
So whysizeof(x)==5andsizeof(y)==4?

Answer:
char x[] = "xxxx"is an array of size 5 containing x x x x and \0.

char *y = "xxxx"is a pointer to a string. It's length is 4 bytes, because that is the length of the pointer, not the string.


Question:
One of my questions, as I'm pretty new to C is about ways to avoid getting the duplication error. Basically, when I build the project in Netbeans if I have the file in the project and also include it, I get that error.

Defining the functions static, is a correct way to avoid it? What other solutions are there? Thanks

Answer:
.c/.cppfiles shouldn't be included.

Move declarations to a common header file and include that.


Question:
Say I have this file:http://www.example.com/somepic.png

Is there a cross platform C or C++ library that could easily allow me to download it to a specified directory?

Thanks

Answer: You can uselibcurlto do this.


Question:
I knowgetppidretrieves the parent pid of the underlying program, but how can you tell this out of that program? I can't find anything useful in/proc/[pid], or is there any useful API that i can use?

UPDATE

I mean , i'm inspecting these procress with another process , so getppid won't work here

Answer: It is the fourth field in /proc/[pid]/stat. It is documented in the man pageproc(5).


Question:
I know some difference between char* and char[].char x[] = "xxxx"Is an array of chars;char *y = "xxxx"is a pointer to the literal (const) string;
Andx[4]=='\0', and*(y+4) == '\0'too.
So whysizeof(x)==5andsizeof(y)==4?

Answer:
char x[] = "xxxx"is an array of size 5 containing x x x x and \0.

char *y = "xxxx"is a pointer to a string. It's length is 4 bytes, because that is the length of the pointer, not the string.


Question:
One of my questions, as I'm pretty new to C is about ways to avoid getting the duplication error. Basically, when I build the project in Netbeans if I have the file in the project and also include it, I get that error.

Defining the functions static, is a correct way to avoid it? What other solutions are there? Thanks

Answer:
.c/.cppfiles shouldn't be included.

Move declarations to a common header file and include that.


Question:
Say I have this file:http://www.example.com/somepic.png

Is there a cross platform C or C++ library that could easily allow me to download it to a specified directory?

Thanks

Answer: You can uselibcurlto do this.


Question: I did search but I did't find any BPF code to use on my computer, also there isn't any example code to use. My goal is to find low level functions to filter packets. I am working in C program language. I am using Ubuntu 12.04 with 3.2.0 kernel.

Answer: You may want to look into thepcaplibrary, from the folks who brought you tcpdump. Pcap is a cross-platform packet filtering library with support for BPF filters.


Question:
I need to panic kernel after some operations are done and verify what operation did

Can some one help me to know if there is any way? I searched a lot but no luck

I am looking for some generic call

thanks in Advance!

Answer:
You can try asysrq trigger:

```
echo c > /proc/sysrq-trigger
```

'c' - Will perform a system crash by a NULL pointer dereference.
        A crashdump will be taken if configured.


Question: Let us say in some part of the code that a macro has been defined. During compilation, I want to learn if it has been defined and is being used. How might I do this?

Answer:
Check with#ifndefdirective and throw an error with#errordirective :

```
#ifndef A_MUST_HAVE_MACRO
#error "A must have macro not defined"
#endif
```


Question:
I am trying to write a code that can get the names of the installed drivers in my Windows computer in C (via winapi)?

I am really new to C and I do not know what I can do ? Can you please help me with this situation ?

Thank you very much

Answer: You need the setup API. Start with this article:How to enumerate hardware devices by using SetupDi calls


Question:
As per my understanding there are two RSA signature schemes - PSS (Probabilistic Signature Scheme) and the old PKCS1-v1_5:

Can I use RSA_verify() API to check RSA signature under both schemes ?

Answer: If you have a recent version - see:http://fixunix.com/openssl/526614-signing-verifying-messages-rsassa-pss.htmlfor how to use it.


Question:
I have downloaded rx. Can somebody please tell of a suitable ide for debugging and building the source code of "rdf-3x". As per the operating system: ubuntu & Windows are both fine for me.

I tried netbeans (C++) but it does not work for me, since it does not treat all the folders within as one project, rather it treats them as separate projects.

Answer:
I'm using Eclipse..

It's user friendly for me..You can try it.http://www.eclipse.org/cdt/

CMIIW


Question:
Can any one tell me how to typecast achar*pointer toint*in OpenCL kernel function??
I tried((int*) char_pointer)but it is not working.

Answer:
You have to qualify the pointer with the correct address space, I think.

If you don't specify the address space,__privateis assumed, but your source pointer seems to be a__globalpointer (from your comment), so the address spaces are incompatible.

So try to use(__global int*)instead of just(int*).


Question: is there an open implementation for an aztec 2D barcode (for the Deutsche Bundesbahn) generator. I do not need the "aztec-data to bitmap", but i need the "input-data to aztec-data" part, the drawing itself is no problem with drawing primitives.

Answer: ZXingalso supports Aztec encoding since version 2.2.


Question:
This question already has answers here:How would I load a PNG image using Win32/GDI (no GDI+ if possible)?(5 answers)Closed9 years ago.

Very simple question: how do I render a png image with GDI in C (including its transparencies)?

Answer: I went with GDI+ instead of GDI.


Question:
Can any one tell me how to typecast achar*pointer toint*in OpenCL kernel function??
I tried((int*) char_pointer)but it is not working.

Answer:
You have to qualify the pointer with the correct address space, I think.

If you don't specify the address space,__privateis assumed, but your source pointer seems to be a__globalpointer (from your comment), so the address spaces are incompatible.

So try to use(__global int*)instead of just(int*).


Question: is there an open implementation for an aztec 2D barcode (for the Deutsche Bundesbahn) generator. I do not need the "aztec-data to bitmap", but i need the "input-data to aztec-data" part, the drawing itself is no problem with drawing primitives.

Answer: ZXingalso supports Aztec encoding since version 2.2.


Question:
This question already has answers here:How would I load a PNG image using Win32/GDI (no GDI+ if possible)?(5 answers)Closed9 years ago.

Very simple question: how do I render a png image with GDI in C (including its transparencies)?

Answer: I went with GDI+ instead of GDI.


Question: Is there a way to tell (on UNIXes) which of a process's memory pages are in the RAM and which have been swapped out?

Answer:
Not in a portable way.

Even if it were possible, it would be mostly useless. A page you have checked is swapped in could very well be swapped out the moment you are ready to use it.


Question:
What is the direct alternative for thevsnwprintffunction on linux machines and what headers should be included to use it?

Thanks for any advice

Answer:
It depends on whatvsnwprintf()(sic)does and what is its parameter list.

TheC99 Standarddescribesvswprintf()(in section 7.24.2.7). To use it you need to #include<stdarg.h>and<wchar.h>. The implementation should be in the Standard library.


Question: I need to pass some arguments to my application,that include the - symbol. The problem is if I passgdb a.out -foo baa, the gdb understand that the arguments are for it, and not to my application. How to fix this?

Answer: gdb -q a.outinside gdb:run -foo baaTip: -q option for gdb suppresses the introductory copyright messages.


Question:
this is a simple question ... is there a way to convert astruct tm ct;to a long integer ? here's how my code look like:

```
struct tm ct;
    scanf("%d", &ct.tm_sec);
    scanf("%d", &ct.tm_min);
    scanf("%d", &ct.tm_hour);
    scanf("%d", &ct.tm_mday);
    scanf("%d", &ct.tm_mon);
    scanf("%d", &ct.tm_year);
```

Answer: You can use themktime()function to convert astruct tminto atime_t, which is an integer value.


Question:
I run a program with LD_PRELOADing a specific library. Like this.

```
LD_PRELOAD=./my.so ./my_program
```

How do I run this program withgdb?

Answer:
Do the following.

```
gdb your_program

(gdb) set environment LD_PRELOAD ./yourso.so
(gdb) start
```


Question:
What is the direct alternative for thevsnwprintffunction on linux machines and what headers should be included to use it?

Thanks for any advice

Answer:
It depends on whatvsnwprintf()(sic)does and what is its parameter list.

TheC99 Standarddescribesvswprintf()(in section 7.24.2.7). To use it you need to #include<stdarg.h>and<wchar.h>. The implementation should be in the Standard library.


Question:
```
int a[2]={1210,15};

    printf("%d",a[33] );
```

OUTPUT

```
1073828132
```

Why it's not throwing error when i'm trying to printa[33]even though the array element doesn't exist

Answer:
Because C does not do bounds-checking.

You will just be reading an arbitrary location in yourcall stack.


Question: In which section is constant volatile variable stored in c.? In micro-controllers we should put such kind of variables in RAM. Right?

Answer: Volatilehas noting to do with where the variable is stored. It just tells the compiler to read the variable from memoryevery timeto avoid any optimization that compiler might perform for that variable.


Question:
```
int a[2]={1210,15};

    printf("%d",a[33] );
```

OUTPUT

```
1073828132
```

Why it's not throwing error when i'm trying to printa[33]even though the array element doesn't exist

Answer:
Because C does not do bounds-checking.

You will just be reading an arbitrary location in yourcall stack.


Question: In which section is constant volatile variable stored in c.? In micro-controllers we should put such kind of variables in RAM. Right?

Answer: Volatilehas noting to do with where the variable is stored. It just tells the compiler to read the variable from memoryevery timeto avoid any optimization that compiler might perform for that variable.


Question:
I tried this but it's not working for me:

```
char * remove_nl(char * newstr)
{
    newstr = strdup(newstr);
    newstr[strlen(newstr)-1] = '\0';
    return newstr;
}
```

Answer:
What you have now is fine, except:

you have to make sure thatnewstrpoints to a valid string;check thatstrlen(newstr) > 0;check thatnewstr[strlen(newstr)-1]is indeed a newline before wiping it;make sure the callerfree()s the returned string.


Question: Canglibcbe compiled into one object file which can then be linked to any program. The main purpose is portability here. Because I don't require to install dynamic libraries this way. Can this be done? If so, how?

Answer: You can compileglibcto.afiles which can be linked into a static executable. The static libraries are built by default.


Question:
I was looking into some old code in my product and i found following code.

```
#include <stdio.h>
#include <string.h>
int main ( int argc, char **argv) {
    const char *str = "abcdefghi";
    int value = strcmp(str, "abcdefghi") == 0;
}
```

What is the purpose ofint value = strcmp(str, "abcdefghi") == 0;of such code.

Answer: It initializesvaluewith the result ofstrcmp(str, "abcdefghi") == 0which will be0or1depending on whatstrcmpreturns.


Question: I have many native libraries with a C API that contain functionality I want to use in a web app. What choices are out there (frameworks/languages) for doing this?

Answer:
To call native C functions from C#, including ASP.Net, use P/Invoke. It exists for exactly that purpose.

Tutorial Here:http://msdn.microsoft.com/en-us/library/aa288468(v=VS.71).aspx