question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
How do I write an openssl server that on a single port has two different active RSA private keys? The openssl documentation seems to implies there can only be one rsa private key active at time with in a context. So I was thinking I have two active context, but what is the code to handle figuring out which connection matches which context. Or am I going about this the wrong way.
|
It's kind of an odd thing to want, but it's doable. You can maintain two activeSSL_CTXhandles, each of which has a different certificate/private key pair loaded.
When you accept a new connection, just pick the rightSSL_CTXto generate the newSSLhandle from (usingSSL_new()). As for "which connection matches which certificate" - that's up to you to determine. You could decide based on the peer address of the connection, or you might have a plain text protocol prior to starting SSL where the peer identifies the certificate it is expecting.
|
How can you view printf output in aWin32application (entering with a WinMain) inVisual Studio 2010?
|
Edit 2021, Visual Studio 2019
To write debug messages to the Output window use theOutputDebugStringAfromdebugapi.h(include windows.h)
test.c
```
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdShow, int nCmdShow)
{
int number = 10;
char str[256];
sprintf_s(str, sizeof(str), "It works! - number: %d \n", number);
OutputDebugStringA(str);
return 0;
}
```
Tested on Visual Studio 2019, Debug / x64.
Or alternatively utilize my drop-inheaderfile.
|
I hear 3 years ago problem and apparently have infinity solutions.
I want to find one of this infinity set.
Problem:Write program (have only one file example "selfsource.c") who printing on stdout self source code and exits.
All techniques all alowed. Anyone can help me?
|
This is called aQuine.
Wikipedia has anexample in C.
|
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 answered with facts and citations.Closed8 years ago.Improve this question
Is there any good tutorials/books on how to use sqlite with C??
|
Yes, right at their website:http://www.sqlite.org/cintro.html
|
I've known that I should use -l option for liking objects using GCC.
that is gcc -o test test.c -L./ -lmy
But I found that "gcc -o test2 test.c libmy.so" is working, too.
When I use readelf for those two executable I can't find any difference.
Then why people use -l option for linking objects? Does it have any advantage?
|
Because you may have either a static or a shared version of the library in your library directory, e. g.libmy.aandlibmy.so, or both of them. This is more relevant to system libraries: if you link to libraries in your local build tree, you know which version you build, static or shared, but you may not know other systems' configuration and libraries mix.
In addition to that,some platforms may have different suffixes. So it's better to specify it in a canonical way.
|
```
struct some_struct{
int a;
};
some_struct n = {};
```
n.a will be 0 after this;
I know this braces form of initialization is inherited from C and is supported for compatibility with C programs, but this only compiles with C++, not with the C compiler. I'm using Visual C++ 2005.
In C this type of initialization
```
struct some_struct n = {0};
```
is correct and will zero-initialize all members of a structure.
Is the empty pair of braces form of initialization standard? I first saw this form of initialization in a WinAPI tutorial from msdn.
|
The empty braces form of initialization is standard in C++ (it's permitted explicitly by the grammar). SeeC Static Array Initialization - how verbose do I need to be?for more details if you're interested.
I assume that it was added to C++ because it might not be appropriate for a 0 value to be used for a default init value in all situations.
|
I'd like to know if my program is accessing NULL pointers or stale memory.
The backtrace looks like this:
```
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x2b0fa4c8 (LWP 1333)]
0x299a6ad4 in pthread_mutex_lock () from /lib/libpthread.so.0
(gdb) bt
#0 0x299a6ad4 in pthread_mutex_lock () from /lib/libpthread.so.0
#1 0x0058e900 in ?? ()
```
|
With GDB 7 and higher, you can examine the$_siginfostructure that is filled out when the signal occurs, and determine the faulting address:
```
(gdb) p $_siginfo._sifields._sigfault.si_addr
```
If it shows(void *) 0x0(or a small number) then you have a NULL pointer dereference.
|
What's the simplest, but efficient compression algorithm?
Deflate, lzma, etc. aren't valid options. I need something that compiles really small, like: RLE, LZX, Huffman, etc..
Note: The data is 95% ASCII textEdit: Data is ~20kb at the moment, but i expect it to grow up to 1mb
Edit2:Other interesting optionssmazhttps://github.com/antirez/smazFastLZhttp://fastlz.org/
|
It sounds likeLZOwas designed to meet your requirements:
Decompression is simple andveryfast.Requires no memory for decompression.Compression is pretty fast.
|
What am I doing wrong here, I can't get the result of this division:
aspectRatio = backingWidth / backingHeight;
I've thought I might try casting to (GLfloat) but that didn't do anything. As I step through the code I see that aspectRatio is 0 after the operation, while backingWidth is clearly 768 and backingHeight is 1029.
Here are the types:
```
GLfloat aspectRatio;
```
and
```
// The pixel dimensions of the CAEAGLLayer
GLint backingWidth;
GLint backingHeight;
```
It must be something basic I'm doing wrong here..
|
You need to cast either of the values to a floating point type, otherwise the division itself is made using integers:
```
aspectRatio = (GLfloat) backingWidth / backingHeight;
```
|
At some places in my code, I print debug messages like this:
```
int ret = getLinkSpeed(device.getSysName(), linkSpeed);
if (ret < 0)
{
logDebug("Failed to obtain port speed for this device. Error: " + std::string(strerror(errno)));
}
```
From thedocumentationit is not entirely clear if strerror will return 0 under certain conditions (which would cause my code to crash). Does anyone know if it's safe?
|
Why not write a function to do this:
```
string ErrStr() {
char * e = strerror(errno);
return e ? e : "";
}
```
This is easy to use, self-documenting, can be adapted to reformat the output and covers the possibility that strerror() might return NULL (I don't know if it can).
|
how to implement the string handling functions. is it necessary to include any libraries. give example on string concatenation
```
main()
{
char a,b
a='A';
b='B';
strcat(b,a);
printf("a:%s b:%s",a,b);
}
```
|
Thechartype only holds a single character. To hold a string, you need an array of characters. In C, arrays are fixed in size, so the programmer must ensure that a character array has enough space to hold the string you want to put in it.
```
#include <stdio.h> //for printf
#include <string.h> //for strncat
#define A_SIZE 10
int main(void)
{
char a[A_SIZE] = "A";
char b[] = "B";
strncat(a, b, A_SIZE - strlen(a) - 1);
printf("a:%s b:%s\n", a, b);
}
```
|
Looks like linux doesnt implement pthread_suspend and continue, but I really need em.
I have tried cond_wait, but it is too slow. The work being threaded mostly executes in 50us but occasionally executes upwards of 500ms. The problem with cond_wait is two-fold. The mutex locking is taking comparable times to the micro second executions and I don't need locking. Second, I have many worker threads and I don't really want to make N condition variables when they need to be woken up.
I know exactly which thread is waiting for which work and could just pthread_continue that thread. A thread knows when there is no more work and can easily pthread_suspend itself. This would use no locking, avoid the stampede, and be faster. Problem is....no pthread_suspend or _continue.
Any ideas?
|
Make the thread wait for a specific signal.
Usepthread_sigmaskandsigwait.
|
I'm experimenting with a piece of C code. Can anyone tell me why is VC 9.0 with SP1 crashing for me? Oh, and the code is meant to be an example used in a discussion why something like
```
void main (void)
```
is evil.
```
struct foo { int i; double d; } main (double argc, struct foo argv)
{
struct foo a;
a.d=0;
a.i=0;
return a.i;
}
```
If I put
```
return a;
```
compiler doesn't crash.
|
The code gives undefined behavior. This doesn't require the compiler to crash, it just says you've basically broken the rules, so the compiler hasn't done anything wrong, no matter what happens.
Edit: that said, as a quality of implementation issue, it's absolutely true that there's basically never an excuse for the compiler to crash -- reasonably speaking, it should always exit normally, no matter what data you feed it.
|
Lets say I have 4 verticies and their texture coordinates. How could I then figure out the texture coords of a 5th vertex?
Thanks
say I have:
```
v1 = (0,0) tex coord(1,0)
v2....
v3...
v4...
v5 = (15,15) tex coord = ??
```
yea linear interpolation I suppose,
To figure out the coords I do:
```
vec.x / polywidth;
vec.y / polyheight;
```
|
texture mapping is about mapping a 2d space to your 3d model. There is no generic way to extrapolate texture coordinates, because those completely depend on how you want to map your texture to your surface. More to the point, there are many possible texture coordinates, that will map a different part of your texture to your mesh.
Now... If your mesh is a regular 2D grid (a special case), on which you want to map a texture uniformly (another special case), then yeah, linear interpolation of the texture coordinates based on the vertex positions would work.
|
I have a function which writes a 32-bit value to a buffer, and auint64_ton the stack. Is the following code a sane way to store it?
```
uint64_t size = 0;
// ...
getBytes((uint32_t*)&size+0x1);
```
I'm assuming that this would be the canonical, safe style:
```
uint64_t size = 0;
// ...
uint32_t smallSize;
getBytes(&smallSize);
size = smallSize;
```
|
No. It works correctly only on big-endian machines. And assuming a particular byte order - without even checking it first - is not sane.
Even if you are sure that your program runs only on big-endian machines right now, you'll never know whether it might have to run on a little-endian machine in the future. (I'm writing this on a computer made by a company which used big-endian processors for decades, then switched to little-endian processors a couple years ago, and is now also quite successful with bi-endian processors in certain devices ;-))
|
I'm using unix system() calls to gunzip and gzip files. With very large files sometimes (i.e. on the cluster compute node) these get aborted, while other times (i.e. on the login nodes) they go through. Is there some soft limit on the time a system call may take? What else could it be?
|
The calling thread should block indefinitely until the task you initiated with system() completes. If what you are observing is that the call returns and the file operation as not completed it is an indication that the spawned operation failed for some reason.
What does the return value indicate?
|
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 answered with facts and citations.Closed3 years ago.Improve this question
Recently came acrosspidgin. Its great, and does what I want, but I am not too keen on the GPL license. Other any alternatives, with less restrictive licenses?
I would prefer the library to be C or C++, as I am most familiar with those languages, but a an IM library implemented in python would be interesting too.
|
Take a look at kde'skopete. The chat client itself is still GPL but it's underlying library libkopete is LGPL. So you could link with it pretty freely.
|
Is there an API that will delete all the values under a specific registry key?
for example, I have the following key
HKEY_CURRENT_USER\Software\MyCompany\Program\Myconfig
under it I have
(Default)SomeValSomeOtherValYetSomeOtherVat...
There might be 10, 20, 100 values there. It depends what you set on the application.
Is there a way in C to delete them all without having to iterate one by one and delete them?
Thanks, code is appreciated.
|
TheSHDeleteKeyfunction from Shlwapi.lib does what you want.
When you only need this on Vista and later OS versions, you can useRegDeleteTree
|
Given the following structure:
```
struct nmslist_elem_s {
nmptr data;
struct nmslist_elem_s *next;
};
typedef struct nmslist_elem_s nmslist_elem;
```
Where:
```
typedef void* nmptr;
```
Is it possible to write a MACRO that retrieves the data from the element and cast it to the right type:
MACRO(type, element)that expands to*((type*)element->data).
For example for int, I would need something like this:*((int*)(element->data)).
Later edit:
Yes they work, I was 'eating' some "(" and ")".
This works:
```
#define NMSLIST_DATA(type,elem) (*((type*)((elem)->data)))
#define NMSLIST_DATA_REF(type,elem) ((type*)((elem)->data))
```
|
```
#define RETRIEVE(type, element) *((type*)((element)->data))
RETRIEVE(int, nmptr)
// expands to
*((int*)((nmptr)->data))
```
(untested, but it should work)
|
anyone has an idea how to?
|
I suggest FindFirstFile() and FindNextFile().
Docs with nice example -http://msdn.microsoft.com/en-us/library/aa364418%28VS.85%29.aspx
|
How to search fast in a non-sorted array? I am unable to think of any other search mechanism apart from linear search.
Any pointers will be helpful.
|
Yes, without sorting the data a linear search is about as good as you can do.
|
```
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,0};
printf("a = %u , &a = %u\n",a,&a);
printf("a+1 = %u , &a+1 = %u\n",a+1,&a+1);
}
```
how a and &a are internally interpreted?
|
Both statements print out addresses and are probably meant to explain pointer arithmetic.
aand&aare NOT the same, they have different types, but hold the same memory address.
&ais of typeint (*)[10](which acts like a pointer to an array)ais of typeint [10](which acts like a pointer to a single element)
So when you add 1 keep those types in mind. The pointer will be offset by the size of the type that the address contains.a+1offsets by the size of int, i.e. to the second element in the array.&a+1offsets completely past the whole array.
|
I would like to write a piece of code for inserting a number into a sorted array at the appropriate position (i.e. the array should still remain sorted after insertion)
My data structure doesn't allow duplicates.
I am planning to do something like this:
Find the right index where I should be putting this element using binary searchCreate space for this element, by moving all the elements from that index down.Put this element there.
Is there any other better way?
|
If you really have an array and not a better data structure, that's optimal. If you're flexible on the implementation, take a look atAA Trees- They're rather fast and easy to implement. Obviously, takes more space than array, and it's not worth it if the number of elements is not big enough to notice the slowness of the blit as compared to pointer magic.
|
This is sample program from "Beginning Linux Programming" book:
```
#include <stdio.h>
#include <term.h>
#include <curses.h>
#include <stdlib.h>
int main()
{
setupterm("unlisted", fileno(stdout), (int *)0);
printf("Done.\n");
exit(0);
}
```
Running it, I have this result:
```
./badterm
'unlisted': unknown terminal type.
```
According to setupterm function definition, it must return 0: "No matching entry in terminfo database". Instead of this, program terminates. Why?
|
It looks like you asked it to do so. Fromman setuptermon my machine:
If errret is null, setupterm prints an error message upon finding an
error and exits. Thus, the simplest call is:
setupterm((char *)0, 1, (int *)0);
which uses all the defaults and sends the output to stdout.
Presumably, if you want to handle any error return yourself, you must supply a non-NULL pointer value for theerrret(third) parameter.
|
I am new to OpenCV and I have only Tiny C compiler configured on my Windows XP machine. Can I use this tiny C compiler to compile opencv programs for image manipulations. I have alredy installed python2.6 and opencv2.0 on my windows xp pc. If we can compile how can we do that? I tried on net but found nothing of use. Please help.
Edit:If not possible in Tiny C compiler then please suggest any links for easily available opencv compatible c compilers for windows.
|
I think try it.
If it doesn't work, theOpenCV Install Guidesays:
C/C++ compiler (OpenCV is known to work with VS2005, VS2008,
including Express Editions, and MinGW on Windows, GCC 4.x on Linux, MacOSX and other Unix-like systems).
Visual Studio
MinGW
|
How can I convert afloatvalue tochar*inClanguage?
|
```
char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);
if (ret < 0) {
return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
/* Result was truncated - resize the buffer and retry.
}
```
That will store the string representation ofmyFloatinmyCharPointer. Make sure that the string is large enough to hold it, though.
snprintfis a better option thansprintfas it guarantees it will never write past the size of the buffer you supply in argument 2.
|
Converting a C++ lib to ANSI C and it seems like though ANSI C doesn't support default values for function variables or am I mistaken?
What I want is something like
```
int funcName(int foo, bar* = NULL);
```
Also, is function overloading possible in ANSI C?
Would need
```
const char* foo_property(foo_t* /* this */, int /* property_number*/);
const char* foo_property(foo_t* /* this */, const char* /* key */, int /* iter */);
```
Could of course just name them differently but being used to C++ I kinda used to function overloading.
|
No, Standard C does not support either. Why do you feel you need to convert your C++ code to C? That could get quite tricky - I'd have thought writing wrappers would be the way to go, if your C++ must be callable from C.
|
I am using Ubuntu and I want to read the version of its kernel. I found a file named version in /proc/ that records the version of the current kernel.
If I dont want to read file, is there any other way, like built-in function in C, that I can read the version in C?
Thanks
|
You can use theuname()system call.
|
I have following file:test_network.pcap: tcpdump capture file (little-endian) - version 2.4 (Ethernet, capture length 65535)I know that in this file are few video streams.
How do I extract them?
[The file is~180 GB]
|
Use a Pcap library (libpcap,WinPcap,Pcap.Net)Extract the TCP over IP over Ethernet.Reconstruct the TCP stream (seeReconstructing data from PCAP sniff).Save the TCP stream data to a file.
Try some Pcap TCP reconstruction tools:
http://www.codeproject.com/KB/IP/TcpRecon.aspx
http://code.google.com/p/pcap-reconst/
|
GDI+ makes use of WCHAR instead of what the WinAPI allows which is CHAR. Usually I can do:
```
char *str = "C:/x.bmp";
```
but how do I do this for wchar? I can't juse do
```
wchar_t *file = "C:/x.bmp";
```
Thanks
|
```
wchar_t *file = L"C:/x.bmp";
```
L introduces a wide string.
In Windows, it's customary to use macros that behave differently according to some preprocessor definitions. Seehttp://msdn.microsoft.com/en-us/library/c426s321(VS.71).aspx
You would write:
```
_TCHAR *file = _TEXT("C:/x.bmp");
```
|
I have the following code snippet. This is a c file in visual studio 2010. If i try to compile this with the line: int hello = 10; commented out it will compile just fine. If I comment that line in it will not compile. Am I missing something or should I not be using Visual Studio 2010 to compile C code. If this is a Visual Studio problem can anyone recommend a easy to use IDE / Compiler that I can for C.
Thank You
```
int* x = (int*) calloc(1, sizeof(int));
*x = 5;
//int hello = 10;
printf("Hello World! %i", *x);
getchar();
```
|
You can't have declarations (likeint hello = 10;) after non-declarations (like*x = 5;) in C89, unlike C99 or C++.
MSVC 2010 still does not support C99.
|
Does C support inheritance? If so, is it by usingstructs since classes are not defined in C?
|
Yes, it does. Seehttp://gcc.gnu.org/ml/gcc/2010-05/msg00725.html. See Axel-Tobias Schreiner's bookObject-Oriented Programming with ANSI C. There's an English translation of it available.
Also, seeObject-orientation in CandHow can Inheritance be modelled using C?.
|
I'm playing with C and I've run into this error:
```
#include <stdio.h>
int main ()
{
char* foo;
scanf("%s", foo);
printf("entered %s", foo);
return 0;
}
```
scanftakes pointer,foois pointer, yet I get bus error. How can I make it work?
|
You never initializefoo, so it points to a more or less random location in memory. Either allocate it on the stack.
```
char foo[10];
```
Or malloc it on the heap:
```
char *foo = (char *)malloc(10 * sizeof(char));
```
But if you malloc, don't forget to free().
And watch out for buffer overflows; if something takes in a buffer but no maximum size, be very careful. You can specify a maximum length forscanfby doing%9s, for instance.scanfwill not account for the terminating null, though, so you need to pass one less than the length of your buffer.
|
I was reading that memcpy takes the number of bytes from a source location and adds it to a destination location. Does this mean that memcpy could possibly change datatype entirely ??
```
memcpy(DoubleOne, CharTwo, strlen(CharTwo));
```
considering that both values are empty still.
|
Yes,memcpydoesn't care about the types. (It converts both its parameters to void pointers anyway)
It doesn't "change datatype" as much as it just writeschardata into adoublearray (in your case) and hopes it makes sense.
|
Delete every 't'th (t>1) node of a single linked list. In the resultant linked list, again delete 't'th node. Repeat this till only t-1 nodes remains.
For this i have come up with:
Traverse until you reach 't'th node, delete all the nodes till the end.
Is there any efficient way other than this?. Can any one please help me out. Thanks.
|
That sounds correct, the algorithm would be O(n).
Make sure you are deleting the t'th node though too because you only want t-1 nodes to remain.
It sounds like they want you to delete 1 node at a time always the t'th one until no more t'th nodes exist. They probably want you to do them 1 at a time so you can calldeletefor C++ orfreefor C on the node you're removing.
|
I have simple from written on C/gtk+ and i have function in this appliction. I need to run this function in a separate thread from gui form. Where can i see example?
Thank you.
|
http://www.yolinux.com/TUTORIALS/GDK_Threads.html
|
I load data with function:
```
gssize g_input_stream_read (GInputStream *stream,
void *buffer, gsize count,
GCancellable *cancellable,
GError **error);
```
What is ma value of buffer parameter. How can I know what should be equal to buffer?
I make:
```
#define LOAD_BUFFER_SIZE 65536
```
But when i try to load image, only visible part of the image.
Thank you.
|
Thebufferis a pointer to the memory you have allocated to contain whatg_input_stream_readreads. It must be big enough to containcountbytes.
Could you expand this question, by showing with code samples how you are allocating the memory forbufferand how you calledg_input_stream_readexactly?
Here isdocumentation on using g_input_stream_read.
|
Let's say I had a char pointer pointing to a buffer that contained these values (in hex):
```
12 34 56 78 00 00 80 00
```
I want to modify the last two bytes to ashortvalue of 42. So I would think I would have to do something like this:
```
(short)*(pointer+6)=42;
```
The compiler doesn't complain but it does not do what I'm expecting it to do. Can someone tell me the correct way to assign the value?
|
The cast to "short" is happening after the assignment. What you want is:
```
*(short*)(pointer+6) = 42;
```
By the way, beware of aliasing issues. In this case you're probably ok since chars are assumed to be able to alias anything (edit: I stand corrected; this example breaks strict aliasing unless this data's actual type is "short"). But in general you should be very wary of cases where you are casting one pointer type to another. Google "strict aliasing" for more info.
|
I have an OpenGL scene with a top left coordinate system. When I glScale it zooms in from (0,0) the top left. I want it to zoom in from the mouse's coordinate (relative to the OGL frame). How is this done?
Thanks
|
I believe this can be done in four steps:
Find the mouse's x and y coordinates using whatever function your windowing system (i.e. GLUT or SDL) has for that, and use gluUnProject to get the object coordinates that correspond to those window coordinatesTranslate by (x,y,0) to put the origin at those coordinatesScale by your desired vector (i,j,k)Translate by (-x,-y,0) to put the origin back at the top left
|
I have this snippet of the code
```
char *str = “123”;
if(str[0] == 1) printf("Hello\n");
```
why I can't receive myHellothanks in advance!
how exactly compiler does this comparisonif(str[0] == 1)?
|
You want to do this:
```
if (str[0] == '1') ...
```
The difference is that you are comparingstr[0]to thenumber1, while my code above is comparingstr[0]to thecharacter'1'(which has ASCII value 49). Not all programming languages treat characters and numbers interchangeably in this way, but C does.
Check outASCIIfor more information about how computers map numbers to characters.
|
I need to write such a define in C/C++
```
#define scanf( fscanf(inf,
```
in order to replace eachscanf(withfscanf(inf,literary
But I do not know how...
Thanks
|
You want to use aVariadic macro.
In your case, I believe you want:
```
#define scanf(...) fscanf(inf,__VA_ARGS__)
```
|
Here is my situation. I'm creating a drawing application using OpenGL and WinAPI. My OpenGL frame has scrollbars which renders the screen and modifies GlTranslatef when it gets a scroll message. The problem is wen I get too many shapes the scrollbar is less responsive since it cannot rerender it each and every time it gets a scroll message. How could I make it so the scrollbar has priority. I want it to skip drawing if it would compromise the smoothness of the scrolling. I thought of doing rendering on a separate thread but I was told all UI things should stay on the same thread.
Thanks
|
You can measure the runtime of your draw routine. When it is greater than a threshold you decide, you should either throttle the updates or draw less (if you can).
|
I load some data from file:
```
GInputStream* input_stream;
GFile *file = g_file_new_for_path(file_path);
input_stream = g_file_read(file,generator_cancellable ,NULL);
g_input_stream_read(input_stream, buffer, sizeof (buffer),generator_cancellable,error);
```
How can i loadg_input_stream_readfunction result to the GdkPixbufLoader object?
Thank you.
|
You need to create a newGdkPixbufLoaderand pass the data you read fromGInputStreamto it:
```
GdkPixbufLoader *loader = gdk_pixbuf_loader_new ();
gint num_bytes = g_input_stream_read (input_stream, buffer, ...);
gdk_pixbuf_loader_write (loader, buffer, num_bytes, error);
```
However, this makes sense if you perform reading asynchronously or in chunks (to e.g. show a progressively loaded JPEG or PNG). If you just read all the data at once in a blocking manner, use simplergdk_pixbuf_new_from_stream().
|
Right now I have a window with horizontal ad vertical scrollbars. I use these parameters to initialize it.
```
//Set OGL Frame scroll bar
SCROLLINFO inf;
inf.cbSize = sizeof(SCROLLINFO);
inf.fMask = SIF_PAGE | SIF_POS;
inf.nPage = 20;
inf.nPos = 30;
```
It creates them in the center and I like their size, but when I scroll I multiply by 50 which creates chopiness. How could I add more resolution to the bars and still keep the same thumb size. Is there a way I can calculate the size and position of the bar based on the above parameters?
Thanks
|
Right, here's my solution even though one is already accepted.
Everytime I have issues with the windows controls I useControlspyto experiment with them. Controlspy also lists all the different messages that can be sent to the different controls. Find one that is similar to what you are trying to do and check that specific message on MSDN.
|
I just came across that ANSI(ISO) ain't allowing nesting of function..
i want to know what makes gnu c ito implement this functionality(why such need arise).If a function say(a()) is define with in another function say(b()) then
the lifetime of a() would be whole program?Will the storage for a() ll be created in a stack allocated to function b().?
|
I believehttp://en.wikipedia.org/wiki/Nested_functionanswers most of your question #1. Question #2 is addressed in more detail inhttp://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html, and question #3 inhttp://gcc.gnu.org/onlinedocs/gccint/Trampolines.html.
Edit:(Aside) The wikipedia article inexplicably leftPL/Moff its list of ALGOL-based languages which support nested functions. Ah, the good old days.
|
So a quick Google search forfflush(stdin)for clearing the input buffer reveals numerous websites warning against using it. And yet that's exactly how my CS professor taught the class to do it.
How bad is usingfflush(stdin)? Should I really abstain from using it, even though my professor is using it and it seems to work flawlessly?
|
Simple: this is undefined behavior, sincefflushis meant to be called on an output stream. This is an excerpt from the C standard:
int fflush(FILE *ostream);ostream points to an output stream or
an update stream in which the most
recent operation was not input, the
fflush function causes any unwritten
data for that stream to be delivered
to the host environment to be written
to the file; otherwise, the behavior
is undefined.
So it's not a question of "how bad" this is.fflush(stdin)is simply not portable, so you should not use it if you want your code to be portable between compilers.
|
Which configuration management tool is the best for FPGA designs, specifically Xilinx FPGA's programmed with VHDL and C for the embedded (microblaze) software?
|
There isn't a "best", but configuration control solutions that work for software will be OK for FPGAs - the flow is very similar. I use Subversion at work and git at home, andwrote a little on 'why' at my blog.
In other answers, binary files keep getting mentioned - the only binary files I deal with are compilation products (equivalent to software object and executables), so I don't keep them in the version control repository, I keep a zipfile for each release/tag that I create with all the important (and irritatingly slow to reproduce) ones in.
|
I load data with function:
```
gssize g_input_stream_read (GInputStream *stream,
void *buffer, gsize count,
GCancellable *cancellable,
GError **error);
```
What is ma value of buffer parameter. How can I know what should be equal to buffer?
I make:
```
#define LOAD_BUFFER_SIZE 65536
```
But when i try to load image, only visible part of the image.
Thank you.
|
Thebufferis a pointer to the memory you have allocated to contain whatg_input_stream_readreads. It must be big enough to containcountbytes.
Could you expand this question, by showing with code samples how you are allocating the memory forbufferand how you calledg_input_stream_readexactly?
Here isdocumentation on using g_input_stream_read.
|
Let's say I had a char pointer pointing to a buffer that contained these values (in hex):
```
12 34 56 78 00 00 80 00
```
I want to modify the last two bytes to ashortvalue of 42. So I would think I would have to do something like this:
```
(short)*(pointer+6)=42;
```
The compiler doesn't complain but it does not do what I'm expecting it to do. Can someone tell me the correct way to assign the value?
|
The cast to "short" is happening after the assignment. What you want is:
```
*(short*)(pointer+6) = 42;
```
By the way, beware of aliasing issues. In this case you're probably ok since chars are assumed to be able to alias anything (edit: I stand corrected; this example breaks strict aliasing unless this data's actual type is "short"). But in general you should be very wary of cases where you are casting one pointer type to another. Google "strict aliasing" for more info.
|
I have an OpenGL scene with a top left coordinate system. When I glScale it zooms in from (0,0) the top left. I want it to zoom in from the mouse's coordinate (relative to the OGL frame). How is this done?
Thanks
|
I believe this can be done in four steps:
Find the mouse's x and y coordinates using whatever function your windowing system (i.e. GLUT or SDL) has for that, and use gluUnProject to get the object coordinates that correspond to those window coordinatesTranslate by (x,y,0) to put the origin at those coordinatesScale by your desired vector (i,j,k)Translate by (-x,-y,0) to put the origin back at the top left
|
I have this snippet of the code
```
char *str = “123”;
if(str[0] == 1) printf("Hello\n");
```
why I can't receive myHellothanks in advance!
how exactly compiler does this comparisonif(str[0] == 1)?
|
You want to do this:
```
if (str[0] == '1') ...
```
The difference is that you are comparingstr[0]to thenumber1, while my code above is comparingstr[0]to thecharacter'1'(which has ASCII value 49). Not all programming languages treat characters and numbers interchangeably in this way, but C does.
Check outASCIIfor more information about how computers map numbers to characters.
|
I need to write such a define in C/C++
```
#define scanf( fscanf(inf,
```
in order to replace eachscanf(withfscanf(inf,literary
But I do not know how...
Thanks
|
You want to use aVariadic macro.
In your case, I believe you want:
```
#define scanf(...) fscanf(inf,__VA_ARGS__)
```
|
Here is my situation. I'm creating a drawing application using OpenGL and WinAPI. My OpenGL frame has scrollbars which renders the screen and modifies GlTranslatef when it gets a scroll message. The problem is wen I get too many shapes the scrollbar is less responsive since it cannot rerender it each and every time it gets a scroll message. How could I make it so the scrollbar has priority. I want it to skip drawing if it would compromise the smoothness of the scrolling. I thought of doing rendering on a separate thread but I was told all UI things should stay on the same thread.
Thanks
|
You can measure the runtime of your draw routine. When it is greater than a threshold you decide, you should either throttle the updates or draw less (if you can).
|
I load some data from file:
```
GInputStream* input_stream;
GFile *file = g_file_new_for_path(file_path);
input_stream = g_file_read(file,generator_cancellable ,NULL);
g_input_stream_read(input_stream, buffer, sizeof (buffer),generator_cancellable,error);
```
How can i loadg_input_stream_readfunction result to the GdkPixbufLoader object?
Thank you.
|
You need to create a newGdkPixbufLoaderand pass the data you read fromGInputStreamto it:
```
GdkPixbufLoader *loader = gdk_pixbuf_loader_new ();
gint num_bytes = g_input_stream_read (input_stream, buffer, ...);
gdk_pixbuf_loader_write (loader, buffer, num_bytes, error);
```
However, this makes sense if you perform reading asynchronously or in chunks (to e.g. show a progressively loaded JPEG or PNG). If you just read all the data at once in a blocking manner, use simplergdk_pixbuf_new_from_stream().
|
Right now I have a window with horizontal ad vertical scrollbars. I use these parameters to initialize it.
```
//Set OGL Frame scroll bar
SCROLLINFO inf;
inf.cbSize = sizeof(SCROLLINFO);
inf.fMask = SIF_PAGE | SIF_POS;
inf.nPage = 20;
inf.nPos = 30;
```
It creates them in the center and I like their size, but when I scroll I multiply by 50 which creates chopiness. How could I add more resolution to the bars and still keep the same thumb size. Is there a way I can calculate the size and position of the bar based on the above parameters?
Thanks
|
Right, here's my solution even though one is already accepted.
Everytime I have issues with the windows controls I useControlspyto experiment with them. Controlspy also lists all the different messages that can be sent to the different controls. Find one that is similar to what you are trying to do and check that specific message on MSDN.
|
I just came across that ANSI(ISO) ain't allowing nesting of function..
i want to know what makes gnu c ito implement this functionality(why such need arise).If a function say(a()) is define with in another function say(b()) then
the lifetime of a() would be whole program?Will the storage for a() ll be created in a stack allocated to function b().?
|
I believehttp://en.wikipedia.org/wiki/Nested_functionanswers most of your question #1. Question #2 is addressed in more detail inhttp://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html, and question #3 inhttp://gcc.gnu.org/onlinedocs/gccint/Trampolines.html.
Edit:(Aside) The wikipedia article inexplicably leftPL/Moff its list of ALGOL-based languages which support nested functions. Ah, the good old days.
|
So a quick Google search forfflush(stdin)for clearing the input buffer reveals numerous websites warning against using it. And yet that's exactly how my CS professor taught the class to do it.
How bad is usingfflush(stdin)? Should I really abstain from using it, even though my professor is using it and it seems to work flawlessly?
|
Simple: this is undefined behavior, sincefflushis meant to be called on an output stream. This is an excerpt from the C standard:
int fflush(FILE *ostream);ostream points to an output stream or
an update stream in which the most
recent operation was not input, the
fflush function causes any unwritten
data for that stream to be delivered
to the host environment to be written
to the file; otherwise, the behavior
is undefined.
So it's not a question of "how bad" this is.fflush(stdin)is simply not portable, so you should not use it if you want your code to be portable between compilers.
|
Which configuration management tool is the best for FPGA designs, specifically Xilinx FPGA's programmed with VHDL and C for the embedded (microblaze) software?
|
There isn't a "best", but configuration control solutions that work for software will be OK for FPGAs - the flow is very similar. I use Subversion at work and git at home, andwrote a little on 'why' at my blog.
In other answers, binary files keep getting mentioned - the only binary files I deal with are compilation products (equivalent to software object and executables), so I don't keep them in the version control repository, I keep a zipfile for each release/tag that I create with all the important (and irritatingly slow to reproduce) ones in.
|
Im trying to write a few simple macros to simplify the task of setting and clearing bits which should be a simple task however I cant seem to get them to work correctly.
```
#define SET_BIT(p,n) ((p) |= (1 << (n)))
#define CLR_BIT(p,n) ((p) &= (~(1) << (n)))
```
|
Try
```
#define CLR_BIT(p,n) ((p) &= ~((1) << (n)))
```
However for various reasons of general macro evil I would advise not using a macro. Use an inline function and pass by reference, something like this:
```
static inline void set_bit(long *x, int bitNum) {
*x |= (1L << bitNum);
}
```
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:What does ‘unsigned temp:3’ means
I just found this code in a book(was used in an example)
```
typedef struct {
unsigned int A:1;
unsigned int B:1;
unsigned int C:1;
} Stage;
```
What is the meaning of this structure definition? (theA:1;)
|
Those are Cbitfields. In compliant compilers, the combination of A B and C do not occupy more than oneint. A, B, and C occupy one bit each in the integer.
|
```
void my_cool_function()
{
obj_scene_data scene;
obj_scene_data *scene_ptr = &scene;
parse_obj_scene(scene_ptr, "test.txt");
}
```
Why would I ever create a pointer to a local variable as above if I can just do
```
void my_cool_function()
{
obj_scene_data scene;
parse_obj_scene(&scene, "test.txt");
}
```
Just in case it's relevant:
int parse_obj_scene(obj_scene_data *data_out, char *filename);
|
In the specific code you linked, there isn't really a reason.
It could be functionally necessary if you have a function taking anobj_scene_data **. You can't do&&scene, so you'd have to create a local variable before passing the address on.
|
What are these data types for? __m64, __m128,
__m256 ?
|
A quick google-search gives me:
The __m64 data type is for use with the MMX and 3DNow! intrinsicsThe __m128 data type, for use with the Streaming SIMD Extensions and Streaming SIMD Extensions 2 instructions intrinsics
Unfortunately I can't readily find what __m256 is but I suspect it is along the same lines.
Basically, data structures for MMX and similar technologies.
|
Just curious, I was told that with dll files, you can make modifications to the dll without recompiling the whole application that uses it. On the other hand .lib files need to be compiled so the code can linked to the application as one.
So I know that the .lib files are turned into machine code. but what about the dll's ?? Are they turned into machine code upon the execution of the application ??
This could probably lead to easy hacking if not used right.
|
The dlls are still machine code. They're just dynamically linked in at run time (hence then name) so (if you don't change the function signatures) you don't have to recompile your main program to use a dll after it's been changed. A static library is physically part of your executable, that's why changes there require a recompile (or really, a relink).
|
I have this code:
```
#include <stdio.h>
#include <wchar.h>
int main()
{
wchar_t *foo = L"ðħ";
wprintf(L"[%ls]\n", foo); return 0;
}
```
And when I compile it, it gives me theimplicit declaration of function ‘wprintf’warning. I know that I should link the wchar library during compilation, but how do I do that?
|
Have you tried invoking the compiler with -std=c99 ?
|
How can I make GNU Make use a different compiler without manually editing the makefile?
|
You should be able to do something like this:
```
make CC=my_compiler
```
This is assuming whoever wrote the Makefile used the variable CC.
|
How can I write an if statement which tells the program if the pointer is assigned or not?
WRONG example
```
if (*badpdr[0]==0);
```
|
You meanif (badptr==NULL)?
Note that you have to initially set your pointer to NULL when you define it or when you "unassign it" (e.g., you delete the object it refers to). Otherwise, it will contain junk and this test would fail because the value would not be a 0.
You can also do the comparison to 0 instead of NULL, there's already enough arguments on SO which is the correct form so I won't repeat them.
|
What is the C equivalent of C++
```
delete[] (char *) foo->bar;
```
Edit: I'm converting some C++ code to ANSI C. And it had:
```
typedef struct keyvalue
{
char *key;
void *value;
struct keyvalue *next;
} keyvalue_rec;
// ...
for (
ptr = this->_properties->next, last = this->_properties;
ptr!=NULL;
last = ptr, ptr = ptr->next)
{
delete[] last->key;
delete[] (char *) last->value;
delete last;
}
```
Would this do it forC?
```
free(last->key);
free(last->value);
free(last)
```
|
In C, you don't havenew; you just havemalloc(); to free memory obtained by a call tomalloc(),free()is called.
That said, why would you cast a pointer to(char*)before passing it todelete? That's almost certainly wrong: the pointer passed todeletemust be of the same type as created withnew(or, if it has class type, then of a base class with a virtual destructor).
|
Is there a difference between having the following code at the begining of program 'progX'
```
if(daemon(0, 0) == -1)
{
printf("daemon error: %s", strerror(errno));
}
```
or running 'progX' via the command: progX & 2>/dev/null 1>/dev/null 0>/dev/null
|
daemon()does several things:
Re-parents the process toinitby forking and then exiting the parent. Look in thepslist and you'll see that daemons are owned by PID 1.Callssetsid().Changes directory to/.Redirects standard in, out, and error to/dev/null.
Your redirections handle the last action but not the rest.
|
```
char in[100], *temp[10],var[10][10];
int i, n = 0,
double val[10];
var[0][]="ANS";
```
I want to assign a string to var[0][0,1,2] which is 'ANS', but does not work and i cannot figure where i am wrong about this
|
Perhaps instead using,
```
strncpy(var[0], "ANS", 3);
```
|
I am using gsoap's wsseapi plugin and would like to store hashed sha1 passwords rather than plain text. I have spent a ridiculous amount of time experimenting with various methods of hashing the plain text password for storage.
Can anyone suggest a way to hash a password so it can be later verified against a username token digest sent by the client?
I can't seem to get the client password to authenticate against my stored hash.
|
Don't roll your own crypto; use a scheme that's well known and accepted by the community, such as PBES2 (as specified byPKCS#5 v2.1). If you're in luck, you'll find a ready-made implementation of it (hint:OpenSSLprobably does).
|
I found this structure called OBJECT_ATTRIBUTE in one of the nt dll functions..I was curious to know about that structure and I went through its documentation(msdn)...In the OBJECT_ATTRIBUTE structure there is a parameter called PUNICODE_STRING objectName...As per the msdn documentation..it says that the objectName "the name of the object for which a handle is to be opened" which is actually a name or some root directory,am confused with this.Can anybody explain this term "name of the object"(root directory).what it represents.
|
This structure is used by device drivers and other kernel mode code to specify attributes of file objects. When you open a file with theNtOpenFileorIoCreateFilefunctions, you have to pass anOBJECT_ATTRIBUTESwith the name of the file.
TheObjectNamemember of the structure is simply a pointer to anUNICODE_STRINGstructure containing the file or directory name.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:How to generate a random number from within a range - C
I'm looking for something I can use in C that will give me a random number between a and b. So something like rand(50) would give me a number between 1 and 50.
|
From the comp.lang.c FAQ:How can I get random integers in a certain range?
|
i know it sounds crazy but, i just want to ask if is a compiler support multi programming language? like Delphi could also support C/C++/C# etc? if there is, please let me know. or how?
|
The GNU Compiler Collection includes
front ends for C, C++, Objective-C,
Fortran, Java, and Ada
http://gcc.gnu.org/
|
I have a function that is doing memcpy, but it's taking up an enormous amount of cycles. Is there a faster alternative/approach than using memcpy to move a piece of memory?
|
memcpyis likely to be the fastest way you can copy bytes around in memory. If you need something faster - try figuring out a way ofnotcopying things around, e.g. swap pointers only, not the data itself.
|
i am working on C source to translate to delphi but i was stuck on reading files on ftell() function, can you help me find the equivalent function in delphi?
|
If you have an object of typeFile, then you may use theFilePos()function,described here.
|
I wanted to know how I can parse an IPv6 address in C and convert it to a 128 bit value?
So a hex address like1:22:333:aaaa:b:c:d:eneeds to be converted to its 128 bit equivalent binary. The problem is the IP address could be of the type::2and its variant since they are valid IPv6 address.
The input is from the keyboard and hence is in ASCII format.
|
You can use POSIXinet_ptonto convert a string to astruct in6_addr.
```
#include <arpa/inet.h>
...
const char *ip6str = "::2";
struct in6_addr result;
if (inet_pton(AF_INET6, ip6str, &result) == 1) // success!
{
//successfully parsed string into "result"
}
else
{
//failed, perhaps not a valid representation of IPv6?
}
```
|
I'm trying to implement a simple FTP server (a variation of theEFTPprotocol) in linux. When a client connects and sends the PASV command, the server should respond with a port number, so the client can connect to that port to transmit the file. How can the server choose a port number? Do I need to iterate through all the ports from 1024 to 65535 until I find a port that the process can bind to?I know that calling bind() with 0 as the port automatically chooses the port to bind to, but then how can I know which port was chosen?
Many thanks.
|
You let the system chose one as you mention with using 0 as the port number and you callgetsockname() to retreive its address - which includes the port number.
|
Is there any C\C++ Cross-platform library for sharing data between app's?
|
Obviously the answer to your question is.. Yes there are many cross platform libs for sharing data between applications. For example Boost hasBoost Serialization, for data storage and reading, andBoost Interprocess, for in-memory data sharing.
|
I can store string of few length in char data type.
But when it exceeds its capacity what can be the alternative way to store string.
I am using char data type.
```
void setString(char* inPoints)
{
if (strcmp(mPoints, inPoints)!= ZERO) {
if (mPoints) {
free(mPoints);
}
mPoints = (char*)malloc((strlen(inPoints) + 1) * sizeof(char));
strcpy(mPoints, inPoints);
}
}
```
|
You can allocate a new, bigger array and copy the old string into it (and delete the old to prevent memory leaks), appending more characters. Or (if possible) switch to C++ string class, which makes this process easier.
|
I'm looking for an equivalent toGetTickCount()on Linux.
Presently I am using Python'stime.time()which presumably calls through togettimeofday(). My concern is that the time returned (the unix epoch), may change erratically if the clock is messed with, such as by NTP. A simple process or system wall time, that only increases positively at a constant rate would suffice.
Does any such time function in C or Python exist?
|
You can useCLOCK_MONOTONICe.g. in C:
```
struct timespec ts;
if(clock_gettime(CLOCK_MONOTONIC,&ts) != 0) {
//error
}
```
See this question for a Python way -How do I get monotonic time durations in python?
|
I am developing a computer vision program using OpenCV (IDE = devcpp). I am able to get the hand contour , move cursor position according to our our hand. i want to implement right click functionality .Please help me with it .
i am using event SetCursorPos(x,y) to set the cursor position on the screen.
is there any simple function to implement rightclick the same way .??
|
Maybe this will help:http://www.codeguru.com/forum/showthread.php?t=377394
```
void RightClick ( )
{
INPUT Input={0};
// right down
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
::SendInput(1,&Input,sizeof(INPUT));
// right up
::ZeroMemory(&Input,sizeof(INPUT));
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
::SendInput(1,&Input,sizeof(INPUT));
}
```
And to use:
```
RightClick();
```
The link shows examples for left clicking, mouse move, etc. too.
|
Is there a way in Emacs to find out which other places in the code call a specific function? With my current setup (GNU emacs 23.1.1, C codebase), I normally have to search the whole codebase for the function name to see which other functions call it. It would be nice if I could efficiently display all the names of the functions that call this specific function that I'm looking at.
|
You can usesemantic-symreffunction (C-c , G) from CEDET package. It can use GNU Global or CTags databases to find callers if they exist. It could also parse sources to find occurrences.
|
I have a thread that sets a value to true when it is done. Until then I wait:
```
while(1)
{
if(done[0] == true)
{
break;
}
}
```
This code works just fine in Debug but in Release it stays in the loop forever even though the debugger clearly says that it is true and not false.
Why would this not work?
Thanks
|
This is symptomatic of not markingdoneasvolatile.
Withoutvolatilethe optimising compiler can cache the value in a register.
e.g.
```
private volatile int i;
```
|
Basically I have a class and it is instincable (not static). Basically I want the class to be able to generate its own threads and manage its own stuff. I don't want to make a global callback for each instance I make, this doesnt seem clean and proper to me. What is the proper way of doing what I want. If I try to pass the threadproc to CreateThread and it is the proc from a class instance the compiler says I cannot do this. What is the best way of achieving what I want? Thanks
|
```
class Obj
{
static ULONG WINAPI ThreadProc(void* p)
{
Obj* pThis = (Obj*)p;
... do stuff ...
return 0;
}
void StartMemberThread()
{
CreateThread(... ThreadProc, this, ... );
}
};
```
Trickiest part is making sure the thread doesn't use pThis after the object goes away.
|
Is there a way to useset_activeon a gtkCheckButton but without the user being able to press/toggle the said button?
In other words, I want to programmatically control theactive stateof the CheckButton but I don't want the user to be able to change it.
|
The "active" property of the gtk.ToggleButtoncombined with the "sensitive" property of the gtk.Widgetshould do what you want. You should just be able to do
```
checkbox1.set_sensitive(False)
checkbox1.set_active(True)
```
...to check it and have it remain unchangeable.
|
Is there a signal that is emitted when a window/dialog ispresentedin GTK+?
Example: when issuing this command to the GTK widget dialog:
dialog.present()
is there a resulting signal? Or is there any signal that denotes the "showing" of a window/dialog?
|
Thenotify::visiblesignal will be emitted whenever the visibility state changes, i.e. the window is shown or hidden. Theshowsignal isn't documented but from the source it appears that it is an action signal; you can call it yourself using
```
dialog.emit('show')
```
and the widget will show itself, apparentlywithouttriggering thenotify::visiblesignal.
|
I want:
```
111 || 100 ---> 111, not 1
100 && 100 ---> 100, not 1
101 && 010 ---> 000, not 0
```
Broken code
```
#include <stdio.h>
main(void){
string hexa = 0xff;
strig hexa2 = 0xf1;
// CONVERT TO INT??? cast
int hexa3 = hexa || hexa2;
int hexa4 = hexa && hexa2;
puts(hexa3);
puts(hexa4);
}
```
|
You want the bitwise operators (|,&) instead of the logical operators (||,&&):
```
110 | 011 --> 111
110 & 101 --> 100
```
As for your broken code, you also have incorrect types forhexaandhexbwhich should both be numeric types:
```
int hexa = 0xff;
int hexa2 = 0xf1;
```
Finally, to output an integer, you would useprintfto format them:
```
printf("hexa3 = 0x%08x\n", heaxa3); // display as 8 digit, 0 padded hex
```
|
I'm trying to make a script that can generate a kind of chat client in cygwin on windows but I don't have a clue how to start, I saw something like gtk+ but how do I get that inside of cygwin, and what have I to do after that?
|
Cygwin has anassortmentof gtk packages. After that you need to read some documentation and learn how to use the toolkit to make your program.Hereis a tutorial to get you started.
|
I was wondering if it was safe to make GL calls with multiple threads. Basically I'm using a GLUtesselator and was wondering if I could divide the objects to draw into 4 and assign a thread to each one.
I'm just wondering if this would cause trouble since the tesselator uses callback functions. Can 2 threads run the same callback at the same time as long as that callback does not access ant global variables?
Are there also other ways I could optimize OpenGL drawing using multithreading?
|
Reading between the lines in your question, the answer is no. You can't make calls to thesameGL context from different threads concurrently. You can find more details in theParallel OpenGL FAQ.
|
I have a short integer variable called s_int that holds value = 2
```
unsighed short s_int = 2;
```
I want to copy this number to a char array to the first and second position of a char array.
Let's say we havechar buffer[10];. We want the two bytes ofs_intto be copied atbuffer[0]andbuffer[1].
How can I do it?
|
The usual way to do this would be with the bitwise operators to slice and dice it, a byte at a time:
```
b[0] = si & 0xff;
b[1] = (si >> 8) & 0xff;
```
though this should really be done into anunsigned char, not a plaincharas they are signed on most systems.
Storing larger integers can be done in a similar way, or with a loop.
|
In theWindows Driver Kit (WDK)there are some driver code samples written in pure C, but sprinkled with some try-catch-finally constructs. Does someone know their semantics ? Thank you microsoft for your great tools and standards compliance.
Code extract fromsome_file.c:
```
try {
...
if (!NT_SUCCESS( status )) {
leave; // ???
}
...
} finally {
...
}
try {
...
} except( EXCEPTION_EXECUTE_HANDLER ) {
...
}
```
|
The try/except handling in the WDK follows the SEH model used throughout windows. Notice that you can continue after catching an exception.
This model predated C++, so the C++ standard is not the same as the exception model used by Win32.
PS: C does not have exception handling, so SEH is a non-standard extension to C.
SEH exception handling in the MSDN
Introduction to SEH
|
I have assign the value of a member variable as under:
```
myValue = (char*)malloc(strlen(inValue) * sizeof(char));
strcpy(mValue, inValue);
```
while assigning it the value was proper as(taking printf output):
```
http://www.w3.org/2001/XMLSchema
```
But, when i get its value after wards i get it as:
```
http://www.w3.org/2001/XMLSchema(!
```
What could be the problem for this issue
|
strlen() returns up to but not including the terminating NUL, so you will need to add 1 to its return in your malloc(). myValue thus ends up unterminated.
```
myValue = malloc((strlen(inValue) + 1) * sizeof(char));
```
|
Suppose I have One set of numbers i.e
{1, 6, 3, 5, 7, 9}
I want to Generate Random number from this set of number only i.e. a Generated number should be random and should be from these number({1, 6, 3, 5, 7, 9}) only.
standard C/C++ function will also do...
|
arc4random%(set count) = a random index.
|
i have a byte array. Now i need to know the count of appearances of a bit pattern which length is N.
For example, my byte array is "00100100 10010010" and the pattern is "001". here N=3, and the count is 5.
Dealing with bits is always my weak side.
|
You could always XOR the first N bits and if you get 0 as a result you have a match. Then shift the searched bit "stream" one bit to the left and repeat. That is assuming you want to get matches if those sub-patterns overlap. Otherwise you should shift by pattern length on match.
|
I have to shift the int one place to the right and return it
In Java i can just return n >> 1;
Is this possible in C?
The method we were given is as follows
```
// Return n after a right circular 1-bit shift
unsigned int right_circular_shift_1(unsigned int n) {
```
|
C does not have a circular shift, so I guess the exercise is to implement it. The way to do this for a left circular shift is to:
```
- get the current leftmost bit and save it
- shift the number leftwards by one
- or the saved bit in at the rightmost bit position
```
For a right circular shift:
```
- get the current rightmost bit and save it
- shift the number rightwards by one
- or the saved bit in at the leftmost bit position
```
|
I have to insert a string into a sqlite data base
my command ..
```
Err=sqlite_exec(DB, "create table tbl5(TEXT varchar(100));", xCallback, (void*)"First Test", &ErrMsg);
Err=sqlite_exec(DB, "insert into tbl5 values ('some string');", xCallback, (void*)"First Test", &ErrMsg);
```
works fine but when I want to puts="some string"ie
```
Err=sqlite_exec(DB, "insert into tbl5 values (s);", xCallback, (void*)"First Test", &ErrMsg);
```
then this is not working so how to add variable then It is not working so how to insert variable in sqlite database
thank u
|
Don't usesprintf()butsqlite3_mprintf().Hereis the documentation.
```
char s[20] = "some string";
char* query = sqlite3_mprintf("insert into tbl5 values ('%q');", s);
```
Otherwise you have a risk ofSQL injection.
The resulting query string should be freed usingsqlite3_free().
Also note the'%q'instead of the usual'%s'.
|
I have written some C/C++ extension modules for PHP, using the 'old fashioned way' - i.e. by using the manual way (as described by Sarah Golemon in her book).
This is too fiddly for me, and since I am lazy, and would like to automate as much as possible. Also, I have used SWIG now to generate extensions to Python, and I am getting to like using it quite a lot.
I am thinking of using SWIG to generate my future PHP extensions. I am using PHP v5.2 (and above) on my production servers.
My questions are:
Is SWIG PHP interface stable yet (i.e. ready for production)?If you answered yes to question 1 -areYOUusing it inYOURproduction site?Are there any 'gotchas' I need to be aware of when creating PHP extension ,modules using SWIG?
|
I have extensively used SWIG in production environment for generating PHP wrappers. Its pretty stable and can be used without issues.
|
So I have some temp data in my program (in RAM). I want to somehow make it seem as it is a file (for example for sending it into another program which takes a file link as argument)?
Is it possible?
How to do such thing?
|
Why not simply write the file to disk? If writing to disk is too slow, you can pass theFILE_ATTRIBUTE_TEMPORARYflag toCreateFileto keep the data in cache (and avoid writing it to the physical device).
Sometimes the obvious solutions are the best...
|
I need to write a C program that will allow me to read/write files that are owned by root. However, I can only run the code under another user. I have the root password, but there are no "sudo" or "su" commands on the system, so I have no way of accessing the root account (there are practically no shell commands whatsoever, actually). I don't know a whole lot about UNIX permissions, so I don't know whether or not it is actually possible to do this without exploiting the system in some way or running a program owned by root itself (with +s or whatever). Any advice?
Thanks!
P.S. No, this isn't anything malicious, this is on an iPhone.
|
Under the UNIX permissions system, you need to run a file owned by root itself that's marked setuid-root (+s, as you said) or communicate with some process that is already running as root.
If there is no such file, you are out of luck.
|
Disclaimer, I not do anything in particular with regards this question, just curious.
Is it possible to take address of instruction or block in C? in essence, is there jump equivalent in C?
for example:
```
void function() {
int k;
{ // is a possible to go to this address from arbitrary point in code?
int i, j;
k += j+i;
}
}
```
thank you
|
I think the closest you can come using standard techniques issetjmpandlongjump. They won't get you access to the actual address though, because thejmp_bufobject is opaque.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.