question
stringlengths 24
425
| answer
stringlengths 5
405
|
---|---|
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?
| 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
```
|
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?
| 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
```
|
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?
| 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.
|
Why
```
printf("%s\n","\061");
```
prints1in output. I expect something like=
| 061 octal == 49 decimal == 0x31 hex. That's the ASCII code for the character'1'
Why do you expect'='?
|
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?
| Store the answer, and callstrstr()again, starting at the returned location + the length of the search string. Continue until it returnsNULL.
|
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.
| 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?.
|
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?
| Try to usestrtol():
```
strtol("FA", NULL, 16);
```
|
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 = ?;
```
| 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 };
```
|
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?
| Try to usestrtol():
```
strtol("FA", NULL, 16);
```
|
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?
| Call avcodec_encode_audio2() with null frame
when flushing an encoder that has the CODEC_CAP_DELAY capability set
|
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?
| 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.
|
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?
| Two percentage signs:
```
printf("%%");
```
|
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?
| Ugh, so to answer theactualquestion:int (*ptrTo2DArr)[4][4];
|
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?
| Ugh, so to answer theactualquestion:int (*ptrTo2DArr)[4][4];
|
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?
| The answer istypedef struct list* ProcList[32];
|
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.
| 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 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.
| Win32 provides its own implementation of the sockets API (Winsock) which uses slightly different headers.
From theMSDN forinet_addr:
Header Winsock2.h
|
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.
| 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.
|
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) ?
| Assign the number of threads at the compile time using upcc flags. For more information on upcc flags checkupcc man page.
|
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?
| 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();
}
```
|
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?
| 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();
}
```
|
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.
| ```
(date[0]<<32);
```
looks wrong.16 + 8is24not32.
|
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
| As mentioned, we have split the regex into smaller chunks and resolved.
Appreciate for the comments.
|
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
| As mentioned, we have split the regex into smaller chunks and resolved.
Appreciate for the comments.
|
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;
}
}
```
| Use the return value fromscanf:
```
int data;
while (1) {
int n = scanf("%d", &data);
if (n != 1)
break;
// ...
}
```
|
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?
| the answer is
```
printf("\xef\xbb\xbf");
```
|
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?
| the answer is
```
printf("\xef\xbb\xbf");
```
|
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?
| the answer is
```
printf("\xef\xbb\xbf");
```
|
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.
| You will need to create a helper 64-bit application that does the injection for you.
|
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 ?
| Some compilers can issue a warning for you when an automatic variable is unused. Try
```
gcc -Wunused-variable
clang -Wunused-variable
```
|
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.
| ```
sscanf("Now it's 2013-12-04 18:01:20", "%*s %*s %*s %*d:%*d:%d", &i)
```
|
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#
| This is somewhat similar:
```
string msg;
int LED = 2;
msg = String.Format("1,{0},1,0", LED);
```
|
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?
| Drop the comma, each-Dis its own argument to the compiler:
```
-DEXAMPLE -DEXAMPLE2
```
|
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?
| Drop the comma, each-Dis its own argument to the compiler:
```
-DEXAMPLE -DEXAMPLE2
```
|
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.
| 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.
|
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?
| Block and unfilled are arrays of Pos. You are zeroing only the first item since you pass sizeof (Pos).
|
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.
| Not doing something you're allowed to do is fine.
Doing something you're not allowed to do is not fine.
|
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?
| For *nix, there isncurses.
Wikipediaexplains it to you: It is a library to write "GUI-like" applications in text format.
Also:Ncurses for Windows
|
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.
| It's convention. It makes reading and understanding code easier. It's not required, but recommended.
|
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.
| 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.
|
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.
| 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.
|
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??
| 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
|
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.
| GetAdaptersAddresses()does this.
UseGetIpAddrTable()if you are interested in IPv4 addresses only.
|
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.
| recent gcc knows a#pragma GCC optimizepragma (http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html)
|
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.
| GetAdaptersAddresses()does this.
UseGetIpAddrTable()if you are interested in IPv4 addresses only.
|
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.
| recent gcc knows a#pragma GCC optimizepragma (http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html)
|
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.?
| May be this can help youstr-replace-c
|
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 ?
| In C, character literals are of typeint.
Note that this was changed in C++, in which character literals have the obvious typechar.
|
Is there a way find the size of the sparse files in the filesystem ext2?
| 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.
|
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
| 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.
|
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 ?
| In C, character literals are of typeint.
Note that this was changed in C++, in which character literals have the obvious typechar.
|
Is there a way find the size of the sparse files in the filesystem ext2?
| 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.
|
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
| 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.
|
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?
| 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;
...
};
```
|
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?
| May be you should try#include "funcs.h"instead of#include <funcs.h>
|
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?
| 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;
...
};
```
|
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?
| May be you should try#include "funcs.h"instead of#include <funcs.h>
|
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
| ```
#!/bin/bash
while read line
do
para=`echo $line | awk '{print $0}'`
./c_code $para
done < your_process_file
```
|
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
| ```
#!/bin/bash
while read line
do
para=`echo $line | awk '{print $0}'`
./c_code $para
done < your_process_file
```
|
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?
| 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);
|
```
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
| Yes, it will. Unsigned integer overflow is well-defined by the standard and it is required to follow modulo-2^nsemantics.
|
I know how arrays stored on the heap. But how are arrays stored on the stack? Is the complete array pushed to the stack?
| 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.
|
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?
| Because it shows the symbol, likecout << char(123) << endl;
You have to use int cast:
```
cout << (int) im.at<uchar>(0, 0) << endl;
```
|
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?
| 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.
|
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?
| 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.
|
I have searched in the MSDN, but nothing meet my needs.
Could anyone help me? THANKS.
```
#include <windows.h>
int main (void)
{
// HOW TO ?
}
```
| To get info on the console's font use:
GetConsoleFontSize()GetCurrentConsoleFont()orGetCurrentConsoleFontEx()
To set font info use:
SetCurrentConsoleFontEx()
|
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.
| 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.
|
I have searched in the MSDN, but nothing meet my needs.
Could anyone help me? THANKS.
```
#include <windows.h>
int main (void)
{
// HOW TO ?
}
```
| To get info on the console's font use:
GetConsoleFontSize()GetCurrentConsoleFont()orGetCurrentConsoleFontEx()
To set font info use:
SetCurrentConsoleFontEx()
|
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.
| 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.
|
How can I enumerate allenumnames and values in C to print it like
```
printf("Name: %s, value: %d\n", name, value);
```
?
| 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
```
|
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 ?
| More accurately:
assuming unsigned int is 16 bits (minimum as specified by C++ standard)
```
i = ( n < 18 ) ? ( ( n >= 2 ) ? ( 1 << (n-2) ) : 1 ) : 0;
```
|
All is in the title: does IEEE-754float,doubleandquadguarantee exact representation of-2,-1,-0,0,1,2?
| It guarantees precise representations of all integers until the number of significant binary digits exceeds the range of the mantissa.
|
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.
| ```
char buffer[SIZE];
if(fwrite(buffer, 1, SIZE, stdout) != SIZE) {
perror("fwrite");
}
```
|
```
pid_t fork(void);
```
I want to know what this command does in C. Process Control.
| 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.
|
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?
| The correct way to change a bit to 0 is toandthe negation, e.g.
```
bits &= ~(1 << 15);
```
|
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.
| To loop, basically. What a spinning function does is busy-waiting with a loop.
|
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")
```
| A somewhat less elegant solution would be to usepopen()or even lesser elegantsystem()to issue an OS specific "shell" command.
|
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.
| You need to cast(unsigned char*)not(unsigned char)
|
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.
| You need to cast(unsigned char*)not(unsigned char)
|
In case I want to programatically clear the recycle bin under Windows, how to implement that?
DoesIFileOperationhelp?
| You can useSHEmptyRecycleBin()function fromshell32.dlllibrary to achieve this.
|
```
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?
| ```
typedef union
{
unsigned i;
float x;
} f;
f array[12];
```
now you can use by this way :
```
array[index].member=value;
```
|
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)
```
| ```
void (*fcn) (void *)
```
Read the type from inside out:fcnis a pointer to a function, that function takes avoid *parameter and returns nothing (void).
|
```
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?
| ```
typedef union
{
unsigned i;
float x;
} f;
f array[12];
```
now you can use by this way :
```
array[index].member=value;
```
|
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)
```
| ```
void (*fcn) (void *)
```
Read the type from inside out:fcnis a pointer to a function, that function takes avoid *parameter and returns nothing (void).
|
What does theENTmean inENOENT?
Shouldn't the error:
No such file or directory
just be named byENOFILE?
Is there any story or reason?
| 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.
|
What does theENTmean inENOENT?
Shouldn't the error:
No such file or directory
just be named byENOFILE?
Is there any story or reason?
| 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.
|
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.
| No, the preprocessor will strip all of that out anyway.
|
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.
| No, the preprocessor will strip all of that out anyway.
|
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");
}
```
| For null terminated C strings:
strstr()
|
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");
}
```
| For null terminated C strings:
strstr()
|
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?
| Wrong indexing, try(*zm)[1]instead. And check for errors from library calls.
|
Is there a function in c that checks whether a file is a block device or charachter device?
Thanks!
| 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.
|
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?
| ```
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;
}
```
|
Is there a function in c that checks whether a file is a block device or charachter device?
Thanks!
| 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.
|
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?
| 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);
```
|
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?
| 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);
```
|
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!
| Change the order:gcc main.c -o main -lsb -lsa
|
I need maximum performances using GMP and I wonder whether there is a better way to compute the absolute value of the difference of two numbers.
Currently I use:
```
mpz_sub(x, a, b);
mpz_abs(x, x);
```
Is there a most efficient way to do that ?
| Your code should already be close to optimal. When the source and destination are the same,mpz_abstakes constant time: it does not read the big number and only performs a trivial operation on the sign.
|
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!
| Change the order:gcc main.c -o main -lsb -lsa
|
If you want a dynamically allocated array ofint size, there two ways you can get that in C:
```
int* array = new int [size]; //method 1
int* array2 = malloc (sizeof(int) * size); //method 2
```
When should you use each method?
| If you're in C, the second one.
If you're in C++, usestd::vector<int>if you can; otherwise use the first one (rarely needed).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.