question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
```
const struct file_operations generic_ro_fops = {
.llseek = generic_file_llseek,
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.mmap = generic_file_readonly_mmap,
.splice_read = generic_file_splice_read,
};
```
What do those ". " mean in this code?
This ... |
They're called "designated initializers". It's a feature introduced in C99 and provided as an extension by GNU C (of course you know, the Linux kernel isn't written in C but in GNU C).
This is really syntactic sugar and provides a convenient way to initialize the members of that struct without worrying about their or... |
I am working on a new project, which relates to creating drive images for backup.
As a part of it, i need to write code which can give much useful information related to disk geometry - cylinders, no. of sectors, partitions, and file systems and even drive specific info, like which partition is present on which drive... |
There is no glibc facility for that. Uselibblkid.
|
I have the program almost done. I am trying to divide CBA0123h by B000h. The quotient comes out right. However, the remainder which is supposed to be in the dx register should be: EA61 (http://www.miniwebtool.com/hex-calculator/?number1=CBA0123&operate=4&number2=B000), but instead its A123. I think this has something ... |
CBA0123h = B000h * 1282 + A123h. The DX value is correct.
|
I have one clarification
What is the difference between calling a function through function pointer and calling a function directly by name ?
Anybody help me in this.
|
There is no difference in the actual call. Parameters are passed the same way, the function runs the same way, and the return value comes back the same way.
The only difference is that you can make the function pointer point somewhere else.
|
I'm trying to set up theHg-Git Mercurial Extension, which recommends using the C compiler for Microsoft Visual C++ 2008. I've installed Visual C++ 2008, but I can't figure out where the C compiler is located so that I can add it to my path.
|
Windows 7 / Vista:
```
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Bin\cl.exe
```
Windows XP:
```
C:\Program Files\Microsoft Visual Studio 9.0\VC\Bin\cl.exe
```
|
For what I am trying to do, I require an array in the formchar **.
I found out that using the following creates a dynamic array that ends up requiring 256 free calls:
```
char** start = malloc(11*sizeof(char));
for (i=0;i<256;i++) {
start[i] = malloc(11*sizeof(char));
}
for (i=0;i<256;i++) {
free(start[i]... |
```
char (*p)[12] = calloc(n, sizeof(*p)); // or malloc
...
free(p);
```
pis a pointer tonarrays, each of length 12.
|
I have astructwhich contains strings and pointer within. Is there any library functions available to do a deep copy of thestructinto another. I don't want to do a field by field copy since the struct I'm having is quite large.
Does glib have any function that does the trick?
|
No. A general-purpose function would have no way to know the structure of your struct (i.e. the information that's only available at compile time). And even if it did, how it would know what constitutes a "deep copy" in all circumstances?
|
I have two 32 bit integers HI & LO, and I need to right shift bits in them, so that last last bit of HI becomes most significant bit of LO. In other words, shifting operation should work, as if two bits is a single 64bit unit. Language C/C++Thanks !
|
This code below right-shifts 1-bit as you described.
It works by masking off all except the lowest bit inhi, and shifting it all the way left (Most Significant Bit), and joining that withloshifted right one-bit.
Then, it simply shiftshito the right one bit.
```
{
lo = ((hi & 0x00000001)<<31) | (lo >> 1);
hi... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Lvalue required error
I am having an error in my C program
```
main () {
int arr[] = {1, 2, 3, 4};
printf("%d", *arr);
arr++;
printf("%d", *arr);
}
```
When I compile this code I get lvalue required error. for theline wit... |
arris a constant, you can't change its value. You can add a
```
int *p = arr;
```
And then do a
```
p++;
```
|
I am using libcurl's "easy" interface to access network devices over HTTP, currently using HTTP Basic authentication (which is the default in curl). I've found that it's possible to allow Digest authentication usingcurl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST)but unfortunately this makes cur... |
Re-use the same easy handle for the subsequent requests!
|
How do I take an input of 2 32 bit unsigned integers, multiply them and get the output as a 64 bit integer in C? Any help is appreciated! Thanks.
|
```
#include <stdint.h>
uint64_t mul64(uint32_t x, uint32_t y) {
return (uint64_t)x*(uint64_t)y;
}
```
|
in sqlite3 using the command line, if I want to enter something very approximate and get the correct output I use
```
select * from <table_name> where <col_name> like '%<query>%';
```
where is the name of my table, is the column name and is the partial query name for example
```
SELECT * FROM suppliers WHERE sup... |
```
char *result = sqlite3_mprintf("SELECT * FROM %s WHERE %s LIKE '%%%q%%';", "suppliers", "supplier_name", "bob");
```
|
My project folders look like this
```
Makefile
/src
/flash
build.xml
/blabla
...
```
I wrote a Makefile like this
```
flash: src/flash/bin-debug/App.swf
src/flash/bin-debug/App.swf:
cd src/flash
ant
```
When I executemake flash, I get the following message:
```
cd src/flash/
ant
Buildfile: bu... |
makecreates a new subshell for each line. Try:
```
src/flash/bin-debug/App.swf:
cd src/flash; ant
```
Otherwise the two commands are executed in two separate subshells. The effect of thecdis lost when the first subshell terminates.
|
I am going to write a Lexical that is going to be part of a kernel module in which I will parse a file and return tokens. For that, I may need to use functions likefopen, getc,putc,fseeketc which obviously are user space functions. I have searched for alternatives to these functions in kernel space and I found functio... |
Don't.
Reading files, and especially complex configuration files, is not something which should be done from the kernel.
There's a lot of information about why this is a bad idea.The KernelNewbies FAQis a good start.
Really, really don't do this. I integrate a lot of vendor (kernel) code, and this is one of the mis... |
For what I am trying to do, I require an array in the formchar **.
I found out that using the following creates a dynamic array that ends up requiring 256 free calls:
```
char** start = malloc(11*sizeof(char));
for (i=0;i<256;i++) {
start[i] = malloc(11*sizeof(char));
}
for (i=0;i<256;i++) {
free(start[i]... |
```
char (*p)[12] = calloc(n, sizeof(*p)); // or malloc
...
free(p);
```
pis a pointer tonarrays, each of length 12.
|
I have astructwhich contains strings and pointer within. Is there any library functions available to do a deep copy of thestructinto another. I don't want to do a field by field copy since the struct I'm having is quite large.
Does glib have any function that does the trick?
|
No. A general-purpose function would have no way to know the structure of your struct (i.e. the information that's only available at compile time). And even if it did, how it would know what constitutes a "deep copy" in all circumstances?
|
I have two 32 bit integers HI & LO, and I need to right shift bits in them, so that last last bit of HI becomes most significant bit of LO. In other words, shifting operation should work, as if two bits is a single 64bit unit. Language C/C++Thanks !
|
This code below right-shifts 1-bit as you described.
It works by masking off all except the lowest bit inhi, and shifting it all the way left (Most Significant Bit), and joining that withloshifted right one-bit.
Then, it simply shiftshito the right one bit.
```
{
lo = ((hi & 0x00000001)<<31) | (lo >> 1);
hi... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Lvalue required error
I am having an error in my C program
```
main () {
int arr[] = {1, 2, 3, 4};
printf("%d", *arr);
arr++;
printf("%d", *arr);
}
```
When I compile this code I get lvalue required error. for theline wit... |
arris a constant, you can't change its value. You can add a
```
int *p = arr;
```
And then do a
```
p++;
```
|
I am using libcurl's "easy" interface to access network devices over HTTP, currently using HTTP Basic authentication (which is the default in curl). I've found that it's possible to allow Digest authentication usingcurl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST)but unfortunately this makes cur... |
Re-use the same easy handle for the subsequent requests!
|
How do I take an input of 2 32 bit unsigned integers, multiply them and get the output as a 64 bit integer in C? Any help is appreciated! Thanks.
|
```
#include <stdint.h>
uint64_t mul64(uint32_t x, uint32_t y) {
return (uint64_t)x*(uint64_t)y;
}
```
|
Anyone know what library/header is required to use the make64 high32 and low32 functions on
MacOS or linux. Couldn't find anything on the web.
```
uint64_t make64(uint32_t high, uint32_t low);
uint32_t high32(uint64_t value);
uint32_t low32(uint64_t value);
```
Thanks
|
I don't know any library with these functions, just write them:
```
uint64_t make64(uint32_t high, uint32_t low)
{
return (uint64_t) high << 32 | low;
}
uint32_t high32(uint64_t value)
{
return value >> 32;
}
uint32_t low32(uint64_t value)
{
return value;
}
```
|
I apologize in advance if this has been asked before, but I haven't been able to find anything on SO which relatesspecificallyto this.
Basically, let's say I have a simple macro:
#define STR "somestring"
When I do aprintforputson that macro, I get a
```
error: expected ')' before ';' token
```
It's literally as s... |
The problem is most likely thatSTRis redefined at some point in your program. The following code compiles just fine.
```
#define STR "something"
int _tmain(int argc, _TCHAR* argv[])
{
puts(STR);
return 0;
}
```
As an experiment try picking a different name, saySTR_TESTand see if that works. If so then you ... |
I am very confused with this kind of casting. Can someone explain what exactly it is happening in this sentence?
```
x = *(char*)&n;
```
That is the complete code, and it is used to know if a machine is little endian or big endian.
```
int n = 0x1234567;
char x;
x = *(char*)&n;
```
|
&ntakes the address ofn, but crucially, it's the lowest-addressed byte ofn.(char *)tells the compiler to treat that address as a pointer to achar, i.e. a pointer to a single byte.*dereferences that, i.e. it obtains the byte value stored at that address.
So the overall effect is thatxis set to the value stored in the ... |
Assume you have 2 positivelongvaluesaandbwhich are greater than2^32(and smaller than2^63), and an long integerc.
What is the best way, in java and\or c, to perform operations such as
```
(a*b)%c
```
while avoiding arithmetic overflow.
Edit :
c is around2^34, and sometimes both a and b are just between2^32andc...
... |
Assuming everything's positive, then you can use the following mathematical identity:
```
(a*b)%c == ((a%c) * (b%c)) % c
```
Of course, this still doesn't eliminate the possibility of overflow.
The easiest way to completely avoid the issue is to use a big-integer library.
|
How can i check that a user has input a url into the terminal for my application? Is there some sort of regex i can use?
I am getting the input from the terminal in Linux and storing it in a char str[100] variable.
EDIT*
I need to check that they can only enter a URL that actually exists, if that is possible.
|
I use this regular expression. It does not allow for the ?.... at the end though.
```
^https?://(((0|([1-9][0-9]{0,1}))(\.(0|([1-9][0-9]{0,1}))){3})|([a-zA-Z]([a-zA-Z0-9$\-_@\.&+*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*(\.([a-zA-Z]([a-zA-Z0-9$\-_@\.&+!*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*))*))(/|((/([a-zA-Z]([a-zA-Z0-9... |
How doesposix_memalignwith alignment size of 4096 bytes differ frommmap? Does it internally usemmapor some other mechanism?
|
posix_memalignis a higher-level API thanmmap, designed to interoperate withmalloc,freeandrealloc.mmapusage is more complicated because it offers more functionality thanposix_memalign(mapping files into a process's address space). How it is implemented (in terms ofmmapor otherwise) is left unspecified by the POSIX stan... |
I'm writing a C program accessing SQLite database.
The table is very simple, two columns, ID and Age.
If ISELECT Age FROM Table WHERE ID=23, that would yield only a result.
So how can I put the age of that person into a int variable?
Edit: Thisblogprovides a great introduction (with source code).
|
Check the reference. It will be something like:
```
ret = sqlite3_prepare_v2 (db, "SELECT Age FROM Table WHERE ID=23", -1, &stmt, &e);
if (sqlite3_step (stmt) == SQLITE_ROW) {
age = sqlite3_column_int (stmt, 0);
}
```
|
I have been trying to program the 3x 7 trick. The full code is available here:https://codereview.stackexchange.com/questions/9419/programming-of-3-x-7-trick.
I am stuck at step 5.
I have this error when i type in the value for the row.
Not sure what the error is. Need some guidance.
step 6:
|
That error comes from the back_to_array function, where you have a typo in the condition of the inner loop. It should bej < numRowsinstead ofi < numRows.
|
I am trying to display a 2-dimensional array.
```
int arr[numRows][numCols] = {{0,1,2,3,4,5,6},{7,8,9,10,11,12,13},{14,15,16,17,18,19,20}};
void display(int p[][numCols])
{
//printf("\n");
for (int i = 0; i< numRows;i++)
{
for ( int j = 0;i< numCols;j++)
{
printf(... |
You have simple misprint - instead:
```
for ( int j = 0;i< numCols;j++)
```
use
```
for ( int j = 0;j< numCols;j++)
```
|
```
#include <stdio.h>
enum {AA, BB, CC} s;
int main()
{
s = 4;
printf("%d\n",s);
return 0;
}
```
The compiler doesn't give any warning and prints 4. What is happening behind the scene? Isstreated as aninttype?
|
The specific type of an enumeration is implementation specific, but it is often anint. So yes, in this casesis probably anint. From the C spec:
Each enumerated type shall be compatible withchar, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of... |
How to find the length of the string which also contains string terminating character in between. Example: ABC\0ABC. Is there any inbuilt function present which returns the length?
If the Input string is: ABC\0ABC
Output: 8
|
Since the end of a C-style string is only detectable because it ends in a'\0'character, what you're asking isn't solvable in a general way. If, like in your example, you know there's exactly one'\0'character in the string, then you can simply do:
```
x = strlen(string); // length of string before the fi... |
In C#.NET I can to useList<myclasstype> vals = new List<myclasstype> ();it's possible do equivalent to in C?
I have an struct like:
```
typedef struct foo {
int x;
int y;
} Baa;
```
and I want do:
```
**BAA vals = ??
int i ;
for(i = 0; i < size; i++)
{
vals[i].x = i;
vals[i].y = i * 10;
}
```
I hop... |
It is the same as you would create any other array in C except that the type is replaced withBaa
```
int size = 5;
Baa baaArray[size];
int i;
for(i = 0; i < size; i++)
{
baaArray[i].x = i;
baaArray[i].y = i*10;
}
```
You can also use pointers and malloc to accomplish this:
```
int size = 5;
Baa *baaPtr = mal... |
I am trying to get network interface information fromstruct ifaddrs
How can I determine if the interface I am looking at is of inet (ipv4) or inet6 (ipv6)?
|
You test theifa_addr->sa_family- it will beAF_INETfor IPv4 addresses, andAF_INET6for IPv6 addresses.
You can then cast theifa_addrmember to eitherstruct sockaddr_in *orstruct sockaddr_in6 *as appropriate.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Objective-C style formatter
I have wrote a program and wonder if there is any software to format the codes the way it should look like a good programmer?
I know I shouldn't rely on it but just for my curiosity and to have this done in a b... |
If you're using XCode, you can re-indent your files (Editor -> Structure -> Re-Indent), or with the keyboard shortcut:ControlI.
|
I was wondering if there is a way I can extract everything before I hit a certain word in a string. The string I have created has been malloced and then populated. I want to create a new string with everything before a certain substring so
String1 = "I need coffee"
how can I extract everything before coffee?
Any id... |
Usestrstrto locate the substring, andstrncpywith a bit of pointer arithmetic (n = startOfPrefix - startOfString) to copy the prefix to a new buffer, don't forget to null terminate the new string.
If you just want to throw away the substring and everything after it you could just set the location returned bystrstrto'... |
I have been looking at various ways to implement a timer or alarm that will executes a cleanup function for a program in an embedded system with minimal resources.
Essentially, I'd like the function to be executed when the system is under minimal load, minimal network activity and/or when a period of time has been re... |
I ended up using variables and a timer to solve my issues. The timer executes, but based off of the variables - I either execute the code.. or not.
|
I notice that the C standard defines the getenv() function but that (7.22.4.2)
the method for altering the environment list [is]
implementation-defined.
I'm trying to have my program work on as many hosted C implementations as possible, is there a good general way to check if an implementation has a method to set a... |
It is possible to have an implementation of C on a system that does not have environment variables. So by that token you you cannot conclude that all host platforms support environment variables. However, that's pretty much nitpicking. You will have to deal with this on a case by case basis but you'll findputenv()pret... |
Anyone know what library/header is required to use the make64 high32 and low32 functions on
MacOS or linux. Couldn't find anything on the web.
```
uint64_t make64(uint32_t high, uint32_t low);
uint32_t high32(uint64_t value);
uint32_t low32(uint64_t value);
```
Thanks
|
I don't know any library with these functions, just write them:
```
uint64_t make64(uint32_t high, uint32_t low)
{
return (uint64_t) high << 32 | low;
}
uint32_t high32(uint64_t value)
{
return value >> 32;
}
uint32_t low32(uint64_t value)
{
return value;
}
```
|
I apologize in advance if this has been asked before, but I haven't been able to find anything on SO which relatesspecificallyto this.
Basically, let's say I have a simple macro:
#define STR "somestring"
When I do aprintforputson that macro, I get a
```
error: expected ')' before ';' token
```
It's literally as s... |
The problem is most likely thatSTRis redefined at some point in your program. The following code compiles just fine.
```
#define STR "something"
int _tmain(int argc, _TCHAR* argv[])
{
puts(STR);
return 0;
}
```
As an experiment try picking a different name, saySTR_TESTand see if that works. If so then you ... |
I am very confused with this kind of casting. Can someone explain what exactly it is happening in this sentence?
```
x = *(char*)&n;
```
That is the complete code, and it is used to know if a machine is little endian or big endian.
```
int n = 0x1234567;
char x;
x = *(char*)&n;
```
|
&ntakes the address ofn, but crucially, it's the lowest-addressed byte ofn.(char *)tells the compiler to treat that address as a pointer to achar, i.e. a pointer to a single byte.*dereferences that, i.e. it obtains the byte value stored at that address.
So the overall effect is thatxis set to the value stored in the ... |
Assume you have 2 positivelongvaluesaandbwhich are greater than2^32(and smaller than2^63), and an long integerc.
What is the best way, in java and\or c, to perform operations such as
```
(a*b)%c
```
while avoiding arithmetic overflow.
Edit :
c is around2^34, and sometimes both a and b are just between2^32andc...
... |
Assuming everything's positive, then you can use the following mathematical identity:
```
(a*b)%c == ((a%c) * (b%c)) % c
```
Of course, this still doesn't eliminate the possibility of overflow.
The easiest way to completely avoid the issue is to use a big-integer library.
|
I wanted to write a C code to zip a file in unix. I implemented it using system function using UNIX shell command "zip -r filepath". The zip -r filepath command is working when I execute it directly through UNIX shell.
I have witten the code as below
```
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int... |
That's not how you call a function in C. Try:
```
system("zip -r /root/Desktop/hi.txt");
```
|
I'm fairly new to MIPS, and I need to convert this MIPS code into C:
```
addi $t0, $t0, 0
sltiu $t1, $t0, 1000
beq $t1, $0, 7
sll $t1, $1, 2
```
After that it goes into some more operations, but this is the section I am having trouble translating. I think it is something along the lines of (not actual code following... |
```
addi $t0, $t0, 0
#t0 = t0 + 0;
sltiu $t1, $t0, 1000
#t1 = (t0 < 1000) ? 1 : 0;
beq $t1, $0, 7
#if (t1 == 0)
# goto foo; /* label foo is 28 bytes down the program counter */
sll $t1, $1, 2
#t1 = $at << 2;
```
You can simplify the code to:
```
if ($t0 >= 1000)
goto foo; /* label foo is 28... |
I'm having a bit of issue with pointers and structures in c.
```
struct foo{
char a[15];
}
void asn_foo(struct foo *pa){
(*pa).a = "123";
}
main()
{
struct foo foo1[2], *pf;
pf = &(foo1[0]);
asn_foo(pf);
}
```
I'm trying to assign a new value by:
```
(*pa).a = "123";
```
but I have the error "Inc... |
You can't assign new values to an array using the assignment operator, you have to copy the contents of the string"123"into your array. Usestrcpyto do so:
```
strcpy(pa->a, "123");
```
Another trick is also wrapping your array in astruct(as you've done here), and assigning one struct to another in order to assign ne... |
How todefine a pointer to function that returns a pointer to function?
```
typedef int(*a)(int,int);
a (*b)(int,int);
```
Why this can work,but the following can't work?
```
(int(*a)(int,int) ) (*b)(int,int);
```
or
```
int(*)(int,int) (*b)(int,int);
```
or
```
( int(*)(int,int) ) (*b)(int,int);
```
|
Here is the correct way to do it:
```
int (*(*b)(int,int))(int,int);
```
You can compile the following code that demonstrates using both of the methods. I would personally use the typedef method for clarity.
```
#include <stdio.h>
int addition(int x,int y)
{
return x + y;
}
int (*test(int x, int y))(int,int)
... |
I have a pipe that all my child processes use, but before a child uses the pipe to talk to the parent I need to clear it so that the parent reads from it correctly. Is there a simple function in C to do this?
|
The way to "clear" a pipe is to read from it until the buffer is empty. This doesn't help you. I am guessing that your real problem is that the parent might read data that is mixed from multiple clients. There are two easy solutions to your problem.
Always write messages less thanPIPE_BUFbytes long, and do this in... |
How (in GCC/"GNU C") do you declare a function pointer which points to an__attribute__((const))function? The idea being that I want the compiler to avoid generating multiple calls to the function called through the function pointer when it can cache the return value from a previous call.
|
```
typedef void (*t_const_function)(void) __attribute__((const));
static __attribute__((const)) void A(void) {
}
static void B(void) {
}
int main(int argc, const char* argv[]) {
t_const_function a = A;
// warning: initialization makes qualified
// function pointer from unqualified:
t_const_functio... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
What results of the implementation ... |
If you mean
```
Num_in_rankA[Arank]++
```
without the spaces, it adds one to "Arank-th" element of the array called Num_in_rankA.
|
If I pass avoid *vptrto a function which takes aother_type *ptras its arg, willvptrbe converted automatically toother_type *? Here is the code,
```
typedef struct A {
//...
}A;
void bar(A *a)
{
//do something with a
}
int main()
{
A a = {..};
void *vp = &a;
bar(vp); //will vp be converted to A*... |
Yes,void*is implicitly convertible to any pointer type, and any pointer type is implicitly convertible tovoid*. This is why you do not need to (and should not) cast the return value ofmalloc, for example.
|
What's the best way to concatenate a string using Win32? If Understand correctly, the normal C approach would be to usestrcat, but since Win32 now deals with Unicode strings (akaLPWSTR), I can't think of a way forstrcatto work with this.
Is there a function for this, or should I just write my own?
|
lstrcatcomes in ANSI and Unicode variants. Actuallylstrcatis simply a macro defined as eitherlstrcatAorlstrcatW.
These functions are available by importingkernel32.dll. Useful if you're trying to completely avoid the C runtime library. In most cases you can just usewcscator_tcscatas roy commented.
Also consider t... |
In C, and C++, assuming that I'm not using smart pointers or any other weird garbage collecting mechanism, does memory get deallocated (garbage collected) when the program exits?
|
When a process terminates, the OS removes the virtual memory which had been assigned to it.
Since the entirety of its address space goes away, so do all the objects within.
However, this is not the same as C++ garbage collection: no destructors get called. The memory just... quietly returns to the operating system.
|
I'm trying to understand this C code from a simple priority queue, especially - why does it need thestruct qnode **firstpart:
```
int quedel(struct qnode **first, struct qnode **last, int *prio, int *val) {
struct qnode *tmp = NULL;
if((NULL == *last) && (*last == *first)) {
fprintf(stderr, "Empty queue.....\n")... |
Since C doesn't have pass-by-reference, only pass-by-value, this approach is the only way to make this assignment:
```
*first = (*first)->next;
```
visible to the caller.
(Iffirstwere just a single pointer, and we wrotefirst = first->next, then the code that calls this function wouldn't see the modification.)
|
During normal browser caching, will a browser re-fetch all file contents if the web server breaks and reopens a tcp connection to the client?
Or will it still cache all contents and only update what has changed, upon the new socket (no difference)?
Thanks!
|
Browsers operate via HTTP protocol. What they can cache and for how long is determined by specialinstructionsof the HTTP protocol (e.g. cache-control header).
Those instructions can be specified by web server. On the other hand browsers can try to cache as much as possible unless it is forbidden by special HTTP instr... |
I'm currently learning theCprogramming language (coming from Java) and I'm a bit confused as to how to define a macro.
In order for other code to use the macro, the header file must have it. But if I define the macro in the header file, then the source file can't use it. Do I have to define it in both or do I have ... |
Source files virtuallyalwaysinclude their "own" header file -- i.e., a header that declares the functions defined in a source file. Declaring a function before actually defining it is perfectly legal and often desirable: you may get compile errors if the header is accidentally mismatched, and that's a good thing.
|
If I have the following expression:
```
c = (a) * (b)
```
What does the C90 standard say about the order evaluation of the subexpression 'a' and 'b'?
|
There is no specified order since the multiplication operator is not a sequence point. Sequence points include the comma operator, the end of a full expression, and function calls. Thus the order of evaluation of(a)and(b)is up to the compiler implementation. Therefore you shouldn't attempt to-do something in(a)that w... |
I would like to put an optional letter before my variables like 2p where p is an ID and 2 is a NUM. My ID matches only letters, and I would like to keep it that way (i.e. I don't want to change the regex for ID). I tried something like this, but it didn't work:
```
var
: NUM ID
;
```
This doesn't work becaus... |
try this
```
var
: NUM ID {...}
| ID {...}
;
```
|
Suppose I have a pointer to a function calledfoo. How do I now run the function that this is pointing to?
|
If you function has the following signature:
```
void foo(int x);
```
And you have defined the following pointer:
```
void (*ptr)(int) = foo;
```
You can execute foo, through "ptr", like this:
```
ptr(12); //actually calls foo(12);
```
|
In OpenCV when displaying an image with:
```
cvSetWindowProperty("displayCVWindow", CV_WND_PROP_FULLSCREEN,
CV_WINDOW_FULLSCREEN);
```
There is a small border around the full screened window if anyone ever noticed. Is there a way to get a rid of this?
Screenshot showing border of window when in full screen mode.No... |
OpenCV does not provide this capability.
If you want to have the image in fullscreen mode or floating around without window/borders you will have 2 choices:
Hack the window created by OpenCV;Create the window yourselfusing native API calls.
If you decide to hack the window, you maytry this codeand replace theSetWin... |
I can't get the following code to work. It's working with normal select or insert, but when I try to insert a variable to it it didn't work. Can some let me know please what's wrong here?
Please note that the output is below.
```
int main(int argc, char **argv)
{
MYSQL *conn;
char str[100] = "test";
conn = my... |
You don't do any error checking. My guess isconn == NULL.
For the record, don't usesprintfever. Usesnprintfinstead, that is, if you're okay with SQL injections.
|
Linux3.2.0
Given the following source:
```
#include <stdio.h>
#include <sched.h>
int main(void)
{
printf("%i \n", CLONE_PTRACE);
return 0;
}
```
I get:
test.c: In function ‘main’:
test.c:6:18: error: ‘CLONE_PTRACE’ undeclared (first use in this function)
Why?
|
You need to#define _GNU_SOURCEone way or another to get those constants. (See theclone(2)man page.)
With your code saved ast.c:
```
$ gcc -std=c99 t.c
t.c: In function ‘main’:
t.c:6:25: error: ‘CLONE_PTRACE’ undeclared (first use in this function)
t.c:6:25: note: each undeclared identifier is reported only once for ... |
InCprogramming.comI found this piece of code:
```
int a,b;
scanf("%d %d",&a,&b);
b=(a+b)-(a=b);
printf("%d %d",a,b);
```
It is claimed to be a tip/trick to "swap without using temporary". My tests on Linux gcc prove it. However, wouldn't the order how different compilers or platforms computing this expression matter... |
No. In the expression(a+b)-(a=b)there is no sequence point betweenabeing written to andabeing read in the(a+b)sub-expression to determine the value to be stored tobso the behaviour is undefined.
|
I got the following string:
"312 ,22 ,+12 , -12 , 5331"
it is possible to have more than 1 space between numbers.
I need to convert it to an array like that:
int arr[] = {312,22,-12,12,5331};
Is there a pretty and elegant way to do this with C89?
|
Usestrtok+atoi:
```
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main(int argc, char const *argv[])
{
char numbers_str[] = "312 ,22 ,+12 ,-12 ,5331", *currnum;
int numbers[5], i = 0;
while ((currnum = strtok(i ? NULL : numbers_str, " ,")) != NULL)
numbers[i++] = atoi(currnum... |
I get a segmentation fault and using gdb and backtrace, it is thrown at vprintf.
```
#0 0x006e8779 in vfprintf () from /lib/libc.so.6
#1 0x006f265f in fprintf () from /lib/libc.so.6
#2 0x08049fd1 in write_tofile (logfile=0x9843090 "~/www/log") at example.c:446
```
It happens when I call
```
file = fopen(log_file... |
Using '~' as an abbreviation for your home directory is a shell thing, and isn't necessarily available in C. This is likely to cause thefopento fail, and you're not checking the return code.
|
I wanted to write a C code to zip a file in unix. I implemented it using system function using UNIX shell command "zip -r filepath". The zip -r filepath command is working when I execute it directly through UNIX shell.
I have witten the code as below
```
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int... |
That's not how you call a function in C. Try:
```
system("zip -r /root/Desktop/hi.txt");
```
|
I'm fairly new to MIPS, and I need to convert this MIPS code into C:
```
addi $t0, $t0, 0
sltiu $t1, $t0, 1000
beq $t1, $0, 7
sll $t1, $1, 2
```
After that it goes into some more operations, but this is the section I am having trouble translating. I think it is something along the lines of (not actual code following... |
```
addi $t0, $t0, 0
#t0 = t0 + 0;
sltiu $t1, $t0, 1000
#t1 = (t0 < 1000) ? 1 : 0;
beq $t1, $0, 7
#if (t1 == 0)
# goto foo; /* label foo is 28 bytes down the program counter */
sll $t1, $1, 2
#t1 = $at << 2;
```
You can simplify the code to:
```
if ($t0 >= 1000)
goto foo; /* label foo is 28... |
I'm having a bit of issue with pointers and structures in c.
```
struct foo{
char a[15];
}
void asn_foo(struct foo *pa){
(*pa).a = "123";
}
main()
{
struct foo foo1[2], *pf;
pf = &(foo1[0]);
asn_foo(pf);
}
```
I'm trying to assign a new value by:
```
(*pa).a = "123";
```
but I have the error "Inc... |
You can't assign new values to an array using the assignment operator, you have to copy the contents of the string"123"into your array. Usestrcpyto do so:
```
strcpy(pa->a, "123");
```
Another trick is also wrapping your array in astruct(as you've done here), and assigning one struct to another in order to assign ne... |
How todefine a pointer to function that returns a pointer to function?
```
typedef int(*a)(int,int);
a (*b)(int,int);
```
Why this can work,but the following can't work?
```
(int(*a)(int,int) ) (*b)(int,int);
```
or
```
int(*)(int,int) (*b)(int,int);
```
or
```
( int(*)(int,int) ) (*b)(int,int);
```
|
Here is the correct way to do it:
```
int (*(*b)(int,int))(int,int);
```
You can compile the following code that demonstrates using both of the methods. I would personally use the typedef method for clarity.
```
#include <stdio.h>
int addition(int x,int y)
{
return x + y;
}
int (*test(int x, int y))(int,int)
... |
I have a pipe that all my child processes use, but before a child uses the pipe to talk to the parent I need to clear it so that the parent reads from it correctly. Is there a simple function in C to do this?
|
The way to "clear" a pipe is to read from it until the buffer is empty. This doesn't help you. I am guessing that your real problem is that the parent might read data that is mixed from multiple clients. There are two easy solutions to your problem.
Always write messages less thanPIPE_BUFbytes long, and do this in... |
How (in GCC/"GNU C") do you declare a function pointer which points to an__attribute__((const))function? The idea being that I want the compiler to avoid generating multiple calls to the function called through the function pointer when it can cache the return value from a previous call.
|
```
typedef void (*t_const_function)(void) __attribute__((const));
static __attribute__((const)) void A(void) {
}
static void B(void) {
}
int main(int argc, const char* argv[]) {
t_const_function a = A;
// warning: initialization makes qualified
// function pointer from unqualified:
t_const_functio... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
What results of the implementation ... |
If you mean
```
Num_in_rankA[Arank]++
```
without the spaces, it adds one to "Arank-th" element of the array called Num_in_rankA.
|
If I pass avoid *vptrto a function which takes aother_type *ptras its arg, willvptrbe converted automatically toother_type *? Here is the code,
```
typedef struct A {
//...
}A;
void bar(A *a)
{
//do something with a
}
int main()
{
A a = {..};
void *vp = &a;
bar(vp); //will vp be converted to A*... |
Yes,void*is implicitly convertible to any pointer type, and any pointer type is implicitly convertible tovoid*. This is why you do not need to (and should not) cast the return value ofmalloc, for example.
|
What's the best way to concatenate a string using Win32? If Understand correctly, the normal C approach would be to usestrcat, but since Win32 now deals with Unicode strings (akaLPWSTR), I can't think of a way forstrcatto work with this.
Is there a function for this, or should I just write my own?
|
lstrcatcomes in ANSI and Unicode variants. Actuallylstrcatis simply a macro defined as eitherlstrcatAorlstrcatW.
These functions are available by importingkernel32.dll. Useful if you're trying to completely avoid the C runtime library. In most cases you can just usewcscator_tcscatas roy commented.
Also consider t... |
In C, and C++, assuming that I'm not using smart pointers or any other weird garbage collecting mechanism, does memory get deallocated (garbage collected) when the program exits?
|
When a process terminates, the OS removes the virtual memory which had been assigned to it.
Since the entirety of its address space goes away, so do all the objects within.
However, this is not the same as C++ garbage collection: no destructors get called. The memory just... quietly returns to the operating system.
|
I'm trying to understand this C code from a simple priority queue, especially - why does it need thestruct qnode **firstpart:
```
int quedel(struct qnode **first, struct qnode **last, int *prio, int *val) {
struct qnode *tmp = NULL;
if((NULL == *last) && (*last == *first)) {
fprintf(stderr, "Empty queue.....\n")... |
Since C doesn't have pass-by-reference, only pass-by-value, this approach is the only way to make this assignment:
```
*first = (*first)->next;
```
visible to the caller.
(Iffirstwere just a single pointer, and we wrotefirst = first->next, then the code that calls this function wouldn't see the modification.)
|
During normal browser caching, will a browser re-fetch all file contents if the web server breaks and reopens a tcp connection to the client?
Or will it still cache all contents and only update what has changed, upon the new socket (no difference)?
Thanks!
|
Browsers operate via HTTP protocol. What they can cache and for how long is determined by specialinstructionsof the HTTP protocol (e.g. cache-control header).
Those instructions can be specified by web server. On the other hand browsers can try to cache as much as possible unless it is forbidden by special HTTP instr... |
I'm currently learning theCprogramming language (coming from Java) and I'm a bit confused as to how to define a macro.
In order for other code to use the macro, the header file must have it. But if I define the macro in the header file, then the source file can't use it. Do I have to define it in both or do I have ... |
Source files virtuallyalwaysinclude their "own" header file -- i.e., a header that declares the functions defined in a source file. Declaring a function before actually defining it is perfectly legal and often desirable: you may get compile errors if the header is accidentally mismatched, and that's a good thing.
|
If I have the following expression:
```
c = (a) * (b)
```
What does the C90 standard say about the order evaluation of the subexpression 'a' and 'b'?
|
There is no specified order since the multiplication operator is not a sequence point. Sequence points include the comma operator, the end of a full expression, and function calls. Thus the order of evaluation of(a)and(b)is up to the compiler implementation. Therefore you shouldn't attempt to-do something in(a)that w... |
I have trouble loading my driver using OSR driver loader. I point the path to my driver, register service successfuly, but when I click start service I receive error message "The system cannot find the file specified."
In the concrete, I have tried to make driver from the sample:
http://www.ndis.com/ndis-ndis6/inspe... |
Making and Signing Driver Packages for NDIS Protocol Drivers
|
What are the gcc's intrinsic for loading 4intsinto__m128and 8 ints into__m256(aligned/unaligned)? What aboutunsigned ints?
|
Using Intel's SSE intrnisics, the ones you're looking for are:
_mm_load_si128()_mm_loadu_si128()_mm256_load_si256()_mm256_loadu_si256()
Documentation:
https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load_si128https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm256_load_si256... |
I was looking over some C++ code and I ran into this memcpy function. I understand what memcpy does but they add an int to the source. I tried looking up the source code for memcpy but I can't seem to understand what the adding is actually doing to the memcpy function.
```
memcpy(Destination, SourceData + intSize, ... |
It is the same thing as:
```
memcpy(&Destination[0], &SourceData[intSize], SourceDataSize);
```
|
In C i can do this:
```
ppackage ppnull() {
return (ppackage) {
.type = NULL
}
}
```
However, in C++ I get syntax errors. I use the GNUg++compiler. Is there a switch to enable this?
|
Withc++11you can use initializer list:
```
struct ppackage
{
void* type;
};
ppackage ppnull()
{
return {nullptr};
}
```
Or just
```
ppackage ppnull()
{
return {};
}
```
|
I'm developing acmdscript to automate a function, however, it depends on one interaction with the user. The user will need to pass one drive letter(C, D, E, F..) to the script and thats all, the script will do all it's tasks. However, I can't find a solution on the internet... If you don't understand what I am mean, w... |
You can
```
set /p dl=Enter a drive:
echo user entered %dl%
```
or it will be n$1if you pass it as an argument.
|
I'm reading through a C code base, and I found a snippet that looks something like this:
```
void foo(int bar) {
const int _bar = bar;
...
}
```
The author then uses _bar throughout the rest of the code. Why is this done? Is it an optimization, or is there some other reason?
|
The author then uses _bar throughout the rest of the code.
If_baris used through out and not using the function parameter, I would qualify the function parameter byconst.
```
void foo( const int bar )
{
// use bar but modifications to bar itself are not allowed.
}
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
Consider, following 2 coding lines in C
```
int a=0;
printf("%d%d%d%d",++a,a+1,a++,++a);
```
in visual C++, it gives
output:3431
But in Turbo C++
gives:
o... |
The C specification does not specify the order that the arguments to your function will be evaluated, so there's no guarantee what output you will get.
|
I am reading from file of format
```
1 32 43 23
32 43
123 43 54 243
123 2222
2
```
Here is my code snippet.
```
string[100];
while(!feof(fp))
fgets(string,100,fp)
```
Now, when I put every string, in the last string I am getting repetition and some more ambiguities (like something else also gets printed say 1... |
You need to check the return value offgets. If a read has been successful,fgetsreturns the pointer to the buffer that you passed to it (i.e.stringin your example). If the End-of-File is encountered and no characters have been read,fgetsreturnsNULL.
Try this:
```
char string[100];
while(fgets(string, 100, fp)) {
... |
In C, how do I extract the first n characters from a string until I find a space in the string? Essentially, which C function will find the position of the next space for me and which C function will give me a substring? I am thinking in terms of C++. such as:
```
string str = "Help me Please!";
int blankPos = str.fi... |
Usestrchrto find the space.Allocate a newcharbuffer to hold the substring.Copy the substring into the buffer withmemcpy.
|
int * const const * b
What does it mean? cdecl saysdeclare b as pointer to const const pointer to int.
Can someone explain it?
|
const constis redundant, it will reduce toconst.
So let's rewrite that:
```
int * const *b;
```
Sobis a pointer to a const pointer to an int. With an example:
```
int main(int argc, char **argv) {
int i = 5;
int *ip = &i;
int * const const * b = &ip;
(**b)++; /* legal */
(*b)++; /* illegal */
... |
I want to transfer 8 bit parallel data from IO to memory ,the data is coming very fast at speed of roughly 5 Mhz ,I am using embedded linux on ARM9 based kit by friendly arm which is using S3C2440(400Mhz) processor can any body pleas tell me where to start,my data is a video signal that is coming from a adc
I have re... |
Forget about DMA on this device. The ADC is not available as a DMA source. One reason for this is that DMA is only useful for transferring multiple bytes/words/whatever - the overhead of setting up, starting the DMA and handling an OnCompletion interrupt makes it pointless for occasional transfers of one item. Your... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:What's this C++ syntax that puts a brace-surrounded block where an expression is expected?
I've just come across this strange C/C++ syntax:
```
#include <stdio.h>
int main() {
printf("%s",
({
static char b__[129];
... |
They're calledstatement expressions, it's a GNU extension. In your example the result of the expression isb__.
|
I want to handle power off button pressing on my notebook with Windows 7. I've configured power management options to do nothing on this event, so it will not turn off immediately, but i want to catch the moment when user presses power button. How it can be done in C++?
|
I think there should be some WMI (Windows Management Instrumentation) events for this. Hope this helps:http://msdn.microsoft.com/en-us/library/aa394101%28v=VS.85%29.aspx
This is not specific to notebooks, nor is it specific to the power button alone. This applies to any means used to shutdown the machine.
|
I would like something like:
```
#define C_OR_CPP(C__, CPP__) #ifdef __cplusplus\
CPP__\
#else\
C__\
#endif
```
Is it possible?
Maybe some dirty hack with #include ?
Reason:
I make a header where a struct uses a member variable of typevector<stuff>*, but in C i want it to simply bevoid*, you know.
TIA
|
What's the problem with
```
#ifdef __cplusplus
#define C_OR_CPP(C, CPP) CPP
#else
#define C_OR_CPP(C, CPP) C
#endif
```
(Leaving names with double underscore to the implementation per phresnel remark)
|
Say I write alibx.so, it contains 3 functions,
```
void bar();
void foo();
void spam();
```
Then I usectypesto access it,
```
>>>libx = ctypes.CDLL("./libx.so")
>>>dir(libx)
...
```
But how can I know how many functionslibx.soexports and what are they?
|
You can usenm libx.soon the shell to view the symbols exported by the library.
However, reading its docs/header file is usually a much better idea - the symbol list will not give you any information about the arguments and return values of the functions.
|
I have a file stream in C and I want to know how many lines are in it without iterating through the file. Each line is the same length. How might I go about this?
|
How about something like this:
Do afgetsand find out how long one line isFind the size of the file usingfseekandftellfseek(fp, 0, SEEK_END);
size = ftell(fp);Divide by the size of the line
You can also usefseekoandftellowhich work withoff_t.
|
I am trying to write a large sum of data to a file. Some suggested i should use binary mode but i already have done it in text mode. Is there a big difference in using the binary in terms of speed? What is the advantage or disadvantage in using the binary mode?
|
Text mode does newline translation, so that
```
fprintf(myfile, "\n");
```
can generate one byte (0x0a, line feed) on Unix-like systems, and two (0x0d,0x0a, carriage return followed by line feed) on Windows. This takes time, since it means each byte has to be inspected. If that really matters when compared to the sp... |
How will you implement a tree structure in C for navigation in preorder depth-first manner?
|
A tree can be represented by two arrays: one that holds pre-order traversal and the second hold in-order traversal.This threaddiscusses [among other things] how it can be done.
Since array traversal is usually faster then tree traversal [due to cache performance mainly], you can represent the tree as 2 arrays, and us... |
Tell me please why this function may take'\0'as second argument, compile and crash?
```
char var[9];
/*some initialization of var */
strcat(var, '\0');
```
|
That function takes aconst char *as the second parameter. You're passing anint.
```
char *strcat(char *restrict s1, const char *restrict s2);
```
You're basically trickingstrcatinto dereferencing\0as a pointer - it dereferencesNULL.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:C++'s “placement new”Help with a c++ statement
I work in a product, where most of the modules have been written in C. Among them, one or two modules are written in C++. I find the below code in a C++ module, which I could not understand wh... |
b = new (a) MyClass();is calledplacement newand it constructs new object of typeMyClasson a pre-allocated memory (memory that pointerapoints to).
You should also check this question:What uses are there for "placement new"?
|
I am currently trying to implement a CRC-32 for an incoming datastream (Serial communication) on an ATMEGA1280 and I am a little lost how to do this on the embedded side in C.... If anyone could point me in the proper direction and/or help in anyway i would greatly appreciate it...
|
There are plenty of CRC-32 implementations in C. The AT MEGA1280 has 128 KB of code space, it shoudn't have any problems running any off-the-shelf implementation.
Hereis pretty much the first one I found.
|
I got aliba.socontaining a functionsay_hi(),
```
char *say_hi()
{
return "hello, world";
}
```
In Python, I accessedliba.soviactypes,
```
>>>liba = ctypes.CDLL("./liba.so")
>>>liba.say_hi()
16422018
```
How can I retrieve the string"hello, world"returned byliba.say_hi()in Python?
PS
Besidesrestype, any other... |
Does this answer your question?
http://docs.python.org/library/ctypes.html#return-types
|
I wrote a JIT compiler for some language withjitasmbut the generated code isn't very nice... Is there a library that I could use to optimize the binary code?
|
You might findASMJITuseful, but the only really decent optimizing JIT libraries I've come across are from bigger engines likeLLVM, or the dotGNUlibJITproject.
EDIT:
Finally managed to dig up the link toMyJIT, which is a proper, light-weight, optimizing JIT engine, similar to GNU Lightning and probably your best bet i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.