question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
On this link I came acrosshttp://lxr.linux.no/#linux+v2.6.36/include/linux/pci.h#L299integer declarationunsigned int is_added:1;I have made C programs and declared integers in them but in the above I see use of:What sort of syntax is that?
|
I think you have come across abit-field:)
|
What is the use of theenumkeyword ? Where can we use enumerated data-type?
Can anyone explain with an example?
|
Anenumgives a name to a number.
```
enum { MAX_LINES = 60 };
```
Superficially, so does a#define:
```
#define MAX_LINES 60
```
The benefit of anenumover a#defineis that the name is recorded in the debugging information, so the debugger can use it.
You can also use anenumto define a set of related values:
```
typedef enum { RED, GREEN, BLUE } Colour;
```
You might then use these to index into a triplet array for the RGB values:
```
typedef unsigned char Pixel[3];
Pixel p;
p[RED] = 128;
p[GREEN] = 128;
p[BLUE] = 255;
```
Probably not the world's best example, but an indication of where anenumcan be used.
|
Folks, my professor has assigned us an assignment involving typing with arrays, pointers, and functions. Now, before you jump on my back with the whole "We aren't going to do your homework for you" thing, the answer to my question will not solve the problem. In fact, I've already taken my best guess at the answer. I am just curious to hear what you think about this.
Here is the C statement I was given:
```
double(*foo(double(*)(double,double[]),double))(double, ...);
```
Our problem involved describing the type of foo. My question is simply this: What on earth does this statement do? As far as I can read it, this is either one of the most obfuscated and unrealistic lines of code I've ever seen, or it's not actually valid C. Let me know what you think.
|
What you want to learn is theClockwise Spiral Rule. Learning this will help you describe, in plain words, what any type in C is. Learn it well.
|
I am doing some work with gdb and have found references in the documentation to "symbols". Is this another word for externally (exported) visible variables ?
Thanks,
Scott
|
A 'symbol' is a symbolic identifier including function and variable names.
The compiler/linker create a symbol table during the build and this is used by the debugger to provide source-level symbolic names to these entities, as opposed to plain addresses (hence the name "symbolic debugger" which you may come across).
|
I was wondering if there are some recommendedread-eval-print loop (REPL)respectively for
(1) C++
(2) C
(3) Java
Thanks!
|
C and C++
You can use CERN'scint.
Java
You can useBeanShell, or if you don't care so much about having Java syntax (e.g. your goal is just to make sure theclassesdo what you want), you can use Groovy, Scala, JRuby, or Jython.
|
I recently installed the autotools plugin for eclipse. I made the Makefile.am for each source subdirectory. I also included the AM_INIT_MAKEFILE macro in the configure.ac file. The pluginDOESuseautoreconf -i. The problem is that I get an error anytime I try to build that says,config.status: error: cannot find input file: 'Makefile.in'Which indicates that automake was never ran. Any ideas?
|
I made a beginner's mistake. I didn't add the extra files automake needs to actually function and make the Makefile.in. Also to run any autotool (aclocal, automake, autoheader, etc.) go to Project->Invoke Autotools->Invoke (name of autotool)
|
I have an integer, retrieved from a file using fscanf.
How do I write this into a binary file as a two-byte integer in hex?
|
This will write a short integer to a binary file. The result is 2 bytes of binary data (Endianness dependent on the system).
```
int main(int argc, char* argv[])
{
short i;
FILE *fh;
i = 1234;
fh = fopen( argv[1], "wb" );
fwrite( &i, sizeof( i ), 1, fh );
fclose(fh);
}
```
|
What is the best (shortest) way to read the next non-blank (not space/newline/tab) character from a file in a C program?
I realize I could probably use gets followed by strtok, but it seems like there has to be something more concise.
If so, let me know; if not, let me know that too.
Thanks.
|
```
char c;
fscanf(f, " %c", &c);
```
OR
```
int c;
while (isspace(c=fgetc(f)));
```
|
I am trying to understand working of pci_resource_start function
So I browsed code via cscope and searched for string pci_resource_start
and got following in pci.h
```
#define pci_resource_start(dev, bar) ((dev)->resource[(bar)].start)
```
I am not able to understand how does this above macro works.
How does it above macro gets appropriate base address register in
configuration space?
|
The macro's purpose is merely to improve readability in source code, it does not cause any address to be retrieved. In fact, the address (denoted by thestartmember) has already been discovered earlier on when the PCI bus and/or device was scanned/initialized. ("Start" in this case also means "start of address range" rather than "begin doing something".)
Details of this are most likely to be found in one of the files namedpci.c.
|
I have been playing around with some debugging and wrote some C code that does a lot of pointer related operations (as a Valgrind tool) that runs on top of Valgrind. In the last one hour I changed something as a result of which the program executes fine but then stops responding to Ctrl+C when I try to terminate it.
I tried running the program throughgdband still observing the same behavior. Can someone tell me what triggers this kind of a behavior?
UPDATE: I figured it was infinite recursion that was causing the error but I am still curious as to why it does not respond to the command.
|
AVERYbadly hung program. Try opening another terminal and doing
```
kill -SIGINT `pidof program-name`
```
(If-SIGINTdoesn't work, move to-SIGTERMand-SIGKILL(be warned that SIGKILL isimmediate terminationwithNOcleanup))
|
I'm trying to make a Lua compiler for Mac OSX with an interface written in Objective-C and the Lua source code written in C.
|
You already are combining C and Objective C. No extra effort is needed.
|
I have a *.exe console file.
I enter my inputs, and everything is great.
but when I enter the last input, the command window closes (because the program has ended)
before I can read the last output.
is there a way to run that *.exe file and force it to stay open after the program ends?
note: this is not my program. I can't edit the source code, so I'm not looking for answers like "add while(1) or scanf at the end".
Thanks ahead.
|
Just open a command prompt and run it, the way it's meant to be used.
Start -> Run -> cmd.exe
or Win+R -> cmd
|
How can I make a control using bitmaps which changes when I drag with the mouse (e.g. a rotating knob)? And this using the Win32 API?
|
Write code to recognize the WM_MOUSEWHEEL message in your control's window procedure.
|
I have
char aa[] = { "Hello, !" };
char bb[] = { "World" };
How to insert bb into aa the most efficiently with cstring ?
|
allocate big enough buffer (malloc/new[])copy the first part of the aa string into the buffer (strncpy/memcpy)copy the bb string (strcpy/memcpy)copy the rest of the aa string (strncpy/memcpy)
|
How could I make a line of code that would exit out of my program after input is given by the user for a specific word?
the psuedo-code of what I have is as follows:
take input;
compare (input) to exit word;
if input is same as exit word
exit the program <------- help here;
else
rest of program;
|
If the code is inside main, you can simply usereturnif somewhere else useexit
|
```
scanf("%ld",&l);
printf ("l=%ld",l);
switch (l)
{
case'1':
XOR(&matrix1[10],&matrix2[10],m);
break;
case'2':
AND(&matrix1[10],&matrix2[10],m);
break;
default:
printf("\n\t\tWrong input");
}
```
When the program reachesswitch, no matter what I enter (whether it's wrong or right), the program keeps showing the massage (Wrong input), though I've entered a right number (1 or 2).
|
Change your case labels from
```
case'1':
...
case'2':
...
```
to
```
case 1:
...
case 2:
...
```
Explanation: your switch value is aninteger, not a character, hence you needintegerconstants for your case labels, notcharacterconstants.
|
This question came to mind after seeing this simple piece of code:
```
if (!x%y)
{
// do something
}
```
Maybe it's the influence of early C books (K&R?), but isn't the following always preferred, if not as cute?
```
if (x%y != 0)
{
// do something
}
```
|
This quoteanswers your question.
"Debugging is twice as hard as writing
the code in the first place.
Therefore, if you write the code as
cleverly as possible, you are, by
definition, not smart enough to debug
it." – Brian W. Kernighan
|
I have this code:
```
if (argv[i] == "-n")
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
```
When this code gets executed I get the following error:
bad argument '-n'
I seriously don't know why it does that. Can someone explain?
|
String comparisons need a function in C - usuallystrcmp()from<string.h>.
```
if (strcmp(argv[i], "-n") == 0)
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
```
Thestrcmp()function returns a negative value (not necessarily -1) if the first argument sorts before the second; a positive value (not necessarily +1) if the first arguments sorts after the second; and zero if the two values are equal.
|
I'm getting a warning for this line:
```
e = strtol(++s, (char **)&s, 10);
```
Moving the++sto a separate statement makes the warning go away, but as far as I can tell, this warning is completely incorrect. Thevalueofsis only used once, in the computation of++s. The second use ofsis only to take its address. Is there something I'm missing?
|
Newer versions of gcc (4.4.3 or 4.4.5) do not generate any warning for the line you posted. The generation of the warning there appears to be a bug in older gcc versions.
|
I need one server to receive ip requests from clients(there are not in the same intranet), and I can
route all the response packets to a special gateway server, and then I send the response packages to
clients after some processing. it is like VPN, but I want to do some development based one
opensource project, so i can control it myself.
any suggestion? thanks!
|
There isOpenVPNwhich is as the name already suggests open source.
|
So I have 2 diffrent apps that use web-cameras (on Windows) I created tham bouth but I need them to be separate, stand alone apps. I want tham bouth to be capable to capture from same camera. What should I add to my capturing OpenCV code?
|
Not sure, but i think the only way is to use COM (on windows) because you can't create two capture filters per one device. But you can create a splitter filter, put it in a DirectShow graph and share access to it through COM. I don't know how to do it exactly, just an idea.
|
The problem is as follows: A wanderer begins on the grid coordinates (x,y) and wants to reach the coordinates (0,0). From every gridpoint, the wanderer can go 8 steps north OR 3 steps south OR 5 steps east OR 6 steps west (8N/3S/5E/6W).
How can I find the shortest route from (X,Y) to (0,0) using breadth-first search?
Clarifications:
Unlimited gridNegative coordinates are allowedA queue (linked list or array) must be usedNo obstacles present
|
The algorithm for this problem would be:
For each axis, step towards it until your position on the other axis is 0.
Pseudocode:
```
while (x!=0) {
if (x>0) x-=6;
else x+=5;
}
while (y!=0) {
if (y>0) y-=8;
else y+=3;
}
```
However, I don't understand why you need to search for a route - it's not that complicated.
|
```
char * val;
val = getenv("ENV_VAR_NAME");
```
above is a code to get environment variable, will it cause memory leak if I dont free memory returned by getenv(char*) ? If no then please answer why?
|
No you shouldn't. Standard 7.20.4.5 says :
The getenv function returns a pointer
to a string associated with the
matched list member.The string
pointed to shall not be modified by
the program, but may be overwritten by
a subsequent call to the getenv
function.
I believe deletion is covered by the text in bold.
|
How in C can we read and makeDWORDvariables with a low and high word and low and high byte?
|
WinAPI provides macros for the manipulations of these types, such as:
HIWORDLOWORDMAKELPARAM
|
Does the ANSI C specification call for size ofintto be equal to the word size (32 bit / 64 bit) of the system?
In other words, can I decipher the word size of the system based on the space allocated to anint?
|
The size of theinttype is implementation-dependent, but cannot be shorter than 16 bits. See theMinimum Type Limitssectionhere.
ThisLinux kernel development siteclaimsthat the size of thelongtype is guaranteed to be the machine's word size, but that statement is likely to be false: I couldn't find any confirmation of that in the standard, andlongis only 32 bits wide on Win64 systems (since these systems use theLLP64data model).
|
How would I get a string representation of a web page's source from URL in C?
|
If you just want to download it,libcurlis a pretty nifty library for fetching files from many different kinds of servers, including HTTP.
|
I know i can set an alarm to "go off" with a SIGALRM after a specified amount of time usingalram(numberOfSeconds)what i am looking to do is to raise the SIGALRM immediately.
Any help would be greatly appreciated.
|
raise(SIGALRM);
|
If I call:
```
./program hello world
```
then:
```
argc would be 3.
argv[0] would be "./program".
argv[1] would be "hello".
argv[2] would be "world".
```
What's the purpose of passing "./program" as an argument? In fact, it's not an argument at all!
|
You can make symbolic links to the same binary. Depending on what link you use, you will get different behaviour. Busybox is an example of this.
|
I am running Ubuntu. I have a folder "Project", and in that folder I have a bunch of sub-folders. In each of the sub-folders I have either a .c file, a .jar file or a .py file. I want to iterate over all the files, and for each file, compile it, and run 5 times with different input it using the "time" command to time the execution time.
I want to create a shell script for this, but I can't seem to find a good way to recurse over all the files in the sub-folders.
|
If you are using Bash4 you can setglobstarto recurse all subdirs without caring about depth
```
#!/bin/bash
shopt -s globstar
for file in /path/to/your/files/**; do
case "${file##.*}" in
c)
gcc -c "$file"
;;
jar)
java -jar "$file"
;;
py)
python "$file"
;;
esac
done
```
|
I don't want to optimize anything, I swear, I just want to ask this question out of curiosity.
I know that on most hardware there's an assembly command of bit-shift (e.g.shl,shr), which is a single command. But does it matter (nanosecond-wise, or CPU-tact-wise) how many bits you shift. In other words, is either of the following faster on any CPU?
```
x << 1;
```
and
```
x << 10;
```
And please don't hate me for this question. :)
|
Potentially depends on the CPU.
However, all modern CPUs (x86, ARM) use a "barrel shifter" -- a hardware module specifically designed to perform arbitrary shifts in constant time.
So the bottom line is... no. No difference.
|
Can anyone please explain me why would the following code print 20 instead of 10?
Thanks
```
#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}
```
|
By definition of a union : you can't simultaneously usev.aandv.bbecause both fields share the same address. To quote the standard :
A union type describesan overlapping
nonempty set of member objects, each
of which has an optionally specified
name and possibly distinct type.
Here, as soon as you assign tov.b, you overridev.a. In your case, things don't get ugly because both variables have the same type, but just imagine what ifawas afloatandba char for example.
If your goal is to havevarbe a compound variable which contains two differentint, then you should usestruct, notunion.
|
I would like to do something like this: In a loop, first iteration write some content into a file named file0.txt, second iteration file1.txt and so on, just increase the number.
```
FILE *img;
int k = 0;
while (true)
{
// here we get some data into variable data
file = fopen("file.txt", "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file );
k++;
// here we check some condition so we can return from the loop
}
```
|
```
int k = 0;
while (true)
{
char buffer[32]; // The filename buffer.
// Put "file" then k then ".txt" in to filename.
snprintf(buffer, sizeof(char) * 32, "file%i.txt", k);
// here we get some data into variable data
file = fopen(buffer, "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file );
k++;
// here we check some condition so we can return from the loop
}
```
|
gcc 4.5.1 c89
compiling with the following flags:-Wall, -Wextra
I have the following structure that I am trying to initialize with default values. However, I get the following warnings:
```
static struct Device {
char *name;
char *config;
} *app = { NULL, NULL };
```
Warnings:
```
warning: initialization from incompatible pointer type
warning: excess elements in scalar initializer
```
However, if I do the following by declaring a non-pointer, I don't get any problems i.e.
```
static struct Device {
char *name;
char *config;
} app = { NULL, NULL };
```
Why is that?
Many thanks for any advice,
|
You can't initialize a pointer that way. You can do this though:
```
static struct Device {
char *name;
char *config;
} *app = NULL;
```
Initialize a pointer toNULL. A pointer is nothing but a memory address. You can't assing{ NULL, NULL }to a memory address.
|
given a pointer to unsigned char value,*ptr.
How to copy its whole value to new char valuechar buff;in a correct way (malloc etc), without looping for each character? Any way to retreive the memory amount currently allocated for the pointer value?
|
If you really have a single character:
```
char buff = (char)*ptr;
```
If you have a string which i assume as you are talking about looping over characters:
```
char *buff = strdup(ptr);
```
|
I've tried using the "grab all of the process IDs enumerated by the desktop" method, however that doesn't work.
Is there a way to convert a handle to a window handle? -or-Is there a way to take a process ID and find out all of the child windows spawned by the process?
I don't want to useFindWindowdue to multiple process issues.
|
You could callEnumWindows()to iterate over all the top-level windows on the screen, then useGetWindowThreadProcessId()to find out which ones belong to your process.
For example, something like:
```
BOOL CALLBACK ForEachTopLevelWindow(HWND hwnd, LPARAM lp)
{
DWORD processId;
GetWindowThreadProcessId(hwnd, &processId);
if (processId == (DWORD) lp) {
// `hwnd` belongs to the target process.
}
return TRUE;
}
VOID LookupProcessWindows(DWORD processId)
{
EnumWindows(ForEachTopLevelWindow, (LPARAM) processId);
}
```
|
Does the ANSI C specification call for size ofintto be equal to the word size (32 bit / 64 bit) of the system?
In other words, can I decipher the word size of the system based on the space allocated to anint?
|
The size of theinttype is implementation-dependent, but cannot be shorter than 16 bits. See theMinimum Type Limitssectionhere.
ThisLinux kernel development siteclaimsthat the size of thelongtype is guaranteed to be the machine's word size, but that statement is likely to be false: I couldn't find any confirmation of that in the standard, andlongis only 32 bits wide on Win64 systems (since these systems use theLLP64data model).
|
How would I get a string representation of a web page's source from URL in C?
|
If you just want to download it,libcurlis a pretty nifty library for fetching files from many different kinds of servers, including HTTP.
|
I know i can set an alarm to "go off" with a SIGALRM after a specified amount of time usingalram(numberOfSeconds)what i am looking to do is to raise the SIGALRM immediately.
Any help would be greatly appreciated.
|
raise(SIGALRM);
|
If I call:
```
./program hello world
```
then:
```
argc would be 3.
argv[0] would be "./program".
argv[1] would be "hello".
argv[2] would be "world".
```
What's the purpose of passing "./program" as an argument? In fact, it's not an argument at all!
|
You can make symbolic links to the same binary. Depending on what link you use, you will get different behaviour. Busybox is an example of this.
|
I am running Ubuntu. I have a folder "Project", and in that folder I have a bunch of sub-folders. In each of the sub-folders I have either a .c file, a .jar file or a .py file. I want to iterate over all the files, and for each file, compile it, and run 5 times with different input it using the "time" command to time the execution time.
I want to create a shell script for this, but I can't seem to find a good way to recurse over all the files in the sub-folders.
|
If you are using Bash4 you can setglobstarto recurse all subdirs without caring about depth
```
#!/bin/bash
shopt -s globstar
for file in /path/to/your/files/**; do
case "${file##.*}" in
c)
gcc -c "$file"
;;
jar)
java -jar "$file"
;;
py)
python "$file"
;;
esac
done
```
|
I don't want to optimize anything, I swear, I just want to ask this question out of curiosity.
I know that on most hardware there's an assembly command of bit-shift (e.g.shl,shr), which is a single command. But does it matter (nanosecond-wise, or CPU-tact-wise) how many bits you shift. In other words, is either of the following faster on any CPU?
```
x << 1;
```
and
```
x << 10;
```
And please don't hate me for this question. :)
|
Potentially depends on the CPU.
However, all modern CPUs (x86, ARM) use a "barrel shifter" -- a hardware module specifically designed to perform arbitrary shifts in constant time.
So the bottom line is... no. No difference.
|
Can anyone please explain me why would the following code print 20 instead of 10?
Thanks
```
#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}
```
|
By definition of a union : you can't simultaneously usev.aandv.bbecause both fields share the same address. To quote the standard :
A union type describesan overlapping
nonempty set of member objects, each
of which has an optionally specified
name and possibly distinct type.
Here, as soon as you assign tov.b, you overridev.a. In your case, things don't get ugly because both variables have the same type, but just imagine what ifawas afloatandba char for example.
If your goal is to havevarbe a compound variable which contains two differentint, then you should usestruct, notunion.
|
I would like to do something like this: In a loop, first iteration write some content into a file named file0.txt, second iteration file1.txt and so on, just increase the number.
```
FILE *img;
int k = 0;
while (true)
{
// here we get some data into variable data
file = fopen("file.txt", "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file );
k++;
// here we check some condition so we can return from the loop
}
```
|
```
int k = 0;
while (true)
{
char buffer[32]; // The filename buffer.
// Put "file" then k then ".txt" in to filename.
snprintf(buffer, sizeof(char) * 32, "file%i.txt", k);
// here we get some data into variable data
file = fopen(buffer, "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file );
k++;
// here we check some condition so we can return from the loop
}
```
|
gcc 4.5.1 c89
compiling with the following flags:-Wall, -Wextra
I have the following structure that I am trying to initialize with default values. However, I get the following warnings:
```
static struct Device {
char *name;
char *config;
} *app = { NULL, NULL };
```
Warnings:
```
warning: initialization from incompatible pointer type
warning: excess elements in scalar initializer
```
However, if I do the following by declaring a non-pointer, I don't get any problems i.e.
```
static struct Device {
char *name;
char *config;
} app = { NULL, NULL };
```
Why is that?
Many thanks for any advice,
|
You can't initialize a pointer that way. You can do this though:
```
static struct Device {
char *name;
char *config;
} *app = NULL;
```
Initialize a pointer toNULL. A pointer is nothing but a memory address. You can't assing{ NULL, NULL }to a memory address.
|
given a pointer to unsigned char value,*ptr.
How to copy its whole value to new char valuechar buff;in a correct way (malloc etc), without looping for each character? Any way to retreive the memory amount currently allocated for the pointer value?
|
If you really have a single character:
```
char buff = (char)*ptr;
```
If you have a string which i assume as you are talking about looping over characters:
```
char *buff = strdup(ptr);
```
|
I've tried using the "grab all of the process IDs enumerated by the desktop" method, however that doesn't work.
Is there a way to convert a handle to a window handle? -or-Is there a way to take a process ID and find out all of the child windows spawned by the process?
I don't want to useFindWindowdue to multiple process issues.
|
You could callEnumWindows()to iterate over all the top-level windows on the screen, then useGetWindowThreadProcessId()to find out which ones belong to your process.
For example, something like:
```
BOOL CALLBACK ForEachTopLevelWindow(HWND hwnd, LPARAM lp)
{
DWORD processId;
GetWindowThreadProcessId(hwnd, &processId);
if (processId == (DWORD) lp) {
// `hwnd` belongs to the target process.
}
return TRUE;
}
VOID LookupProcessWindows(DWORD processId)
{
EnumWindows(ForEachTopLevelWindow, (LPARAM) processId);
}
```
|
I know i can set an alarm to "go off" with a SIGALRM after a specified amount of time usingalram(numberOfSeconds)what i am looking to do is to raise the SIGALRM immediately.
Any help would be greatly appreciated.
|
raise(SIGALRM);
|
If I call:
```
./program hello world
```
then:
```
argc would be 3.
argv[0] would be "./program".
argv[1] would be "hello".
argv[2] would be "world".
```
What's the purpose of passing "./program" as an argument? In fact, it's not an argument at all!
|
You can make symbolic links to the same binary. Depending on what link you use, you will get different behaviour. Busybox is an example of this.
|
I am running Ubuntu. I have a folder "Project", and in that folder I have a bunch of sub-folders. In each of the sub-folders I have either a .c file, a .jar file or a .py file. I want to iterate over all the files, and for each file, compile it, and run 5 times with different input it using the "time" command to time the execution time.
I want to create a shell script for this, but I can't seem to find a good way to recurse over all the files in the sub-folders.
|
If you are using Bash4 you can setglobstarto recurse all subdirs without caring about depth
```
#!/bin/bash
shopt -s globstar
for file in /path/to/your/files/**; do
case "${file##.*}" in
c)
gcc -c "$file"
;;
jar)
java -jar "$file"
;;
py)
python "$file"
;;
esac
done
```
|
I don't want to optimize anything, I swear, I just want to ask this question out of curiosity.
I know that on most hardware there's an assembly command of bit-shift (e.g.shl,shr), which is a single command. But does it matter (nanosecond-wise, or CPU-tact-wise) how many bits you shift. In other words, is either of the following faster on any CPU?
```
x << 1;
```
and
```
x << 10;
```
And please don't hate me for this question. :)
|
Potentially depends on the CPU.
However, all modern CPUs (x86, ARM) use a "barrel shifter" -- a hardware module specifically designed to perform arbitrary shifts in constant time.
So the bottom line is... no. No difference.
|
Can anyone please explain me why would the following code print 20 instead of 10?
Thanks
```
#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}
```
|
By definition of a union : you can't simultaneously usev.aandv.bbecause both fields share the same address. To quote the standard :
A union type describesan overlapping
nonempty set of member objects, each
of which has an optionally specified
name and possibly distinct type.
Here, as soon as you assign tov.b, you overridev.a. In your case, things don't get ugly because both variables have the same type, but just imagine what ifawas afloatandba char for example.
If your goal is to havevarbe a compound variable which contains two differentint, then you should usestruct, notunion.
|
I would like to do something like this: In a loop, first iteration write some content into a file named file0.txt, second iteration file1.txt and so on, just increase the number.
```
FILE *img;
int k = 0;
while (true)
{
// here we get some data into variable data
file = fopen("file.txt", "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file );
k++;
// here we check some condition so we can return from the loop
}
```
|
```
int k = 0;
while (true)
{
char buffer[32]; // The filename buffer.
// Put "file" then k then ".txt" in to filename.
snprintf(buffer, sizeof(char) * 32, "file%i.txt", k);
// here we get some data into variable data
file = fopen(buffer, "wb");
fwrite (data, 1, strlen(data) , file);
fclose(file );
k++;
// here we check some condition so we can return from the loop
}
```
|
gcc 4.5.1 c89
compiling with the following flags:-Wall, -Wextra
I have the following structure that I am trying to initialize with default values. However, I get the following warnings:
```
static struct Device {
char *name;
char *config;
} *app = { NULL, NULL };
```
Warnings:
```
warning: initialization from incompatible pointer type
warning: excess elements in scalar initializer
```
However, if I do the following by declaring a non-pointer, I don't get any problems i.e.
```
static struct Device {
char *name;
char *config;
} app = { NULL, NULL };
```
Why is that?
Many thanks for any advice,
|
You can't initialize a pointer that way. You can do this though:
```
static struct Device {
char *name;
char *config;
} *app = NULL;
```
Initialize a pointer toNULL. A pointer is nothing but a memory address. You can't assing{ NULL, NULL }to a memory address.
|
given a pointer to unsigned char value,*ptr.
How to copy its whole value to new char valuechar buff;in a correct way (malloc etc), without looping for each character? Any way to retreive the memory amount currently allocated for the pointer value?
|
If you really have a single character:
```
char buff = (char)*ptr;
```
If you have a string which i assume as you are talking about looping over characters:
```
char *buff = strdup(ptr);
```
|
I've tried using the "grab all of the process IDs enumerated by the desktop" method, however that doesn't work.
Is there a way to convert a handle to a window handle? -or-Is there a way to take a process ID and find out all of the child windows spawned by the process?
I don't want to useFindWindowdue to multiple process issues.
|
You could callEnumWindows()to iterate over all the top-level windows on the screen, then useGetWindowThreadProcessId()to find out which ones belong to your process.
For example, something like:
```
BOOL CALLBACK ForEachTopLevelWindow(HWND hwnd, LPARAM lp)
{
DWORD processId;
GetWindowThreadProcessId(hwnd, &processId);
if (processId == (DWORD) lp) {
// `hwnd` belongs to the target process.
}
return TRUE;
}
VOID LookupProcessWindows(DWORD processId)
{
EnumWindows(ForEachTopLevelWindow, (LPARAM) processId);
}
```
|
I understand that there is both an ANSI standard and an ISO standard for C. Are there any differences between these two standards? If so, what are they? And if there is not a difference then what's the point of having two standards?
|
In 1990, the ANSI C standard (with a few minor modifications) was adopted by the International Organization for Standardization as ISO/IEC 9899:1990. This version is sometimes called C90. Therefore, the terms "C89" and "C90" refer to essentially the same language.
Source, the situation is similar but reversed forC99. There is also aC FAQ entryon the matter.
The reason that there are two standards is simple: ANSI is a north-american standards body while ISO is an international one.
|
What isTrailing Array Idiom?
P.S : Googling this term givesThe vectors are implemented using the trailing array idiom, thus they are not resizeable without changing the address of the vector object itself.
|
If you mean the trailing array idiom mentioned in theGCC source code(where your quote comes from), it seems to refer to the old C trick to implement a dynamic array:
```
typedef struct {
/* header */
size_t nelems;
/* actual array */
int a[1];
} IntVector;
```
where an array would be created with
```
IntVector *make_intvector(size_t n)
{
IntVector *v = malloc(sizeof(IntVector) + sizeof(int) * (n-1));
if (v != NULL)
v->nelems = n;
return v;
}
```
|
My program is as follows;
```
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "Gentlemen start your engines!";
printf("That string is %s characters long.\r\n", strlen(string));
return 0;
}
```
I'm compiling under gcc, and although it doesn't give me any errors the program crashes every time I run it. The code seems to be fine from examples I've seen. It'd be great to know if I'm doing anything wrong.
Thanks.
|
Using incorrect format specifier inprintf()invokes Undefined Behaviour. Correct format specifier should be%zu(not%d) because the return type ofstrlen()issize_t
Note: Length modifierzin%zurepresents an integer of length same assize_t
|
```
int main()
{
char *temp = "Paras";
int i;
i=0;
temp[3]='F';
for (i =0 ; i < 5 ; i++ )
printf("%c\n", temp[i]);
return 0;
}
```
Whytemp[3]='F';will cause segmentation fault sincetempis notconst?
|
You are not allowed to modify string literals.
|
I am playing around with tool development in Valgrind and am getting the following error:
```
valgrind: mmap(0x8048000, 4096) failed in UME with error 22 (Invalid argument).
valgrind: this can be caused by executables with very large text, data or bss segments.
```
but my executable has nothing but simple variable assignments. I am not able to understand how to fix this problem. Any suggestions?
|
I don't have an answer, but there is an open bug on this issue.
http://bugs.kde.org/show_bug.cgi?id=138424
|
What would be the fastest/shortest way to create a string of repeating characters.
For instance,n = 10, char = '*', resulting allocated string: **********
|
Usememset.
```
int n = 10;
char c = '*';
char* buf = malloc(n+1);
memset(buf, c, n);
buf[n] = '\0';
free(buf);
```
|
I'm trying to get theCPU serialormotherboard serialusingCorPythonfor licensing purposes. Is it possible?
I'm usingLinux.
|
Under Linux, you could use "lshw -quiet -xml" and parse its output. You'll find plenty of system information here: cpuid, motherboard id and much more.
|
I am looking into the code written by other members and I came across the code shown below:
```
struct myType
{
int myInt : 1;
int reserved : 31;
};
```
What is 1 and 31 stands above and when above notation is used?
|
Those are bit fields, the number after the colon specifies the width, in bits, reserved for that field. They are often used when trying to conserve space, or when trying to map an external (think hardware-owned) register that has bitfields. Note that packing and endianness affect how the bits are layed out in memory, so they're not to be used if portability is important.
Note that it's a very bad idea to use signed bit fields with very small sizes, such as 1. Since one bit is needed for the sign, no bits are left for the actual value which is generally not a very good situation. Usingunsigned int myUnsigned : 1fixes this.
|
What is the C# equivalent of the following C code:
```
while((c = getchar())!= EOF)
putchar(c);
```
I know getchar() and putchar() are going to be replaced by Console.Read and Console.Write respectively but what about the EOF. Especially keeping in mind, C# works with unicode and C with ASCII, what are the implications of that ??
|
Console.Read()returns -1 on EOF (coincidentally,EOFis defined as-1on most platforms).
You can do:
```
int c;
while ((c = Console.Read()) != -1) {
Console.Write(Convert.ToChar(c));
}
```
Also, C# works natively withUNICODEin the same way that C works natively withASCII, i.e. there are no more implications.System.Charrepresents anUCS-2UNICODEcharacter, which also fits into anint, so everything will be all right.
|
On this linkhttp://lxr.free-electrons.com/source/drivers/parport/parport_pc.c?v=2.6.29#L97they defined a structure superio_struct and initialized as
```
superios[NR_SUPERIOS] = { {0,},};
```
I am not able to understand above initialization has what is it getting initialized to.
What I deduce till now is superios is a structure array of struct superio_struct
and NR_SUPERIOS is defined as 3 hence an array of structure of size 3
but
```
superios[0]=??
superios[1]=??
superios[2]=??
```
|
It's just initialising the entire array to zero. The commas are redundant (and not all compilers will allow them). It should really just be:
```
superios[NR_SUPERIOS] = { { 0 } };
```
|
This question already has answers here:Copying a part of a string (substring) in C(13 answers)Closed9 years ago.
For example, I have this
```
char *buff = "this is a test string";
```
and want to get"test". How can I do that?
|
```
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
```
Job done :)
|
I am having too many confusions in native coding for android. My application wants to play mms:// stream and I'm facing some serious problems in that. But the basic question is
What is the difference between ndk-build(that i usually use)and make APP(i have seen many blogs on them one of them isthis)
Another related question
Suppose my project is in E:\WorkSpace\mmsTests\AnotherMMS (path edited if you want to test : it contained whitespace)
And my ndk path is D:\android-ndk-r4b-windows\android-ndk-r4b
How can i use make APP with cygwin?My os is windows xp sp2.
EDIT: I have added ndk location in my PATH variable
Thanks in advance
|
The 'make APP=...' method was the original NDK build system but is now deprecated in favor of the ndk-build method.
Anything that can be built with make APP=xxx can be built with ndk-build. ndk-build requires less manual setup and hard coded paths.
|
```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &r1, &n, &r2, &m)
```
What's"ss"for here?
|
The type specifier in your case is"ss". The specifiersis for a string. Since you are requestingtwostring parameters you need to supply twosasss:
```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &field1 &field1_length,
&field2, &field2_length)
```
|
I have following problem:
I have main (parent) procces, which creates another processes (childs) using fork function. I am catching child's status to eliminate zombies. When there is 1 child process, it is catched correctly, but when there are more processes (aprx. 30) created by parent process, there are aprx. 4 zombies left = parent does not catch all the children (return status/state = <defunct>).
Child status is catched using
```
void selfkill(int status) {
wait(&status);
}
signal(SIGCHLD, selfkill);
```
Thanks in advance.
|
You should probably usewaitpid()with WNOHANG in a loop inside the signal handler.
What probably happens is that not all the signals are delivered - because some of them arrive too close to each other. You could perhaps alleviate that problem by usingsigaction()instead ofsignal(), too.
|
I have this struct:
```
#define sbuffer 128
#define xbuffer 1024
typedef struct{
char name[sbuffer];
char att[sbuffer];
char type[sbuffer];
int noOfVal;
int ints[xbuffer];
double doubles[xbuffer];
char *strings[xbuffer];
} variable;
```
I need to create an array from this struct, I did this
```
variable *vars[512]; //is it right
```
If I want to put a string that I had in s into the name, I did this:
```
char *s = "What Ever";
strcpy(vars[0]->name,s);
```
but this doesn't work for me, can anyone help?
|
Get rid of the*in this line:
```
variable *vars[512]; //is it right
```
And usedot syntaxto access the struct member instrcpy:
```
char *s = "What Ever";
strcpy(vars[0].name,s);
```
|
Is there any way to change anintfile descriptor to aFILEstruct pointer or/and changeFILE*to a file descriptor in C?
|
The functionfdopen()returns a new (FILE *) associated with an open file descriptor.
The functionfileno()returns the file descriptor associated with an open FILE *.
|
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.Closed12 years ago.
I want to use abc1 ,abc2, abc3,abc4,..abc100,as struct variable name. But I don't know how to set this? have no idea.
Can anybody help me out?
Thanks indeed.
|
It sounds like you're looking for an array.
```
typedef struct {
/* ... */
} whatever;
whatever abc[100];
abc[0] = xxx;
abc[3] = yyy;
```
|
I'm programming my first socket lines, and have accomplish to make a client server system that transfer messages between. The next step is to make a header sow the receiver know how much data the message is and how the message is to. How can I accomplish this?
I want the header to contain two int:
```
int to_phone_number;
int size;
```
How can is send a header ?
```
send(sock, the_message, max_message_length, 0);
```
|
Header, body, it's still data.
You will send your header the same way you'd send anything.
You'd probably want to have astruct message_headerthat would compose your header.
```
struct message_header {
int to_phone_number;
int size;
};
```
Create astruct message_headervariable, set its fields, then send it.
```
struct message_header header;
// ...
send(sock, &header, sizeof(header), 0);
```
|
I know how to send signals to child process in C using thekill(pid_t pid, int sig)function. What about sending signals to threads? is it possible?. If so, how to catch signals on the "child" thread. For example, if the main thread sends me a terminate signal, how can I in the other thread catch it.
|
With POSIX threads, you have the functionspthread_cond_waitandpthread_cond_signal.
```
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex)
int pthread_cond_signal(pthread_cond_t *cond)
```
The signaled thread should block on apthread_cond_waitcall until another thread sends a signal usingpthread_cond_signal, with the same condition variable.
Considering the analogy with signals delivered to processes, this is a bit different because the signaled thread has already suspended its execution waiting for a signal, unlike a process that simply gets interrupted and goes on.
|
I am using MSVS 2008. I am writing an application in c, and would like to know whats the best way to determine hard disk information such as space available and total capacity.
Thanks
|
The Win32 API reference is where you should be looking.
The call for free space isGetDiskFreeSpaceEx()
|
My solution (for every bit of the input block, there is such a line):
```
*parity ^= (((x[0] >> 30) & 0x00000001) * 0xc3e0d69f);
```
All types areuint32. This line takes the second bit of the input x, shifts it to theLSBand sets all other bits to zero. Then, the 32-bit parity is XORed with the corresponding parity set for this bit.
I found that this multiplication solution is the fastest way to do this conditional XOR. Is there a faster way?
|
SeeCompute parity in parallelfor some neat hacks for calculating parity of a word, byte, etc.
|
Since a function in C returns only one value, all the time, how canfork(), which is also a function, return two values?
|
The fork function returns 0 to the child process that was created and returns the childs ID to the parent process.
The two seperate processes are each returned a single value.
So think of it more as one return being called on eachthreadprocess.
|
How do you test to see if your program is working and able to connect with server? I tried stackoverflow server's ip through port 40 and it fails after a min atconnect().
```
test.exe 64.34.119.12 echo 40
```
Program arguments take a syntax:<Server IP> <Echo Word> [<Echo Port>]
Also, can you test without having to connect to internet?
|
You should be able to connect to your own echo server on 127.0.0.1:7 if it is running, or get a 'connection refused' (ECONN) if it isn't running. Either would show that your code is OK actually.
|
Some have the habit of adding header file imports/includes to the header file. Some on the other hand, write a forward declaration in the header file and write the actual #include or #import lines in the implementation file.
Is there a standard practice for this? Which is better and why?
|
Given X.h and X.c, if you#includeeverything from X.h then clients of "X" that#include <X.h>will also include all those headers, even though some may only be needed in X.c.
X.h should include only what's needed to parse X.h. It should assume no other headers will have been included by the translation unit to ensure that reordering inclusions won't break a client. X.c should include any extras needed for implementation.
This minimises recompilation dependencies. You don't want a change only to the implementation to affect the header and hence trigger a client recompilation. You should simply include directly from X.c.
|
In C, how should I execute external program and get its results as if it was ran in the console?
if there is an executable called dummy, and it displays 4 digit number in command prompt when executed, I want to know how to run that executable and get the 4 digit number that it had generated. In C.
|
popen() handles this quite nicely. For instance if you want to call something and read the results line by line:
```
char buffer[140];
FILE *in;
extern FILE *popen();
if(! (in = popen(somecommand, "r"""))){
exit(1);
}
while(fgets(buff, sizeof(buff), in) != NULL){
//buff is now the output of your command, line by line, do with it what you will
}
pclose(in);
```
This has worked for me before, hopefully it's helpful. Make sure to include stdio in order to use this.
|
I'm trying to learn on multithreading, and I have a simple question. On most of the examples I find, the standard output buffer is turned off before letting multiple threads to use it with:
setbuf(stdout,NULL);
Why? Codes print the same if I remove that line on them!
|
It is possible that they would not print out the same - when the output is buffered it may not be displayed right away which can change the order in which the lines are output between threads.
Turning off buffering makes sure you know what order the statements were executed.
|
I am seeking for a C library that does approximate string matching. Calculating Levenshtein distance for example. My query strings will be ~512 bytes. I know aboutFlamingobut it is C++.
|
Not a library but simple function you findhere
A GPL Version
|
```
$ getconf BUFSIZ
getconf: Unrecognized variable 'BUFSIZ'
```
Is there a standard way to determine the value of BUFSIZ from a shell? It's easy enough to write a simple C program to output the value, but I don't quite understand why getconf doesn't do it.
|
Because BUFSIZ is a somewhat-arbitary configuration parameter for the stdio library, and not a system configuration parameter
|
The question is almost all in the title.
I was wondering, given that:
- I use a raw socket (on GNU/Linux);
- the option IP_HDRINCL is set so that I craft the IP headers by myself.
As the dest IP addr is provided in the crafted IP header, does the dst_addr argument still plays a role or is it totally useless & only here cause that's how the function prototype is ?
|
The destination address is used to route the packet - it'll be the key that's used for a routing table lookup to determine the next hop address to send it to. It should usually be the same as the destination address you set in the header.
|
I have recently bought thisbookto get to know some basics about building networking sockets under windows. I'm having problems with compiling the code written in this book for example - in first program it tells you to include
```
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
```
I tried these in visual c++ but the compiler return errors; include files not found. has anyone read from the book or know something about it?
|
In Windows you need to includeWinSock2.hto get access to the Windows Sockets API. The info in your question looks like it's targeted at Unix system sockets access.
Windows Sockets API (WinSock v2.0) docs arehere. The actual function calls from Unix sockets are mostly also available on Windows but there are also a bunch of Windows-specific functions namedWSA*that are very helpful in writing efficient Windows-specific sockets code.
|
I'm trying to get theCPU serialormotherboard serialusingCorPythonfor licensing purposes. Is it possible?
I'm usingLinux.
|
Under Linux, you could use "lshw -quiet -xml" and parse its output. You'll find plenty of system information here: cpuid, motherboard id and much more.
|
I am looking into the code written by other members and I came across the code shown below:
```
struct myType
{
int myInt : 1;
int reserved : 31;
};
```
What is 1 and 31 stands above and when above notation is used?
|
Those are bit fields, the number after the colon specifies the width, in bits, reserved for that field. They are often used when trying to conserve space, or when trying to map an external (think hardware-owned) register that has bitfields. Note that packing and endianness affect how the bits are layed out in memory, so they're not to be used if portability is important.
Note that it's a very bad idea to use signed bit fields with very small sizes, such as 1. Since one bit is needed for the sign, no bits are left for the actual value which is generally not a very good situation. Usingunsigned int myUnsigned : 1fixes this.
|
What is the C# equivalent of the following C code:
```
while((c = getchar())!= EOF)
putchar(c);
```
I know getchar() and putchar() are going to be replaced by Console.Read and Console.Write respectively but what about the EOF. Especially keeping in mind, C# works with unicode and C with ASCII, what are the implications of that ??
|
Console.Read()returns -1 on EOF (coincidentally,EOFis defined as-1on most platforms).
You can do:
```
int c;
while ((c = Console.Read()) != -1) {
Console.Write(Convert.ToChar(c));
}
```
Also, C# works natively withUNICODEin the same way that C works natively withASCII, i.e. there are no more implications.System.Charrepresents anUCS-2UNICODEcharacter, which also fits into anint, so everything will be all right.
|
On this linkhttp://lxr.free-electrons.com/source/drivers/parport/parport_pc.c?v=2.6.29#L97they defined a structure superio_struct and initialized as
```
superios[NR_SUPERIOS] = { {0,},};
```
I am not able to understand above initialization has what is it getting initialized to.
What I deduce till now is superios is a structure array of struct superio_struct
and NR_SUPERIOS is defined as 3 hence an array of structure of size 3
but
```
superios[0]=??
superios[1]=??
superios[2]=??
```
|
It's just initialising the entire array to zero. The commas are redundant (and not all compilers will allow them). It should really just be:
```
superios[NR_SUPERIOS] = { { 0 } };
```
|
This question already has answers here:Copying a part of a string (substring) in C(13 answers)Closed9 years ago.
For example, I have this
```
char *buff = "this is a test string";
```
and want to get"test". How can I do that?
|
```
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
```
Job done :)
|
I am having too many confusions in native coding for android. My application wants to play mms:// stream and I'm facing some serious problems in that. But the basic question is
What is the difference between ndk-build(that i usually use)and make APP(i have seen many blogs on them one of them isthis)
Another related question
Suppose my project is in E:\WorkSpace\mmsTests\AnotherMMS (path edited if you want to test : it contained whitespace)
And my ndk path is D:\android-ndk-r4b-windows\android-ndk-r4b
How can i use make APP with cygwin?My os is windows xp sp2.
EDIT: I have added ndk location in my PATH variable
Thanks in advance
|
The 'make APP=...' method was the original NDK build system but is now deprecated in favor of the ndk-build method.
Anything that can be built with make APP=xxx can be built with ndk-build. ndk-build requires less manual setup and hard coded paths.
|
```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &r1, &n, &r2, &m)
```
What's"ss"for here?
|
The type specifier in your case is"ss". The specifiersis for a string. Since you are requestingtwostring parameters you need to supply twosasss:
```
zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &field1 &field1_length,
&field2, &field2_length)
```
|
I have following problem:
I have main (parent) procces, which creates another processes (childs) using fork function. I am catching child's status to eliminate zombies. When there is 1 child process, it is catched correctly, but when there are more processes (aprx. 30) created by parent process, there are aprx. 4 zombies left = parent does not catch all the children (return status/state = <defunct>).
Child status is catched using
```
void selfkill(int status) {
wait(&status);
}
signal(SIGCHLD, selfkill);
```
Thanks in advance.
|
You should probably usewaitpid()with WNOHANG in a loop inside the signal handler.
What probably happens is that not all the signals are delivered - because some of them arrive too close to each other. You could perhaps alleviate that problem by usingsigaction()instead ofsignal(), too.
|
I have this struct:
```
#define sbuffer 128
#define xbuffer 1024
typedef struct{
char name[sbuffer];
char att[sbuffer];
char type[sbuffer];
int noOfVal;
int ints[xbuffer];
double doubles[xbuffer];
char *strings[xbuffer];
} variable;
```
I need to create an array from this struct, I did this
```
variable *vars[512]; //is it right
```
If I want to put a string that I had in s into the name, I did this:
```
char *s = "What Ever";
strcpy(vars[0]->name,s);
```
but this doesn't work for me, can anyone help?
|
Get rid of the*in this line:
```
variable *vars[512]; //is it right
```
And usedot syntaxto access the struct member instrcpy:
```
char *s = "What Ever";
strcpy(vars[0].name,s);
```
|
Is there any way to change anintfile descriptor to aFILEstruct pointer or/and changeFILE*to a file descriptor in C?
|
The functionfdopen()returns a new (FILE *) associated with an open file descriptor.
The functionfileno()returns the file descriptor associated with an open FILE *.
|
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.Closed12 years ago.
I want to use abc1 ,abc2, abc3,abc4,..abc100,as struct variable name. But I don't know how to set this? have no idea.
Can anybody help me out?
Thanks indeed.
|
It sounds like you're looking for an array.
```
typedef struct {
/* ... */
} whatever;
whatever abc[100];
abc[0] = xxx;
abc[3] = yyy;
```
|
I'm programming my first socket lines, and have accomplish to make a client server system that transfer messages between. The next step is to make a header sow the receiver know how much data the message is and how the message is to. How can I accomplish this?
I want the header to contain two int:
```
int to_phone_number;
int size;
```
How can is send a header ?
```
send(sock, the_message, max_message_length, 0);
```
|
Header, body, it's still data.
You will send your header the same way you'd send anything.
You'd probably want to have astruct message_headerthat would compose your header.
```
struct message_header {
int to_phone_number;
int size;
};
```
Create astruct message_headervariable, set its fields, then send it.
```
struct message_header header;
// ...
send(sock, &header, sizeof(header), 0);
```
|
I know how to send signals to child process in C using thekill(pid_t pid, int sig)function. What about sending signals to threads? is it possible?. If so, how to catch signals on the "child" thread. For example, if the main thread sends me a terminate signal, how can I in the other thread catch it.
|
With POSIX threads, you have the functionspthread_cond_waitandpthread_cond_signal.
```
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex)
int pthread_cond_signal(pthread_cond_t *cond)
```
The signaled thread should block on apthread_cond_waitcall until another thread sends a signal usingpthread_cond_signal, with the same condition variable.
Considering the analogy with signals delivered to processes, this is a bit different because the signaled thread has already suspended its execution waiting for a signal, unlike a process that simply gets interrupted and goes on.
|
I am using MSVS 2008. I am writing an application in c, and would like to know whats the best way to determine hard disk information such as space available and total capacity.
Thanks
|
The Win32 API reference is where you should be looking.
The call for free space isGetDiskFreeSpaceEx()
|
My solution (for every bit of the input block, there is such a line):
```
*parity ^= (((x[0] >> 30) & 0x00000001) * 0xc3e0d69f);
```
All types areuint32. This line takes the second bit of the input x, shifts it to theLSBand sets all other bits to zero. Then, the 32-bit parity is XORed with the corresponding parity set for this bit.
I found that this multiplication solution is the fastest way to do this conditional XOR. Is there a faster way?
|
SeeCompute parity in parallelfor some neat hacks for calculating parity of a word, byte, etc.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.