question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I'm experimenting with pthread library and I've got the following piece of code:
```
for (int j = 0; j < NUM_THREADS; j++)
{
int *threadNum = malloc(sizeof(int));
*threadNum = j;
pthread_create(..., (void *)threadNum);
}
```
Since there is no free, this code has a memory leak. Where should I place fre... |
The thread which uses it (since it is passed as the parameter) should free it when it is done with it.
|
I am trying to write something like this:
```
#define COV_ON(x) \
#ifdef COVERAGE_TOOL \
_Pragma (COVERAGE #x)
#endif
```
Is there any way to defineCOV_ONlike this? I know what I have done above is wrong as I can't have#ifdefinside #define. (#is not an allowed char... |
Not possible. Do it the other way around:
```
#ifdef COVERAGE_TOOL
#define COV_ON(x) _Pragma (COVERAGE #x)
#else
#define COV_ON(x)
#endif
```
|
Gstreamer on IPhone, Android, Blackberry, Nokia. How can we make it using C or D or Vala languages? Or should we just use Java or Lua?
1) Glib porting to IPhone, Android, Blackberry, Nokia is available?
For Android, there is a tipshttp://gstreamer.freedesktop.org/wiki/GstreamerAndroid_InstallInstructionsFor IPhone, ... |
I don't know much about mobile development, but your best bet would be to look intoGtkD. This project provides bindings to GTK and GObject. AFAIK no D bindings to GStreamer exist yet, butcalling C code from D isn't difficult. Furthermore, to compile for ARM architectures, you'll probably want to look atGDCsince the... |
How would one create a make file for running e.g. xml parser with the following command line command
```
gcc source.c -I/usr/include/libxml2 -lxml2 -o output
```
I use this to include libxml when compiling using the command line.
How would this be made using a make file instead of the command line usage?
|
```
SOURCES:=source.c
OBJECTS:=$(SOURCES:%.c=%.o)
CC=gcc
CFLAGS=-g -Wall -I/usr/include/libxml2
LD=gcc
LDFLAGS=
LIBS=-lxml2
TARGET:=output
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(LD) -o $@ $(OBJECTS) $(LDFLAGS) $(LIBS)
.c.o:
$(CC) $(CFLAGS) -c $< -o $@
depend:
$(CC) $(CFLAGS) -MM $(SOURCES... |
How do I write a function for this in C language?
y = 20 ln (x + 3) ?
How do I write the ln function?
|
```
#include <math.h>
double fun(double x)
{
return 20 * log( x + 3 ); //base-e logarithm!
}
//usage
double y = fun(30);
```
For base-10 logarithm, uselog10().
|
what is gendep? it builds dependencies, how? any good book to read about this entire gnu make gamut?
|
Not an expert by any means, but it appears to look at the system calls to open() that a particular binary makes and looks to see if the opened file matches a particular regular expression. If it finds a match, it records this match in a file GNU make can parse.
http://www.hep.phy.cam.ac.uk/~lester/gendep/index.html
... |
As all we know: the sequence of evalutation is determined by the priority and associativity.
For this example,the associativity determined that a+b,then the result plus c. This is what ANSI C compliant compiler do(leave out the optimization).But will it be evaluated like foregoing manner in the title? In what compiler... |
Let me throw this at you:
Operator Precedence vs Order of Evaluation
|
Greetings Overflowers,
I know in C we can define a struct inline with the variable declaration so that the struct type is specific to this variable. This is instead of defining the type alone then declaring the variable to be of that struct type. Is this possible in C#?
Thank !
|
This is not possible in C#, however you can define an instance of an anonymous type like this:
```
var x = new { SomeField = 1, SomeOtherField = "Two" };
```
This would effectively be the same, giving you an instance of a type that is specific to that variable and cannot used outside the variable's scope.
|
Until now I used Netbeans and want to try eclipse now.
I went to the eclipse site and wanted to download it. I am totally confused with the package.
There are different packages for C, Java, PHP ... development. Well I want to develop in all these languages and in addition in PERL and Python.
When I download one of ... |
As far as I know there is not a ready-made package that contains support for everything.
You can download one of the packages and add support for other languages, frameworks etc. later by installing more plug-ins (select Help / Install New Software... in Eclipse's menu).
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
how does OS know to differentiate b... |
By co-incidence, the first 3 letters of 'integer' are the same as the first 3 letters of 'interrupt'. Two different languages have used these 3 letters, and they mean different things.
Similarly, 'chat' is a word in both French and English, but in French it means 'cat' and in English it means 'talk'.
|
this question bothers me this few days.
I want to read a string for example, input = (-0.001999,-0.919191,-0.777777,999999.999999)
using sscanf. And my code is
```
char x[10], y[10], z[10], angle[10];
sscanf( input+1, "%[^,],%[^,],%[^,],%[^)]", &x, %y, &z, &angle);
printf("%s %s %s %s\n", x, y, z, angle);
```
the ex... |
angle is not big enough to hold the input data and thus z is getting overwritten. Try this:
```
char x[80], y[80], z[80], angle[80];
```
|
I have wrote a sharedlibA.so. My programPwill dynamic loadlibA.so(uses dlopen, dlsym...).
Here's my problem:
InlibA.so, I have to use functions (such asfun1()) in a staticlibB.a, butlibB.ais not compiled with-fPIC, and I can't recompilelibB.a, so I can't linklibB.aintolibA.so.
I have tried linklibB.aintoP(with -Wl,... |
If you want to linklibB.aintoP, so that the functions are available tolibA.sowhen it is loaded byP, you need to compilePwith the-rdynamicoption.
|
Perhaps not a really important question, but just starting out in c.
Why will this not compile correctly?
```
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 15;
char word[100];
itoa (i,word,10);
printf("After conversion, int i = %d, char word = %s", i, word);
}
```
I keep getting the error message
... |
Use sprintf instead, itoa is not part of the C standard and it's probably not included in your stdlib implementation.
```
sprintf(word,"%d",i);
```
UPDATE:
As noted in the comments snprintf is safer to use to avoid buffer overflows. In this case it's not necessary because your buffer is longer than the largest int... |
The following C statement is invalid in C++.
```
int *a = malloc(sizeof(*a));
```
Why? How do you fix it?
The answer is :
C performs an implicit conversion for
void *, while C++ does not. Use an
explicit cast to work around this.
My question is: explicit cast to whom and where?
thanks.
|
In C++ you have to say
```
int *a = (int*)malloc(sizeof(*a));
```
because casting avoid*into anint*isn't implicitly done by the compiler.
Better yet, just usenewanddelete:
```
int *a = new int();
```
|
1)(pointer) What is %p used for? To show the address or something else? (can you give example too?)
2) As using graph.h library and creating graphs, ellipse() function has 6 parameters. What are them? I could't find full list of them.
Thank you
editsorry. it should be<graphics.h>library. and yes, it is an external ... |
%pis used to print out a pointer's value (the address) usingprintf:printf("%p", &printf); //Prints out the address of the 'printf' functionI have no idea whatgraph.hyou're referring to, and I doubt many others do either; could you post more information on what that library is for?
|
```
int (*rdPtrList[4])(unsigned int addr, unsigned int data);
```
The above declares an array of size 4 of pointers for functions that returns an int and takes two unsigned int. I would like to make a pointer to this array. Is this possible in C?
|
Leaving out the parameters to keep the following easier to read:
```
p -- p
*p -- is a pointer
(*p)[4] -- to a 4-element array
*(*p)[4] -- of pointers
(*(*p)[4])() -- to functions
int (*(*p)[4])(); -- returning int.
```
|
I would like to use a variable in the ldap command ldap_search_s in C. I used strcat to create the string i needed. The error is "bad search filter". I'm pretty sure it has something to do with the string i have created. Here is my code:
```
char *numero = randomID1() ;
char *var1="\"(studentID=";
char *var2= numer... |
I haven't tried it, but after looking at the documentation, I would suspect you should not include the double quotes in the filter:
```
char *var1="(studentID=";
char *var2= numero;
char *var3= ")";
```
|
If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?
|
See theGNU Make Debugger
|
When i execute this code
```
#include<stdio.h>
int main() {
int (*x)[5];
printf("\nx = %u\nx+1 = %u\n&x = %u\n&x + 1 = %u",x,x+1,&x,&x+1);
}
```
This is the output in C or C++:
```
x = 134513520
x+1 = 134513540
&x = 3221191940
&x + 1 = 3221191944
```
Please explain. Also what is the difference between:
int x[5]... |
int x[5]is an array of 5 integersint (*x)[5]is apointer toan array of 5 integers
When you increment a pointer, you increment by the size of the pointed to type.x+1is therefore5*sizeof(int)bytes larger than justx- giving the8048370and8048384hex values with a difference of 0x14, or 20.
&xis a pointer to a pointer - so... |
I have some code that moves bytes in a buffer usingmemmove(). The buffer is accessed by multiple threads. I get a very weird behavior; sometimes the buffer it's not what it should be and I was thinking ifmemmove()or/andmalloc()are thread safe. I'm working on iOS (in case this is platform dependent).
|
In an implementation that provides threads,mallocwill normally be thread safe (i.e., it will take steps to assure the heap doesn't get corrupted, even ifmallocgets called from multiple threads). The exact way it will do that varies: some use a single heap, and internal synchronization to ensure against corruption. Oth... |
How to get the "inside" of a tab control, i.e. the area in which you can place controls?
```
// doesn't work:
WINDOWINFO tabsInfo;
GetWindowInfo(GetDlgItem(hwndDialog, IDC_TABS), &tabsInfo);
MoveWindow(someHwnd, tabsInfo.rcClient.left, tabsInfo.rcClient.top, ...
```
tabsInfo.rcClient gives the entire region used by ... |
You can useTabCtrl_AdjustRect-- pass in the bounding rectangle of the tab control and on output, the rectangle will be adjusted to the content area.
Also, if you only need the client rectangle of the window, it's simpler to useGetClientRectinstead ofGetWindowInfo.
|
Let say i have a listListand i havepthread_t t1that polls from the list and i have many other pthreads that insert elements to the list.
The list is locked with a locklistLock.
whent1has the lock - if the list is empty he goes to sleep withpthread_cond_wait(..)and when a thread inserts to the list he signals him.
my ... |
It will fight, however it's a fair fight. All callers are put into a queue based on the order that they called the wait. It's completely deterministic.
However given the way that you're using things, you may possibly want to think about using a read/write lock. It allowsNsimultaneous readers, but anytime something tr... |
In my c++ application I want to change working directory to specified one. But when I specifying"~/dev/"as working directorychdir()fails and returns -1. Instead it works when I'm specifying"/home/myusername/dev". Why this happens? How can I solve this problem (except of checking if string first charachter is~and repla... |
The expansion of tilde (~) to HOME environment variable is done by bash. That expansion is done before that is passed to chdir command. The bottom line is ~ is handled by bash, not by chdir command. So you can not use it in chdir() function call.
In order to find other kind of expansions (and the details of ~ expansi... |
Greetings,
I had been studying C++ for a while now.
I'm getting in to pointers now.
But I'm creating a program on C++ that will ask for a string("%s") input.
And I want to display its character on a different line.
But when I run the program I get the wrong letters.
Here's my code;
```
#include<stdio.h>
#include<std... |
malloc(sizeof(char))allocates space for a single character. This is probably not what you want. As the comments below point out, the dereferencing in*name++is pointless. It does no harm, but perhaps indicates that you're thinking incorrectly about something.name++has the same effect.
|
I am currently reading Cormen's "Introduction to Algorithms" and I found something called a sentinel.
It's used in the mergesort algorithm as a tool to decide when one of the two merging lists is exhausted. Cormen uses the infinity symbol for the sentinels in his pseudocode and I would like to know how such an infini... |
A sentinel is just a dummy value. For strings, you might use a NULL pointer since that's not a sensible thing to have in a list. For integers, you might use a value unlikely to occur in your data set e.g. if you are dealing with a list ages, then you can use the age -1 to denote the list.
|
Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.
|
float *mat2d = malloc( rows * cols * sizeof( float
));
to access a value from the matrix use this adressing scheme:
float val = mat2d[ x + y * cols ];
|
this question bothers me this few days.
I want to read a string for example, input = (-0.001999,-0.919191,-0.777777,999999.999999)
using sscanf. And my code is
```
char x[10], y[10], z[10], angle[10];
sscanf( input+1, "%[^,],%[^,],%[^,],%[^)]", &x, %y, &z, &angle);
printf("%s %s %s %s\n", x, y, z, angle);
```
the ex... |
angle is not big enough to hold the input data and thus z is getting overwritten. Try this:
```
char x[80], y[80], z[80], angle[80];
```
|
I have wrote a sharedlibA.so. My programPwill dynamic loadlibA.so(uses dlopen, dlsym...).
Here's my problem:
InlibA.so, I have to use functions (such asfun1()) in a staticlibB.a, butlibB.ais not compiled with-fPIC, and I can't recompilelibB.a, so I can't linklibB.aintolibA.so.
I have tried linklibB.aintoP(with -Wl,... |
If you want to linklibB.aintoP, so that the functions are available tolibA.sowhen it is loaded byP, you need to compilePwith the-rdynamicoption.
|
Perhaps not a really important question, but just starting out in c.
Why will this not compile correctly?
```
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 15;
char word[100];
itoa (i,word,10);
printf("After conversion, int i = %d, char word = %s", i, word);
}
```
I keep getting the error message
... |
Use sprintf instead, itoa is not part of the C standard and it's probably not included in your stdlib implementation.
```
sprintf(word,"%d",i);
```
UPDATE:
As noted in the comments snprintf is safer to use to avoid buffer overflows. In this case it's not necessary because your buffer is longer than the largest int... |
The following C statement is invalid in C++.
```
int *a = malloc(sizeof(*a));
```
Why? How do you fix it?
The answer is :
C performs an implicit conversion for
void *, while C++ does not. Use an
explicit cast to work around this.
My question is: explicit cast to whom and where?
thanks.
|
In C++ you have to say
```
int *a = (int*)malloc(sizeof(*a));
```
because casting avoid*into anint*isn't implicitly done by the compiler.
Better yet, just usenewanddelete:
```
int *a = new int();
```
|
1)(pointer) What is %p used for? To show the address or something else? (can you give example too?)
2) As using graph.h library and creating graphs, ellipse() function has 6 parameters. What are them? I could't find full list of them.
Thank you
editsorry. it should be<graphics.h>library. and yes, it is an external ... |
%pis used to print out a pointer's value (the address) usingprintf:printf("%p", &printf); //Prints out the address of the 'printf' functionI have no idea whatgraph.hyou're referring to, and I doubt many others do either; could you post more information on what that library is for?
|
```
int (*rdPtrList[4])(unsigned int addr, unsigned int data);
```
The above declares an array of size 4 of pointers for functions that returns an int and takes two unsigned int. I would like to make a pointer to this array. Is this possible in C?
|
Leaving out the parameters to keep the following easier to read:
```
p -- p
*p -- is a pointer
(*p)[4] -- to a 4-element array
*(*p)[4] -- of pointers
(*(*p)[4])() -- to functions
int (*(*p)[4])(); -- returning int.
```
|
I would like to use a variable in the ldap command ldap_search_s in C. I used strcat to create the string i needed. The error is "bad search filter". I'm pretty sure it has something to do with the string i have created. Here is my code:
```
char *numero = randomID1() ;
char *var1="\"(studentID=";
char *var2= numer... |
I haven't tried it, but after looking at the documentation, I would suspect you should not include the double quotes in the filter:
```
char *var1="(studentID=";
char *var2= numero;
char *var3= ")";
```
|
If make fails with: "bmake: don't know how to make blah", what/where is the best place to start looking for problems? why did it fail? What does it mean by "don't know"?
|
See theGNU Make Debugger
|
When i execute this code
```
#include<stdio.h>
int main() {
int (*x)[5];
printf("\nx = %u\nx+1 = %u\n&x = %u\n&x + 1 = %u",x,x+1,&x,&x+1);
}
```
This is the output in C or C++:
```
x = 134513520
x+1 = 134513540
&x = 3221191940
&x + 1 = 3221191944
```
Please explain. Also what is the difference between:
int x[5]... |
int x[5]is an array of 5 integersint (*x)[5]is apointer toan array of 5 integers
When you increment a pointer, you increment by the size of the pointed to type.x+1is therefore5*sizeof(int)bytes larger than justx- giving the8048370and8048384hex values with a difference of 0x14, or 20.
&xis a pointer to a pointer - so... |
I have some code that moves bytes in a buffer usingmemmove(). The buffer is accessed by multiple threads. I get a very weird behavior; sometimes the buffer it's not what it should be and I was thinking ifmemmove()or/andmalloc()are thread safe. I'm working on iOS (in case this is platform dependent).
|
In an implementation that provides threads,mallocwill normally be thread safe (i.e., it will take steps to assure the heap doesn't get corrupted, even ifmallocgets called from multiple threads). The exact way it will do that varies: some use a single heap, and internal synchronization to ensure against corruption. Oth... |
How to get the "inside" of a tab control, i.e. the area in which you can place controls?
```
// doesn't work:
WINDOWINFO tabsInfo;
GetWindowInfo(GetDlgItem(hwndDialog, IDC_TABS), &tabsInfo);
MoveWindow(someHwnd, tabsInfo.rcClient.left, tabsInfo.rcClient.top, ...
```
tabsInfo.rcClient gives the entire region used by ... |
You can useTabCtrl_AdjustRect-- pass in the bounding rectangle of the tab control and on output, the rectangle will be adjusted to the content area.
Also, if you only need the client rectangle of the window, it's simpler to useGetClientRectinstead ofGetWindowInfo.
|
Let say i have a listListand i havepthread_t t1that polls from the list and i have many other pthreads that insert elements to the list.
The list is locked with a locklistLock.
whent1has the lock - if the list is empty he goes to sleep withpthread_cond_wait(..)and when a thread inserts to the list he signals him.
my ... |
It will fight, however it's a fair fight. All callers are put into a queue based on the order that they called the wait. It's completely deterministic.
However given the way that you're using things, you may possibly want to think about using a read/write lock. It allowsNsimultaneous readers, but anytime something tr... |
In my c++ application I want to change working directory to specified one. But when I specifying"~/dev/"as working directorychdir()fails and returns -1. Instead it works when I'm specifying"/home/myusername/dev". Why this happens? How can I solve this problem (except of checking if string first charachter is~and repla... |
The expansion of tilde (~) to HOME environment variable is done by bash. That expansion is done before that is passed to chdir command. The bottom line is ~ is handled by bash, not by chdir command. So you can not use it in chdir() function call.
In order to find other kind of expansions (and the details of ~ expansi... |
Greetings,
I had been studying C++ for a while now.
I'm getting in to pointers now.
But I'm creating a program on C++ that will ask for a string("%s") input.
And I want to display its character on a different line.
But when I run the program I get the wrong letters.
Here's my code;
```
#include<stdio.h>
#include<std... |
malloc(sizeof(char))allocates space for a single character. This is probably not what you want. As the comments below point out, the dereferencing in*name++is pointless. It does no harm, but perhaps indicates that you're thinking incorrectly about something.name++has the same effect.
|
I am currently reading Cormen's "Introduction to Algorithms" and I found something called a sentinel.
It's used in the mergesort algorithm as a tool to decide when one of the two merging lists is exhausted. Cormen uses the infinity symbol for the sentinels in his pseudocode and I would like to know how such an infini... |
A sentinel is just a dummy value. For strings, you might use a NULL pointer since that's not a sensible thing to have in a list. For integers, you might use a value unlikely to occur in your data set e.g. if you are dealing with a list ages, then you can use the age -1 to denote the list.
|
Is there any way how tomalloc()a 2D matrix in C? I have successfully triedmalloc()ing a 1D field, but in matrix I am getting errors.
|
float *mat2d = malloc( rows * cols * sizeof( float
));
to access a value from the matrix use this adressing scheme:
float val = mat2d[ x + y * cols ];
|
Consider the following program:
```
#define _POSIX_C_SOURCE 200809L
#include <time.h>
#include <pthread.h>
#include <signal.h>
void timerfunc(union sigval val) { }
int main()
{
struct sigevent sev = { .sigev_notify = SIGEV_THREAD,
.sigev_notify_function = timerfunc };
timer_t t;
... |
Well,POSIX specifically saysit is
...impossible to determine the
lifetime of the created thread...
which implies that any lifetime is allowed.
SIGEV_THREADis simply bad mojo, and should be avoided.
|
Does C have an equivalent to the Obj c #pragma mark?
|
Objective-C is a superset of C.#pragmadirectives are part of the C standard, so they also exist in Objective-C also.
There are only a handful of#pragmadirectives that are actually standardised, but, any conforming compiler is supposed to ignore#pragmadirectives that it doesn't understand.
The problem though, is that ... |
I just found out that thegetline()function which is originally a GNU extension is now part of the POSIX 2008 standard.
Is there some overview of how broadly is this version of POSIX supported?
|
I would just go ahead and use it. It's possible to implementgetline(but not the more powerfulgetdelim) as a very fast/efficient wrapper aroundfgets, so if you're willing to do that as a fallback, usinggetlinedoesn't really make your program any less portable. (Versus something like using__fpending, which cannot be imp... |
I need to generate a simple "Hello World" ELF32 executable using gcc.
I don't seem to have the gcc-elf command though.
Is it possible to create ELF binaries instead of a.out without building gcc again?
(I'm assuming it should be possible with some options, but am unsure how to proceed)
|
Check the file a.out$ file a.outa.out:ELF32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
I believe the default name is retained as a.out but the format is ELF.
|
I seem to be able to compile code that callswsprintfwith theMinGWgccif I have these includes (in this order):
```
#include <stdarg.h>
#include <wingdi.h>
#include <winuser.h>
```
But I feel like there might be some "cleaner" way to do this. Perhaps with only a single header inclusion. I arrived at this list by searc... |
Include<Windows.h>
|
I have a C source code for as application that I want to use in my iPhone App. I thought the best way of doing it was to call the main method of that C Application in anNSOperationsubclass.
This works fine, except for cases where something in the C application goes wrong and anexit()/abort()is called, which takes my ... |
How about to compile with -Dexit=my_exit -Dabort=my_abort options and implement my_exit and my_abort as the following?
```
void my_exit(int status)
{
if (!/* check thread ID or so forth, and check during calling the NSOperation */) {
exit(status);
}
}
```
|
I am trying to read user input with multiple fields. But the number of fields is not specified. I want to read all the words till the carriage return. i tried this code but it isnt working:
```
char str[256];
while(1)
{
scanf("%s", str);
if(str[strlen(str)] == '\n')
break;
else
printf("G... |
Use
```
char str[256]
scanf("%255[^\n]", str); /*edit*/
```
which will read to a newline or (Edit:) 255 characters, whichever comes first.
|
```
enum protocol {
ascii_prot = 3, /* arbitrary value. */
binary_prot,
negotiating_prot = 4 /* Discovering the protocol */
};
```
Bothbinary_protandnegotiating_protequals to4?
|
Yes.
|
Does %*d mean one or more integer? in sprintf function
|
It is used to manipulate the minimum width of the numerical value printed, and it specifically means that the width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. In other words, if you wanted to use a width that was stored in a vari... |
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0?
```
int r = arc4random() % (9);
NSLog(@"Random Number: %d",r);
```
|
int r = (arc4random() % 8) + 1
|
hello everyone I found this function in Kernel of the Linux:
```
inline task_t *context_switch(task_t *prev, task_t *next) {
...
switch_to(prev, next, prev);
return prev;
}
```
this function is making context switch, my question is why this function should be inline and not macro for example, thanks in advance...
|
It may not be a macro because a macro to do this would evaluate prev and next twice each, when they may be expressions with side effects. Also, after some searching I found that switch_to is (on some platforms) a macro that is a statement in braces, and therefore cannot return a value to be used in an expression.
I f... |
I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?
|
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't).
Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.
|
I have a C source code for as application that I want to use in my iPhone App. I thought the best way of doing it was to call the main method of that C Application in anNSOperationsubclass.
This works fine, except for cases where something in the C application goes wrong and anexit()/abort()is called, which takes my ... |
How about to compile with -Dexit=my_exit -Dabort=my_abort options and implement my_exit and my_abort as the following?
```
void my_exit(int status)
{
if (!/* check thread ID or so forth, and check during calling the NSOperation */) {
exit(status);
}
}
```
|
I am trying to read user input with multiple fields. But the number of fields is not specified. I want to read all the words till the carriage return. i tried this code but it isnt working:
```
char str[256];
while(1)
{
scanf("%s", str);
if(str[strlen(str)] == '\n')
break;
else
printf("G... |
Use
```
char str[256]
scanf("%255[^\n]", str); /*edit*/
```
which will read to a newline or (Edit:) 255 characters, whichever comes first.
|
```
enum protocol {
ascii_prot = 3, /* arbitrary value. */
binary_prot,
negotiating_prot = 4 /* Discovering the protocol */
};
```
Bothbinary_protandnegotiating_protequals to4?
|
Yes.
|
Does %*d mean one or more integer? in sprintf function
|
It is used to manipulate the minimum width of the numerical value printed, and it specifically means that the width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. In other words, if you wanted to use a width that was stored in a vari... |
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0?
```
int r = arc4random() % (9);
NSLog(@"Random Number: %d",r);
```
|
int r = (arc4random() % 8) + 1
|
hello everyone I found this function in Kernel of the Linux:
```
inline task_t *context_switch(task_t *prev, task_t *next) {
...
switch_to(prev, next, prev);
return prev;
}
```
this function is making context switch, my question is why this function should be inline and not macro for example, thanks in advance...
|
It may not be a macro because a macro to do this would evaluate prev and next twice each, when they may be expressions with side effects. Also, after some searching I found that switch_to is (on some platforms) a macro that is a statement in braces, and therefore cannot return a value to be used in an expression.
I f... |
I am creating window inside my program, then sending HWND of this window to another application. Will drawing on window's HDC be valid for another process?
|
Windows are owned by other windows, not by processes. You can draw to any HWND on your desktop (at least if the window has the same integrity -- I'm not sure what happens if they don't).
Web browsers that host plug-ins or tabs in a separate process generally make use of this functionality.
|
If I have some lua code like this:
```
doSomething(function()
print("Hello!")
end)
```
How can I make it that, using the C API, I create C Lua function for doSomething that can then save the function passed to it to be executed a later date?
|
It's just a normal entry on the stack. Check it withlua_isfunction()then useluaL_ref()to generate a reference (so that the garbage collector doesn't steal it), and then maybelua_topointer()to store a pointer to this object, depends what you want to do with it.
When you're finished it's just aluaL_unref().
|
is safe if I use this macro in my code?
```
#define my_calloc(x, n) ((x) = (__typeof__ (x))calloc((n), sizeof(__typeof__ (&(x)))))
```
I'm usign gcc as compiler...
In my programm there is a lot of memory allocation point, so I use this.
I tried it 5 minutes ago and I get some weird sigabort and sigsev, now I'm goin... |
I think it should probably be:
```
#define my_calloc(x, n) do { (x) = calloc((n), sizeof *(x)); } while (0)
```
unnecessary/dangerous cast has been removedredundant parentheses removeddo/while added for correct behaviour betweenif (...)andelsefixed size of typeremove redundant and non-portable__typeof__
|
lets say I am doing mk "target" to build something. Is it possible to pass an argument to it?
i.e. mk "target" "x" and it will do things accordingly? I know that I will be providing mk "target" an argument and I know its semantics, just dont know the name well in advance.
Possible?
|
You might want to make use ofGNU Make's "Variables":
```
$ cat Makefile
ifndef LOLCAKES
LOLCAKES=1
endif
all:
@echo $(LOLCAKES)
$ make all LOLCAKES=42
```
You didn't explain what you're trying to accomplish, so it's hard to know what kind of "argument" you're after.
|
As we know java is a platform independent language due to JVM it's program can run at any OS.
What about C/C++? could C/C++ exe run at any OS ? Could we have done something about this(Like write once run anywhere)? please clear my doubt about this.
Thanks
|
No - an executable is built for a specific operating system and hardware (CPU) architecture.
If you are carefull not to use any OS specific functions, or any assumptions about word size etc, then c++ source can be recompiled to run anywhere.
|
I'm learning C and hope someone can explain what's the logic of using#ifndef?
I also find many C programs I looked, people seems following a convention using the filename following the#ifndef,#defineand#endif. Is there any rule or tip on how to choose this name?
```
#ifndef BITSTREAM_H
#define BITSTREAM_H
#include ... |
Header files will often use logic like this to avoid being included
more than once. The first time a source file includes them, the name
isn't defined, so it gets defined and other things are done.
Subsequent times, the name is defined, so all that is skipped.
|
I have made some c code for a program, which does some psycho-acoustics on sound data.
There is a piece of code which runs very slowly.
I think it would be best to use a look up table. How would one go about implementing it?
Any pointers or help would be appreciated! :)
|
Your values are not equidistant so it is not that easy. But its still possible: take your greatest common divisor of all your condition-values (thats here 50) and then make your table
byteout = lut[difference/50 + 12];
And in the lookup table you can just use your values in the posted order, where you duplicate the ... |
I have to to game for my school project.
I have a little problem with selecting part of game screen where there is no enemy.
Please see this screens, where i tried to explain a little bit.First screen, Second screen.
Ok, so I have player and i can move him around a play ground - from one border to second one.
And t... |
Useflood fillalgorithm.
|
Is there an alternative way of rewriting this same script in C++ w/o using thescanforprintffunctions?
Thanks!
```
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char * argv[], char* env[]) {
char quer[222];
printf("Content-type: text/plain\n\n");
scanf("%s",quer);
printf("%s\n",... |
```
#include <iostream>
#include <string>
int main()
{
std::cout << "Content-type: text/plain\n\n";
std::string quer;
std::getline(std::cin, quer);
std::cout << quer << '\n';
}
```
|
I'm a newbie in UNIX programming. Normally, when we use local socket to communicate, the domain is always AF_UNIX or AF_LOCAL. So in this case, struct sockaddr_un serves always for the local communication. Why there is still "short sun_family"? For a historical reason?
```
struct sockaddr_un{
short sun_family; ... |
You pass asockaddr *to several socket functions (e.g.connect,bind,sendto) - these will look at the family variable before casting to e.g.sockaddr_un *orsockaddr_in *
|
How does one create a timer in C?
I want a piece of code to continuously fetch data from a gps parsers output.
Are there good libraries for this or should it be self written?
|
Simplest method available:
```
#include <pthread.h>
void *do_smth_periodically(void *data)
{
int interval = *(int *)data;
for (;;) {
do_smth();
usleep(interval);
}
}
int main()
{
pthread_t thread;
int interval = 5000;
pthread_create(&thread, NULL, do_smth_periodically, &interval)
...
}
```
|
I have a C source code spread over many source files (*.c). For porting reasons say I need to comment out below statements from all source files
```
fprintf(stderr,"......",....);
```
The problem is these fprintfs could be multiline statements, meaning broken into two/or more lines spread over two lines in source fi... |
What you are looking for is named "coccinelle", it's semantic patch tool for C, via this you can easily do this. viz.http://coccinelle.lip6.fr/
|
Is there any simple way to create a GUI using OpenCV library or linking some other library with OpenCV.
Just Like the trackbar in OpenCV, is there any way to create push buttons also?
|
OpenCV is a computer vision framework, not a GUI framework (even though OpenCV contains some very basic GUI functions).
For a real GUI, better use something like GTK or Qt.
|
When I givesizeof(a), wherea=13.33, a float variable, the size is 4 bytes.
But if i givesizeof(13.33)directly, the size is 8 bytes.
I do not understand what is happening. Can someone help?
|
Those are the rules of the language.
13.33 is a numeric literal. It is treated as a double because it is a double. If you want 13.33 to be treated as a float literal, then you state 13.33f.
13.33 is a double literal. If sizeof(float) == 4, sizeof(13.33f) == 4 should also hold because 13.33f is a float literal.
|
suppose I have a macro, like
```
#define max(a,b) (((a) > (b)) ? (a) : (b))
```
then I use it in the "normal code"
```
int foo()
{
...
c = max(a,b);
...
}
```
Is there a way to see the code after precompiling?
Does exist a way to see the effect of macro substituion (maybe done by compiler, I use gcc)?
I'd like to... |
You want to see the preprocessed source code. Usually your C compiler has a switch to output the preprocessed output.
For gcc, it'sgcc -E [C-filename].
For msvc, it'scl /EPorcl /P. SeeMSVC /P (Preprocess to a File)
|
I have already GtkTreeView. And I want hide some cells.
There is method
```
gtk_cell_renderer_set_visible (GtkCellRenderer *cell, gboolean visible);
```
But How I can apply this method for some cells? Use iterator?
|
The only way is to 'mask' your model using aGtkTreeModelFilter. With this, you can supply an extra 'visible' column that tells whether the row should be visible or not; or you can use a function to decide which rows should be visible.
|
Besides not closing a comment/*..., what constitutes a lexical error in C?
|
Here are some:
```
"abc<EOF>
```
where EOF is the end of the file. In fact, EOF in the middle of many lexemes should produce errors:
```
0x<EOF>
```
I assume that using bad escapes in strings is illegal:
```
"ab\qcd"
```
Probably trouble with floating point exponents
```
1e+%
```
Arguably, you shouldn't have ... |
For example,printfis dynamically linked.
But how does the compiler(gcc) know that?
|
gcc doesn't know that. It knows there is a functionprintfand it knows how to call it, but the object file it generates contains a call to an unresolved symbol.
The symbol is then resolved by the linker, which is given all your object files and libraries. The linker finds the symbolprintfin a library, and after its co... |
I created a very small code to add two integers and save the result in another variables, both in assembly language and c language. code in assembly cost me 617 bytes but code in C took 25k bytes!! why there is a huge difference?
Also how can I view the assembly symbolic instructions for C code I wrote?
|
High level languages have a certain amount of overhead. While in assembly all you have is exactly what you say.
The overhead you are seeing in this case is likely the static binding of standard components, such asprintf. Likely an include statement added these.
If you want to see what your output is like you will ne... |
I need to create a read-only lock on a certain file in Windows, in C. The lockf function is completely useless, as it creates an exclusive lock. I need to protect the file from writes, but multiple processes should be able to read it at the same time.
I cannot use CygWin or MINGW libraries, I am limited to the Micros... |
if you mean for a termporary period, then use CreateFile() with dwShareMode=FILE_SHARE_READ, else use SetFileAttributes()
|
I have seen people use addition where a bitwise OR would be more conceptually appropriate, because they believe it is faster. Is this true? If yes, do all modern compilers know this trick?
|
Both addition and logical OR are probably performed in a similar part of the ALU of the CPU. There is unlikely to be any measurable performance difference, but this would have be measured in your situation to be certain.
Compilers won't need to bother with this because usually the only way the compiler can know that ... |
If I create pipe in windows this way:
```
CreatePipe(hRead, hWrite, &sec_atr, NULL)
```
Then makeFILE *fromhReadthis way:
```
int fd = _open_osfhandle((intptr_t)hRead, _O_RDONLY|_O_TEXT);
FILE *pipe_read = _fdopen(fd, "rt");
```
Then how should I close this file (pipe_read)?
fclose(pipe_read)_pclose(pipe_read)Clo... |
From the examplehere, usefclose. The documentation forfclosefurther clarifies with:
When these functions are used to close a stream, the underlying file descriptor and OS file handle (or socket) are closed, as well as the stream. Thus, if the file was originally opened as a file handle or file descriptor and is clos... |
```
void (*a)(char*, char*);
```
is this a function called a. returns void pointer?
in c?
|
This is a functionpointernameda. The function signature ofais a function that returns void and takes twochar *arguments.
SeeFunction Pointer Tutorialsfor more information on function pointers.
|
Does it make sense in terms of better performance to build a LRU type cache in C/C++ and get java to access it via JNI ?
|
Doubtful
JVMs do quite a decent job these days, especially considering that any applications that need a cache would probably stay up long enough for the JVM to optimise it quite a bit. Whatever your cache code would gain in speed by avoiding the JVM, you would probably lose pushing objects back and forth through JNI... |
I have a function that returns a const char * to a fixed value and when i am using this function i do a "==" operator to find eguality between the value returned and the one i expect. Is this a good practice? Should it be an anti-pattern?
Ex:
```
const char * LOL = "LOL";
const char * getI() {
return LOL;
... |
Is this a good practice?
Well, that depends.
It's the right thing to do if and only if you want to test whether the pointer returned bygetl()points to the same string literal as the globalLOLpointer. If that's not what you want to do, then, no, it's not good practice.
|
I define several functions in a file (the main function is defined by someone else).
I can use gprof to analyze how many times my functions have been called, but is there a way of getting a list with the functions by the order they are called in the main program?
of course I could write a message in the beginning of... |
And you don't want to use trace or truss or similar?
|
Is this even possible? Would be extra cool if somehow I manage to have a function called every time a buffer has been processed. Any other ideas besides polling the source it's welcomed :D
|
You know how many samples are in each buffer and you know the sample rate that the source is playing at. That should give you a pretty good idea of when the source will finish processing a buffer.
If you're feeling very intrepid, you could hack this into the OpenAL-soft source. By the looks of the code, you would p... |
I have a source file that I can run via the terminal using
```
gcc source.c -I/usr/include/libxml2 -lxml2 -o output
```
but when I#includethe source file which includes the libxml source files, the compiler complains that thelibxml/xmlmemory.h:,libxml/parser.h:,libxml/xpath.hcannot be found : no such file or directo... |
You need always to keep the-I/usr/include/libxml2in your gcc statement, so that it can find the header files.
|
I have made some c code for a program, which does some psycho-acoustics on sound data.
There is a piece of code which runs very slowly.
I think it would be best to use a look up table. How would one go about implementing it?
Any pointers or help would be appreciated! :)
|
Your values are not equidistant so it is not that easy. But its still possible: take your greatest common divisor of all your condition-values (thats here 50) and then make your table
byteout = lut[difference/50 + 12];
And in the lookup table you can just use your values in the posted order, where you duplicate the ... |
I have to to game for my school project.
I have a little problem with selecting part of game screen where there is no enemy.
Please see this screens, where i tried to explain a little bit.First screen, Second screen.
Ok, so I have player and i can move him around a play ground - from one border to second one.
And t... |
Useflood fillalgorithm.
|
Is there an alternative way of rewriting this same script in C++ w/o using thescanforprintffunctions?
Thanks!
```
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char * argv[], char* env[]) {
char quer[222];
printf("Content-type: text/plain\n\n");
scanf("%s",quer);
printf("%s\n",... |
```
#include <iostream>
#include <string>
int main()
{
std::cout << "Content-type: text/plain\n\n";
std::string quer;
std::getline(std::cin, quer);
std::cout << quer << '\n';
}
```
|
I'm a newbie in UNIX programming. Normally, when we use local socket to communicate, the domain is always AF_UNIX or AF_LOCAL. So in this case, struct sockaddr_un serves always for the local communication. Why there is still "short sun_family"? For a historical reason?
```
struct sockaddr_un{
short sun_family; ... |
You pass asockaddr *to several socket functions (e.g.connect,bind,sendto) - these will look at the family variable before casting to e.g.sockaddr_un *orsockaddr_in *
|
How does one create a timer in C?
I want a piece of code to continuously fetch data from a gps parsers output.
Are there good libraries for this or should it be self written?
|
Simplest method available:
```
#include <pthread.h>
void *do_smth_periodically(void *data)
{
int interval = *(int *)data;
for (;;) {
do_smth();
usleep(interval);
}
}
int main()
{
pthread_t thread;
int interval = 5000;
pthread_create(&thread, NULL, do_smth_periodically, &interval)
...
}
```
|
I have a C source code spread over many source files (*.c). For porting reasons say I need to comment out below statements from all source files
```
fprintf(stderr,"......",....);
```
The problem is these fprintfs could be multiline statements, meaning broken into two/or more lines spread over two lines in source fi... |
What you are looking for is named "coccinelle", it's semantic patch tool for C, via this you can easily do this. viz.http://coccinelle.lip6.fr/
|
Is it possible to print (tostdout, or a file) an number (int,float,double,long, etc.) without actually using any of the*printffunctions (printf,fprintf,sprintf,snprintf,vsprintf, …)?
|
If your libc contains anitoa()function, you can use it to convert an integer to a string.Otherwise you'll have to write the code to convert a number to a string yourself.
itoa()implementation fromC Programming Language, 2nd Edition - Kernighan and Ritchiepage 64:
```
/* itoa: convert n to characters in s */
void ito... |
This question already has answers here:Closed12 years ago.
Possible Duplicate:What should main() return in C/C++?
Example1
```
#include <stdio.h>
int main(void)
{
printf ("Hello World!\n");
getch();
}
```
Example2
```
#include <stdio.h>
void main()
{
printf ("Hello World!\n");
getch();
}
``... |
The first example is recommended but also you need to put this line as the last one in the main()
```
return 0;
```
which returns zero to the system indicating that everything went alright.
|
Does anyone know why the following code
```
void foo(const int X)
{
#pragma omp parallel for private(X)
for (int i = 0; i < 100; i++)
{ }
}
```
gives this error
error: 'X' is predetermined 'shared' for 'private'
and how I can really makeXprivate to each thread?
|
You are getting an error becauseXis constant. Just removeconstand everything should work.
|
I'm looking for a very portable, minimalistic/small XML/configuration language library in ANSI C with no external dependencies (or very few), compiling down to less than 100K. I need it for a moderately complex configuration file, and it must support Unicode.
Some more requirements:
OK to use/embed/staticallylink in... |
This is somehow similar to this question:Is there a good tiny XML parser for an embedded C project?
I was able to tweak the compilation flags of the following XML parser libraries for C, and cut down more than 50% of their size on my Ubuntu machine. Mini-XML is the only one close to what you requested:
Mini-XML(36K)... |
I'm trying to call the Vista functionSHGetKnownFolderPath()from C using Visual Studio 2008. The code works fine as C++ but refuses to compile as C code with this output:
xyz\indexwiki.cpp(316) : error C2440:
'function' : cannot convert from
'const GUID' to 'const KNOWNFOLDERID
*const ' xyz\indexwiki.cpp(316) : ... |
How about the following?
HRESULT hr = SHGetKnownFolderPath(&FOLDERID_Profile, 0, NULL, &path);
|
When I have to open a folder inWindows Explorer(for exampled:\myfolder\test), I use::GetForegroundWindow()to get itsWindow Handle, and use::GetWindowTextto get the Title Text. But in the default windows the full path of the current window is not displayed (of course you can throughtools-folder option-view-display full... |
By using theShellWindowsCOM object. Seethis exampleon how the get the folder that an Explorer window is viewing.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.