question
stringlengths 24
425
| answer
stringlengths 5
405
|
---|---|
```
void func(int num){
if(num< 3){
printf("%d ", num);
func(num+ 1);
printf("%d ", num);
}
}
```
Suppose I call this function with func(0).
Why is the result 0 1 2 2 1 0 ?
I don't know why it's decreasing.
| Here's a stack trace
```
f(0)
print 0
f(1)
print 1
f(2)
print 2
f(3) // 3 < 3 == false
print 2
print 1
print 0
```
|
Set PriorityWhat are all possible priorities in KPRIORITY in win kernel?
| From thedocumentation for KeQueryPriorityThread:
Thread priorities range from 0 to 31, where 0 is the lowest priority and 31 is the highest.
|
I've used OpenSSLBIGNUMto implement some cryptosystems and I am now wondering if it also offers big decimal support. I could not find anything in the documentation but perhaps there is an extension/add-on somewhere preferably in C (not C++)?
Note: I am aware of GMP and NTL, I am not looking for those.
| Does OpenSSL offer Big Decimal support?
No.
|
From this page:http://linux.die.net/man/2/mprotect
I understand the flags except for PROT_EXEC. What is the effect of calling
```
mprotect(ptr, size, PROT_EXEC);
```
| From the manual page you link to:
PROT_EXECThe memory can be executed.
It marks the memory as executable, meaning it can contain code you can call and run.
|
I would like a check box to be automatically unchecked when a certain value is reached. But I can't find an option to set the state of a check box
| Send it aBM_SETCHECKmessage:
```
SendMessage(hWndOfCheckbox, BM_SETCHECK, BST_UNCHECKED, 0);
```
Alternatively, use theButton_SetCheckmacro, that expands to the same call toSendMessage(but doesn't expose unused formal parameters):
```
Button_SetCheck(hWndOfCheckbox, BST_UNCHECKED);
```
|
I want to compile several c files and I want to have executables whose names are same as the c file's names i.e if I have trial1.c, how can I have trial1.out?
| Do you want something like this?
```
for i in *.c; do gcc ${i::1}.c -o ${i::1}.out; done
```
Or, if you are interested on just knowing if they compile successfully:
```
for i in *.c; do gcc $i 2>/dev/null && echo "$i : OK" || echo "$i : FAIL"; done
```
|
I know * indicates it is a pointer, but what's the difference betweenint (* a)[2]and(int (*)[2]) ainC?
| int (* a)[2];declaresaasa pointer to an array of twointwhile(int (*)[2]) acastsatoa pointer to an array of twoint.
|
How can I useperf_event_open()to retrieve callchain? I do not want to use the callchains provided by oprofile and perf. I want to get them directly. It seems that I need tommap()the file descriptor returned byperf_event_open(). I do not know the size ofmmap()and how to read from it.
| Chapter 8 ofthis bookdescribes, by example, how to useperf_event_open()for bothcountingandsamplingmodes.
|
In C, if the array is initialised while declaration then the dimension is optional. Why?
| Because if you tell it to create an array holding a1,2, and3, it can easily figure out the required size since you gave it 3 elements.
|
Given the following lines:
```
char szInline[80];
char szDescription[80] = { NULL };
float fCost = 0;
sscanf (szInline, "%80[^,], %f", szDescription, &fCost);
```
What does the %80[^,] do?
| Read at most 80 chars up to the next,comma.
Btw, theszDescriptionbuffer is too small by 1.
|
I know what a delimiter is, but what does the string" \t\r\n\a"stand for in the example below?
```
#define DELIMITER " \t\r\n\a"
```
| ```
\t = tab
\r = carriage return
\n = newline
\a = alert (bell)
```
Looks like the author was creating a preprocessor DEFINE containing these common delimiters.
|
What is maximum length of user space APC queue to one thread in Windows? I read Windows Internals 6 Part 1 and didn't finded any information about this.
| There is no fixed limit. KAPC structures are allocated fromnonpaged pooland linked to a thread by a singleLIST_ENTRYstructure. Nonpaged pool islimited by available system resources only.
|
As for System V messageint msgget(key_t key, int msgflg);,
Can syscallreadwork likemsgsndto send a message?Can syscallwritework likemsgrcvto receive a message?
| No, they can't. The message queue identifier (returned bymsgget) is not a descriptor.
Different sub-systems, different identifiers.
|
I have some operation like this C++ code that I want to convert in C89:
return reinterpret_cast<uint8_t *>(stream.buffer) - buffer;
How can I replace the reinterpret cast in C?
| Nothing very exciting, you've seen this before:
```
(uint8_t *)(stream.buffer)
```
That's the only way to cast something in C.
|
I've been programming in C for a while and i wondered why is important to separate this processes (Compile and Linking)?
Can someone explain please?
| It is useful in order to decrease rebuilt time. If you change just one source file - it is often no need to recompile whole project but only one or few files.
|
This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago.
Does a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored?
```
#define NUMBER 10
```
| No, macros don't work like that.
They are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10.
In this respect, C and C++ are identical.
|
I would like to close a socket but before notify all threads blocking onaccept/connect, therefore I am sending a user specific signal, however not knowing the tid of the signal receiving threads. I cannot use syscallkill(pid, signal)
| Why not just shutdown the socket without notifying? Each thread that is blocked on accept or read from that socket will return with the corresponding error that you can parse to take the necessary actions
|
This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago.
Does a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored?
```
#define NUMBER 10
```
| No, macros don't work like that.
They are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10.
In this respect, C and C++ are identical.
|
```
#define HELPER(param) Wazz ##param
HELPER(hek)
```
Doing agcc -E filenameshows me
```
Wazzhek
```
How do I getWazz hek? How do I insert a space between the 2 tokens?
```
#define HELPER(param) Wazz ## ## ##param
```
Doesnt work either. Any suggestions?
| Just do not use token concatenation operator when you don't want to do token concatenation.
```
#define HELPER(param) Wazz param
HELPER(hek)
```
|
What is the quickest bit-hack to achieve the following result?
Let x be a 4 byte int, in a C program.
If x is0x00000000, then x should be0xFFFFFFFF, else x should be untouched.
| x |= -(x == 0);x |= -!x;x = x ? x : 0xFFFFFFFF;if (x == 0)
x = 0xFFFFFFFF;...
Benchmark and choose what's appropriate for you
|
I know I can do this:
```
//With A = tax(x);
return tan(arctan(A)/2);
```
but I wanted something more efficient.
| Whenxis between -π/2 and π/2 you can use this formula:
```
t / (1 + sqrt(1 + t*t))
```
This is hardly an improvement on the original formula, but it uses one function call instead of two.
Note:I found this formulahere. The wikipedia page is in Russian, and the equivalent English page does not include the same formula.
|
I am reading lines from a file, the lines look like this:
```
89f81a03eb30a03c8708dde38cf:000391716
```
The thing is: I want to remove everything after the:(including the:).
I tried everything I could find online but they seem to useconst charand the lines arecharpointers.
| You can usestrchr:
```
char str[] = "89f81a03eb30a03c8708dde38cf:000391716";
char *ptr;
ptr = strchr(str, ':');
if (ptr != NULL) {
*ptr = '\0';
}
```
|
I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it?
(Does it actually make sense?)
| Iffoois of typechar[n]for integraln, then you can use
&foo[0]
to give you the pointer to the zeroth element offoo. The type of this expression ischar*.
|
I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it?
(Does it actually make sense?)
| Iffoois of typechar[n]for integraln, then you can use
&foo[0]
to give you the pointer to the zeroth element offoo. The type of this expression ischar*.
|
I want to dynamically load library from SD card, with dlopen, but when I do it, get error:
dlopen failed: couldn't map "/storage/emulated/0/Documents/Tests/armeabi-v7a/libtest.so" segment 2: Operation not permitted
When i use it for internal storage it's work.
What can i do to solve this problem?
| This is disallowed by Android's security policy. Anyone can write to that location, so loading code from it is an easily exploitable attack vector.
|
My code:
```
PGresult *res = PQexec(m_IConnection, "MOVE NEXT in my_cursor_name");
ExecStatusType status = PQresultStatus(res);
if (status != PGRES_COMMAND_OK)
{
PQclear(res);
return;
}
```
But it does not fail after it reaches the last row.
I've searched all over and can find no reference for detecting the end of rows.
| Per the first comment,
if(!stricmp(PQcmdTuples(res), "0"))
works to check for the last row of the MOVE
|
I am building a C application that uses OpenCV.
when compiling, I get the following error:
```
fatal error C1189: #error : core.hpp header must be compiled as C++
```
I did not find how to resolve this error.
How to use OpenCV from a C project?
| Select the required file.Launch its properties windowGoto C/C++ -> Advanced, and changeCompile astoCompile as C++ Code (/TP)
|
I need to create a function in which there is a default argument:
```
void func ( int a, int b = 1 );
// and
func (1, 2);
func (1);
```
| C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor:
```
void func(int a, int b);
#define TWO_ARGS(A, B, ...) A, B
#define func(...) func(TWO_ARGS(__VA_ARGS__, 1))
func(1, 2); /* calls func(1, 2); */
func(1); /* calls func(1, 1); */
```
|
I need to create a function in which there is a default argument:
```
void func ( int a, int b = 1 );
// and
func (1, 2);
func (1);
```
| C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor:
```
void func(int a, int b);
#define TWO_ARGS(A, B, ...) A, B
#define func(...) func(TWO_ARGS(__VA_ARGS__, 1))
func(1, 2); /* calls func(1, 2); */
func(1); /* calls func(1, 1); */
```
|
```
#include <stdio.h>
int main()
{
int i;
i=0;
printf("%d\n%d\n%d\n", i, &i, &(&i));
return 0;
}
```
i think that &i is just a value of address, and assume that it's 0xFF so &(&i)should be the address of 0xFF but why it's not valid?
| Unary&operator need an lvalue as its operand and returns an rvalue.&iis an rvalue, therefore&ican't be an operand of&.
|
if I have a pointer to an integer such as:
```
int num = 12;
int *p = #
```
and then print the address so
```
printf("%p\n", (void*)p);
```
What is the difference between the previous and this:
```
printf("%p\n", (void*)&p);
```
| Here,pcontains the address ofnum, so the firstprintfoutputs the address ofnum.
On the other hand,&pis the address ofp, so the secondprintfprints the address ofp.
|
I want to be able to do this:
```
typedef int a[2], b[2], c[2];
```
without having to type the[2]. One solution is to do:
```
typedef struct { int a[2] } a, b, c;
```
but then you have to always do stuff likea.a[0]and that's no good.
| For C or C++98, a simple typedef will do:
```
typedef int int2[2];
int2 a, b, c;
```
|
I have array defined like this
```
float array [1000][3]
```
I want to extract third column
```
float third[1000]
for (i = 0; i < 999,i++)
```
and then what?
| ```
for (i=0; i<1000; i++)
{
third[i]=array[i][2];
}
```
This should do it if I understood your question correctly.
|
I have array defined like this
```
float array [1000][3]
```
I want to extract third column
```
float third[1000]
for (i = 0; i < 999,i++)
```
and then what?
| ```
for (i=0; i<1000; i++)
{
third[i]=array[i][2];
}
```
This should do it if I understood your question correctly.
|
I have an array which is stored in my program memory
```
const char* const paragraph[] PROGMEM = {
"First Line",
"Second Line"
};
```
How do I read one string at a time so that it output
```
First Line
Second Line
```
| ```
int i;
for (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {
printf("%s\n", paragraph[i]);
}
```
|
I have an array which is stored in my program memory
```
const char* const paragraph[] PROGMEM = {
"First Line",
"Second Line"
};
```
How do I read one string at a time so that it output
```
First Line
Second Line
```
| ```
int i;
for (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {
printf("%s\n", paragraph[i]);
}
```
|
2d array declared by me.
```
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
```
I want address location of the element [1][5].
When I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p = &(*(*daytab+1)+5);then it shows error?
| That's becausea[i]is equivalent to*(a+i), not*a+i.
|
Can you use a pipe to share threads between two processes in C? I am writing my own shell and want to know if this implementation would be more optimal, if it is even possible?
| Each thread is specific to a process and share memory of the calling thread.
If you want efficient inter process communication, you can use shared memory.
Seehttp://man7.org/linux/man-pages/man7/shm_overview.7.html
|
2d array declared by me.
```
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
```
I want address location of the element [1][5].
When I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p = &(*(*daytab+1)+5);then it shows error?
| That's becausea[i]is equivalent to*(a+i), not*a+i.
|
As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search.
is there any other option for this one? just want to know tho
| Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value.
And doing that is O(N).
|
As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search.
is there any other option for this one? just want to know tho
| Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value.
And doing that is O(N).
|
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?
Thanks in advance.
| Open the project properties and do :
|
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?
Thanks in advance.
| Open the project properties and do :
|
I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?
Thanks in advance.
| Open the project properties and do :
|
I am usingrecv()to read data from a socket andfcntl()to set the socket blocking/non-blocking. My question is: If I calledrecv()(blocking) and I callfcntl()from another thread and set the socket non-blocking, will the currently runningrecv()return or the effect offcntl()will only take place after the blockingrecv()returns and I call it again?
| It won't affect the current receive operation.
Strange thing to do.
|
Is there a way to go from the below
```
int a; ///< This is a variable
int b = 3; ///< This is another variable
```
To the below?
```
int a; ///< This is a variable
int b = 3; ///< This is another variable
```
| align_right_cmt_spanshould be the correct setting.
|
Is there a way to go from the below
```
int a; ///< This is a variable
int b = 3; ///< This is another variable
```
To the below?
```
int a; ///< This is a variable
int b = 3; ///< This is another variable
```
| align_right_cmt_spanshould be the correct setting.
|
Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. we have to do this in sub-linear time. I.e. do not just go through each element searching for that element.
can we solve this using binary search???
| you could perform a binary search on the array,it means the index the binary search resulted was not the first occurence.
|
The exposed API from c is:
```
bam_hdr_t *bam_hdr_init(void);
```
how do I write its wrapper in Julia?
ccall((:bam_hdr_init,"lib.so"), Ptr{bam_hdr_t})works in Julia v0.5, but not in v0.4.
| ccall((:bam_hdr_init,"lib.so"), Ptr{bam_hdr_t},())works for both versions of Julia
|
Output is:10and it gives no error.
```
int main(){
int j=10;
int *i=&j;
printf("%d",*i);
return 0;
}
```
but it gives me an error:
```
int main(){
int *i;
int j=10;
*i=&j;
printf("%d",*i);
return 0;
}
```
I understand that pointer de-referencing is causing the error. But how is that happening?
| Because you are using an uninitialized pointer.
Your*i = &jshould bei = &j
|
I need to select one processor from my Comm to do some works ( I don`t want other processors do the work ).
Since I split my Comm to the groups, I cannot always pick one specific rank ( for example 0) as my master. I need to choose it from my current comm. Any suggestion?
Thank you.
| The rank of a process is always relative to a communicator. After you split your processes, you can just take process 0 in the new communicator to perform the work you want.
|
FromSSL_CTX_load_verify_locations:
SSL_CTX_load_verify_locations - set default locations for trusted CA certificates
Does this means I can put certificates in location (or file), which passed as parameter toSSL_CTX_load_verify_locationsfunction. And are these certificates automatically will be trusted?
| That is correct. This is how you specify the list of certificate authorities that are trusted.
|
Is using__MSDOS__enough with djgpp or should__DJGPP__be used instead?
By comparison, I know_WIN32isn’t defined by default on cygwin(based on the assumption djgpp and cygwin have the purpose to build an Unix layer to hide real OS details).
I no longer have a DOS machine to test it.
| To list the predefined macros and their values, use
```
djgpp -E -x c -dM /dev/null
```
|
Is there a way to read a HH:MM format from a file usingfscanf(), and treat it like an int? The file has this format :
```
3 14:50 20.10
```
Is it possible to do something likefscanf(fp, "%d ... %f, &a, &b, &c);andbwill have 1450?
| I'm afraid you can't do this in a line. However, you can:
```
fscanf(fp, "%d %d:%d %f", &a, &b1, &b2, &c);
b = b1 * 100 + ((b1 > 0) * 2 - 1) * b2; // in case b1, b2 are the different sign.
```
|
I have a pointer*pthat points to astruct S.Shas various fields.
Is it possible to assign structureSto the structure pointed to by*pusing only one assignment?OR,do I need to assign the fields, one by one?
| This example assigns a struct using a pointer and one statement.
```
int main(void) {
struct Foo {
char a;
int b;
double c;
} *foo, *bar;
foo->b = 10;
bar = foo; /* now bar->b=10 as well */
}
```
|
I need to determine x from the expression root(y).
"Y" has a range to its separated value with maximum 10^1000.
I solved it in the normal way and I saw the right result. But when Y is very large, the program outputs the wrong answer.
```
#include<stdio.h>
#include<math.h>
int main()
{
long long int x,y;
scanf("%lld",&y);
x=sqrt(y);
printf("%lld",x);
return 0;
}
```
| Use some bignum library, for exampleGMP
|
As show in the following code, what is the difference between 0 and CVMX_FAU_REG_64_ADDR(0) in the cvmx_fau_reg_64_t?
```
#define CVMX_FAU_REG_64_ADDR(x) ((x <<3) + CVMX_FAU_REG_64_START)
typedef enum
{
CVMX_FAU_REG_64_START = 0,
CVMX_FAU_REG_64_END = CVMX_FAU_REG_64_ADDR(0),
} cvmx_fau_reg_64_t;
```
| In the code as written, both values == 0. There is no difference in the actual value.
|
Is there in C/C++ standart constant that reflects how many bits are there in one byte (8)? Something like CHAR_BIT but for byte.
| According to the C standard, acharis one byte. ThereforeCHAR_BITis the number of bits in a byte.
The C standard says thatCHAR_BITis"number of bits for smallest object that is not a bit-field (byte)".
|
I have a text like this. And I want to show it in doxygen documentation as it is.
What type of command should I use.
| You can use verbatim, endverbatim.
http://www.doxygen.nl/manual/commands.html#cmdverbatim
|
If you useprintfsuch as:
```
printf("Time as a basic string = %s", ctime(&seconds));
```
The output would be:
```
Wed, 28 Oct 2009 11:35:37
```
How do I store this output thatctimegenerates so that:
```
char result[80] = ctime(&seconds);
```
Whatever I try just doesn't seem to work.
| You want to usectime_rinstead ofctime.
```
char result[80];
ctime_r(&seconds, result);
```
|
In C, what is the best way to ignore the commas when usingscanfon a number like 1,000,000?
| I would say the best way is tonotusescanffor this. At least not using any number formats.
Instead read it as a string, then remove the commas, and finallyconvert to a number.
|
I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be "#include"d? Should I send also specific flags to the gcc?
| You can usepthread_createincluded in<pthread.h>, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.
|
I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be "#include"d? Should I send also specific flags to the gcc?
| You can usepthread_createincluded in<pthread.h>, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.
|
This command
```
gcc file.c -c
```
outputs me this
```
file.o
```
how to run above command so it outputs me object file with specified name for examplefile.dbg.o?
| That's it:
```
gcc -o file.dbg.o -c file.c
```
|
We need check whetherstat()call willaccess Hard diskduring its operation?
i coulnt find answer for above question.
can anyone help me on this?
| Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.
I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.
|
We need check whetherstat()call willaccess Hard diskduring its operation?
i coulnt find answer for above question.
can anyone help me on this?
| Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.
I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.
|
We need check whetherstat()call willaccess Hard diskduring its operation?
i coulnt find answer for above question.
can anyone help me on this?
| Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.
I suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.
|
I want run a command write execlp function within c file in linux.
I want to run the following command :
ls -l
I can do ls command as follows :
execlp("/bin/ls" , "ls", NULL)
| Add the option to the parameter list:
```
execlp("/bin/ls", "ls", "-l", NULL);
```
|
This question already has answers here:Using pointers to iterate through argv[](6 answers)Closed7 years ago.
If I havechar **argshow can I loop through therowsof the array to determine how many there are?
For example, ifchar **args == {"one", "two", "three"}, how can I loop through each element, keeping count, and then return 3?
| Since yourargsis null-terminated, simply write
```
int i;
for (i = 0; args[i]; i++)
// do something
```
|
I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?
| Your question embodies a contradiction in terms.
'Abortively close' == RST.
Even if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.
|
I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?
| Your question embodies a contradiction in terms.
'Abortively close' == RST.
Even if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.
|
Im curious if they have an official name or just 'dot' and 'arrow'? I try search this in cpluscplus and in Deitel, but didn't find anything
| The C standard calls themmember access operators, but only in the index. They aren't given a name anywhere else except the one place in the index. In the same place, the->operator is calledarrow operator,the.operator is calledstructure/union member operator.
|
I want to send duplicate string to my bison file.
In my flex file I use it like this
```
"<" {return strdup(tOPEN);}
">" {return strdup(tCLOSE);}
```
Is this right things to do?
Or should I use it like below the code.
```
"<" { yyval. sval = strdup(yytext); return tOPEN;}
```
| ```
"<" { yyval. sval = strdup(yytext); return tOPEN;}
```
this is the right way of the using.
|
If I open a text file withopen("file.txt",O_RDONLY), do I need to close it withclose()?
Silly question, I know, but I am not entirely sure if the end of a process leaves open files open.
| The file will remain open until you close it or your process terminates. The process terminating will invalidate the file descriptors for that process, and so in essence "close" the files.
I would always close them explicitly, and as early as reasonable.
|
I want to get a integer from to user. But I wonder what is the difference betweenfscanf(stdin, "%d", &x);andscanf("%d", &x);?
| What is the difference between stdin with fscanf and scanf?
Thescanffunction is equivalent tofscanfwith the argumentstdininterposed before the arguments toscanf. C11 §7.21.6.4 2
So aside from a different amount of typing the code, they are the same.
|
I have an array
```
char msgID[16];
```
How do I increment this by 1? I read the high and low 8 bytes into 2 differentuint64_tintegers
```
uint64_t high, low;
memcpy(&low, msgID, sizeof(uint64_t));
memcpy(&high, msgID + sizeof(uint64_t) , sizeof(uint64_t));
```
If I do
```
low += 1;
```
How do I account for overflow?
Thanks for any help provided.
| It's quite simple, actually:
```
if(++low == 0)
++high;
```
|
Since Lua 5.3, inegers are supported.
But how can I do :
```
if type( 123 ) == "integer" then
end
```
Or
```
switch( lua_type( L, -1 ) )
{
case LUA_TINTEGER:
break;
}
```
Sincetype()is still going to return"number"for both integer and reals, andLUA_TINTEGERdoes not exist ?
Thanks.
| usemath.typefor Lua 5.3
Returns "integer" if x is an integer, "float" if it is a float, or nil
if x is not a number.
|
I code in C and I am little weak in C++, in my research I came across many methods to read XML from URL for my win32 application.
I found cURL andXmlTextReaderbut it's in C++.
Is there any function or other ways, where I can download XML from the URL and parse that XML using only C language and not C++?
I can work with C++ as well, but I want to avoid it as it's not I am comfortable with.
| Libcurlhas pure C API.Expatandlibxmlare written in pure C too.
|
I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried:
```
char test[256] = {'N'};
```
But this only initializes the first index to'N'and the rest to 0.
| Usememset:
```
#include <string.h>
char test[256];
memset(test, 'N', 256);
```
|
I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried:
```
char test[256] = {'N'};
```
But this only initializes the first index to'N'and the rest to 0.
| Usememset:
```
#include <string.h>
char test[256];
memset(test, 'N', 256);
```
|
In C, If I have:
```
char *reg = "[R5]";
```
and I want
char *reg_alt = "R5"(equal to the same thing, but without the brackets), how do I do this?
I tried
```
*char reg_alt = reg[1:2];
```
but this doesn't work.
| There is no built-in syntax for dealing with substrings like that, so you need to copy the content manually:
```
char res[3];
memcpy(res, ®[1], 2);
res[2] = '\0';
```
|
Given the short notation to declare arrays, how do I specify the type of myArray to be arrays?
```
[] myArray = { //here [] should be array type
{"obj1, "obj2"},
{"obj1, "obj2"}
}
```
| Assuming you want a two-dimensional array of character strings:
```
const char *myArray[][2] = {
{"obj1", "obj2"},
{"obj1", "obj2"}
/* any other elements */
};
```
|
Is it good practice to use the weak attribute in production code so that for test code one can override functions?
| I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code:
using macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.
|
Is it good practice to use the weak attribute in production code so that for test code one can override functions?
| I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code:
using macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.
|
I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...
| The following types resemble natural numbers set with 0 included in C++:
unsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11.
Each one differs with the other in the range of values it can represent.
|
I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...
| The following types resemble natural numbers set with 0 included in C++:
unsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11.
Each one differs with the other in the range of values it can represent.
|
I was given a piece of code in C, and the question asked about it is whats wrong with it? I would be fine answering, but the asterisk in front of the malloc casting is confusing the heck out of me!
```
char f() { return *(char*)malloc(10); }
```
| The function returns an indeterminate value and has a memory leak because the dynamically allocated memory is not freed.
|
Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.
| Example of sending a raw Ethernet frame in Linux:
https://gist.github.com/austinmarton/1922600
|
Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.
| Example of sending a raw Ethernet frame in Linux:
https://gist.github.com/austinmarton/1922600
|
I currently have a code that checks whether a file is a directory or not, it goes as follows;
```
file = readdir (dir);
if(file->d_type & DT_DIR){
\* some code*\
}
```
I was wondering, what is the if statement for the exact opposite of this. Something along the line "if file is not directory".
| Any boolean expression can be negated with thenotoperator (!):
```
if (!(file->d_type & DT_DIR)) {
```
|
```
#include <stdio.h>
int main(void)
{
char c[] = "Gate2011";
char *p = c;
printf("%s", p+p[3]-p[1]);
return 0;
}
```
Output:2011
Why does it give this output? I tried different combinations and it always gives junk.
| becausep[3] = 'e' = 101andp[1] = 'a' = 97
101 - 97 = 4
p + 4= address of "2001" in "Gate2001"
interpreted as string ... there you go.
I also do not understand the downvotes :(
|
Is it possible to change the options in Clion so that the variables are aligned like so:
This should be applied in structs and methods.
| Yes.
Settings -> Editor -> Code Style -> C/C++ -> Wrapping and Braces -> Variable groups -> Align in columns
You can of course also use a custom formatting tool that does it as well.
|
I want to assign ' to a character but it keeps giving me error
any help?
```
void main()
{
char c = ''';
}
```
| Special characters like ' or \ must be escaped with a backslash in these situations. In this particular case you got an error because the compiler thinks you opened and closed a null character with the first two '' and then opened another character without closing it with the third one.
|
I have a makefile, called "Makefile", and some target in it like:
```
file.o: file.c Makefile
gcc <some flags & options> file.c
```
What exactly doesfile.o: file.c Makefiledo?
| That line describes the dependencies forfile.o.
If any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.
|
I have a makefile, called "Makefile", and some target in it like:
```
file.o: file.c Makefile
gcc <some flags & options> file.c
```
What exactly doesfile.o: file.c Makefiledo?
| That line describes the dependencies forfile.o.
If any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.
|
Is it possible for a function in a linux kernel module calling a function in another module ?
| Yes. Of course, the other kernel module must be loaded.
For an example, look at the USB code, which is implemented as a mullti-layer driver, with each layer in its own module.Reference linkhere.
|
I've searched the standard but didn't notice the mentioned part.
Is it just "anything but 0" and 1 or it is compiler-dependent?
| The result of the logical negation operator!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint.
Appears in C89/C90, C99, and C11.
|
This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.
Say I declare a global arrayint arr[10];Should I free it somehow in the end?
| You need not free it.You should usefree()only when you have usemalloc().
|
This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.
Say I declare a global arrayint arr[10];Should I free it somehow in the end?
| You need not free it.You should usefree()only when you have usemalloc().
|
why this code is showing value of a = 1120403456 (may be garbage) in Dev-C++.
```
#include<stdio.h>
int main()
{
int a=5;
float * pf;
pf=(float *)&a;
*pf=100.0;
printf("%d",a);
return 0;
}
```
| The floating point number 100.0 is represented as 0x42C80000 in memory, which in decimal is 1120403456. You're printing out the 32-bit integer representation of 100.0.
|