question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Given two events with integer start and end times, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap.
I have the solution, but I'm curious to see what others come up with.
EDIT: OK, here's my solution:
```
e1 > s2 || (s1 > s2 && e2 < s1)
```
|
bool overlap = (s1 <= e2) && (s2 <= e1)
|
I am writing C functions for Lua.
I have many calls like lua_gettable, lua_touserdata, etc
My C function may receive complex structures like table with tables as fields.
It is hard for me to program stacked machine.
Is there way to write Lua script that would be converted to C code.
Or some other tools that may he... |
TryLuaToCee.
|
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC,... |
How about using sockets?
http://www.alhem.net/Sockets/tutorial/
|
I want to copy folder A and paste to desktop.
I am currently using C++ so preferably an OO interface if available.
|
On Windows (Win32), you could useSHFileOperation, eg:
```
SHFILEOPSTRUCT s = { 0 };
s.hwnd = m_hWnd;
s.wFunc = FO_COPY;
s.fFlags = FOF_SILENT;
s.pTo = "C:\\target folder\0";
s.pFrom = "C:\\source folder\\*\0";
SHFileOperation(&s);
```
|
If you have a client/server application and you want to duplicate the same series of random numbers that the rand() function produces on the client, but on a server, what is the algorithm/pseudo code? The client and server would be given the same seed (srand() on the client).
Thank you!
Please note:
Is this not kn... |
From Apple's Darwin source code,here is the Mac implementation ofrand(), which should be the same as the one used on iOS.Herealso is therandom()implementation. They both appear to be drawn from FreeBSD.
|
I am currently running a Lua script with a hook attached usingLUA_MASKCALLand the hook function implemented as follows:
```
void LuaHook(lua_State *L, lua_Debug *ar) {
switch(ar->event) {
case LUA_HOOKCALL:
lua_getinfo(L, ">n", ar);
//breakpoint here...
} break;
def... |
lua_getstackdid the trick so never mind
|
There is a Ruby process and has a string var named "switch", and the "switch" will be updated by user. There are also 2 C daemon process, which need to access the "switch" in a loop and decide the logic in runtime, how to deal with this case ? thanks!
|
A socket (or a common file) can be used as a pipe between them.
|
This was my previous question:
Can someone give me simple example in C, of usingpipe()system call to and use ssh to connect to a remote server and execute a simplelscommand and parse the reply. Thanks in advance, [...]
I got an answer for that, but I need something more.
I would like to ask how to use a pipe and c... |
Are you doing this for a challenge?, if yes that's cool because you are doing a hard thing to the end, if notderobertsuggestion is the best solution in case you want to communicate with the MySQL server.
|
I remember having read a very good guide to writing collections. By that I mean, it described using macros to generate types with type parameters, kind of like C++ templates. I'm not sure if it was written by Rusty Russell, but it was someone I recognized. It was posted on hackernews or proggit... I wanted to write a ... |
This guide fits your description:
Collections in Cby Armin Ronacher.
|
if anyone could answer me why this works, it would be greatly appreciated. The exercise (chapter 4, ex 7 and 8) says that if you have the expression:
9 - ((total - 1) % 10)
then, you could be tempted to simplify it like this:
10 - (total % 10)
But this would not work. Instead he offers the alternative:
(10 - (total % ... |
x %m has a range of (-m, m) in most C implementations. Mathematically it is generally defined from (0, m). Hence by adding m the modulo again will convert the C to the mathematical one.
|
The reason I'm asking:
```
#include <string.h>
using namespace std;
int main()
{
unsigned char file[512000];
unsigned char key[512000];
for(int i = 0; i < 512000; i++)
file[i] = key[i];
return 0;
}
```
When I compile this with cl.exe on windows I get an executable that is about 31kb in ... |
In this case, the buffers will be allocated on the program'sstack spaceat runtime. There's no need for them to be statically built into theexefile.
|
Given two events with integer start and end times, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap.
I have the solution, but I'm curious to see what others come up with.
EDIT: OK, here's my solution:
```
e1 > s2 || (s1 > s2 && e2 < s1)
```
|
bool overlap = (s1 <= e2) && (s2 <= e1)
|
I want to make console window with a functional tray icon. I figured out that most probably it is necessary to replace initial console's window procedure so I will be able to control all messages including notify area events. ButSetWindowLong()function returns 0, andGetLastError()tells that access is denied.
```
hwnd... |
If all you want to do is create a notification icon for a console application, there's nothing that says your Shell_NotifyIcon call has to point to the console window. Create an invisible dummy window with your own window class and procedure instead. Note that you'll probably have to do this from a secondary thread in... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:What does 'unsigned temp:3' mean?
please what does this notation mean
int a:16;
I found it is code like this and it does compile.
struct name {
int a:16; }
|
This is abitfield.
This particular bitfield doesn't make much sense as you just could use a 16-bit type and you're wasting some space as the bitfield is padded to the size ofint.
Usually, you are using it for structures that contain elements of bit size:
```
struct {
unsigned nibble1 : 4;
unsigned nibble2 :... |
This question already has answers here:Closed12 years ago.
Possible Duplicates:Output of multiple post and pre increments in one statementPost-increment and pre-increment in 'for' loop
The following code snippet
```
int i=0;
printf("%d %d",i++,i++);
```
gives the output
1 0
I can understand that, but the followi... |
Both printfs invoke undefined-behavior. See this :Undefined behavior and sequence points
Quoted from this link:
In short, undefined behaviour means
anything can happen from daemons
flying out of your nose to your
girlfriend getting pregnant.
For newbies :Don't ever try to modify values of your variablestwice ... |
How can I invoke crypt(3) from a c program on a windows platform? I can't find a header file to include. I have MinGW with gcc and msys installed.
Edit: as an alternative, I would also accept a way to call this function (or an equivalent) from Visual Studio.
|
Have you seen this?http://sourceforge.net/projects/mingw/files/MSYS/crypt/
I suppose you may be missing it, or just don't realize you have it, but it seems like the answer, and I found it by typing "crypt mingw" into Google.
|
I know thatEOFand'\0'are of type integers, but if so shouldn't they have a fixed value?
I printed both and got -1 forEOFand 0 for'\0'. But are these values fixed?
I also had this
```
int a=-1;
printf("%d",a==EOF); //printed 1
```
Are the value forEOFand'\0'fixed integers?
|
EOFis a macro which expands to an integer constant expression with typeintand an implementation dependent negative value but is very commonly -1.
'\0'is acharwith value 0 in C++ and anintwith the value 0 in C.
The reason whyprintf("%d",a==EOF);resulted in1was because you didn't assign the valueEOFtoa. Instead you ch... |
This question already has answers here:Closed12 years ago.
Possible Duplicate:Are nested functions a bad thing in gcc ?
As far as I know, C does not allow a function to be defined within other function. But the following code compiles and runs without any error in gcc. Can someone explain the reason why? See this al... |
gcc(but notg++) supportsnested functionsas aC language extension.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it
For example if i give a input as "This is a string"
I should get the output as "string a is T... |
First Reverse the string in place
Then Reverse each word in place (words are delimited by a space)
|
binary tree, where each node has at most two child nodes, child nodes may contain references to their parents.
we do not differentiate the nodes and all nodes are considered identical.How can we find the number of different binary trees that can be formed with N identical nodes.
eg: if 3 nodes then 5 diff treesif 7 ... |
Now, if you really want to understand this, instead of just getting (or experimenting to find) the answer, you can check out "The Art of Computer Programming", Volume 4, Fascicle 4:Generating all trees.
|
I am trying to create a mini task manager where I can show all the process and details. I am able to get all the details by using CreateToolhelp32Snapshot, OpenProcess etc. Now for GUI I am not sure what to use? I can use windows form or windows APIs. Windows forms can make my job easier but I read somewhere that wind... |
You can use both together.
Simply choose what you you are familiar with. The goal is to make it done and working, isn't it? :-)
|
To move objects with a variable time step I just have to do:
```
ship.position += ship.velocity * deltaTime;
```
But when I try this with:
```
ship.velocity += ship.power * deltaTime;
```
I get different results with different time steps. How can I fix this?
EDIT:
I am modelling an object falling to the ground o... |
```
ship.position = ship.position + ship.velocity * deltaTime + 0.5 * ship.power * deltaTime ^ 2;
ship.velocity += ship.power * deltaTime;
```
http://www.ugrad.math.ubc.ca/coursedoc/math101/notes/applications/velocity.html
The velocity part of your equations is correct and they must both be updated at every time ste... |
I have some code, that I'm currently porting from OS X to Linux (console tool).
Somewhere in this code, I get a segmentation fault. The problem is, that if I run the program without GDB, I clearly see the segmentation fault, and the program is killed. But when I'm running GDB it just halts, and GDB never returns to t... |
gdb will suspend your program when the seg fault signal is received
typewhereto see the stack trace and start inspecting what's going on from there.
Also consider enabling core dumps, that way you can load the core dump in GDB and investigate what is going on
you can then load the core dump like this
> gdb your_pr... |
I want to make console window with a functional tray icon. I figured out that most probably it is necessary to replace initial console's window procedure so I will be able to control all messages including notify area events. ButSetWindowLong()function returns 0, andGetLastError()tells that access is denied.
```
hwnd... |
If all you want to do is create a notification icon for a console application, there's nothing that says your Shell_NotifyIcon call has to point to the console window. Create an invisible dummy window with your own window class and procedure instead. Note that you'll probably have to do this from a secondary thread in... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:What does 'unsigned temp:3' mean?
please what does this notation mean
int a:16;
I found it is code like this and it does compile.
struct name {
int a:16; }
|
This is abitfield.
This particular bitfield doesn't make much sense as you just could use a 16-bit type and you're wasting some space as the bitfield is padded to the size ofint.
Usually, you are using it for structures that contain elements of bit size:
```
struct {
unsigned nibble1 : 4;
unsigned nibble2 :... |
This question already has answers here:Closed12 years ago.
Possible Duplicates:Output of multiple post and pre increments in one statementPost-increment and pre-increment in 'for' loop
The following code snippet
```
int i=0;
printf("%d %d",i++,i++);
```
gives the output
1 0
I can understand that, but the followi... |
Both printfs invoke undefined-behavior. See this :Undefined behavior and sequence points
Quoted from this link:
In short, undefined behaviour means
anything can happen from daemons
flying out of your nose to your
girlfriend getting pregnant.
For newbies :Don't ever try to modify values of your variablestwice ... |
How can I invoke crypt(3) from a c program on a windows platform? I can't find a header file to include. I have MinGW with gcc and msys installed.
Edit: as an alternative, I would also accept a way to call this function (or an equivalent) from Visual Studio.
|
Have you seen this?http://sourceforge.net/projects/mingw/files/MSYS/crypt/
I suppose you may be missing it, or just don't realize you have it, but it seems like the answer, and I found it by typing "crypt mingw" into Google.
|
I know thatEOFand'\0'are of type integers, but if so shouldn't they have a fixed value?
I printed both and got -1 forEOFand 0 for'\0'. But are these values fixed?
I also had this
```
int a=-1;
printf("%d",a==EOF); //printed 1
```
Are the value forEOFand'\0'fixed integers?
|
EOFis a macro which expands to an integer constant expression with typeintand an implementation dependent negative value but is very commonly -1.
'\0'is acharwith value 0 in C++ and anintwith the value 0 in C.
The reason whyprintf("%d",a==EOF);resulted in1was because you didn't assign the valueEOFtoa. Instead you ch... |
This question already has answers here:Closed12 years ago.
Possible Duplicate:Are nested functions a bad thing in gcc ?
As far as I know, C does not allow a function to be defined within other function. But the following code compiles and runs without any error in gcc. Can someone explain the reason why? See this al... |
gcc(but notg++) supportsnested functionsas aC language extension.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it
For example if i give a input as "This is a string"
I should get the output as "string a is T... |
First Reverse the string in place
Then Reverse each word in place (words are delimited by a space)
|
binary tree, where each node has at most two child nodes, child nodes may contain references to their parents.
we do not differentiate the nodes and all nodes are considered identical.How can we find the number of different binary trees that can be formed with N identical nodes.
eg: if 3 nodes then 5 diff treesif 7 ... |
Now, if you really want to understand this, instead of just getting (or experimenting to find) the answer, you can check out "The Art of Computer Programming", Volume 4, Fascicle 4:Generating all trees.
|
I am trying to create a mini task manager where I can show all the process and details. I am able to get all the details by using CreateToolhelp32Snapshot, OpenProcess etc. Now for GUI I am not sure what to use? I can use windows form or windows APIs. Windows forms can make my job easier but I read somewhere that wind... |
You can use both together.
Simply choose what you you are familiar with. The goal is to make it done and working, isn't it? :-)
|
To move objects with a variable time step I just have to do:
```
ship.position += ship.velocity * deltaTime;
```
But when I try this with:
```
ship.velocity += ship.power * deltaTime;
```
I get different results with different time steps. How can I fix this?
EDIT:
I am modelling an object falling to the ground o... |
```
ship.position = ship.position + ship.velocity * deltaTime + 0.5 * ship.power * deltaTime ^ 2;
ship.velocity += ship.power * deltaTime;
```
http://www.ugrad.math.ubc.ca/coursedoc/math101/notes/applications/velocity.html
The velocity part of your equations is correct and they must both be updated at every time ste... |
Is there a way to convert a hexdump e.g. aec4d2f3c6a4e70ea6cea074f65812d2a34b180cc92b817edcd867167e7a91c5beb942f0
to a string in c so that every two hexadecimal digits make a char? If so, what?
|
Reads from stdin and prints to stdout:
```
int main()
{
int ch;
while(scanf("%2x", &ch) == 1)
putchar(ch);
}
```
I think you can modify it easily yourself for your specific source and destination requirements.
|
In the given code snippet, I expected the errorsymbol Record not found. But it compiled and ran fine on Visual Studio 2010 Compiler. I ran it as a C program from Visual Studio 2010 Command Prompt in the manner -
cl Record.cRecord
Now the doubt is, doesn'ttypedefcheck for symbols ? Does it work more like aforward dec... |
You can always refer to undefined structures, which is a typical way to implement linked lists, after all. They just have to be defined when you want to make use of their fields.This pagecontains some details.
|
is it possible to get just one bit of an int in C and then flip it without reading the entire int and writing it back to memory?
context:
trying to avoid too many locks/unlocks in pthread.
|
You can not read a single bit from the memory, actually you can not force CPU to read only a single byte. It is always reading a full cache line, which could have different sizes for different CPUs.
But from the language point of view you can use bit fieldshttp://publications.gbdirect.co.uk/c_book/chapter6/bitfields.... |
I've read aboutSetScrollRangebut still didn't get what the range (min, max) is in scrollbar. I've set the rich edit control's vertical scroll bar range to (0, 100)
```
SetScrollRange(hwndRichEditControl, SB_VERT, 0, 100, TRUE);
```
Now, If I tryGetScrollPosto get the position i'm getting the value over max range.
Sh... |
It shouldn't. The RichEdit control itself determines the scroll range of the scroll bar. Which it does depending on how much text it displays. Overriding it isn't going to last long, if at all. You can only use GetScrollInfo() to find out what it is using currently. This is going to change as soon as the user add... |
I'm running throughtheForger's Win32 API Programming Tutorial. Onpage 4he suggests it would be handy to find the list of #define statements in the API header files which list all the WM_* messages. I decided it probably would be worth my while to take a gander at them all, so I tried to find them, but was unsuccessful... |
Trywinuser.hin the platform SDK include folder.
|
I am checking to make sure a float is not zero. It is impossible for the float to become negative. So is it faster to do thisfloat != 0.0for thisfloat > 0.0f?
Thanks.
Edit: Yes, I know this is micro-optimisation. But this is going to be called every time through my game loop, and I would like to know anyway.
|
There is not likely to be a detectable difference in performance.
|
0x7F000000is0111 1111 0000 0000 0000 0000 0000 0000in 32 bit binary.0x01000058is0000 0001 0000 0000 0000 0000 0101 1000.
When I AND the two numbers together I expect0000 0001 0000 0000 0000 0000 0000 0000, but for some reason I get 0.
Here is my code:
```
#define MASK_binop 0x80000000
#define MASK_operation 0x7... |
If line contains "0x01000058" then atoi will return 0 as atoi works with decimal representation, not hex 0x representation. And then the AND obviously is zero. Try to printf the value of instruction.
|
I have a 32 bit integer, split into parts like this:
```
--------------------------------------
| Part1 | Part2 | Part 3 |
--------------------------------------
```
Part 1 higher 16 bits. (Part 2 + Part 3) = lower 16 bits.
Part 2 is 10 bits and Part 3 is 6 bits
I need help on how do we read and upda... |
Given an integerxwith the above format, you can replace Part2 like this:
```
x = (x & ~(0x3ff << 6)) | (newPart2 << 6);
```
and Part3 like so:
```
x = (x & ~0x3f) | newPart3;
```
This assumes that bothnewPart2andnewPart3are e.g.unsigned intwith their new values right-adjusted.
|
Does anybody experience mixing -g (debugging symbols) and -O2 (best safe optimization) with gcc compiler?I have to debug crashes of a release program distributed to final users that could send me back the core file.I've always used to call:
gdb << myprogram >> << core file >>
and see where the trouble is. Now I can ... |
It works fine.
Or well, due to the optimization sometimes the source you're stepping through with the debugger doesn't match up exactly with the source, but IMHO despite this having the debug symbols makes debugging much easier.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How do you read C declarations?
I Don't understand the following:
```
int * (*(*p)[2][2])(int,int);
```
Can you help?
|
For things like this trycdecl, decoded to;
```
declare p as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int
```
|
```
valgrind-3.6.0.SVN-Debian
gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
2.6.35-22-generic
```
I am using valgrind to detect memory errors in our code.
However, are application uses some third party libraries (shared library). When we start to capture using valgrind. It goes into this library, and displays many memor... |
You can try suppressing the errors generated by the library code:
http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress
|
Why is thetimefunction usually used like this:
```
time_t currentTime;
currentTime = time( NULL );
```
instead of this:
```
time_t currentTime;
time( ¤tTime );
```
Is the first method used more just because it is arguably more readable? Or is there another reason?
Thanks.
Edit: Also, why was thetimefunctio... |
It always seems to make more sense to return a value from a function than pass a paramter that is changed.
This might be because we learned on languages where functions and subroutines were different, don't know about these youngsters today.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:How to write program during compiling?
I found this problem on a site full of interview questions, and was stumped by it. Is there some preprocessor directive that allows one to read from standard input during compilation?
Write a small C... |
#include "/dev/stdin"is the trick.
A silly interview question at best.
|
```
struct A
{
int member1;
int member2;
struct B
{
int member3;
int member4;
} *b;
};
```
How can I initializeAand at the same time create an array ofB's to fill thebfield? I want a static variable, so preferably function calling.
I tried this but it does not work (I didn't think... |
I think the problem with this code is this line:
```
& { {3, 4}, {5, 6} }
```
The problem is that{{3, 4}, {5, 6}}is an rvalue (a value, not an object) and you can't take the address of an rvalue. After all, where is the memory for this object going to come from? However, you might be able to get away with rewritin... |
Is there a way to test for the existence of C functions in Objective-C? I'm looking for something like "respondsToSelector," but for C functions.
More specifically, I'm trying to test for the existence of "UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque>, CGFloat scale)" in iOS.
Thanks.
|
```
if(&UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions();
else NSLog(@"No UIGraphicsBeginImageContextWithOptions function");
```
|
I am working on a moderately large C file where I need to do processing for 3 different exclusive conditions. (if condition 1 is present do this, if 2 is present do something else and likewise). So, at many places in that file, I need to do if/else checks - which looks dirty.
I have some 50 places where I am doing th... |
If the conditions are really exclusive then I'd start with three separate functions, one for each process. Break any common code out into their own functions that you can call from the three process functions. The only conditional left should be where you decide which of the three process functions to call.
|
In the C programing language, why do the bitwise operators (& and |) have lower precedence than the equality operator (==)? It does not make sense to me.
|
You need to ask Brian Kernighan or Dennis Ritchie.From this forum:http://bytes.com/topic/c/answers/167377-operator-precedence
The && and || operators were added later
for their "short-circuiting" behavior. Dennis Ritchie admits in
retrospect that the precedence of the bitwise operators should have
b... |
So I have compiled a small testing program that uses SWIG as a bridge between python and C. The main part of the program is the python file. The thing runs fine on my own pc, but as soon as I transfer it to another, it immediately throws a "ImportError: DLL load failed: The specified module could not be found." error.... |
Everyone having this problem should probably check out thedependency walker, and see what DLLs are missing. It solved my problem.
|
I'm looking for a library in c or objective c that does node-data visualizations similar tohttp://arborjs.org/
helpful answers include,
what are graphs like that called?names of libraries that do something like that.suggestions for implementation.
I'm targeting iOS and/or MacOS, hence c or objective-c/cocoa. On i... |
Actually there seems to be an Objective-C port of arborjs, seehttps://github.com/epreston/PSArborTouch.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:function overloading in C
So I wonder if we can use something likevoid A(){}andvoid A(int b){}in same code file?
|
That's not functionoverriding, but functionoverloading.
Anyway no, C doesn't provide it.
The rationale (well, one of them, the one I prefer) is that to provide function overloading you should find a way to give a symbol to a function based also on its parameters, not only on its name.This would cause a few problems ... |
Is there a hack to support range case in a c(99?) or objective C switch statement ?
I know this is not supported to write something like this:
```
switch(x)
case 1:
case 2..10:
case 11:
```
But I was thinking there should be a way to generate code with a #define macro. Of course
I can define a macro with th... |
GCC has anextension to the C languagethat allows something similar to your first example, but other than that, if there was a portable/ANSI way of doing it, it would have been done by now. I don't believe there is one.
|
Why do the variables take garbage values?
|
I guess the rationale for this is that your program will be faster.
If compiler automaticallyreset(ie: initialize to 0 or to NaN for float/doubles etc etc) your variables, it would take some time doing that (it'd have to write to memory).In many cases initializing variables could be unneeded: maybe you will never acc... |
What is the difference between
```
int* a = 0;
```
and
```
int* a = 10;
```
?
|
int* adeclares variableaas a pointer to integer.
=0and=10assign some value to the variable.
Note thatais a pointer, its value is supposed to be an address.
Address0has a particular meaning: it'sNULL, represent anemptypointer.Address10has no meaning: it's a random memory address. Since it's notNULL, most functions w... |
```
#include<stdio.h>
double i;
int main()
{
(int)(float)(char) i;
printf("%d", sizeof((int)(float)(char)i));
return 0;
}
```
The above outputs 4 on a Micrsoft compiler. Why?
|
sizeofis the size, in bytes, of the variable. In this case,iis being cast to anintwhich is 4 bytes.
These are the sizes of types on MS C++:http://msdn.microsoft.com/en-us/library/cc953fe1(v=vs.71).aspx
|
Where are the Python bindings, or what is the current status of thePython bindingsforGIO'sGSocketand otherlowlevel network support?
|
The Gnome documentation is known to be somewhat not up to date. One may endlessly say words like community, manpower, time, effort, et cetera.
The fact is that when you do
```
>>> import gio
>>> help(gio.Socket)
```
you will see that the class is there (and others too). That is just the doc missing its description.... |
I did this:
```
import cStringIO.StringIO as StringIO
```
And I realize I've been using it everywhere. Is that fine?
Is it treated the same as StringIO?
|
They are not the same.cStringIOdoesn't correctly handle unicode characters.
```
>>> StringIO.StringIO().write(u'\u0080')
>>> cStringIO.StringIO().write(u'\u0080')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: o... |
Is there a stable library that can validate JSON against aschema?
json-schema.orgprovides alist of implementations. Notably C and C++ are missing.
Is there a reason I can't easily find a C++ JSON schema validator?Doesn't anyone else want a quick way to validate incoming JSON files?
|
Is there a stable library that can validate JSON against a schema?
I found a couple hits on google:
From the Chromium project:http://aaronboodman-com-v1.blogspot.com/2010/11/c-version-of-json-schema.htmlhttp://avro.apache.org/docs/1.4.1/api/cpp/html/index.html
You could also plug a Python or Javascript interpreter ... |
I write a struct
```
struct Tree{
struct Node *root;
struct Node NIL_t;
struct Node * const NIL; //sentinel
}
```
I want
```
struct Node * const NIL = &NIL_t;
```
I can't initialize it inside the struct.
I'm using msvs.
I use C, NOT C++.
I know I can use initialization list in C++.
How to do so i... |
If you are using C99, you can used designated initializers to do this:
```
struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
```
This only works in C99, though. I've tested this on gcc and it seems to work just fine.
|
I have two threads, communicating with each other; each thread employs 'while(1) ..'. Now I need to let the threads exit upon a specific condition met, and therefore finish the application.
My question: is it safe to just 'return (NULL)' from the thread, or do I have to use 'pthread_exit' or 'pthread_join' functions ... |
It is safe to return null from the thread functions; the code that waits for them should be OK.
POSIX says ofpthread_exit():
An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it.
You do need somethi... |
The general strategy for boost file locking (sharable and scoped file_locks), and file locking in general I think, is this:
openlockoperate on file contentsunlockclose the file
However, I will be opening the file for append and want to call tellp to see where I am. Is this safe to do in the above scenario? Won't th... |
This may be environment-specific, but on the majority of platforms:
When a file is opened for append the file pointer is adjusted immediately before every write. So, if you usetellpbefore locking the file, it might not tell you where your newly appended bytes are going to go, but you shouldn't have two processes usi... |
I was wondering what is the difference between these two lines of code?
```
int hi;
int *hi;
```
In the C programming language?
Thanks!
Amit
|
```
int hi;
```
reserves the space for anintin memory, and each time you referencehi, you either read or write directly thatintin memory space.
```
int *hi;
```
reserves the space for apointerto anintin memory, each timehiis used, the pointer is either read or written. Meaning that you arenotworking with anint, onl... |
SDL_Eventis a union of an unsigned 8 bit type, and many structs whose first element is an unsigned 8 bit type. The reccomended usage is to access the Uint8 element of the union to determine what type the event is, and then access the union by the element appropriate to that type.
This obviously depends on all of the ... |
The first element of a struct is guaranteed to be at "offset 0" from the struct's beginning. So it should be safe.
|
The following C/C++ code results in an Unused Entity Issue with XCode 4 (Clang LLVM).
```
void stringMethod(const char *string){
while(*string!=0){
*string++;
//...
}
}
```
Its on that line: *string++; so it seems like clang didnt realize that the pointer address is increased?
I don't get, how to adjust ... |
Try to remove the dereferencing operator*, you don't need to dereference the pointer when you increase it.
|
With C/ C++,getopt_long()can be used to parse command line arguments. Is it possible to tell the function that some of the options are mandatory? For example, how can I tellgetopt_longthat the parsing should give error ifstartServeris called without mentioning the port below?
./startServer -port 80
Note: I am not ta... |
getopt_long()is not part of the C language. It is a GNU invention which is available in some C implementations, but far from all.
The version ofgetopt_long()in glibc (used in most Linux distributions) does not allow you to specify that an option is mandatory. You'll have to check them explicitly after you're done p... |
I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++
Thank you all.
|
For JSON,json.orghas a list of implementations for a variety of languages, including C. Most of them should be fairly lightweight and fast.
To replace urllib, you probably want to look atlibcURL.
|
```
int i; // A.
extern int i; // B.
```
I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variablei. But what is B? What's the difference between the definition and the declaration?
|
It's a declaration. It says there is an integerithat will be defined elsewhere.
|
Consider that my system has memory, but it is scattered in different places (fragmented). There are no four contiguous memory locations that are free. In that scenario, if I declare a character array of size 10 in the C language, what will happen ?
|
If"my system has memory, but it is scattered in different places(fragmented)"means, thatheap virtual memoryis fragmented, and"declare a character array of size 10"means, that you create character array of size 10 instack memory:
```
char str[10];
```
, then array will be successfully created.
If"declare a character... |
I tried the code in my system. This is what I got......
1)
```
#include <stdio.h>
int main()
{
//int a = 10;
printf("%s");
return 0;
}
Output:
1í^áäðPTRhh
```
2)
```
#include <stdio.h>
int main()
{
int a = 10;
printf("%s\n");
return 0;
}
Ou... |
You're dealing withundefined behavior, so you can't expect it to be consistent, nor follow any kind of pattern across compilers, architectures or even runs of the same program.
|
I want to include an IP packet in Socket programming. I have a readymade Ip packet which contains igmp packet. I don't want to design igmp protocol but want to use that packet to sent igmp query. By some how the Ip packet I have must be recognize as IP packet and not as TCP/UDP data.
|
You have to usethe raw socketwithsendmsg. This needrootpermission.
|
What is a good way to create a three-state Boolean in a C-based language?
|
While others have offered answers, I'd like to offer a justification for the best one.
Use integer values -1/0/1 (or really, any negative/zero/positive).
With this scheme, there is an extremely efficient check for any subset of possible values:
```
(x<0) /* {-1} */
(!x) /* {0} */
(x>0) /* {1} */
(x<=0) ... |
I was wondering what is the difference between these two lines of code?
```
int hi;
int *hi;
```
In the C programming language?
Thanks!
Amit
|
```
int hi;
```
reserves the space for anintin memory, and each time you referencehi, you either read or write directly thatintin memory space.
```
int *hi;
```
reserves the space for apointerto anintin memory, each timehiis used, the pointer is either read or written. Meaning that you arenotworking with anint, onl... |
SDL_Eventis a union of an unsigned 8 bit type, and many structs whose first element is an unsigned 8 bit type. The reccomended usage is to access the Uint8 element of the union to determine what type the event is, and then access the union by the element appropriate to that type.
This obviously depends on all of the ... |
The first element of a struct is guaranteed to be at "offset 0" from the struct's beginning. So it should be safe.
|
The following C/C++ code results in an Unused Entity Issue with XCode 4 (Clang LLVM).
```
void stringMethod(const char *string){
while(*string!=0){
*string++;
//...
}
}
```
Its on that line: *string++; so it seems like clang didnt realize that the pointer address is increased?
I don't get, how to adjust ... |
Try to remove the dereferencing operator*, you don't need to dereference the pointer when you increase it.
|
With C/ C++,getopt_long()can be used to parse command line arguments. Is it possible to tell the function that some of the options are mandatory? For example, how can I tellgetopt_longthat the parsing should give error ifstartServeris called without mentioning the port below?
./startServer -port 80
Note: I am not ta... |
getopt_long()is not part of the C language. It is a GNU invention which is available in some C implementations, but far from all.
The version ofgetopt_long()in glibc (used in most Linux distributions) does not allow you to specify that an option is mandatory. You'll have to check them explicitly after you're done p... |
I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++
Thank you all.
|
For JSON,json.orghas a list of implementations for a variety of languages, including C. Most of them should be fairly lightweight and fast.
To replace urllib, you probably want to look atlibcURL.
|
```
int i; // A.
extern int i; // B.
```
I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variablei. But what is B? What's the difference between the definition and the declaration?
|
It's a declaration. It says there is an integerithat will be defined elsewhere.
|
Consider that my system has memory, but it is scattered in different places (fragmented). There are no four contiguous memory locations that are free. In that scenario, if I declare a character array of size 10 in the C language, what will happen ?
|
If"my system has memory, but it is scattered in different places(fragmented)"means, thatheap virtual memoryis fragmented, and"declare a character array of size 10"means, that you create character array of size 10 instack memory:
```
char str[10];
```
, then array will be successfully created.
If"declare a character... |
I tried the code in my system. This is what I got......
1)
```
#include <stdio.h>
int main()
{
//int a = 10;
printf("%s");
return 0;
}
Output:
1í^áäðPTRhh
```
2)
```
#include <stdio.h>
int main()
{
int a = 10;
printf("%s\n");
return 0;
}
Ou... |
You're dealing withundefined behavior, so you can't expect it to be consistent, nor follow any kind of pattern across compilers, architectures or even runs of the same program.
|
I want to include an IP packet in Socket programming. I have a readymade Ip packet which contains igmp packet. I don't want to design igmp protocol but want to use that packet to sent igmp query. By some how the Ip packet I have must be recognize as IP packet and not as TCP/UDP data.
|
You have to usethe raw socketwithsendmsg. This needrootpermission.
|
What is a good way to create a three-state Boolean in a C-based language?
|
While others have offered answers, I'd like to offer a justification for the best one.
Use integer values -1/0/1 (or really, any negative/zero/positive).
With this scheme, there is an extremely efficient check for any subset of possible values:
```
(x<0) /* {-1} */
(!x) /* {0} */
(x>0) /* {1} */
(x<=0) ... |
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
Algorithms in C(Sedgewick) is also good
The Algorithm Design Manualis very readable
|
I'm trying to write a HTTP to ZeroMQ proxy with libevent (2.0.4) which should be able to handle very large (up to 4GB) file upload.
The problem is I don't know how large post requests (larger than memory) are handled by libevent so if you have hints on how to implement large file uploading, please led me on the righ... |
have you read the libevent source code? it's very readable.
If you're using it's HTTP code, i think it uses the 'bufferedevent' (or is it evented buffers?) feature. You can simply set callbacks when the input buffer reaches the highwater mark.
|
I see "printf" instruction in sample codes of c language for microcontroller particularly in 8051. Since microcontrollers has no fixed output display what is the use of the "printf" instruction?
|
More likely than not, so you can attach a debugging console, either through an RS232 port, or as virtual output from an in-circuit emulator.
|
```
int main(int argc, char **argv) {
char username[256];
username = ?;
}
```
thanks~
|
You probably want to makeusernamebe a pointer, then you can just assign it:
```
int
main(int argc, const char *const *argv)
{
const char *username;
if (argc >= 2)
username = argv[1];
else
{
fprintf(stderr, "usage: %s username ...\n", argv[0]);
return 2;
}
/* ... */
}
``... |
gcc 4.4.4 c89
I was just readinga discussion at DevXabout calling C++ code from C since I have to do something similar. I am just wondering what user Vijayan meant by "make sure that non POD types in C++ are opaque to C clients."
Many thanks for any suggestions,
|
C can only deal with POD types.
Consequently, you cannot pass objects of non-POD types to C programs (by value). Also, if you pass pointers of non-POD types to C programs, they can't interact with the objects pointed to.
|
This may sound like a strange question, but I am curious. If you want to make your code as efficient as possible, would this be something common for people to do? For example, you could use short datatypes instead of the int datatypes to do your processing. Or is it usually the case that the efficiency is much less... |
You shouldneveruse the typesshort,char,float, or similar except for making arrays. Otherwise, useint,size_t,double, or larger types as-needed.
|
I have a little problem picking the right language to write my daemon,
I am confused between C and C++, I want to use C++ because it is more expanded than C,
but I want to use C because it is the starting point of everything in linux,
I want to go for C++ as I have many resources about it, so, does it make any differ... |
Use whichever language you know best right now.
|
I would like to pack 2 floats into an long long. What would be the correct way to do this?
|
Slightly depends how portable you want it to be, in two senses: what platforms it works on at all, and what platforms it gives the same answer on. But something like this.
```
#include <stdint.h>
long long pack(float lo, float hi) {
assert(sizeof(float) == 4);
assert(sizeof(long long) == 8);
assert(CHAR_... |
I have the following code
```
#include <stdio.h>
#include <stdlib.h>
char UPC[]="123456789ABC";
main()
{
int rc=0;
printf("%016s\n",UPC);
exit(rc);
}
```
On AIX using the xlC compiler this code prints out with leading 0's
```
0000123456789ABC
```
On Sles 11 it prints leading spaces using gcc version 4.3.... |
```
printf("%.*d%s", (int)(w-strlen(s)), 0, s);
```
|
gcc 4.4.4 c89
Does any one know any sdp parses. That I can link to my application. Currently we are developing a SIP project. However, we need to parse the SDP for incoming/answering.
However, we don't have much time to implement. So just wondering if there are some simple ones out there they are easy and quick to w... |
Check outFreeSDP. But it is distributed under GPL
|
Is it possible to store more than a byte value to a char type?
Say for examplechar c;and I want to store 1000 inc. is it possible to do that?
|
Technically, no, you can't store more than a byte value to achartype. In C, acharand a byte are the same size, but not necessarily limited to 8 bits. Many standards bodies tend to use the term "octet" for an exactly-8-bit value.
If you look insidelimits.h(from memory), you'll see theCHAR_BITsymbol (among others) tell... |
In some C project, I have seen this code:
```
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
(void)ud;
(void)osize;
/* some code not using `ud` or `osize` */
return ptr;
}
```
Do the two casts to void serve any purpose?
|
It is there to avoid warnings from the compiler because some parameters are unused.
|
suppose i have a variable
int a=512
Now when i apply ~a which means one's complement in c.How i am getting -513 as the output.
int is minimum 16 bits in size and binary equivalent of 512 is
0000 0010 0000 0000 And now when you do its one's complement it becomes
1111 1101 1111 1111. Now could someone tell me why t... |
Negative numbers are often represented astwo's complement, which is why it is interpreted the way it is.
Assumingintis 16-bit, you will have the bitpattern1111 1101 1111 1111. Since the top-most bit is set, the number is negative. To convert to decimal, according to the rules for two's complement, the number is first... |
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.
```
int main()
{
signed int bit... |
The correct answer is d:http://ideone.com/frKOz
bit is 0 becausebit & ~bitalways results in a zero (1000000000 & 0111111111).mbit is -513 because inverting 512 is -513.
Edit: Why ismbit-513?
See explanation of signed-integer-handling:http://www.rwc.uc.edu/koehler/comath/13.html
|
I am beginnner to programming. I wrote this little program to reverse a string. But if I try to reverse a string which is less than 5 characters long then it gives wrong output. I cant seem to find whats wrong.
```
#include<stdio.h>
#include<string.h>
int main()
{
char test[50];
char rtest[50];
int i, j=0;
printf... |
You are not terminating the reversed string with a 0. (all strings in C are 0-terminated)
In this case, the printf will (likely, depending on the unitialized contents of the rtest array) create a buffer overflow.
Add artest[max+1]=0;after the for loop and everything should be fine.
Otherwise you can declarechar rtes... |
```
#include <stdio.h>
#include <stdlib.h>
void copyint(char *i,char** temp);
int main()
{
char* a="00313";
char* temp;
int inte;
temp=(char*)malloc(sizeof(char));
copyint(a,&temp);
inte=atoi(temp);
printf("%s\n",temp);
system("PAUSE");
free(temp);
}
void copyint(char *i,char**... |
no question so point what is wrong on the first sight:
- copyint copies single char into pointed memory.
so what is being done: temp value is '0', random, random....
'0',random random is parsed by atoi - undefined since we don't know what under this pointer resides.
and then it's printed out...
usestrlen malloc strc... |
How can I make sure not to happen like this? Is there any way to show exact place by numbers?
```
Name UID GID Dir Host
root 0 0 /root
paingpyi 500 500 /home/paingpyi 192.168.12.1
paingpyi 500 500 /home/paingpyi 192.168.12.1
```
Code is
```
print... |
Theprintfwidth specifiers are more appropriate for this kind of tasks than\t. You should have a look into the 'field width' section ofthe manual.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.