Question:
I want to do a screenshot of a GUI window from C/C++ into the memory.
It would be really nice if it's a two dimension array of RGB values or something similar.

Im at the moment searching for a Linux based solution, but would be nice if there is a platform independent solution.

Answer:
You could utilizexlibfor Linux:How do take a screenshot correctly with xlib?

AndGDIon Windows:MSDN - Capturing an Image


Question:
I want to do a screenshot of a GUI window from C/C++ into the memory.
It would be really nice if it's a two dimension array of RGB values or something similar.

Im at the moment searching for a Linux based solution, but would be nice if there is a platform independent solution.

Answer:
You could utilizexlibfor Linux:How do take a screenshot correctly with xlib?

AndGDIon Windows:MSDN - Capturing an Image


Question: I cannot find in Internet any links to "official" GLU downloads or documentation. The links about GLU on opengl.org are defunct. The only GLU API documentation that I found is on MSDN about windows version of GLU. Is there such page as "official" GLU page and documentation and downloads for Linux?

Answer:
http://www.opengl.org/sdk/docs/man2/

GLU documentation is the part of OpenGL 2 documentation. There isa special section for GLU functions.


Question:
If I want to return strdup from a function whose return type is char*, then what are the risks or chances of memory leak ?

```
char* fun () {
    return strdup("hello");
}

int main() {
    for(;;)
    printf("%s\n", fun());
}
```

Answer: strdup()returns a pointer to newly-allocated memory that must be freed later withfree().  You'll leak memory if you don't callfree()on it — which, in your example, you don't.


Question: I am working on a linux system.  I have a multi-threaded application that hasnfile handles open on a single filef.  How can I see during run-time how many file handles in my process refer ton?

Answer: You could check the symbolic links in/proc/self/fd/and see if there are multiple descriptors pointing to the same file.


Question:
Here is my structure:

```
typedef struct {
    char apagado;
    char prop[MAXPLEN];
    char mat[6];
    double valor;
    } veiculo_t;

veiculo_t.apagado='\0';
```

Why can't I initialize theapagadovariable like that?

Answer:
veiculo_tisn't a variable. It's a type. You still have to create a variable of that type:

```
veiculo_t veiculo;
veiculo.apagado='\0';
```


Question: I have a variable of typeint array[10]. Is it possible to initialize only the last item of the array?

Answer:
Yes, using designated initializers (introduced in C99), you can write code like this:

```
int array[10] = {[9] = 42};
```

which is equivalent to:

```
int array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 42};
```

This feature is also available in some compiler as an extension, for instance,GCC.


Question: I'm not very familiar with the source code behind the entity we know as PHP, so I don't know whether the SPL library in general and SplFixedArray in particular are implemented in C/C++. Would anyone have the information?

Answer: Here you´ll find a link to a "spl_fixedarray.c" file:http://git.php.net/?p=php-src.git;a=tree;f=ext/spl=> It is C


Question: What are equivalents for_tsystem and _wsystemin linux?

Answer: Justsystem. There are no wide-string (Unicode) APIs in Linux.


Question:
In the below code why does the struct have two variable names?

```
#include <sys/resource.h>

int main (int argc, char **argv)
{
    const rlim_t kStackSize = 64L * 1024L * 1024L;

    struct rlimit rl;    //HERE

    int result = getrlimit(RLIMIT_STACK, &rl);

    return 0;
}
```

Answer:
In C, struct with its tag together is a name, unless it'stypedefed.

In C++, you can omit thestructkeyword.


Question:
This question already has answers here:What does ~0 do?(4 answers)Closed9 years ago.

I see this type data in code program. But I don't know this type data. What means this type of data?

```
(uint16_t)~0U
```

Answer:
```
(uint16_t) ~ 0 U
     ^     ^ ^ ^
     |     | | |____ unsigned constant
     |     | |______ the number 0
     |     |________ bitwise not operator
     |______________ casting to 16 bits integer
```

As a result you get a 0xffff


Question: What is the inner working ofgetchar_unlocked()?Why is it thread unsafe?And why it is not employed in windows POSIX?

Answer:
getchar_unlocked() is not threadsafe, because it might manipulates internal data structures without locking or any other type of synchronisation. For any more detailled answer, you must look at the exact implementation in question.

Omitting thread safety (and being inlined/a preprocessor define) is what makes it fast.


Question: I would like to check if the firewall is enabled in Windows through C code, I found some methods in C# but only a little bit information from C, How I could do that?, thanks

Answer: You could use theWindows Firewall API. For Windows XP you read theInetFwProfile::FirewallEnabledproperty. On Vista or later you could use theWindows Firewall with Advanced Security API.


Question: I'm very confused on how these two functions work with mutex and what they do. Can someone explain them to me and give an example? Thanks!

Answer:
pthread_cond_signal() -> This is explainhere

More explanation :

You can do a lots of actions with thread, create, remove, make them stop (lock), make them unlock ... ect

pthread_cond_signal() permit to unlock some lock thread.

pthread_cond_wait() is used to lock some thread.


Question:
I encountered code where:

```
typedef wchar_t     str_param_t[WP_STR_MAX_LEN];
```

And then:

```
typedef struct work_t
{
    u32_t           val1;
    u32_t           val2;
    str_param_t     data[WP_MAX_COUNT_STR];
} work_t;
```

My question is what type isdata?

Answer: It is an array of lengthWP_MAX_COUNT_STRcontainingwchar_t-based strings of lengthWP_STR_MAX_LENeach.


Question:
I encountered code where:

```
typedef wchar_t     str_param_t[WP_STR_MAX_LEN];
```

And then:

```
typedef struct work_t
{
    u32_t           val1;
    u32_t           val2;
    str_param_t     data[WP_MAX_COUNT_STR];
} work_t;
```

My question is what type isdata?

Answer: It is an array of lengthWP_MAX_COUNT_STRcontainingwchar_t-based strings of lengthWP_STR_MAX_LENeach.


Question:
So, I'm getting an error on this line of code;

```
else if(lockError == EBUSY)
```

I get the error;

```
use of undeclared identifier 'EBUSY'
```

How do I compare my int lockError to the EBUSY that might be returned when I try a pthread_mutex_unlock.

Answer: You forgot to include#include<errno.h>whereEBSUYis defined. Seeerrno.h.


Question:
So, I'm getting an error on this line of code;

```
else if(lockError == EBUSY)
```

I get the error;

```
use of undeclared identifier 'EBUSY'
```

How do I compare my int lockError to the EBUSY that might be returned when I try a pthread_mutex_unlock.

Answer: You forgot to include#include<errno.h>whereEBSUYis defined. Seeerrno.h.


Question: I am new to open CV and C. How do i specify multiple images for the same kind of operation.

Answer:
if your images are (sequentially) numbered, you could abuse a hidden feature with VideoCapture, just pass it a (format) string:

```
VideoCapture cap("/my/folder/p%05d.jpg"); // would work with: "/my/folder/p00013.jpg", etc
while( cap.isOpened() )
{
    Mat img;
    cap.read(img);
    // process(img);
}
```


Question: I want to check if a library is present either in my app or the System. In java I usually do System.loadlibrary, but does anyone know a similar corresponding call in C ?

Answer: It isdlopento open a library, anddlsymto get pointer to function from loaded library. Beware, some details may vary in thisglibcdocumentation and actual android implementation. See ChrisStratton comment.


Question:
I could use following code to get the /proc entry, but how to get the /proc entry directly? Any function in the kernel to do this directly(without creating one dummy sub-entry)?

```
new_proc = proc_create("dummy", 0644, 0, &fileops_struct);
  root = new_proc->parent;
```

Answer:
I haven't found a function, but you might accessproc_rootdirectly.

It is located infs/proc/root.cand should be accessible from outside.


Question: Just confused, why is not mL = 1?

Answer:
Visual studio treatsint mL = 400/400as two step process.

First step would be allocating memory in stack. So, you see a garbage value. Press F10/F11 (step once more) you should see 1.

-858993460 translates to 0xCCCCCCCC which is a bit pattern used by Microsoft compilers to detect buffer overruns and to initialize an empty stack.Some more details here -softwareverify.com/memory-bit-patterns.php


Question:
I want to convert some bytes to an int.
This is my code so far:

```
unsigned char *bytePtr = (unsigned char *)[aNSDataFrame];
```

I want to take 4 bytes from this unsigned char:myFrame[10],myFrame[11],myFrame[12]andmyFrame[13]and convert them to an integer.

Answer:
```
int val = *(const int*)&myFrame[10];
```


Question: How can I usesched_setschedulerexplained in thistopic? It seems that I have to write a C code and run it on shell?

Answer: To change the policy of a process from the shell you need to usechrt. To choose real time priorities you must be root. Beware that this is dangerous, raising priorities higher than the kernel interrupts will definitely have strange side effects!


Question: I am using aLinux operating systemand the library functions I am talking about C programming language.

Answer: Those functions are part of the system's C library, which on most GNU/Linux systems isGNU libc, also known as "glibc".  Since glibc is open-source free software, you can download its source code and read whatever parts you're interested in.  Thedownload pageis the place to start.


Question: Should there be any errors, if a.hfile contains a signature, which has no implementation in a.cfile?

Answer: If you use the function, and it isn't implemented, you will get a link error.  Otherwise, no errors or warnings will occur.


Question:
Hello i'm new to C and have some confusion Regardingfprintf

I'm trying to create a Data table and i want it to look exactly like this:

```
Rectangle A                    Rectangle B
SW corner   Height   Width     SW corner   Height   Width
```

Most of my confusion is coming from the white spaces, surely there is a better way than just adding an empty String.

Answer:
You can use width specifier:

```
printf("[%5d] [%-5d]\n", 42, 42);
```


Question:
Need to write a program to take input from a user in the form of an int and validate that what they entered is not a char from a-z.

Is there another way to do this other than:

if((num != 'a') && (num != 'b') && (num != 'c') && (num != 'd') etc.....)
         printf("You entered %d", num);

Answer: Yes, use theisdigit()function provided in thectype.hheader file


Question: I'm trying to track a certain applications behaviour, I've grabbed the visible thread that draws the Window, having that thread is there any way to determine the process it belongs to?

Answer:
You can useGetProcessIdOfThreadapi for newer versions of windows.

For older versions you have to find it manually using the ToolHelp library functionsThread32First/Thread32Nextsearching for the threadid and getting the process id from the THREADENTRY32 structure.


Question:
```
if(tree->left)

if(!(*tree))
```

Do they mean:

```
if(tree->left==0)

 if((*tree)==1)
```

I did not find anything about this.

Answer:
In C there are not booleans but only integers. The if statement just check for equality with 0, evaluating 0 as false and everything else as true, so your examples are equivalent to

```
if(tree->left != 0)

if((*tree)==0)
```


Question:
```
if(tree->left)

if(!(*tree))
```

Do they mean:

```
if(tree->left==0)

 if((*tree)==1)
```

I did not find anything about this.

Answer:
In C there are not booleans but only integers. The if statement just check for equality with 0, evaluating 0 as false and everything else as true, so your examples are equivalent to

```
if(tree->left != 0)

if((*tree)==0)
```


Question:
This question already has answers here:How do I check if an integer is even or odd? [closed](30 answers)Closed9 years ago.

How can I check if a variable (an int) is even (that is, not odd) in C without using "%" operator?
I am running on linux platform.

Thank you.

Answer:
```
if (!(v & 1))
```

should be true for even numbers


Question:
What does the following c code trying to do. I am not sure what does it calculate the value of width to

```
(width+31)&~31
```

Thank you.

Answer:
It is rounding up to the next multiple of 32.  It only works because 32 is a power of 2.

```
The bit pattern for  31 is ...000000000011111
The bit pattern for ~31 is ...111111111100000
```

When you and ~31 with any positive integer, you get a multiple of 32 (five low order bits are all zeroes).


Question:
I executed following piece of code:

```
int a[] = {5,1,15,20,25};
int i,j,m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d",i,j,m);
```

and I got output as follow :-

```
3 2 15
```

The part which I don't understand is how I got value ofias3

It should be2right?

Or is it related with C compiler's right to left evaluation ofprintf()statement?

Answer: Them = a[i++]line incrementedifor a second time, from 2 to 3.


Question:
I roughly read

http://linux.die.net/man/2/forkandhttp://linux.die.net/man/3/fork

got confused.
can anybody briefly explain to me difference between fork(3) and fork(2)
thank you

Answer: fork(2) is the kernel call and fork(3) is the posix library call


Question:
I executed following piece of code:

```
int a[] = {5,1,15,20,25};
int i,j,m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d",i,j,m);
```

and I got output as follow :-

```
3 2 15
```

The part which I don't understand is how I got value ofias3

It should be2right?

Or is it related with C compiler's right to left evaluation ofprintf()statement?

Answer: Them = a[i++]line incrementedifor a second time, from 2 to 3.


Question:
I roughly read

http://linux.die.net/man/2/forkandhttp://linux.die.net/man/3/fork

got confused.
can anybody briefly explain to me difference between fork(3) and fork(2)
thank you

Answer: fork(2) is the kernel call and fork(3) is the posix library call


Question:
As we know, the C can open the /dev file node by the Linux system API. Like this:

```
int fd = open("/dev/hello", O_RDONLY|O_NONBLOCK);
```

So , is there any way to do this using JAVA without JNI ?

Thanks.

Answer:
Yes, since on Unix "everything is a file". You just open/dev/hellolike you open your file/home/jerikc/some.txt...

Perhaps your question is how to passO_NONBLOCKtoopen(2)syscall in Java....


Question:
This question already has answers here:What is the difference between int* ptr and int *ptr in C? [duplicate](5 answers)Closed9 years ago.

I have seen,

```
int *pnum;
int * pnum;
int* pnum;
```

Are these all the same?

Answer: Yes, all those three are the same. And in them, that*is notdereferencing operator, it is part of the typeint *, pointer toint.


Question:
```
int b = 0xf ^ 0xc;
printf("value is %04X", b);
```

Output is:

```
value is 0003
```

I know that the decimal value of the xor operation between1111and1100is3although I want integerbto be printed out in hex.

Answer: 0003 is a hexadecimal value; a hexa digit has values between 0..F


Question:
This question already has answers here:What is the difference between int* ptr and int *ptr in C? [duplicate](5 answers)Closed9 years ago.

I have seen,

```
int *pnum;
int * pnum;
int* pnum;
```

Are these all the same?

Answer: Yes, all those three are the same. And in them, that*is notdereferencing operator, it is part of the typeint *, pointer toint.


Question:
For example if I received the following ASCII value: 123456

How would I combine two digits into a byte? So my bytes become like this ...

```
byte1 = 0x12;

byte2 = 0x34;

byte3 = 0x56;
```

Thanks!

Answer:
This is called BCD (binary-coded decimal).

```
char s[] = "123456";
byte1 = (s[0] - '0') * 0x10 + (s[1] - '0');
```


Question:
How can I clonechar** argvtochar** copy?

original -char** argvcopyto -char** copy

Answer:
Withargcbeing the number of elements in argv:

```
char** copy = (char**)malloc(argc * sizeof(char*)) ;

  for (int i = 0; i < argc ; i++)
  {
    copy[i] = strdup(argv[i]) ;
  }
```

Freeing the allocated memory once we are done with the clone, is left as an exercise to the reader.


Question: Is there a way to find out if a particular interface exits using C .

Answer: getifaddrs.  There is an example program on the manpage.  Basically you would have to just loop through the list looking for a match.  Optionally you can look atif_nameindexif_indextonameandif_nametoindex


Question: What's the difference betweenstrtokandstrtok_rinCand when are we supposed to use which?

Answer:
strtokis equivalent to (and often defined as):

```
char *strtok(char *str, const char *delim) {
    static char *save;
    return strtok_r(str, delim, &save);
}
```

in general, you should usestrtok_rdirectly rather thanstrtok, unless you need to make your code portable to pre-POSIX-2001 systems that only supportstrtok


Question:
I'm trying to access a website url(https) and read back it's contents(a json from an api).
What c commands would I use?

Answer: Have you looked atlibcurl?  Never used it, but I've seen it used quite a bit.  Otherwise it's going to be somewhat system dependant, if you're on linux you could use popen() on a command that dumps to stdout.


Question:
Whenever I try to compile my c program on mac it gives the following error. I am completely clueless about it.

'sys/cdefs.h' file not found

Answer:
have you installed "Xcode Command Line Tools" ? just install it in your terminal.

```
sudo xcode-select --install
```


Question:
So I need to print a title using \ __ ||

it will become something like this

```
______
 |_   _ \
   | |_) |
   |  __'.
  _| |__) |
 |_______/
```

how to print all, and i get error even though i use \ to print \

Answer: To print \ you need to put \\ in your string, because \ is an escape (e.g. \n for a new line).


Question:
I added this to my.profile  but I stil get warnings :

```
QMAKE_CXXFLAGS_WARN_OFF = -Wunused-parameter
```

Answer: UseQMAKE_CXXFLAGS_WARN_ON += -Wno-unused-parameter,because the flags in QMAKE_CXX_FLAGS will always before QMAKE_CXXFLAGS_WARN_ON, and QMAKE_CXXFLAGS_WARN_ON contains the flag -Wall. This means your flag will be overwrite by flag -Wall.


Question:
How do I execute below mentioned command using exec inside a C language program in linux?

wget -P ./Folder http://www.google.com

Answer:
execl("/usr/bin/wget", "-P", "./Folder", "http://www.google.com", NULL);

Unless you have to use exec, I suggest usingsystemfrom libc, since it is more portable (in case you ever decide you want to port it).


Question:
As we known, we can usepoll/selectwith Netmap:http://info.iet.unipi.it/~luigi/netmap/

Is it possible to useepolland whether it makes sense to use epoll with Netmap, or it has no advantages in speed?

Answer: netmap author here: we have changes to enable epoll() for linux (the equivalent kevent() on FreeBSD is already supported). The advantage only exists when you have to handle several file descriptors in the same poll/select/epoll/kqueue operation.


Question:
I suppose I am just stupid (I tried all). Help me out of here:

```
#include <stdio.h>
#include <string.h>
int main()
{
    const char * y = "747.0";
    double x;
    x = atof(y);
    printf("%.5f\n",x);
    printf("%e\n",x);
    return 0;
}
```

result:

```
0.00000
0.000000e+00
```

Answer: You need to includestdlib.hto offeratof()a prototype, without proper prototype, compiler will suppose its return value be anint.


Question:
As we known, we can usepoll/selectwith Netmap:http://info.iet.unipi.it/~luigi/netmap/

Is it possible to useepolland whether it makes sense to use epoll with Netmap, or it has no advantages in speed?

Answer: netmap author here: we have changes to enable epoll() for linux (the equivalent kevent() on FreeBSD is already supported). The advantage only exists when you have to handle several file descriptors in the same poll/select/epoll/kqueue operation.


Question:
I suppose I am just stupid (I tried all). Help me out of here:

```
#include <stdio.h>
#include <string.h>
int main()
{
    const char * y = "747.0";
    double x;
    x = atof(y);
    printf("%.5f\n",x);
    printf("%e\n",x);
    return 0;
}
```

result:

```
0.00000
0.000000e+00
```

Answer: You need to includestdlib.hto offeratof()a prototype, without proper prototype, compiler will suppose its return value be anint.


Question:
I want to know if there is any alternate C library for the unix command groups,

$ groups  ---- lists all the group id's of the user.

There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.

Answer:
```
#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
```


Question:
I want to know if there is any alternate C library for the unix command groups,

$ groups  ---- lists all the group id's of the user.

There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.

Answer:
```
#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
```


Question:
I'm looking for an easy way to trigger a real page fault (and not a segfault resulting from accessing an already mapped address or a protected address).

What could be one?

I thought of simply run

```
int main(void) {
    int *x = 1000;
    *x = 2000;
}
```

But it does not seem to result in a page fault but rather a memory violation.

Answer: I believemmap()a disk file, and read from or write to it should be enough. At least it is enough on Linux.


Question:
This question already has answers here:Character size in Java vs. C(5 answers)Closed9 years ago.

I've stumbled on this while learning JAVA
I've noticed that char takes 16 bit , while I remember that it takes 8 in C.
can someone explain why they are not resemble ?

Answer: C# chars are Unicode, which is 16-bit, while C only uses ASCII, which is actually only 7 bits.


Question:
how can I sscanf the following string

empty(1)

empty(20)

I tried the following but always failed

```
int count;
sscanf(buf, "%*s(%d)", &count)
```

Thanks in advance!

Answer:
change to

```
sscanf(buf, "%*[^(](%d", &count);
```


Question:
This question already has answers here:Character size in Java vs. C(5 answers)Closed9 years ago.

I've stumbled on this while learning JAVA
I've noticed that char takes 16 bit , while I remember that it takes 8 in C.
can someone explain why they are not resemble ?

Answer: C# chars are Unicode, which is 16-bit, while C only uses ASCII, which is actually only 7 bits.


Question:
how can I sscanf the following string

empty(1)

empty(20)

I tried the following but always failed

```
int count;
sscanf(buf, "%*s(%d)", &count)
```

Thanks in advance!

Answer:
change to

```
sscanf(buf, "%*[^(](%d", &count);
```


Question:
how can I sscanf the following string

empty(1)

empty(20)

I tried the following but always failed

```
int count;
sscanf(buf, "%*s(%d)", &count)
```

Thanks in advance!

Answer:
change to

```
sscanf(buf, "%*[^(](%d", &count);
```


Question:
I am working on a bit complex project, and i wonder is it possible to debug just part of code not entire application because its too slow.
Like i write some lines and code, compile, and then tell to debugger from where to start execution and to assign variable values manually.

Answer: This is only possible if you set up the environment for your part of code which will model the real project. Look atmock objects(brief description).


Question:
```
#include <stdio.h>
#include <time.h>
int main (void)
{
double diff = 0.0;
time_t start;
time_t stop;
time(&start);
print("Enter millisecond to stop");
```

so what is code should add to stop timer after given interval of timer

Answer:
```
int seconds;
scanf ("%d",&seconds);
stop = 0;
while (stop < start + seconds)
    time(&stop);
```


Question:
I would like to change the value of the third letter in apple to "a".
Using the indirection this way gives me a compiler error saying:
invalid type argument of unary ‘*’ (have ‘int’)

```
#include<stdio.h>
int main(){
char c[6]="apple";
*c[2]="a";
return 0;
}
```

Answer:
You should use the following:

```
c[2]='a';
```

In C and C++"x"is a type ofconst char [2]. To specify a character you need to use'x'that is a type ofconst char.


Question:
I have char[] as such

```
char string[] = "Hello world !!!";
```

when I'm trying to reallocate it's memory I'm getting error

```
realloc(string, 50); // error here
```

Answer: You can onlyreallocthings youmalloc/calloc/realloc'ed. Achararray is not any of those things, so it is normal for you to get an error in this case.


Question:
```
#include <stdio.h>
#include <time.h>
int main (void)
{
double diff = 0.0;
time_t start;
time_t stop;
time(&start);
print("Enter millisecond to stop");
```

so what is code should add to stop timer after given interval of timer

Answer:
```
int seconds;
scanf ("%d",&seconds);
stop = 0;
while (stop < start + seconds)
    time(&stop);
```


Question:
my question is about

```
gets()
```

and

```
puts()
```

are they a perfect solution for string input and output?

Answer:
getsis marked as obsolescent in C99 and has been removed in C11 because of security issues with this function. Don't use it, usefgetsinstead. As an historical note,getswas exploited (in fingerd) by the first massive internet worm: the inet worm back in 1988.

putsfunction is OK if it fits your needs.


Question:
I'm trying my C code to build with autotools on mingw+msys.

Could you tell me how to link library likews2_32.libwhen I useautotools.

I think I have to editconfigure.acorMakefile.am.

Answer:
Like this, in the Makefile.am:

```
AM_LDFLAGS = -lws2_32

bin_PROGRAMS = myApp
myApp_SOURCES = myApp.c
...
```


Question:
I have .c files and .f files which are interdependent.
That means, the function used in .c files are defined in .f files.

Now, I want to call for some functions in .c file from my R. How can I do this using R CMD SHLIB?

Answer:
Oh, I figured out this can be easily done by

```
R CMD SHLIB code1.f  code2.c -o myLib
```

Then in R, I can call the myLib via

```
dyn.load("myLib")
```


Question: I am just back from an interview and this question is bugging me. I was asked to write an equivalent expression forx % 8and I couldn't get it. I know it's something to do with 8 being in powers of 2 but I just can't figure it out. This seems like a great programmer community so I'm hoping anyone here can answer this?

Answer: x&7is the answer. (I'm not some hot shot I just googled it)


Question: I am just back from an interview and this question is bugging me. I was asked to write an equivalent expression forx % 8and I couldn't get it. I know it's something to do with 8 being in powers of 2 but I just can't figure it out. This seems like a great programmer community so I'm hoping anyone here can answer this?

Answer: x&7is the answer. (I'm not some hot shot I just googled it)


Question:
```
main()
{
    int a = 10, b = 5, c = 5;
    int d;
    d = a == (b + c);
    printf("%d", d);
}
```

OUTPUT:  1

Can anyone please explain how this value is assigned to d??

Answer:
==has a higher precedence than=, so

```
d = a == (b + c);
```

is equivalent to:

```
d = (a == (b + c));
```

it tests ifais equal tob + c,1if true, and0if false.


Question:
I am trying to gcc my library with another static library and I get this error while runtime

```
undefined symbol: security_getenforce
```

I am thinking this is related to selinux, not sure though... how do I resolve this?

Thanks,
Vik.

Answer: Figured it out, use -lselinux as the flag to resolve the issue and load the necessary libraries.


Question:
```
int a[10];
int *p = a; //way 1
int *p1 = &a[0]; //way 2
```

Could you tell me the differences between two ways above?

Answer:
There is no difference. Both assign the address of the first element to the pointerpandp1respectively.

In the first case,ais automatically converted to the address of the first element. In the second case it uses the address of the first element explicitly.


Question:
Trying to open a file using open(). Returns the correct file descriptor when we call it like so:

```
fd = open("a.txt", O_RDONLY);
```

But when we use a token generated from strtok(), it returns -1:

```
token = strtok(NULL, " ");
fd = open(token, O_RDONLY);
```

Answer: Correctly guessed in comments:tokenis not actually the same string as"a.txt", but contains extra whitespace at the end, which makes it hard to see when printed as a string.


Question:
I'm trying

```
typedef struct
{
    int x = 5;
    char str[20];
}  nodeStr;
```

It works in C++, but doesn't in C. For it to work in C I need to cut the definition ofx(i.e.,= 5) from the code. Is there in conceptual difference in C and C++ explaining this? Thanks!

Answer: In-class initialization is a new C++11 feature - if you use a (not much) older C++ compiler, it won't compile. So yes, it's a difference between C and C++.


Question:
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed9 years ago.

What makes this construction?

```
int a[10];
int x;
x = 2[a];
```

I do not understand what makes 2 [a]. It is another senility of C language?

Answer:
It is

2[a] = *(2 + a) = *(a + 2) = a[2]

Note:+operator holds commutative property


Question:
I am using a serial port in my c program. If there is nothing connected to this serial port, what can I expect from a call of read( )in my program? Would the program hang or return an error?
Thank you!

Answer:
From theman pageit would probably returnEBADF.

Have you tried it? If not, it might be better to tell us what you want to achieve (block until something is connected, throw an error, etc.) so users can better guide you.


Question:
I have 2 enums.

```
typedef enum {
 BLUE = 1,
 RED = 2
} FavoriteColor;

typedef enum {
 ORANGE = 1,
 YELLOW = 2,
 RED = 3
} Color;
```

In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?

Answer:
You can't. And the compiler should warn you about that.

enumconstants live in the global namespace. The second definition is a redefinition that should produce an error.


Question:
I am using a serial port in my c program. If there is nothing connected to this serial port, what can I expect from a call of read( )in my program? Would the program hang or return an error?
Thank you!

Answer:
From theman pageit would probably returnEBADF.

Have you tried it? If not, it might be better to tell us what you want to achieve (block until something is connected, throw an error, etc.) so users can better guide you.


Question:
I have 2 enums.

```
typedef enum {
 BLUE = 1,
 RED = 2
} FavoriteColor;

typedef enum {
 ORANGE = 1,
 YELLOW = 2,
 RED = 3
} Color;
```

In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?

Answer:
You can't. And the compiler should warn you about that.

enumconstants live in the global namespace. The second definition is a redefinition that should produce an error.


Question:
I am using a serial port in my c program. If there is nothing connected to this serial port, what can I expect from a call of read( )in my program? Would the program hang or return an error?
Thank you!

Answer:
From theman pageit would probably returnEBADF.

Have you tried it? If not, it might be better to tell us what you want to achieve (block until something is connected, throw an error, etc.) so users can better guide you.


Question:
I have 2 enums.

```
typedef enum {
 BLUE = 1,
 RED = 2
} FavoriteColor;

typedef enum {
 ORANGE = 1,
 YELLOW = 2,
 RED = 3
} Color;
```

In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?

Answer:
You can't. And the compiler should warn you about that.

enumconstants live in the global namespace. The second definition is a redefinition that should produce an error.


Question:
I have an array that is already sorted in partitions of 4:

```
2, 23, 45, 55, 1, 4, 23, 74545, 75, 234, 323, 9090, 2, 43, 6342, 323452
```

What would be the most efficient way to sort this array?  Note: the array size is always even and the program knows that every 4 elements are sorted.

Answer: I think you can usemerge sortfor problems like this.


Question:
I have an array that is already sorted in partitions of 4:

```
2, 23, 45, 55, 1, 4, 23, 74545, 75, 234, 323, 9090, 2, 43, 6342, 323452
```

What would be the most efficient way to sort this array?  Note: the array size is always even and the program knows that every 4 elements are sorted.

Answer: I think you can usemerge sortfor problems like this.


Question:
If I have two file pointers and do the following:

```
FILE *f1,*f2;
f1= fopen("inputfile","r+");
f2=f1;
fclose(f2);
```

Is the equal operation valid, if it is, will the last line close f1 as well?

Answer:
It is enough, both will be closed and both will point to a closed file.

Assigningf2=f1doesn't do anything magical (increasing a reference count or duplicating descriptors).


Question:
I'm trying to rename a file through a system() command and I get (The filename, directory name, or volume label syntax is incorrect)

This is the line from my code:
system("ren" "C:\Users\Mac\Desktop\new folder\03 Elfsong - Shar.mp3 test.mp3");

What is the syntax problem here?

Answer:
renis a cmd.exe built-in command, it's not a standalone executable, so you'd have to do

```
system("CMD", "/c ren originalname newname");
```


Question:
I want to compare datetime in C. I googled but I didn't get any proper solution. I am having datetime in string format i.e date1 = "2014-02-13 12:22:21" and date2 = "2014-02-10 12:22:21".
Now, I want comparison b/w date1 and date2.
Please suggest me proper solution.

Answer: Just usestrcmp.  It works because with this particular date/time format, the lexicographical order is the same as the chronological order.


Question:
If I have an instruction:

```
imull $eax, $ecx
```

so that it is multiplying what is stored in the two registers, where is the answer stored?

Answer: Different assemblers work differently.   For the GNU Assembler the result will go in$ecx.  This is the opposite convention from most windows assemblers.


Question:
How can I compile it on a 32-bit system so it can run as backward compatible under a 64-bit system? I know it can be done because Adobe, Dropbox and other companies have such binaries. How should I link them, dynamically, statically? Static only some libraries and other dynamic?

I'm talking about a simple code like:

```
int main() {
  printf("Hello world!\n");
}
```

Thank you!

Answer: Normally. Then install the 32-bit libraries on the 64-bit system.


Question:
How can I compile it on a 32-bit system so it can run as backward compatible under a 64-bit system? I know it can be done because Adobe, Dropbox and other companies have such binaries. How should I link them, dynamically, statically? Static only some libraries and other dynamic?

I'm talking about a simple code like:

```
int main() {
  printf("Hello world!\n");
}
```

Thank you!

Answer: Normally. Then install the 32-bit libraries on the 64-bit system.


Question: I am writing a C program, that uses *NIX System calls. Now, when the user calls for deleting a particular file, I want to remove all the symbolic links created to the file, also to be removed. How can this be achieved?

Answer: You can't, unless you search the whole directory tree, or you have some other means of knowing where these symbolic links are. A file doesn't "know" which symlinks point to it. You have to locate each symlink on your own andunlink()it.


Question: I am writing a C program, that uses *NIX System calls. Now, when the user calls for deleting a particular file, I want to remove all the symbolic links created to the file, also to be removed. How can this be achieved?

Answer: You can't, unless you search the whole directory tree, or you have some other means of knowing where these symbolic links are. A file doesn't "know" which symlinks point to it. You have to locate each symlink on your own andunlink()it.


Question:
Can I put#define MY_VAR 1in a file and#define MY_VAR 2in a different file without any problem?

In other words, is#definea local or a global definition?

Answer:
The answer depends on what kind of file you are talking about:

If it is a header file, then your#define-d constant is visible in all files including the headerIf it is a .c/.m/.mm./.cpp file, then#defined constant is limited in scope to the file where it is defined.


Question:
Can I put#define MY_VAR 1in a file and#define MY_VAR 2in a different file without any problem?

In other words, is#definea local or a global definition?

Answer:
The answer depends on what kind of file you are talking about:

If it is a header file, then your#define-d constant is visible in all files including the headerIf it is a .c/.m/.mm./.cpp file, then#defined constant is limited in scope to the file where it is defined.


Question:
when i'm tryin' to use malloc with string pointers to scan, it's givin' a segmentation fault

```
main(){
    char *a;
    a = (char)malloc(50);
    printf("enter a string\t");
    scanf("%s", a);
    printf("%s\n", a);
}
```

Answer:
```
a = (char)malloc(50);
```

Here, you meant to cast its type tochar *instead ofchar.

Note that it's better not to cast the return type ofmalloc. SeeDo I cast the result of malloc?


Question:
For example having string:

```
Hello World!
```

How to make strcopy function working from position 6 and copy onlyWorld!to another buffer ?

Answer:
```
char source[] = "Hello World!";
char destination[7]; // 7 = strlen("World!") + 1

strcpy(destination, source + 6);
```


Question: Is there a way to grow an array in C, but only if the memory can be grown in place (That is, fail to grow if the pointer needs to be changed)?

Answer: In standard C there is no function capable of doing that.


Question:
```
int main()
{
    struct books
    {
        char name;
        float price;
    }b1;
    printf("%u   %u",&b1.name,&b1.price);
}
```

When I run the above code, I get the following output:-

```
2686728    2686732
```

As thesizeof(char)is 1, so why there is a difference of 4 in the above two addresses?

Answer: Padding. The compiler inserts 3 bytes of padding between thenameandpricefields so accessingpricedoesn't run into alignment troubles.


Question:
```
int main()
{
    struct books
    {
        char name;
        float price;
    }b1;
    printf("%u   %u",&b1.name,&b1.price);
}
```

When I run the above code, I get the following output:-

```
2686728    2686732
```

As thesizeof(char)is 1, so why there is a difference of 4 in the above two addresses?

Answer: Padding. The compiler inserts 3 bytes of padding between thenameandpricefields so accessingpricedoesn't run into alignment troubles.


Question:
This question already has answers here:Detect 32-bit or 64-bit of Windows(14 answers)Closed9 years ago.

I was looking for a way to determine the above. I could not really find it easily and google somehow couldn't help me much with it too.

Thanks.

Answer: You need theGetNativeSystemInfo()API Call. The information you are looking for will be returned in theSYSTEM_INFOstructure in thewProcessorArchitecturemember.


Question:
This question already has answers here:Detect 32-bit or 64-bit of Windows(14 answers)Closed9 years ago.

I was looking for a way to determine the above. I could not really find it easily and google somehow couldn't help me much with it too.

Thanks.

Answer: You need theGetNativeSystemInfo()API Call. The information you are looking for will be returned in theSYSTEM_INFOstructure in thewProcessorArchitecturemember.


Question:
I have an unsigned char and i want to write0x06on the four most significant, and i want to write0x04on its 4 least significant bits.
So the Char representation should be like0110 0010

Can some can guide me how i can do this in C?

Answer:
```
c = (0x06 << 4) | 0x04;
```

Because:

```
0x04    = 0000 0100
0x06    = 0000 0110

0x06<<4 = 0110 0000
or op:  = 0110 0100
```


Question: If type of the value cannot be analyzed or found out by looking into the bits(As written in books I have referred), how does the machine know how the value should be manipulated?

Answer: C and C++ arestatically typed, meaning that types are a compile-time concept. The compiler generates code to manipulate the bits in a manner appropriate to the type; the machine executes that code, and doesn't need to know anything about the type.


Question:
I'm trying to reverse some pointers that were read from a binary encoded file.

When I try to reverse the pointer 0xfffe0024540 stored in big endian format, I get
0xffffffffe0024540

The pointer is stored in the file in the format:
0000 ff0f 02e0 4045

Answer:
The behaviour of right-shifting a negative signed integer is implementation dependent,
as far as I remember. You should replacelongbyunsigned longoruint64_t.


Question:
New to both python, and fairly beginner in C. Why will the subject code return an error in python?

Does the assignment not have a return value?

Answer: This is simply not valid in Python. You can't use an assignment as an expression.


Question:
I went through the documentation, but still didn't get what does optlen do ingetsockopt(int s, int level, int optname, void *optval,
               socklen_t *optlen), can anyone explain?

Answer:
You set it to the size of the data item you're receiving the option value into. On return the size may have been adjusted.

The documentation does say that.


Question:
Givennandmunsigned integral types, will the expression

```
(n & m) <= m
```

always be true ?

Answer:
Yes, it is true.

It should be readily apparent that a necessary condition fory > xis that at least one bit position is set to1inybut0inx.  As&cannot set a bit to1if the corresponding operand bits were not already1, the result cannot be larger than the operands.


Question:
New to both python, and fairly beginner in C. Why will the subject code return an error in python?

Does the assignment not have a return value?

Answer: This is simply not valid in Python. You can't use an assignment as an expression.


Question:
I went through the documentation, but still didn't get what does optlen do ingetsockopt(int s, int level, int optname, void *optval,
               socklen_t *optlen), can anyone explain?

Answer:
You set it to the size of the data item you're receiving the option value into. On return the size may have been adjusted.

The documentation does say that.


Question:
Givennandmunsigned integral types, will the expression

```
(n & m) <= m
```

always be true ?

Answer:
Yes, it is true.

It should be readily apparent that a necessary condition fory > xis that at least one bit position is set to1inybut0inx.  As&cannot set a bit to1if the corresponding operand bits were not already1, the result cannot be larger than the operands.


Question:
Suppose I have

```
char *t = "XX";
```

I am wondering what is the type of &t. Is it char or array?

Answer: The type of&tfor any expression is a pointer to the type oft.  In this case the type oftischar*hence the the type of&tischar**


Question:
If I have

```
a = 3;
b = 5;
```

How can I make it so that

double result = 3e5, but only using variables?

I know aeb won't work, obviously.

Answer:
Try:

```
double result = a * pow(10.0,(double)b);
```

Or, with GNU extensions:

```
double result = a * exp10((double)b);
```

In either case, #include math.h and link with the math library (eg.-lm).  This is likely much more efficient than piecing together a string and converting to double.


Question: How to find which data is currently union variable is holding out of the many fields present in the union without keeping extra variable to track it.

Answer: Unfortunately, you can't do this. All of the variables are holding some or all of the same data in memory, whether that data is meaningful or not.


Question: How to find which data is currently union variable is holding out of the many fields present in the union without keeping extra variable to track it.

Answer: Unfortunately, you can't do this. All of the variables are holding some or all of the same data in memory, whether that data is meaningful or not.


Question: What is a good way to create a double from a coefficient and a power of 10? Or in other words, what is a good way to create a double from the significand and the exponent of a written scientific notation value at runtime?

Answer:
Not sure about numerical quality, but the obvious way would be:

```
double make_double(double coefficient, int power)
{
  return coefficient * pow(10.0, power);
}
```


Question:
This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed9 years ago.

```
int (*ptr)[10];
```

I know whatint *ptr[10];its a 10 member array where each element is a pointer to an integer.

But what does the above piece code create ?

Answer:
```
int *ptr[10]
```

is an array of 10intpointers,

int (*ptr)[10]

is a pointer to an array of 10ints


Question:
This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed9 years ago.

```
int (*ptr)[10];
```

I know whatint *ptr[10];its a 10 member array where each element is a pointer to an integer.

But what does the above piece code create ?

Answer:
```
int *ptr[10]
```

is an array of 10intpointers,

int (*ptr)[10]

is a pointer to an array of 10ints


Question:
gcov primarily is a code coverage tool. However, is there any way we can find LOC (excluding comments...etc) with gcov?

It must be easy for gcov to get that information, but I didn't find any documentation on that.

Also, let me know if you know any other tool which can calculate lines of code in such manner.

Answer: You can also look atSLOCCount, which is available in packages on most Linux distributions.


Question:
I'm trying to create a folder inside /var/mobile/Library/MyAppName. I read on internet that I must use the command:

```
mkdir(“/var/mobile/Library/YOURAPPNAME”, 0755);
```

but xcode cannot recognize that command... how can I solve?

Answer:
Formkdir(), add

```
#include <sys/stat.h>
```

You can get this information from "man 2 mkdir" on the command line,
or fromhttp://pubs.opengroup.org/onlinepubs/009695399/functions/mkdir.html.


Question:
I'm trying to create a folder inside /var/mobile/Library/MyAppName. I read on internet that I must use the command:

```
mkdir(“/var/mobile/Library/YOURAPPNAME”, 0755);
```

but xcode cannot recognize that command... how can I solve?

Answer:
Formkdir(), add

```
#include <sys/stat.h>
```

You can get this information from "man 2 mkdir" on the command line,
or fromhttp://pubs.opengroup.org/onlinepubs/009695399/functions/mkdir.html.


Question: I have a statically linked executable compiled from a C program.objdump -x a.outindicates the presence of the.eh_framesection, even afterstrip -s.Why is this section useful in a C(non-C++) program?What are the risksof stripping it (withstrip -R .eh_frame)?

Answer:
From remyabel's comment and OP's confirmation, the answer to the OP question is available via another SO question as linked by:

Why GCC compiled C program needs .eh_frame section?


Question:
This question already has answers here:MIN and MAX in C(16 answers)Closed9 years ago.

Is there any library function incfor finding out the largest number between two numbers?

Answer:
You can do

```
#define new_max(x,y) (((x) >= (y)) ? (x) : (y))
#define new_min(x,y) (((x) <= (y)) ? (x) : (y))
```

valter


Question: If I try objdump -t /usr/bin/sort command it says no symbols. But it seems to work on my programs. What is the reason for this?

Answer: The symbols of /usr/bin/sort has been removed, e.g. with thestripprogram - for most executables the symbol table is not needed (or only needed for debugging).Hereis a bit more info.


Question:
I have the following data

```
uint16_t a[1] = { 0x2321 };
```

I want to convert to uint8_t as:

```
uint8_t b[1] = { 0x21 };
```

How can I do it in a C program?

Answer:
Cast the lower byte:

```
uint16_t a[1] = {0x2321};
uint8_t b[1] = {(uint8_t)(a[0] & 0xFF)};
```


Question:
I have the following data

```
uint16_t a[1] = { 0x2321 };
```

I want to convert to uint8_t as:

```
uint8_t b[1] = { 0x21 };
```

How can I do it in a C program?

Answer:
Cast the lower byte:

```
uint16_t a[1] = {0x2321};
uint8_t b[1] = {(uint8_t)(a[0] & 0xFF)};
```


Question: I am using C/C++ Eclipse. Is there an option in the IDE or an external tool to figure out the chain as to how a header file is eventually being included?

Answer:
You could just put an#errorin the header file, the compiler should give you a trace like:

```
In file included from someheader.h:1:0,
                 from myheader.h:1,
                 from mysourcefile.c:1:
header_im_tracing.h:1:2: error: #error foobar
```


Question:
Can we write or call "C code" in XAML for Windows Phone 8,

i'm having C library and i have to use it in WP8 application. any idea..

Answer:
Yes you can - but you have to link it against a C++ project. What you need is a WinRT component that links against that library and acts as a wrapper. That component can then be used in C#.

Check outMSDN docs.


Question:
I know that we can create a macros in c- language by using preprocessor(#define), but can we create macros with out using preprocessors i;e without #define. if there is any please help me..

Thank you

Answer: In the standard C language, macros are created with#define. There is no other way.


Question: I don't know why this code works. it supposed to print out every student which follows chem. but why does a number for instance 21&4(student 123001) evaluate to true while a number like 49&4(123008) doesn't?

Answer:
I think it is due to bit operation AND.

In binary

```
49 is 110001
 4 is 000100
 & =  000000
```

So it evaluates tofalse

wheras

```
21 is 10101
 4 is 00100
 & =  00100
```

So you get a non-zero result which is true.


Question:
I am trying to setup MinGW with NetBeans IDE.
I've downloaded mingw-get-setup.exe but i do not understand which packages should i choose for c and c++ compiler.
please help

Answer:
For basic C/C++ installation you can choose following options from Installation Manager as highlighted :

Msys-Base is not necessary


Question:
```
#include<stdio.h>
void main()
{
float a=10.5;
printf("%d%d",sizeof(a),sizeof(10.5));
}
```

OUTPUT:
4 8

I want to know why it happens?

Answer: In C a floating point literal is actually a double unless you suffix it with an f (i.e.10.5f).


Question: Say there is a very large number, 100 digits which is stored in an array. Now i want to divide this number by another number(say 2) , Can anyone suggest how to do it?

Answer: Try to do it exactly as you would do that on paper. For small divisors (as 2) this is an O(d) algorithm (where d is the number of digits) and it is impossible to find anything asymptotically better since you need to check each digit at least once.


Question:
Is there anyway in C to get an image, stream by stream and how can I understand how many stream there are in an Image?

the Image is in JPEEG type.
and for saving this stream in another file I'll have any problem?

Answer:
You can have a look to the free OpenCV library :http://opencv.org/

Here there is a tutorial with some examples :http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/

It's largely used for this kind of treatments.


Question:
I have a C program running on a Unix box.

I would like to print a timestamp to an output file - at the moment I use the commanddateto print the datetime on the terminal.

```
fprintf(outputfile, "%s ", date);
```

How do I go about doing this?

Answer:
Use POSIXstrftime(3) - format date and timefor a C solution.  It use the same format strings asdate(1)

I also recommend you read thestandard library intro(3).


Question: I have mp4 video which has around 50000 frames of size 1920x720. I have to remove a specific area in the video (all frames). Can you suggest a method in MATLAB?

Answer: Specify a ROI(Region of Interest) for each individual frame of the video, where the ROI is the specific area that you wanted to remove. Quite simple. Hope my advice helped. If u are still not sure, comment on this answer, I will add in more hints.


Question: I have mp4 video which has around 50000 frames of size 1920x720. I have to remove a specific area in the video (all frames). Can you suggest a method in MATLAB?

Answer: Specify a ROI(Region of Interest) for each individual frame of the video, where the ROI is the specific area that you wanted to remove. Quite simple. Hope my advice helped. If u are still not sure, comment on this answer, I will add in more hints.


Question: I have mp4 video which has around 50000 frames of size 1920x720. I have to remove a specific area in the video (all frames). Can you suggest a method in MATLAB?

Answer: Specify a ROI(Region of Interest) for each individual frame of the video, where the ROI is the specific area that you wanted to remove. Quite simple. Hope my advice helped. If u are still not sure, comment on this answer, I will add in more hints.


Question:
Doxygen seems to expect C++ and lists my structs as "classes" in the HTML output.

How can I get Doxygen to process my source as C not C++?

Answer:
Try

```
OPTIMIZE_OUTPUT_FOR_C=YES
```

in yourDoxyfile, see if that's more to liking.


Question:
How to

```
if (x == 1) printf("2\n");
else if (x == 2) printf("1\n");
else printf("0\n");
```

using bitwise operators?

My attempt is:

```
for (x = 0; x < 8; x++) {
    printf("%d\n",  0x03 & (0x03 ^ x));
}
```

Output:

```
3
2
1
0
3
2
1
0
```

Desired output:

```
0
2
1
0
0
0
0
0
```

Answer:
This is insane, but I finally figured it out:

```
printf("%d\n", (3 & ~(x & 3)) & (0xfc >> (x << 1)));
```


Question:
So, that's the question: can I increment theivariable insideforloop?:

```
for(int i = 0; i < 1000; i++)
{
    i++; // is this legal? if not what is the alternative?
}
```

Answer:
Absolutely legal but not very intuitive.

Consider using a while loop instead if you need to manipulate your looping in this way (it's just a code clarity thing, not a legal thing).


Question: I understand a condition is supposed to be for example y==3, but y-3 is totally confusing to me. I can't understand this code. If y-3 is true it prints 1. How can y-3 be true or false?

Answer: The expressiony - 3results in a value which can be tested for truthness.  In C 0 is false and any non-zero value is true.  Sayingif (y - 3)is essentially sayingif (y - 3 != 0)or even more succinctlyif (y != 3)


Question:
I'm writing this code to use sizeof() function with a char array of 7 elements, I thought that the output should be 8 because of the 7 elements PLUS the terminator of the array but surprised that the output was 5?? HOW COME?

```
#include<stdio.h>

int main(void)
{
    char str[]="S\065AB";
    printf("\n%d",sizeof(str));

return 0;
}
```

Answer: \065is a single character, represented as an octal escape sequence.


Question:
i cannot figure out why NULL is not printed

```
#include "stdio.h"
#include "stddef.h"

typedef struct{

    int info;
    struct DEMO1* next;
} DEMO1;

int main()
{
    int temp;
    DEMO1 *head ;
    if(head==NULL)
    printf("NULL");
}
```

Answer: Memory is not initialized upon allocation. You cannot expect it to have a particular value until you set it.


Question:
I want to know how to make Cmake give me a target that will allow me to save the .i files from myCprogram with the macro expansion, etc completed.

Will I need to make a custom target to do this?

Answer: If your are using the Makefile generator, then there are already targets for .i files. Typemake help, and you will see all the targets, including those suffixed by.i,.s, and.o.


Question:
I want to know how to make Cmake give me a target that will allow me to save the .i files from myCprogram with the macro expansion, etc completed.

Will I need to make a custom target to do this?

Answer: If your are using the Makefile generator, then there are already targets for .i files. Typemake help, and you will see all the targets, including those suffixed by.i,.s, and.o.


Question: I am trying to access a column from an excel document from a C code in Linux. Is there a simple way to do this? There are more than 47000 rows and I want to store the data of particular column into an array of data structure.

Answer: Use xlsLib library for parsing excel file. You can find more informationhereandHere


Question:
Is it possible, under some circumstance, in ANSI-C, to start arrays in index 1 instead of 0? (some compiler options which stays under the definition of ANSI-C, not MACROS or such)

e.g

```
int arr[2];
arr[2] = 5;
arr[1] = 4;
```

will be valid code which will behave properly.

Answer:
No.

There is no such thing in ANSI C.


Question:
How can I castvoid*toint ( * () ) (int,...)?

Thevoid*is coming from adlsym. This code isn't compiling:

```
typedef  int ( *PSYS () ) (int,...);
PSYS getf =  (PSYS) dlsym(lib, "function" );
```

Answer:
PSYS is the type of a function, not a pointer to a function. You want

```
typedef  int ( *PSYS () ) (int,...);
PSYS* getf =  (PSYS*) dlsym(lib, "function" );
```


Question:
I would like to know what does this expression test:

```
if ((a=b)!=0)
```

Is it equivalent to(if (a!=0))?

Answer:
When used as an operator,=both assigns the value from the right side to the variable on the left side and returns the new value of that variable (for example, ifais an integer value,(a=3.4)returns 3). So this is equivalent to:

```
a=b;
if(a!=0)
```


Question:
I'm not sure what I am doing wrong here, I am following a tutorial online(thenewboston) and I am getting an error that says "w used as the name of the previous parameter rather than as part of the selector."

```
-(void)setWH: (int) w:(int) height;
```

Answer:
You're missing part of the selector name:

```
- (void)setWidth:(int)width height:(int)height;
//                          ^--- You're missing this.
```


Question:
I'm programming in C. I'd like to search a string inside of a string.
Are there any built-in function that does that in string.h ? Or do you know how to create one ?

Answer:
Are there any built-in function that does that in string.h ?

Yes. Take a look atstrstr(), which is part of the standard library and declared in string.h.


Question:
I have set the "Architectures" setting in Xcode to armv7, armv7s.

What happens when I run my app on an arm64 device like the iPhone5s.

Will the size oflongbe 64bit or 32bit ?

Answer:
Thecompilercreates 32-bit or 64-bit code, depending on the selected architecture.

Therefore, if the app is compiled for a 32-bit architecture (like armv7, armv7s),
the size oflongis 32-bit, regardless of the actual device that the code is
running on.


Question:
I'm programming in C. I'd like to search a string inside of a string.
Are there any built-in function that does that in string.h ? Or do you know how to create one ?

Answer:
Are there any built-in function that does that in string.h ?

Yes. Take a look atstrstr(), which is part of the standard library and declared in string.h.


Question:
I have set the "Architectures" setting in Xcode to armv7, armv7s.

What happens when I run my app on an arm64 device like the iPhone5s.

Will the size oflongbe 64bit or 32bit ?

Answer:
Thecompilercreates 32-bit or 64-bit code, depending on the selected architecture.

Therefore, if the app is compiled for a 32-bit architecture (like armv7, armv7s),
the size oflongis 32-bit, regardless of the actual device that the code is
running on.


Question:
This question already has an answer here:Determining if file has been copied or not in C [closed](1 answer)Closed9 years ago.

In Windows, if you go to a file's properties it shows the last access time right under the time last modified. This changes when I copy it.

How do I view this in C?

Answer: You can use theGetFileTime()function to get it. ThisMSDN articlehas more details about file times.


Question: I know how to count nodes on a level of a tree recursively (used tips from this answerhttps://stackoverflow.com/a/12879973/2663649), but I can't form an iterative algorithm, and not sure if I should use stack or pointer array to save previous nodes (to return to root).

Answer: You can turn your recursive algorithm into an iterative one.Just use a stack structure where you do the recursion.


Question:
I have a text file in which of its line, there is two numbers. each of them are nodes of a graph. the size of the file is 1.5 gb and had has 92522018 lines. the wanted thing is the node with maximum number of edges.

i need the the array for solving this problem.

is there any way to allocate this size of array or even bigger?

Answer:
For C,

Usemalloc

For C++,

UseVectors


Question:
I wrote a simple code with dev but it does not return any thing.but with code block answer shows.what is the problem?

```
#include <stdio.h>

int main() {
    int x,y,z;
    scanf("%d%d",&x,&y);
    while(z!=0){
        z=x%y;
        printf("%d",z);
    }
    return 0;
}
```

Answer:
Two problems I can see:

```
1. Value to z is un-assigned. So garbage.
2. Value of z will not change, so it's infinite loop.
```


Question:
The following prints the percentage of memory used.

```
printf (TEXT("There is  %*ld percent of memory in use.\n"),
            WIDTH, statex.dwMemoryLoad);
```

WIDTH is defined to be equal to 7.

What does TEXT mean, and where is this sort of syntax defined in printf?

Answer:
As others already said,TEXTis probably a macro.

To see what they become, simply look at the preprocessor output. If are using gcc:

```
gcc -E file.c
```


Question:
I have a text file in which of its line, there is two numbers. each of them are nodes of a graph. the size of the file is 1.5 gb and had has 92522018 lines. the wanted thing is the node with maximum number of edges.

i need the the array for solving this problem.

is there any way to allocate this size of array or even bigger?

Answer:
For C,

Usemalloc

For C++,

UseVectors


Question:
I wrote a simple code with dev but it does not return any thing.but with code block answer shows.what is the problem?

```
#include <stdio.h>

int main() {
    int x,y,z;
    scanf("%d%d",&x,&y);
    while(z!=0){
        z=x%y;
        printf("%d",z);
    }
    return 0;
}
```

Answer:
Two problems I can see:

```
1. Value to z is un-assigned. So garbage.
2. Value of z will not change, so it's infinite loop.
```


Question:
The following prints the percentage of memory used.

```
printf (TEXT("There is  %*ld percent of memory in use.\n"),
            WIDTH, statex.dwMemoryLoad);
```

WIDTH is defined to be equal to 7.

What does TEXT mean, and where is this sort of syntax defined in printf?

Answer:
As others already said,TEXTis probably a macro.

To see what they become, simply look at the preprocessor output. If are using gcc:

```
gcc -E file.c
```


Question:
The following prints the percentage of memory used.

```
printf (TEXT("There is  %*ld percent of memory in use.\n"),
            WIDTH, statex.dwMemoryLoad);
```

WIDTH is defined to be equal to 7.

What does TEXT mean, and where is this sort of syntax defined in printf?

Answer:
As others already said,TEXTis probably a macro.

To see what they become, simply look at the preprocessor output. If are using gcc:

```
gcc -E file.c
```


Question: Should I use the header ctgmath? It automatically includes cmath and ccomplex. It has some predefined macros. Should its inclusion affect my code or usage of these macros decrease the efficacy?

Answer: No, Simply including the headers in your code doesn't decrease the efficiency... Also macro inclusion doesn't change the speed cos, macro expansion happens during compile time not at run time.


Question:
Why

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

prints1in output. I expect something like=

Answer:
061 octal == 49 decimal == 0x31 hex. That's the ASCII code for the character'1'

Why do you expect'='?


Question: Currently,strstrfunction returns the starting location of the found string; but I want to search for multiple strings and it should return me the location of the found string otherwise return NULL. Can anyone help how I can do that?

Answer: Store the answer, and callstrstr()again, starting at the returned location + the length of the search string. Continue until it returnsNULL.


Question: I have been searching for some time and haven't found a definitive answer yet. The only link I found till now which sheds some light on this ishere.

Answer:
According to thePOSIX Specificationsyslog(), openlog() and closelog() are thread safe.

There's another thread that answers this question as well and it is dated as far back as 2009. Here's the linksyslog_r for Linux?.


Question: Need to make int from hex representation string like"0xFA"or better"FA". Need something likeatoi("FA"). Is there are any standard solutions for that?

Answer:
Try to usestrtol():

```
strtol("FA", NULL, 16);
```


Question:
When I initialize variables, I do bellow.

```
int i = 0;
char *myText = NULL;
```

Then, haw can I initializestruct sockaddr_intype variables?

```
struct sockaddr_in addr = ?;
```

Answer:
If you want to set all fields to zero in a declaration, no matter the structure, then do e.g.

```
struct some_struct var = { 0 };
```


Question: Need to make int from hex representation string like"0xFA"or better"FA". Need something likeatoi("FA"). Is there are any standard solutions for that?

Answer:
Try to usestrtol():

```
strtol("FA", NULL, 16);
```


Question:
Looking atffmpegexamples/muxing.c. When I encodemp3, in 2/3 casesgot_packetis zero and if it's zero for the last frame, I have noAVPacketto write to the file.

How to tellffmpegto flush the remaining data to a packet?

Answer:
Call avcodec_encode_audio2() with null frame

when flushing an encoder that has the CODEC_CAP_DELAY capability set


Question:
Is it safe to doconnect()in blocking and after that, make the socket nonblock and do all nonblocking stuff for exampleepoll()/select()?

Does it cause to lack of some nonblocking operation that might I'm not considering?

Answer: It's perfectly safe so long as you make sure to check the return value offnctlfor an error.  If not, then you could find your program halting unexpectedly.


Question:
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed9 years ago.

I have tried escaping it using a backslash.

```
#include <stdio.h>

int main(void) {
    printf("\%");
    return 1;
}
```

But it doesn't work. What is the correct syntax?

Answer:
Two percentage signs:

```
printf("%%");
```


Question:
I have a 2D array.

```
int MARIO[4][4];
```

I want to show the values of this array on the screen. The problem is that I don't know how to declare a pointer to a 2D array. Can anyone help?

Answer: Ugh, so to answer theactualquestion:int (*ptrTo2DArr)[4][4];


Question:
I have a 2D array.

```
int MARIO[4][4];
```

I want to show the values of this array on the screen. The problem is that I don't know how to declare a pointer to a 2D array. Can anyone help?

Answer: Ugh, so to answer theactualquestion:int (*ptrTo2DArr)[4][4];


Question:
This question already has answers here:typedef fixed length array(7 answers)Closed9 years ago.

One of my C functions takes the following as it first argument

```
struct list *items[32]
```

how do I make atypedeffor this?

Answer: The answer istypedef struct list* ProcList[32];


Question:
I need to read/write to INI file in C. It is a little strange for me that I can't find any standard way of doing that. What is the common way of dealing with INI files in C?

I prefer both - platform independent and Linux INI file parser libs.

Answer: Thislinkmay shed some light on the matter (written by the guy that authoredinihas mentioned by Zagorulkin Dmitry) - I have usedminIniand been happy with it..


Question:
Question is really simple.
I need a tool to convertchar*to ip adress and use it in

```
sockaddr_in.s_addr
```

arpa/inet.h hasinet_addr()function, but I am not sure if I already have this file somewhere in MS VS 2010 installation or should I get it elsewhere.

Answer:
Win32 provides its own implementation of the sockets API (Winsock) which uses slightly different headers.

From theMSDN forinet_addr:

Header Winsock2.h


Question:
I have to print 1,000,000 four digit numbers. I usedprintffor this purpose

```
for(i=0;i<1000000;i++)
 {
     printf("%d\n", students[i]);
 }
```

and it turns out to be too slow.Is there a faster way so that I can print it.

Answer: You could create an array, fill it with output data and then print out that array at once. Or if there is memory problem, just break that array to smaller chunks and print them one by one.


Question:
I want to declare a shared matrix in the global address space but not to perform any calculations by the UPC threads, but the GPU using CUDA.

So is it possible to declare a UPC shared array in which the number elements in the array is NOT equal or a multiply of the number of threads (THREADS variable) ?

Answer: Assign the number of threads at the compile time using upcc flags. For more information on upcc flags checkupcc man page.


Question: How would I verify that there is only one white space between each parameter, string, int, int in this string "string int int" using sscanf?

Answer:
Use%n

```
// "string int int"
char dest[100];
int d[2];
int n[4];
int result = sscanf(buf, "%99s%n %n%d%n %n%d",
  dest, &n[0], &n[1], &d[0], &n[2], &n[3], &d[1]);
if ((result == 3) && (n[1] - n[0] == 1) && (n[3] - n[2] == 1)) {
  LifeIsGood();
}
```


Question: How would I verify that there is only one white space between each parameter, string, int, int in this string "string int int" using sscanf?

Answer:
Use%n

```
// "string int int"
char dest[100];
int d[2];
int n[4];
int result = sscanf(buf, "%99s%n %n%d%n %n%d",
  dest, &n[0], &n[1], &d[0], &n[2], &n[3], &d[1]);
if ((result == 3) && (n[1] - n[0] == 1) && (n[3] - n[2] == 1)) {
  LifeIsGood();
}
```


Question:
I have a date encoded (big endian) in 4 bytes that I'm trying to read from a binary file.

I do:

```
char date[4];
long seconds;
s = read(fd, date, sizeof(char) * 4);
seconds = (date[3]<<0) | (date[2]<<8) | (date[1]<<16) | (date[0]<<32);

printf("%s\n", ctime(&seconds));
```

But I get:

```
Thu Jan  1 00:59:27 1970
```

What's wrong with my code ? Thanks.

Answer:
```
(date[0]<<32);
```

looks wrong.16 + 8is24not32.


Question:
We are using PCRE pattern in our C code to do the matching. We are keep on adding patterns and now it crossed 1024 characters. Now the PCRE is not loading for this key at all.

Is there any limitation on PCRE like above?

What all are the alternatives?

Appreciate your support.

Thanks,
Mathew Liju

Answer:
As mentioned, we have split the regex into smaller chunks and resolved.

Appreciate for the comments.


Question:
We are using PCRE pattern in our C code to do the matching. We are keep on adding patterns and now it crossed 1024 characters. Now the PCRE is not loading for this key at all.

Is there any limitation on PCRE like above?

What all are the alternatives?

Appreciate your support.

Thanks,
Mathew Liju

Answer:
As mentioned, we have split the regex into smaller chunks and resolved.

Appreciate for the comments.


Question:
I'm new to C and couldn't have the answer after some research.

I have a while loop that I want to terminate if I input nothing (hit enter) to scanf(). The below doesn't work...

```
int data;
while(1){
    scanf("%d", &data);
    if data == NULL{
        break;
    }
}
```

Answer:
Use the return value fromscanf:

```
int data;
while (1) {
    int n = scanf("%d", &data);
    if (n != 1)
        break;
    // ...
}
```


Question:
how can i add Byte order mark (BOM) to output file using C?

my output file is ANSI as UTF-8 (which mean UTF-8 without BOM)

but i need it to be UTF-8 with BOM

how can i do that?

Answer:
the answer is

```
printf("\xef\xbb\xbf");
```


Question:
how can i add Byte order mark (BOM) to output file using C?

my output file is ANSI as UTF-8 (which mean UTF-8 without BOM)

but i need it to be UTF-8 with BOM

how can i do that?

Answer:
the answer is

```
printf("\xef\xbb\xbf");
```


Question:
how can i add Byte order mark (BOM) to output file using C?

my output file is ANSI as UTF-8 (which mean UTF-8 without BOM)

but i need it to be UTF-8 with BOM

how can i do that?

Answer:
the answer is

```
printf("\xef\xbb\xbf");
```


Question:
Is it possible to inject 64 bit dll into 64 bit host app from 32 bit app in native c? (not C# or managed c++)

I compiled the dll I want to inject in both 32 and 64 form, but when I call

```
RhInjectLibrary(pid,0,EASYHOOK_INJECT_DEFAULT,path,path64,NULL);
```

I get WOW error.

32 into 32 injection works fine.

Answer: You will need to create a helper 64-bit application that does the injection for you.


Question:
I developed new C project and I use some time variables to debug or to check value ...

I want to be sure if I don't forget any unused variable after achieving project.

there is a Linux utilities or command to do that ?

Answer:
Some compilers can issue a warning for you when an automatic variable is unused. Try

```
gcc -Wunused-variable
clang -Wunused-variable
```


Question:
Trying to extract seconds from next string using sscanf:
Now it's 2013-12-04 18:01:20

sscanf(buf, "%*s %*s %*d%*s%*d%*s%*d %*d%*s%*d%*s%d", &i);

And it fails, any ideas how to make proper format for it? Or any ideas to extract it easier? All I need is last second.

Answer:
```
sscanf("Now it's 2013-12-04 18:01:20", "%*s %*s %*s %*d:%*d:%d", &i)
```


Question:
I am searching for the equal from.
C code:

```
char msg[100];
    int LED=2;
    sprintf(msg,"1,%d,1,0",LED);
   //msg is now (1,2,1,0)
```

but in C# the old functionsprintffrom c disappears.
How can I do this in C#

Answer:
This is somewhat similar:

```
string msg;
int LED = 2;
msg = String.Format("1,{0},1,0", LED);
```


Question:
In Build settings, at custom compiler Flags, how can i declare two otherCflags names?

For example:

Other C Flags:-DEXAMPLE

I tried:

Other C Flags:-DEXAMPLE,-DEXAMPLE2

-DEXAMPLE2is not working. How can i declare multipleCFlags?

Answer:
Drop the comma, each-Dis its own argument to the compiler:

```
-DEXAMPLE -DEXAMPLE2
```


Question:
In Build settings, at custom compiler Flags, how can i declare two otherCflags names?

For example:

Other C Flags:-DEXAMPLE

I tried:

Other C Flags:-DEXAMPLE,-DEXAMPLE2

-DEXAMPLE2is not working. How can i declare multipleCFlags?

Answer:
Drop the comma, each-Dis its own argument to the compiler:

```
-DEXAMPLE -DEXAMPLE2
```


Question: I know the switch in gcc but there is nothing about such option in TTC. I read about something _winstart or what swich but I don't know where to put it.

Answer: Ok, it seems it is possible to make non-console app in tcc. I didn't figured out yet what are the key elements necessary here. But in tcc package there ishello_win.cexample.


Question:
Here is my code snippet

```
typedef struct Position
{
    short X;
    short Y;
} Pos;

Pos Block[25*25+1];

void Clear_String (void)
{
    memset (&Block, 0, sizeof (Pos));
}
```

Here is my full code in plain text:Click Me

Whyvoid Clear_String (void)doesn't clear all of the elements in structure?

Answer: Block and unfilled are arrays of Pos. You are zeroing only the first item since you pass sizeof (Pos).


Question:
when I pass a const int array to a function that gets int array there is compiler error but
when I pass an  int array to a function that gets const int array its OK.

why is this happening? I thought mispassing argument is compiler error.

Answer:
Not doing something you're allowed to do is fine.

Doing something you're not allowed to do is not fine.


Question: I have been trying to figure out how to make an app similar to emacs in that when you run it, it runs in the terminal but it takes up the whole terminal and acts almost like a window.  I can't find anything online about this, can anyone give me pointers of where to get started to figure this out?

Answer:
For *nix, there isncurses.

Wikipediaexplains it to you: It is a library to write "GUI-like" applications in text format.

Also:Ncurses for Windows


Question: When defining a macro (e.g.#define BALL). Why do people use uppercase letters? I can write something like#define ball. It is not in uppercase, but it works.

Answer: It's convention. It makes reading and understanding code easier. It's not required, but recommended.


Question:
I have got snippet of old c-code with that lines (result is just slash sign):

```
putchar('/' //**/
    1 / 1 /'\1');
```

Can anyone explain this snippet? What does this symbols mean?

P.S. By the way it compiles well with std=c89 flag in gcc, but not with std=c99.

Answer: That's a division, followed by an empty comment. In C99 mode, it's a new-style comment, causing a syntax error because there's no division operator now.


Question:
I have got snippet of old c-code with that lines (result is just slash sign):

```
putchar('/' //**/
    1 / 1 /'\1');
```

Can anyone explain this snippet? What does this symbols mean?

P.S. By the way it compiles well with std=c89 flag in gcc, but not with std=c99.

Answer: That's a division, followed by an empty comment. In C99 mode, it's a new-style comment, causing a syntax error because there's no division operator now.


Question:
I am using two different datatypes and doing the calculation by mathematical operators.

```
int x = 1;
 double y = 2;
 int z;
 z = x*y;
 printf("Result %d\n", z);
```

Will it be Ok??

Answer:
You'll lose precision (probably getting a warning) if the value has a fractional part. It will be truncated.

Example:

```
const float PI = 3.14;
int notPi = PI;
```

notPiwill be truncated to3


Question:
In Windows' C API, how can you get a list of network interface names?  (Equivalent togetifaddrs()in Linux)

TheWSAIoctl(sock, SIO_GET_INTERFACE_LIST_EX, ...)function seems to only return IP addresses, plus a little metadata.

Answer:
GetAdaptersAddresses()does this.

UseGetIpAddrTable()if you are interested in IPv4 addresses only.


Question:
Is it possible to write C code so that when it is compiled with

```
gcc -o foo foo.c
```

it in fact compiles foo.c with -O2?

I am using gcc 4.4.6.

Answer: recent gcc knows a#pragma GCC optimizepragma (http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html)


Question:
In Windows' C API, how can you get a list of network interface names?  (Equivalent togetifaddrs()in Linux)

TheWSAIoctl(sock, SIO_GET_INTERFACE_LIST_EX, ...)function seems to only return IP addresses, plus a little metadata.

Answer:
GetAdaptersAddresses()does this.

UseGetIpAddrTable()if you are interested in IPv4 addresses only.


Question:
Is it possible to write C code so that when it is compiled with

```
gcc -o foo foo.c
```

it in fact compiles foo.c with -O2?

I am using gcc 4.4.6.

Answer: recent gcc knows a#pragma GCC optimizepragma (http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html)


Question:
I'm having trouble replacing a whole word in a sentence.

For example:

Replace:

thetoahellotohihousetotree

Input:

Hello there, this is the house.

Output:

Hi there, this is a tree.

Is it possible to do it only with the<string.h>library, with no Regex etc.?

Answer: May be this can help youstr-replace-c


Question:
This question already has answers here:Why are C character literals ints instead of chars?(11 answers)Closed9 years ago.

```
void main()
{
printf("%d\n",sizeof('1'));
}
```

Output : 4

```
void main()
{
char a='1';
printf("%d\n",sizeof(a));
}
```

Output : 1

Can somebody say why it is different ?

Answer:
In C, character literals are of typeint.

Note that this was changed in C++, in which character literals have the obvious typechar.


Question: Is there a way find the size of the sparse files in the filesystem ext2?

Answer:
Get thestat()of the file. The fieldst_sizegives the regular size in bytes, including holes. The fieldst_blocksshows the actually allocated blocks (in units of 512 byte blocks), sost_blocks * 512is the number of bytes it actually takes up on disk.

This works on any filesystem, not just ext2.


Question:
i have this for loop

for (i = 0, j = N-1; i < j; ++i , --j )

and i want to increment i with 4 not 1 and j decrement with 4 not 1.

Something like this, but i don't know the sintax:

```
for (i = 0, j = N-1; i < j; 4+=i , 4-=j )
```

Thanks

Answer: Try the other way around:i += 4. This is shorthand fori = i + 4. Now you have written4 += iwhich means4 = 4 + i- which does not make sense of course.


Question:
This question already has answers here:Why are C character literals ints instead of chars?(11 answers)Closed9 years ago.

```
void main()
{
printf("%d\n",sizeof('1'));
}
```

Output : 4

```
void main()
{
char a='1';
printf("%d\n",sizeof(a));
}
```

Output : 1

Can somebody say why it is different ?

Answer:
In C, character literals are of typeint.

Note that this was changed in C++, in which character literals have the obvious typechar.


Question: Is there a way find the size of the sparse files in the filesystem ext2?

Answer:
Get thestat()of the file. The fieldst_sizegives the regular size in bytes, including holes. The fieldst_blocksshows the actually allocated blocks (in units of 512 byte blocks), sost_blocks * 512is the number of bytes it actually takes up on disk.

This works on any filesystem, not just ext2.


Question:
i have this for loop

for (i = 0, j = N-1; i < j; ++i , --j )

and i want to increment i with 4 not 1 and j decrement with 4 not 1.

Something like this, but i don't know the sintax:

```
for (i = 0, j = N-1; i < j; 4+=i , 4-=j )
```

Thanks

Answer: Try the other way around:i += 4. This is shorthand fori = i + 4. Now you have written4 += iwhich means4 = 4 + i- which does not make sense of course.


Question:
I have following code in packet sniffer:

```
struct ip_header {
       unsigned char ip_ver:4;
...
};

...

printf("Version: %i\n", (int)ip_hdr->ip_ver)
```

The output of ths is "Version: 5". I think version can onl be 4 or 6, right?

Answer:
I got it it is just the Header length first 4 bits and version is second 4bits, so it should be

```
struct ip_header {
       unsigned char ip_hl:4;
       unsigned char ip_ver:4;
...
};
```


Question: The header file is in the same folder as the other files, it's #include'ed and all, but some reason the other source files just can't find it. Same with compiler. Help?

Answer: May be you should try#include "funcs.h"instead of#include <funcs.h>


Question:
I have following code in packet sniffer:

```
struct ip_header {
       unsigned char ip_ver:4;
...
};

...

printf("Version: %i\n", (int)ip_hdr->ip_ver)
```

The output of ths is "Version: 5". I think version can onl be 4 or 6, right?

Answer:
I got it it is just the Header length first 4 bits and version is second 4bits, so it should be

```
struct ip_header {
       unsigned char ip_hl:4;
       unsigned char ip_ver:4;
...
};
```


Question: The header file is in the same folder as the other files, it's #include'ed and all, but some reason the other source files just can't find it. Same with compiler. Help?

Answer: May be you should try#include "funcs.h"instead of#include <funcs.h>


Question:
This question already has answers here:Calling an executable program using awk(10 answers)Closed9 years ago.

I want to call Code.c from within awk. Note that the Code.c takes current record (i.e. $0) as argument.

I am new to shell scripting so any help would be appreciated.

Best Regards

Answer:
```
#!/bin/bash

while read line
do
    para=`echo $line | awk '{print $0}'`
    ./c_code $para
done < your_process_file
```


Question:
This question already has answers here:Calling an executable program using awk(10 answers)Closed9 years ago.

I want to call Code.c from within awk. Note that the Code.c takes current record (i.e. $0) as argument.

I am new to shell scripting so any help would be appreciated.

Best Regards

Answer:
```
#!/bin/bash

while read line
do
    para=`echo $line | awk '{print $0}'`
    ./c_code $para
done < your_process_file
```


Question:
If I have the code on a 32-bit word machine:

```
struct myStruct {
//structure that occupies six bytes
uint32_t value1;
uint16_t value2;

} *p = (myStruct *)0x10;
```

How much does p++ equal? 0x14? 0x11? or 0x16?

Answer: It is incremented by the sizeof(myStruct).  Pointer arithmetic is in units of the size of what is pointed at.  for char *, p++; p = p + sizeof(char);


Question:
```
uint32_t var32;
uint8_t var8;
var32 = 0xFEEDABCD;
var8 = 0;
var8 = var32;
```

Will the above code always (meaning platform dependent such as Windows vs Linux etc) have the following values:

var32 = 0xFEEDABCD

var8 = 0xCD

Answer: Yes, it will. Unsigned integer overflow is well-defined by the standard and it is required to follow modulo-2^nsemantics.


Question: I know how arrays stored on the heap. But how are arrays stored on the stack? Is the complete array pushed to the stack?

Answer: Arrays are stored the same no matter where they are. It doesn't matter if they are declared as local variables, global variables, or allocated dynamically off the heap. The only thing that differs iswherethey are stored.


Question:
I don't understand why output is a strange number when I run my code:

```
int main(int argc, char** argv)
{
    Mat im;
    im = imread("lena.png", CV_LOAD_IMAGE_GRAYSCALE);
    cout << im.at<uchar>(0, 0) << endl;
    waitKey(0);
}
```

If I visualize image I see the correct image.
Where am I wrong?

Answer:
Because it shows the symbol, likecout << char(123) << endl;

You have to use int cast:

```
cout << (int) im.at<uchar>(0, 0) << endl;
```


Question:
I've got astd::vectorand I need to get the hash of its contents from libgcrypt.

How do I get the contents ofstd::vector<int-type> vecintogcry_md_hash_buffer(GCRY_MD_MD5, (void*)&digest, (void*)buffer, vec.size());wherebufferis thedatainvec?

Answer:
If you are using C++11, pass

```
vec.data()
```

forbuffer.

Reference:Vector::data()

If not, pass&(vec.front()).  The elements ofvecare guaranteed to be in contiguous storage.


Question:
I've got astd::vectorand I need to get the hash of its contents from libgcrypt.

How do I get the contents ofstd::vector<int-type> vecintogcry_md_hash_buffer(GCRY_MD_MD5, (void*)&digest, (void*)buffer, vec.size());wherebufferis thedatainvec?

Answer:
If you are using C++11, pass

```
vec.data()
```

forbuffer.

Reference:Vector::data()

If not, pass&(vec.front()).  The elements ofvecare guaranteed to be in contiguous storage.


Question:
I have searched in the MSDN, but nothing meet my needs.

Could anyone help me? THANKS.

```
#include <windows.h>
int main (void)
{
    // HOW TO ?
}
```

Answer:
To get info on the console's font use:

GetConsoleFontSize()GetCurrentConsoleFont()orGetCurrentConsoleFontEx()

To set font info use:

SetCurrentConsoleFontEx()


Question: I need it because I have to modify the linker, specifically that part where it resolves the symbols in plt section and updates them in GOT.

Answer:
As I've already posted in my previous answer to your question,this page is great.

Read it carefully — there is also a number of references and books in the beginning (Useful books and referencesheading).

You may also want to look atLinkers and Loadersby Levine for reference.


Question:
I have searched in the MSDN, but nothing meet my needs.

Could anyone help me? THANKS.

```
#include <windows.h>
int main (void)
{
    // HOW TO ?
}
```

Answer:
To get info on the console's font use:

GetConsoleFontSize()GetCurrentConsoleFont()orGetCurrentConsoleFontEx()

To set font info use:

SetCurrentConsoleFontEx()


Question: I need it because I have to modify the linker, specifically that part where it resolves the symbols in plt section and updates them in GOT.

Answer:
As I've already posted in my previous answer to your question,this page is great.

Read it carefully — there is also a number of references and books in the beginning (Useful books and referencesheading).

You may also want to look atLinkers and Loadersby Levine for reference.


Question:
How can I enumerate allenumnames and values in C to print it like

```
printf("Name: %s, value: %d\n", name, value);
```

?

Answer:
Check outthe X macro:

```
#define COLORS \
    X(Cred, "red") \
    X(Cblue, "blue") \
    X(Cgreen, "green")

#define X(a, b) a,
enum Color { COLORS };
#undef X

#define X(a, b) b,
static char *ColorStrings[] = { COLORS };
#undef X

printf("%s\n", ColorStrings[Cred]); // output: red
```


Question:
I found the following code in a program example:

```
const unsigned int n = /* something */
unsigned int i = 1;
for (unsigned int j = 1; j < n-1; ++j) {
    i <<= 1;
}
```

Is there a direct formula to computeifromnwithout a loop ?

Answer:
More accurately:

assuming unsigned int is 16 bits (minimum as specified by C++ standard)

```
i = ( n < 18 ) ? ( ( n >= 2 ) ? ( 1 << (n-2) ) : 1 ) : 0;
```


Question: All is in the title: does IEEE-754float,doubleandquadguarantee exact representation of-2,-1,-0,0,1,2?

Answer: It guarantees precise representations of all integers until the number of significant binary digits exceeds the range of the mantissa.


Question:
I've got an array of characters which could contain a NULL character.The array is not null-terminated, but I do know it's length.

QuestionHow do I output this exact array (including null characters) and nothing else (no trailing \n) to stdout? Unfortunately, I am not allowed to output one character at a time.

Answer:
```
char buffer[SIZE];

if(fwrite(buffer, 1, SIZE, stdout) != SIZE) {
    perror("fwrite");
}
```


Question:
```
pid_t fork(void);
```

I want to know what this command does in C.  Process Control.

Answer:
This creates a child process which has a copy of the parent’s heap, stack and data space.
You need to#include <unistd.h>.  You could use this when you want a process to duplicate itself so that the parent and child can each execute different sections of code at the same time.


Question:
I got

```
uint32_t bits = 0;

bits |= 1<< 31;
bits |= 1<< 15;
bits |= 1<< 14;
bits |= 1<< 13;
```

which gives me 10000000000000001110000000000000

and in another function I do*(bits) |= 0 << 15;but it doesn't do anything, it should change the 16th 1 to a 0, so the following should come: 10000000000000000110000000000000

any help?

Answer:
The correct way to change a bit to 0 is toandthe negation, e.g.

```
bits &= ~(1 << 15);
```


Question:
What does it mean for a function call to "spin?" Is it the same as blocking?

This is the context I'm referring to:

```
/*
     * Obtain a free channel
     * This call spins till a free channel is obtained
     */
    chNum = _getFreeChannel(&tccNum);
```

Thanks.

Answer: To loop, basically. What a spinning function does is busy-waiting with a loop.


Question:
Is there any function to check file(s) exist with specific extension or pattern in a directory(s) in Windows and Linux?

For example, to check for files with bbram extension in nvmdir directory.

```
file_exists(nvmdir .. "\\*.bbram")
```

Answer: A somewhat less elegant solution would be to usepopen()or even lesser elegantsystem()to issue an OS specific "shell" command.


Question:
I have:

```
unsigned char *programBinary = (unsigned char) malloc(binarySize);
```

But I'm getting the following errors:

```
test.c:127:34: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
test.c:127:33: error: invalid type argument of unary ‘*’ (have ‘int’)
```

This is fairly new to me so I'm unsure as to how to fix this.

Answer: You need to cast(unsigned char*)not(unsigned char)


Question:
I have:

```
unsigned char *programBinary = (unsigned char) malloc(binarySize);
```

But I'm getting the following errors:

```
test.c:127:34: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
test.c:127:33: error: invalid type argument of unary ‘*’ (have ‘int’)
```

This is fairly new to me so I'm unsure as to how to fix this.

Answer: You need to cast(unsigned char*)not(unsigned char)


Question:
In case I want to programatically clear the recycle bin under Windows, how to implement that?

DoesIFileOperationhelp?

Answer: You can useSHEmptyRecycleBin()function fromshell32.dlllibrary to achieve this.


Question:
```
typedef union
{
    unsigned i;
    float x;
} f;

f array[12];
```

What do I need to do to address theunionmembers in an array like this?  If not possible, how can I do this?

Answer:
```
typedef union
{
    unsigned i;
    float x;
} f;

f array[12];
```

now you can use by this way :

```
array[index].member=value;
```


Question:
I encountered the following line as a C function declaration. I'm confused by the type of the first argument passed in. Can anyone explain how to understand the type of the first argument?

```
int clone(void (*fcn) (void *) , void *arg, void *stack)
```

Answer:
```
void (*fcn) (void *)
```

Read the type from inside out:fcnis a pointer to a function, that function takes avoid *parameter and returns nothing (void).


Question:
```
typedef union
{
    unsigned i;
    float x;
} f;

f array[12];
```

What do I need to do to address theunionmembers in an array like this?  If not possible, how can I do this?

Answer:
```
typedef union
{
    unsigned i;
    float x;
} f;

f array[12];
```

now you can use by this way :

```
array[index].member=value;
```


Question:
I encountered the following line as a C function declaration. I'm confused by the type of the first argument passed in. Can anyone explain how to understand the type of the first argument?

```
int clone(void (*fcn) (void *) , void *arg, void *stack)
```

Answer:
```
void (*fcn) (void *)
```

Read the type from inside out:fcnis a pointer to a function, that function takes avoid *parameter and returns nothing (void).


Question:
What does theENTmean inENOENT?

Shouldn't the error:

No such file or directory

just be named byENOFILE?

Is there any story or reason?

Answer:
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.


Question:
What does theENTmean inENOENT?

Shouldn't the error:

No such file or directory

just be named byENOFILE?

Is there any story or reason?

Answer:
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.


Question:
This might be a simple question, but I want to make sure.

I want some comments in my .c files to use symbols not supported in the default encoding. If I save the file as UTF-8 for instance, and I only use symbols in comments, is there any way this can affect the compiler in any way?

Need to be sure of this.

Answer: No, the preprocessor will strip all of that out anyway.


Question:
This might be a simple question, but I want to make sure.

I want some comments in my .c files to use symbols not supported in the default encoding. If I save the file as UTF-8 for instance, and I only use symbols in comments, is there any way this can affect the compiler in any way?

Need to be sure of this.

Answer: No, the preprocessor will strip all of that out anyway.


Question:
Exists in C method for finding a substring in a string?

If not, how to effectively deal with this problem?

In for cycle? And what is the correct syntax in c?

```
const char subString[] = { "car", "blue", "red"};
char String[] = "I love red color and i hate blue color";

for .... String lenght... {

      printf("I found subString");

}
```

Answer:
For null terminated C strings:

strstr()


Question:
Exists in C method for finding a substring in a string?

If not, how to effectively deal with this problem?

In for cycle? And what is the correct syntax in c?

```
const char subString[] = { "car", "blue", "red"};
char String[] = "I love red color and i hate blue color";

for .... String lenght... {

      printf("I found subString");

}
```

Answer:
For null terminated C strings:

strstr()


Question:
Probably my brain is not working properly now... I wonder why I receive mentioned error in my code:

```
int ** zm;
zm = (int**)calloc(1, sizeof(int*));
*zm = (int*)calloc(1, sizeof(int));
*zm[0] = 5;
*zm = (int*)realloc(*zm, 2*sizeof(int));
*zm[1] = 10; // Access violation reading location 0xFFFFFFFFFFFFFFFF
```

Could someone explain what happend in that code?

Answer: Wrong indexing, try(*zm)[1]instead. And check for errors from library calls.


Question:
Is there a function in c that checks whether a file is a block device or charachter device?

Thanks!

Answer:
You're probably looking forlstat, if you're under linux:

http://linux.die.net/man/2/lstat

You should have access to the macrosS_ISCHRandS_ISBLK.


Question:
Here's my ramdomize code:

```
int monstername;
monstername = rand() % 3;
```

but I want 0 with 70% of output 1 with 20% 2 with 10% how I can do this with C?

Answer:
```
int monstername;
int random_var = rand() % 10;

if(random_var < 7) {
    // 0-70%
    monstername = 0;
}
else if(random_var < 9) {
    // 70-90% here
    monstername = 1;
}
else {
    // 90-100% here
    monstername = 2;
}
```


Question:
Is there a function in c that checks whether a file is a block device or charachter device?

Thanks!

Answer:
You're probably looking forlstat, if you're under linux:

http://linux.die.net/man/2/lstat

You should have access to the macrosS_ISCHRandS_ISBLK.


Question:
I've been using theread(2)andwrite(2)functions to read and write to a file given a file descriptor.

Is there any function like this that allows you to put an offset into the file for read/write?

Answer:
There arepread/pwritefunctions that accept file offset:

```
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
```


Question:
I've been using theread(2)andwrite(2)functions to read and write to a file given a file descriptor.

Is there any function like this that allows you to put an offset into the file for read/write?

Answer:
There arepread/pwritefunctions that accept file offset:

```
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
```


Question:
I have make two librarieslibsa.aandlibsb.a.
The functionfuncainlibsa.aandfuncbinlibsb.awhich callsfunca.

In the main function, I only callfuncb. The compiler display that "... undefined reference to `funca'". The compiler command like "gcc main.c -o main -lsa -lsb".

The problem is resolved when I add afuncain the main function.

What can I do?

Sorry for my poor English!

Answer: Change the order:gcc main.c -o main -lsb -lsa