question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
In C I have a pointer that is declared volatile and initialized null.
```
void* volatile pvoid;
```
Thread 1 is occasionally reading the pointer value to check if it is non-null. Thread 1 will not set the value of the pointer.
Thread 2 will set the value of a pointer just once.
I believe I can get away without usi... |
To make it thread safe, you have to make atomic reads/writes to the variable, it being volatile is not safe in all timing situations. Under Win32 there are the Interlocked functions, under Linux you canbuild it yourself with assemblyif you do not want to use the heavy weight mutexes and conditional variables.
If you ... |
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... |
If you like to learn by example then you may find this code useful. It's a Windows toolbar wrapper class I created some time ago. It's somewhat advanced though because it uses Custom Draw.
WindowsToolbar.hWindowsToolbar.cppWindowsToolbarItem.hWindowsToolbarItem.cpp
|
gcc 4.4.3
c89
I have the following string
```
sip:12387654345443222118765@xxx.xxx.xxx.xxx
```
How can I extract just the number? I just want the number.
```
12387654345443222118765
```
Many thanks for any advice,
|
There are lots of ways to do it, if the string is well-formatted you could usestrchr()to search for the:and usestrchr()again to search for the@and take everything in between.
Here is another method that looks for a continuous sequence of digits:
```
char *start = sipStr + strcspn(sipStr, "0123456789");
int len = str... |
Primary goal is to learn from a popular web server codebase (implemented in C) with priority given to structure/design instead of neat tricks throughout the code.
I didn't include Apache since its code base is an order of magnitude larger than the two mentioned.
|
Ngxinx might just be the best straight-c code-base I have encountered. I have read large chunks of Apache, and I always came out feeling unclean, it is a monolithic mess.
You will not just learn about web-servers by exploring Nginx, but pretty much the best practises for writing networked software under Unix and stra... |
Can anyone explain what I'm doing wrong here to not get 11 as my output?
```
void foo {
int *n = malloc(sizeof(int));
*n = 10;
n++;
printf("%d", *n)
}
```
|
n++increments the pointern, not the integer pointed to byn. To increment the integer, you need to dereference the pointer and then increment the result of that:
```
(*n)++;
```
|
What are some data structures that help me storing and calculating the factorial for numbers with more than 50 digits?
|
Try anArbitrary Precisioninteger library likeGMPorBigDigits.
|
Some laptops have a trackpad that can do horizontal scrolling as well as vertical (WM_MOUSEWHEEL), and some desktop mice have ability to tilt their wheels.
How can I handle horizontal scrolling from a trackpad or mouse wheel?
|
WM_MOUSEHWHEELis sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated, and is also useful for horizontal scrolling from a trackpad's horizontal scrolling control
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Can you write object oriented code in C?
I'm wondering if it's possible to use strict ANSI C as a object oriented language. And if it's possible, how do I make a class in ANSI C. Allthough the language isn't designed for OO, I'm really eag... |
C doesn't have direct support for OO via classes, but you can easily emulate it.
The basics of how to do this is that you can make a struct which holds your data members and an associated list of functions which takes a pointer to that struct as it's first parameter.
More information
|
In the following piece of code,
```
#include<stdio.h>
typedef struct {
int bit1:1;
int bit3:4;
int bit4:4;
} node;
int main(){
node n,n1,n2,ff[10];
printf("%d\n",sizeof(node));
return 0;
}
```
How do I predict the size of the structure?
|
You cannot predict it without knowing the compiler and the target platform it compiles to.
|
How can I retrieve uptime under linux using C? (without using popen and/or /proc)
Thanks
|
Viatopor viauptime, but I don't know about any syscall, someone will for sure :)
uptimeshould be rather easy to parse.
Just stumbled into this:
```
#include <sys/sysinfo.h>
struct sysinfo info;
sysinfo(&info);
printf("Uptime = %ld\n", info.uptime);
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
take a look atiaxmodem
|
Hey there, I have the following code:
```
sVal = analogRead(potPin); // read the value from the sensor
valMin = min(sVal, 1);
valMax = max(sVal, 128);
constrain(sVal,valMin,valMax);
itoa(sVal, res, 10);
println(res);
println(" ");
delay(150);
clearScreen();
```
Now for some reason, the output on ... |
Your code indicates a lack of understanding of the min, max and constrain functions. I suggest you read the documentation more carefully.
In the meantime, here is what Ithinkyou're after:
```
sVal = analogRead(potPin);
sVal = sVal / 8 + 1; //scale value [0.. 1023] to [1.. 128]
itoa(sVal, res, 10);
println(res);
pri... |
For Example:
If I need to read a multiple line input like(and I dont know How many lines would be there!!):
1 20
2 31
3 41
I am using something like
```
int main()
{
string line;
while(getline(cin,line) != NULL)
{
// some code
// some code
}
}
```
Now the program never stops- i.e al... |
Just test the variablelinefor empty each time you read a line. If the use presses enter with no other data, thenlinewill be empty.
```
#include <iostream>
#include <string>
using std::cin;
using std::getline;
using std::string;
int main(int argc, char *argv[]) {
string line;
while (true) {
getlin... |
In javascript I am used to just being able to pick any character from a string like "exm[2]" and it would return to me the third character in a string. In C is there a way to do that or something without a function that requires a buffer?
|
Since in C "strings" are just character arrays, you can do the same there, too:
```
char* foo = "Hello World";
printf("%c", foo[4]); // prints o
```
More to the point, a "string" is just a pointer pointing to the first element of an array of characters ending with a zero character ('\0'). String functions just itera... |
Is there a Cocoa class has similar functionality to enumerated values from C? I know that I can just use enums in Cocoa, but what if I want to put an enum in an NSArray (which only accepts objects)?
|
An enum is just an integer type - you can wrap it inNSNumberto put it in anNSArray.
|
Is there any way to write log(base 2) function?
The C language has 2 built in function -->>
1.logwhich is base e.
2.log10base 10;
But I need log function of base 2.How to calculate this.
|
Simple math:
log2(x) = logy(x) / logy(2)
whereycan be anything, which for standard log functions is either 10 ore.
|
in the configuration file i have entries similar to this one:
filepath = c:\Program Files\some value
Where the path can contain spaces and there are no quotes on that string. I tried parsing this with strtok like:
```
char *option;
char *value;
value = strtok(line, " =");
strcpy(option, value);
value = strtok(NULL... |
Remove the space in the delimiter:
```
value = strtok(line, "=");
```
|
Is it possible to determine the throughput of an application on a processor from the cycle counts (Processor instruction cycles) consumed by the application ? If yes, how to calculate it ?
|
If the process is entirely CPU bound, then you divide the processor speed by the number of cycles to get the throughput.
In reality, few processes are entirely CPU bound though, in which case you have to take other factors (disk speed, memory speed, serialization, etc.) into account.
|
Supposing that memory is not an issue does targeting a 64 bit OS make a C/C++ Windows console application run faster?
Update: Prompted by a few comments/answers the application involves statistical algorithms (e.g., linear algebra, random number draws etc).
|
Replying mostly to the edit, not the original question: I've ported one application that's heavy on statistics and (especially) linear algebra to run as 64-bit code. For that code, the effort was minimal, and we got about a 3:1 improvement in speed.
I suspect that the majority of the notion that there often won't be ... |
During the various stages of compilation in C or C++, I know that an object file gets generated (i.e., any_name.o file). What does this .o file contain? I can't open it since it's a binary file.
Could anybody please help me? Are the contents of the object file mainly dependent on the compiler which we use on Unix?
|
Object files can contain a bunch of stuff: Basically it's some or all of the list below:
Symbol NamesCompiled codeConstant data, eg. stringsImports - which symbols the compiled code references (gets fixed up by linker)Exports - which symbols the object file makes available to OTHER object files.
The linker turns a b... |
I would like to create a pseudo filesystem like /proc to access an applications configuration.
How could i achieve this or where could i find some introductory documentation about it?
|
The easiest way is to useFUSE. This is particularly easy with high-level language bindings, such asfuse-python.
|
I'm looking to construct a script that would go through an XML file. Would find specific tags in it, put them in a table and fill the table with specific tags within them. I'm using MySQL 5.1 so loadXML isn't an option and I think that ExtractData() method wont be much use either.. but I don't really know. What would ... |
Per your edit, using theMySQL client library, you would just usemysql_query()with the standardCREATE TABLEsyntax.
I'm not quite sure why you are doing it the way you are doing it, but I'm not working on whatever you are working on :)
|
I read something like pointer must be byte-aligned.
My understanding in a typical 32bit architecture... all pointers are byte aligned...No ?
Please confirm.
can there be a pointer which is not byte-aligned ?
Basically this is mentioned in a hardware reference manual for tx descriptor memory.
|
Yes, you cannot address any amount of memory smaller than a byte.
|
I have the following structure,
```
typedef struct _MainWin
{
GtkWindow parent;
GtkWidget* scroll;
GtkWidget* box;
}MainWin;
```
I have created the application main window from this structure. Now I need the main window in full screen. When I tried to call,
```
gtk_window_fullscree(G... |
What they did in the Viewnior code that you posted is to make a subclass ofGtkWindow. You have copied part of the code to do that properly, but not all of it. You should read the tutorial part of the GObject documentation on how to define new classes. You can find it onlinehere.
|
I'm relatively new toC, and am curious what this syntax means in a function declaration:
```
int DEFAULT_CC foo(void)
```
where DEFAULT_CC is probably defined somewhere else as:
```
#define DEFAULT_CC "something"
```
(I realized the previous example I had up had to do with something completely irrelevant).
|
More likely calling convention. A calling convention defines exactly how values are passed to and returned from a function. Typical values might becdeclorstdcall. For a comprehensive explanation of x86 conventions, seeWikipedia.
```
int "cc" foo(void)
```
wouldn't compile.
|
I want to print"%SomeString%"in C.
Is this correct?
```
printf("%%s%",SomeString);
```
|
No, %% outputs %, so the right syntax is:
```
printf("%%%s%%",string);
```
|
What is the correct syntax for this code:
is it:
```
printf("printf(\"\%d\",%s);", some_var);
```
or
```
printf("printf(\"%%d\",%s);", some_var);
```
Or something else?
|
The second one.%dis defined by printf, not the C language, so you need to escape it with the printf%%, not a character escape.
A more complex example with a character escape sequence:
```
printf("printf(\"%%d\\n\",%s);\n", some_var);
```
|
I need to sort a 2 dimensional array of doubles on multiple columns using either C or C++. Could someone point me to the algorithm that I should use or an existing library (perhaps boost?) that has this functionality?
I have a feeling that writing a recursive function may be the way to go but I am too lazy to write o... |
You can usestd::sort(C++) orqsort(C or C++) to perform the sorting operation. The tricky part is that you need to define a custom comparison function for comparing your rows. For example:
```
bool compareTwoRows(double* rowA, double* rowB){
return ( (rowA[0]<rowB[0]) || ((rowA[0]==rowB[0])&&(rowA[1]<rowB[1])) );... |
I'm using OpenGL and was told I should draw circles at each vertex of my outline to get smoothness. I tried this and it works great. The problem is speed. It crippled my application to draw a circle at each vertex. I'm not sure how else to fix the anomaly of my outlines other than circles, but using display lists and ... |
One (perhaps too fancy) alternative is to draw a single polygon that bounds the circle (say, a quad), and then use a fragment program to discard the fragments. This would not be entirely trivial to write, but I would bet it's the fastest way.
You would simply pass the circle parameters to the fragment program and dis... |
Is there a way to draw many filled circles using one vertex array. Is there a way to draw a circle with triangles? I basically have hundreds of circles far apart from each other that need to be drawn but I feeling calling the vertex pointer for each circle is inefficient. I'd rather make 1 call for all circles if poss... |
Take a look at Instancing, that is esp.GL_EXT_draw_instanced
For your convenience:http://www.opengl.org/registry/specs/EXT/draw_instanced.txt
(Note: This extension requires at least GeForce 8 series. As an EXT, it should be supported by ATI/Intel as well, but I do not know the requirements there - Probably hardware ... |
I'm implementing an FTP-like protocol in Linux kernel 2.4 (homework), and I was under the impression that if a file is open for writing any subsequent attempt to open it by another thread should fail, until I actually tried it and discovered it goes through.
How do I prevent this from happening?
PS: I'm using open()... |
You could keep a list of open files, and then before opening a file check to see if it has already been opened by another thread. Some issues with this approach are:
You will need to use a synchronization primitive such as a Mutex to ensure the list is thread-safe.Files will need to be removed from the list once your... |
I have a project for Linux that i've been developing for some time. Basically it's a bunch of C and H files together with a directory structure and a Makefile.
Every time I need to debug something it's so painful, I need to manually search for var. definitions, structs, etc.
Is there any good IDE out there for Linux... |
Eclipse with the CDT
CDT is pretty much Makefile based, just create an empty 'make' project then drop your files into it and refresh in eclipse then add your make targets.
Eclipse should pick stuff up from make output.
|
I am trying to identify a method for obtaining nearby wifi access points using C in Windows. I am coding in Visual Studio 2010. I have read the necessary documentation but am lacking in guidance on how to implement code that would accomplish this.
I am specifically interested in obtaining the MAC address of nearby ac... |
If C/C++, lookherein theMicrosoft NativeWifilibrary. XP SP2 or higher.1
|
My program uses sockets, what Parallel computing APIs could I use that would help me without obligating me to go from sockets to anything else?
When we are on a cluster with a special, non-socket infrastructure system this API would emulate something like sockets but using that infrastructure (so programs perform muc... |
Are you familiar with theMessage Passing Interface (MPI)? That's generally the way to go for scaling your code on parallel computers. As you noted it's not compatible with most socket APIs, but the benefits in scaling will almost certainly outweigh the costs in converting your code.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Cross Platform C library for GUI Apps?
Is there any crossplatform GUI library for C language? (I mean at least win mac lin) If there is any XML-like GUI editing model, any GUI editing crossplatform visual programms it'l be grate!)
|
Take a look at theIUP Toolkit. It is written largely in C, and is also easily bound toLua.
|
Why doesZeroMemory(), and similar calls exist in the Windows API when there are memset and related calls in the C standard library already? Which ones should I call? I can guess the answer is "depends". On what?
|
In C and C++,ZeroMemory()andmemset()are the exact same thing.
```
/* In winnt.h */
#define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length))
/* In winbase.h */
#define ZeroMemory RtlZeroMemory
```
Why useZeroMemory()then?To make it obvious.But I prefermemset()in C or C++ programs.
|
Does anyone know of a good steganography library I can use thats written in C or Objective-C? It would need to be used in a Mac OS X application.
|
My provocative answer will be that you should try to implement/learn some algorithms for image hiding/unhiding yourself. Sample algorithm of 3-bit image hiding into 24-bit image is very simple and consists of about 10 Python lines or so (of course it may be a bit more with C/Obj-C). And you will get not bad quality of... |
In C in Windows, how do I open a website using the default browser? In Mac OS X, I dosystem("open http://url");
|
You have to useShellExecute().
The C code to do that is as simple as:
```
ShellExecute(NULL, "open", "http://url", NULL, NULL, SW_SHOWNORMAL);
```
This was documented by Microsoft Knowledge Base article KB 224816, but unfortunately the article has been retired and there's no archived version of it.
|
I'v created a C header file (It's compiled), now when i compile my program it comes up with tons of errors like:
warning: null character(s) ignored
error: stray ‘\23’ in program
TheFunctions.h:1722: error: stray ‘\200’ in program
Inside the header file is simply two functions, which work in the normal c program.
Pl... |
It sounds as though you're trying to directly include a precompiled header (a binary file). When you include files via the#includepre-processor statement, those are text files, not compiled files.
Edit(now that we know what compiler it is): I don't know GCC's precompiled headers stuff well enough toanswerthis questio... |
The following code produces a "lvalue required as left operand of assignment"
```
if( c >= 'A' && c <= 'Z' || c = " " || c = ",") {
```
I assume I'm writing this wrong, what is wrong? and how would I write it correctly?
|
You should use single quotes for chars and do double equals for equality (otherwise it changes the value of c)
```
if( c >= 'A' && c <= 'Z' || c == ' ' || c == ',') {
```
Furthermore, you might consider something like this to make your boolean logic more clear:
```
if( (c >= 'A' && c <= 'Z') || c == ' ' || c == '... |
This code produces a segmentation fault during the array declaration. I'm confused as to why this happens. I intentionally selected 2000000000 as a value because it is below 2^31 and can fit into an integer variable.
```
int main()
{
int nums_size = 2000000000;
int nums[nums_size];
int i;
for(i = ... |
Well, for one thing, that's two billion integers. If you have a 32-bit address space andinthas a size of four bytes on your platform (typical for a 32-bit platform), you can't store that many integers, period.
Even still, you only have so much space available to you on the stack, which is where automatic variables a... |
What type T makes the following code compilable?
```
T f(){ return &f; }
```
I'd prefer a C answer, but I marked the question as C and C++ in case there is only an answer using templates.
|
I hope this isn't cheating (C++ only):
```
class T {
private:
T (*_func)();
public:
T(T (*func)()) : _func(func) {}
T operator()() {
return *this;
}
};
T f() { return &f; }
int main() {
f()()()()()()()();
}
```
|
Is there any way to get a pointer to the current function, maybe through gcc extensions or some other trickery?
EditI'm curious whether it is possible to get the function pointer without ever explicitly using the function's name. I thought I had a good reason for wanting this, realized that I didn't really, but am s... |
This isn't especially portable, but should work on at least some platforms (i.e., Linux and OSX, where I can check the documentation; it definitely doesn't work on Windows which lacks the API):
```
#include <dlfcn.h>
// ...
void *handle = dlopen(NULL, RTLD_LAZY);
void *thisfunction = handle ? dlsym(handle, __FUNCTIO... |
Is there any crossplatform C library for using Pixel Shading filters? to run pixel shader inside your programm, beter as native part of your programm (not like precompiled file), and better for using with abstract data - not only images
|
Does this do what you want?http://www.khronos.org/opencl/The question is not very detailed, or clear, but I think OpenCL qualifies as an answer...
|
Is there any crossplatform small\portable C image editing library?
|
TheIMlibrary is cross platform and supports a very wide array of operations on images out of the box. It can also be extended. Its close relativeCDis also occasionally useful for creating text and line art to annotate an image. Both are readily scripted fromLua.
|
If I run something like Sleep(10000), and the system clock changes during that, will the thread still sleep for 10 seconds of wall-clock time, or less or more? I.e. does the Sleep() function convert milliseconds into hardware ticks?
|
Sleep() is independent of the wall-clock time. It is based on the same timer that is used for thread scheduling.
You will mostly not sleep exactly 10 seconds though, due to the frequency of the system clock and when you actually get scheduled to run after the timeout elapses.
|
What is the best way to detect if a graphics card and compiled openGL binary supports textures which are not a power of 2 at run time?
|
You can check withglGetforARB_texture_non_power_of_twoor use GLEW.
Edit to reflect the comments:As of OpenGL 2.0 this feature is required and ARB_texture_non_power_of_two need not be defined. How to find the current version is describedhere. As Jerry points out: Depending on the GPU the feature might be implemented i... |
During the various stages of compilation in C or C++, I know that an object file gets generated (i.e., any_name.o file). What does this .o file contain? I can't open it since it's a binary file.
Could anybody please help me? Are the contents of the object file mainly dependent on the compiler which we use on Unix?
|
Object files can contain a bunch of stuff: Basically it's some or all of the list below:
Symbol NamesCompiled codeConstant data, eg. stringsImports - which symbols the compiled code references (gets fixed up by linker)Exports - which symbols the object file makes available to OTHER object files.
The linker turns a b... |
I would like to create a pseudo filesystem like /proc to access an applications configuration.
How could i achieve this or where could i find some introductory documentation about it?
|
The easiest way is to useFUSE. This is particularly easy with high-level language bindings, such asfuse-python.
|
I'm looking to construct a script that would go through an XML file. Would find specific tags in it, put them in a table and fill the table with specific tags within them. I'm using MySQL 5.1 so loadXML isn't an option and I think that ExtractData() method wont be much use either.. but I don't really know. What would ... |
Per your edit, using theMySQL client library, you would just usemysql_query()with the standardCREATE TABLEsyntax.
I'm not quite sure why you are doing it the way you are doing it, but I'm not working on whatever you are working on :)
|
I read something like pointer must be byte-aligned.
My understanding in a typical 32bit architecture... all pointers are byte aligned...No ?
Please confirm.
can there be a pointer which is not byte-aligned ?
Basically this is mentioned in a hardware reference manual for tx descriptor memory.
|
Yes, you cannot address any amount of memory smaller than a byte.
|
I have the following structure,
```
typedef struct _MainWin
{
GtkWindow parent;
GtkWidget* scroll;
GtkWidget* box;
}MainWin;
```
I have created the application main window from this structure. Now I need the main window in full screen. When I tried to call,
```
gtk_window_fullscree(G... |
What they did in the Viewnior code that you posted is to make a subclass ofGtkWindow. You have copied part of the code to do that properly, but not all of it. You should read the tutorial part of the GObject documentation on how to define new classes. You can find it onlinehere.
|
I'm relatively new toC, and am curious what this syntax means in a function declaration:
```
int DEFAULT_CC foo(void)
```
where DEFAULT_CC is probably defined somewhere else as:
```
#define DEFAULT_CC "something"
```
(I realized the previous example I had up had to do with something completely irrelevant).
|
More likely calling convention. A calling convention defines exactly how values are passed to and returned from a function. Typical values might becdeclorstdcall. For a comprehensive explanation of x86 conventions, seeWikipedia.
```
int "cc" foo(void)
```
wouldn't compile.
|
I want to print"%SomeString%"in C.
Is this correct?
```
printf("%%s%",SomeString);
```
|
No, %% outputs %, so the right syntax is:
```
printf("%%%s%%",string);
```
|
Is it possible to create a display list for Tesselated objects? If so would it be more efficient?
Thanks
|
Yes -- after tessellation you just have a bunch of triangles, which you can put in a display list about like anything else. Efficiency will depend; on nVidia display lists work quite well, but on ATI a display list is little different from multiple calls to glVertex.
If you want to assure efficiency across both, cons... |
Does mutex guarantee to execute thread in order of arriving?
that is, if, thread 2 and thread 3 arrive is waiting while thread 1 is in critical section
what exactly happen after thread 1 exit critical section if thread 2 arrive at mutex lock before thread 3, thread 2 will be allowed to enter critical section before ... |
That sort of behaviour would have to be an implementation detail of your threading library (which you didn't mention). I would guess most threading libraries don't make any such a guarantee, though. Unless the waiting threads had different priorities, of course.
|
Why is stillC99 mixed declarations and codenot used in open source C projects like theLinux kernelorGNOME?
I really like mixed declarations and code since it makes the code more readable and prevents hard to see bugs by restricting the scope of the variables to the narrowest possible. This is recommended by Googlefo... |
Youdon'tneed mixed declaration and code to limit scope. You can do:
```
{
int c;
c = 1;
{
int d = c + 1;
}
}
```
in C89. As for why these projects haven't used mixed declarations (assuming this is true), it's most likely a case of "If it ain't broke don't fix it."
|
I have enabled blur on my window. I have some edit fields and some custom controls and I would not want these to be affected by the blur, they are semi transparent as a result. How could I only blur the main window itself, not its child controls (sort of like Chrome). Thanks
|
Black is treated as transparent since good old GDI does not support alpha channel (the alpha byte in ARGB is always 0) I'm thinking you have to do some sort ofowner draw.
|
What is considered best practice when referring to a program's name? I've seen:
```
#define PROGRAM_NAME "myprog"
printf("this is %s\n", PROGRAM_NAME);
```
as well as:
```
printf("this is %s\n", argv[0]);
```
I know, that the second approach will give me./myprograther thanmyprogwhen the program is not called from$... |
The second approach is superior when you have multiple links. In *nix systems, sometimes behavior depends on how you call a program. So hard coding the program name would clearly be a problem -- it could never check that.
|
I have compared gcc assembler output of
```
do {
// some code
} while (0);
```
with
```
do {
// some code
break;
} while (1);
```
The output is equal, with or without optimization but..
It's always that way?
No experiment can prove theories, they can only show they are wrong
|
There is a slight difference:
```
do {
// code
if ( condition )
continue;
// code
break;
} while(1);
```
Will restart the loop whenconditionis true, whereas in the} while(0);version, thecontinuewill be equivalent tobreak.
If nocontinueis present, then they should produce exactly the same code.
|
Right now I'm drawing a cube with OpenGL, I'm using Windows and WGL context. I have blending enabled so my cube looks semi transparent. Basically the background == the clear color (Black). I'd like to be able to save the image in raw RGBA format which I can then make into a png. I basically want the cube to blend in w... |
Just draw the cube, setting the clear color to (0, 0, 0, 0), and save the output using glReadPixels.
|
How can i get the paths of a folder and its content. Say i have folder named MyFolder as
/tmp/MyFolder/ where it has subfolders SubFolder1, SubFolder2... and some files
|
You may take a look at theopendir()family functions.
|
How can i copy multiple char* variables into one char* at single instance operation.
say i have
char* text1 = "Hello";
char* text2 = "World";
i want to copy text1, text2 and '2' and "12345" into char* text3 in single function call.
|
```
char text3[100];
sprintf( text3, "%s%s%s%s", text1, text2, "2", "12345" );
```
|
Is it possible to access 32-bit registers in C ? If it is, how ? And if not, then is there any way to embed Assembly code in C ? I`m using the MinGW compiler, by the way.
Thanks in advance!
|
If you want to only read the register, you can simply:
```
register int ecx asm("ecx");
```
Obviously it's tied to instantiation.
Another way is using inline assembly. For example:
```
asm("movl %%ecx, %0;" : "=r" (value) : );
```
This stores theecxvalue into the variablevalue. I've already posted a similar answe... |
How can i create a temporary folder in /tmp directory.
|
Try themkdtempfunction.
```
char *tmpdir;
strcpy (template, "/tmp/myprog.XXXXXX");
tmpdir = mkdtemp (template);
if (!tmpdir) {
// Error out here
}
printf ("Temporary directory created : %s", tmpdir);
```
|
How can I get the path of home directory inMac OS XusingClanguage inXCodeeditor.
|
This should work under Linux, Unix and OS X, for Windows you need to make a slight modification.
```
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
int main(void)
{
const char *homeDir = getenv("HOME");
if (!homeDir) {
struct passwd* pwd = getpwuid(getuid());
... |
The shell command$ avrdude -c usbtinyoutputs text to stderr. I cannot read it with commmands such as head-less-more cos it is not stdout. I want the text to stdout or to a file. How can I do it in C? I have tried to solve the problem bymy last questionbut still unsolved.
|
I've not tried something like this in OpenBSD, but in at least a few *nix-like systems, you can do this usingdup2.
```
#include <unistd.h>
#include <stdio.h>
int main(void) {
fprintf(stderr, "This goes to stderr\n");
dup2(1, 2); //redirects stderr to stdout below this line.
fprintf(stderr, "This goes to ... |
```
char testStr[] = " trim this ";
char** pTestStr = &testStr;
trim(pTestStr);
int trim(char** pStr)
{
char* str = *pStr;
while(isspace(*str)) {
(*pStr)++;
str++;
}
if(*str == 0) {
return 0;
}
char *end = str + strlen(str) - 1;
while(end > str && isspace(*end))
end--;
*(end+1) = ... |
You need to maketestStrwriteable:
```
char testStr[] = " trim this ";
```
The problem is thatchar *ptr = ...hasptrpointing to the actual literal string which is in read-only memory.
By usingchar testStr[] = ...you are allocating an array and having the array initialized with the same contents as ... |
Is it possible to create a display list for Tesselated objects? If so would it be more efficient?
Thanks
|
Yes -- after tessellation you just have a bunch of triangles, which you can put in a display list about like anything else. Efficiency will depend; on nVidia display lists work quite well, but on ATI a display list is little different from multiple calls to glVertex.
If you want to assure efficiency across both, cons... |
Does mutex guarantee to execute thread in order of arriving?
that is, if, thread 2 and thread 3 arrive is waiting while thread 1 is in critical section
what exactly happen after thread 1 exit critical section if thread 2 arrive at mutex lock before thread 3, thread 2 will be allowed to enter critical section before ... |
That sort of behaviour would have to be an implementation detail of your threading library (which you didn't mention). I would guess most threading libraries don't make any such a guarantee, though. Unless the waiting threads had different priorities, of course.
|
Why is stillC99 mixed declarations and codenot used in open source C projects like theLinux kernelorGNOME?
I really like mixed declarations and code since it makes the code more readable and prevents hard to see bugs by restricting the scope of the variables to the narrowest possible. This is recommended by Googlefo... |
Youdon'tneed mixed declaration and code to limit scope. You can do:
```
{
int c;
c = 1;
{
int d = c + 1;
}
}
```
in C89. As for why these projects haven't used mixed declarations (assuming this is true), it's most likely a case of "If it ain't broke don't fix it."
|
I have enabled blur on my window. I have some edit fields and some custom controls and I would not want these to be affected by the blur, they are semi transparent as a result. How could I only blur the main window itself, not its child controls (sort of like Chrome). Thanks
|
Black is treated as transparent since good old GDI does not support alpha channel (the alpha byte in ARGB is always 0) I'm thinking you have to do some sort ofowner draw.
|
What is considered best practice when referring to a program's name? I've seen:
```
#define PROGRAM_NAME "myprog"
printf("this is %s\n", PROGRAM_NAME);
```
as well as:
```
printf("this is %s\n", argv[0]);
```
I know, that the second approach will give me./myprograther thanmyprogwhen the program is not called from$... |
The second approach is superior when you have multiple links. In *nix systems, sometimes behavior depends on how you call a program. So hard coding the program name would clearly be a problem -- it could never check that.
|
I have compared gcc assembler output of
```
do {
// some code
} while (0);
```
with
```
do {
// some code
break;
} while (1);
```
The output is equal, with or without optimization but..
It's always that way?
No experiment can prove theories, they can only show they are wrong
|
There is a slight difference:
```
do {
// code
if ( condition )
continue;
// code
break;
} while(1);
```
Will restart the loop whenconditionis true, whereas in the} while(0);version, thecontinuewill be equivalent tobreak.
If nocontinueis present, then they should produce exactly the same code.
|
Right now I'm drawing a cube with OpenGL, I'm using Windows and WGL context. I have blending enabled so my cube looks semi transparent. Basically the background == the clear color (Black). I'd like to be able to save the image in raw RGBA format which I can then make into a png. I basically want the cube to blend in w... |
Just draw the cube, setting the clear color to (0, 0, 0, 0), and save the output using glReadPixels.
|
How can i get the paths of a folder and its content. Say i have folder named MyFolder as
/tmp/MyFolder/ where it has subfolders SubFolder1, SubFolder2... and some files
|
You may take a look at theopendir()family functions.
|
How can i copy multiple char* variables into one char* at single instance operation.
say i have
char* text1 = "Hello";
char* text2 = "World";
i want to copy text1, text2 and '2' and "12345" into char* text3 in single function call.
|
```
char text3[100];
sprintf( text3, "%s%s%s%s", text1, text2, "2", "12345" );
```
|
Is it possible to access 32-bit registers in C ? If it is, how ? And if not, then is there any way to embed Assembly code in C ? I`m using the MinGW compiler, by the way.
Thanks in advance!
|
If you want to only read the register, you can simply:
```
register int ecx asm("ecx");
```
Obviously it's tied to instantiation.
Another way is using inline assembly. For example:
```
asm("movl %%ecx, %0;" : "=r" (value) : );
```
This stores theecxvalue into the variablevalue. I've already posted a similar answe... |
How can i create a temporary folder in /tmp directory.
|
Try themkdtempfunction.
```
char *tmpdir;
strcpy (template, "/tmp/myprog.XXXXXX");
tmpdir = mkdtemp (template);
if (!tmpdir) {
// Error out here
}
printf ("Temporary directory created : %s", tmpdir);
```
|
How can I get the path of home directory inMac OS XusingClanguage inXCodeeditor.
|
This should work under Linux, Unix and OS X, for Windows you need to make a slight modification.
```
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
int main(void)
{
const char *homeDir = getenv("HOME");
if (!homeDir) {
struct passwd* pwd = getpwuid(getuid());
... |
The shell command$ avrdude -c usbtinyoutputs text to stderr. I cannot read it with commmands such as head-less-more cos it is not stdout. I want the text to stdout or to a file. How can I do it in C? I have tried to solve the problem bymy last questionbut still unsolved.
|
I've not tried something like this in OpenBSD, but in at least a few *nix-like systems, you can do this usingdup2.
```
#include <unistd.h>
#include <stdio.h>
int main(void) {
fprintf(stderr, "This goes to stderr\n");
dup2(1, 2); //redirects stderr to stdout below this line.
fprintf(stderr, "This goes to ... |
```
char testStr[] = " trim this ";
char** pTestStr = &testStr;
trim(pTestStr);
int trim(char** pStr)
{
char* str = *pStr;
while(isspace(*str)) {
(*pStr)++;
str++;
}
if(*str == 0) {
return 0;
}
char *end = str + strlen(str) - 1;
while(end > str && isspace(*end))
end--;
*(end+1) = ... |
You need to maketestStrwriteable:
```
char testStr[] = " trim this ";
```
The problem is thatchar *ptr = ...hasptrpointing to the actual literal string which is in read-only memory.
By usingchar testStr[] = ...you are allocating an array and having the array initialized with the same contents as ... |
This question already has answers here:Alternative (K&R) C syntax for function declaration versus prototypes(6 answers)Closed8 years ago.
I've seen a few function definitions like this recently while playing with GNU Bison:
```
static VALUE
ripper_pos(self)
VALUE self;
{
//code here
}
```
Why is the type of... |
Those are old K&R style function parameter declarations, declaring the types of the parameters separately:
```
int func(a, b, c)
int a;
int b;
int c;
{
return a + b + c;
}
```
This is the same as the more modern way to declare function parameters:
```
int func(int a, int b, int c)
{
return a + b + c;
}... |
Gentoo Wikitold me the following:
Warning: GCC 4.2 and above support
-march=native. -march=native applies additional settings beyond -march,
specific to your CPU. Unless you have
a specific reason not to (e.g. distcc
cross-compiling), you should probably
be using -march=native, rather than
anything listed... |
Nevermind.
```
$ cc -march=core2 -E -v - </dev/null 2>&1 | grep cc1
/[...]/cc1 -E -quiet -v -iprefix /[...]/4.3.2/ - -march=core2
$ cc -march=native -E -v - </dev/null 2>&1 | grep cc1
/[...]/cc1 -E -quiet -v -iprefix /[...]/4.3.2/ - -march=core2 -mcx16 -msahf --param l1-cache-size=32 --param l1-cache-line-size=64 ... |
How can i create a temporary folder in tmp folder using C++ language.
I have 3 volumes. Leopard, Development and 10.6 (in Mac OS X) and I want to create a temp directory in current home directory.
Here is my code. I am confused about this linechar* tempdir = "/Volumes/Development/NewFolder.XXXXXX":
```
if (!mkdtemp... |
Under POSIX, you can usemkdtempto create a directory with a unique name. On Windows, useGetTempPathto retrieve the name of the temp directory, then create a directory with a random name there.
|
I have a c++ application linked against some c libraries.
Are there possible approaches to encapsulate the signal handling in a C++ class, so it could be handled as a c++ exception?
|
You can't and if you could a lot of things would break.
What you should do is set a flag in the signal handler, periodically check in your code and throw an exception when you detect the flag is set.
Such an approach is similar to how threads get interrupted inBoost.Threads, which I strongly suggest you study.
|
Is this from the C standard?
|
If you're confused by a C declaration, you can use thecdeclprogram to explain it:
```
~$ cdecl
Type `help' or `?' for help
cdecl> explain char (*a)[12];
declare a as pointer to array 12 of char
```
|
How can I create global variables that are shared in C? If I put it in a header file, then the linker complains that the variables are already defined. Is the only way to declare the variable in one of my C files and to manually put inexterns at the top of all the other C files that want to use it? That sounds not ide... |
In one header file (shared.h):
```
extern int this_is_global;
```
In every file that you want to use this global symbol, include header containing the extern declaration:
```
#include "shared.h"
```
To avoid multiple linker definitions,just one declaration of your global symbol must be present across your compilat... |
I haven't done much c programming but when I do when I need a false I put 0 when I want true I put 1, (ex. while(1)), in other cases I use things like "while(ptr)" or "if(x)".
Should I try using C99 booleans, should I recommend them to others if I'm helping people new to programming learn c basics(thinking of cs 1?... |
In C++ there is no reason to not use it. In C, i only useintfor this task, without any#defineor something like that. Variable-names likeisDefinitionare clear enough to indicate what's going on, in my opinion.
Of course, there is nothing wrong with defining your own bool or using the ones of<stdbool.h>.
|
I have code which works on windows, that callsLocalAllocas follows:
```
LocalAlloc(LMEM_ZEROINIT, size)
```
I need the equivalent malloc or calloc call to get this to work on Unix systems, through Mono. Simple answer?
|
From what I understand it just allocs zeroed memory, so acalloc(1, size)should suffice to allocatesizezeroed bytes.
|
I have this algorithm here:
```
pc = # the point you are coloring now
p0 = # start point
p1 = # end point
v = p1 - p0
d = Length(v)
v = Normalize(v) # or Scale(v, 1/d)
v0 = pc - p0
t = Dot(v0, v)
t = Clamp(t/d, 0, 1)
color = (start_color * t) + (end_color * (1 - t))
```
to generate point to point linear gradients... |
```
//loop through vector
//x and y px position
int x = i%w;
int y = i/w;
float d = distance(center,int2(x,y));
//if within the grad circle
if(d < radius)
{
//somehow set v[i] alpha to this:
float a = d/r;
}
```
|
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 ... |
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 cer... |
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 st... |
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.
|
I have a c++ application linked against some c libraries.
Are there possible approaches to encapsulate the signal handling in a C++ class, so it could be handled as a c++ exception?
|
You can't and if you could a lot of things would break.
What you should do is set a flag in the signal handler, periodically check in your code and throw an exception when you detect the flag is set.
Such an approach is similar to how threads get interrupted inBoost.Threads, which I strongly suggest you study.
|
Is this from the C standard?
|
If you're confused by a C declaration, you can use thecdeclprogram to explain it:
```
~$ cdecl
Type `help' or `?' for help
cdecl> explain char (*a)[12];
declare a as pointer to array 12 of char
```
|
How can I create global variables that are shared in C? If I put it in a header file, then the linker complains that the variables are already defined. Is the only way to declare the variable in one of my C files and to manually put inexterns at the top of all the other C files that want to use it? That sounds not ide... |
In one header file (shared.h):
```
extern int this_is_global;
```
In every file that you want to use this global symbol, include header containing the extern declaration:
```
#include "shared.h"
```
To avoid multiple linker definitions,just one declaration of your global symbol must be present across your compilat... |
I haven't done much c programming but when I do when I need a false I put 0 when I want true I put 1, (ex. while(1)), in other cases I use things like "while(ptr)" or "if(x)".
Should I try using C99 booleans, should I recommend them to others if I'm helping people new to programming learn c basics(thinking of cs 1?... |
In C++ there is no reason to not use it. In C, i only useintfor this task, without any#defineor something like that. Variable-names likeisDefinitionare clear enough to indicate what's going on, in my opinion.
Of course, there is nothing wrong with defining your own bool or using the ones of<stdbool.h>.
|
I have code which works on windows, that callsLocalAllocas follows:
```
LocalAlloc(LMEM_ZEROINIT, size)
```
I need the equivalent malloc or calloc call to get this to work on Unix systems, through Mono. Simple answer?
|
From what I understand it just allocs zeroed memory, so acalloc(1, size)should suffice to allocatesizezeroed bytes.
|
I have this algorithm here:
```
pc = # the point you are coloring now
p0 = # start point
p1 = # end point
v = p1 - p0
d = Length(v)
v = Normalize(v) # or Scale(v, 1/d)
v0 = pc - p0
t = Dot(v0, v)
t = Clamp(t/d, 0, 1)
color = (start_color * t) + (end_color * (1 - t))
```
to generate point to point linear gradients... |
```
//loop through vector
//x and y px position
int x = i%w;
int y = i/w;
float d = distance(center,int2(x,y));
//if within the grad circle
if(d < radius)
{
//somehow set v[i] alpha to this:
float a = d/r;
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.