question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am trying to find a way to test symbol equality in the Ruby C API. Consider the following C function:
```
static VALUE test_symbol_equality(VALUE self, VALUE symbol) {
if (rb_intern("test") == symbol) {
return Qtrue;
} else {
return Qfalse;
}
}
```
From the Ruby point of view, this method does not be... |
You are not comparing the same thing in your example.
rb_internreturns anID, but you are comparing it to theVALUEdirectly. You first have to "unwrap" theVALUE, retrieving theIDit is associated with. Replacing yourifstatement by this should solve your problem:
```
if (rb_intern("test") == SYM2ID(symbol)) {
...
``... |
I just upgraded to Mac OS X Mountain Lion and found out thatvalgrindis still not compatible with Mountain Lion.
I have a 600 line C code that I need to check against memory leaks.
What are possible ways to do it other than valgrind? Can I use Xcode instruments?
|
You could check theclang static analyzer. It's pretty awesome tool for finding bugs in the code.
It's better than valgrind in the fact that it does static analysis rather than running the code — so it can find bugs which you rarely reach. However, it is more likely to trigger false positives as well. And it's not as ... |
I have two calls to two different methods :
```
void func1()
{
// do something
if (fail)
{
// then set errno to EEXIST
}
}
```
And the second method :
```
void func2()
{
// do something
if (fail)
{
// then set errno to ENOENT
}
}
```
When I set theerrnoto some value , what does it... |
For all practical purposes, you can treaterrnolike a global variable (although it's usually not). So includeerrno.hand just use it:
```
errno = ENOENT;
```
You should ask yourself iferrnois the best error-reporting mechanism for your purposes. Can the functions be engineered to return the error code themselves ?
|
This is common in functional languages especially with TCO. I was just wondering if it provided any performance benefits besides being easier to write and keep track of. Is it just as fast to access the variables in the struct as it is to access them if they were just normal arguments? Is there any cons to this method... |
There is no benefit, because structs are passed by value. Passing multiple arguments one by one will take the same amount of allocations from a running program as the allocation of astruct. Moreover,structmay give you worse results because of padding.
Even if you pass yourstructby pointer, you would still need to all... |
I'm compiling a DLL which needs to use portaudio. It uses all sorts of windows libraries for sockets and such too, but the linker wouldn't recognize the portaudio library. Then I remembered portaudio uses __cdcel instead of __stdcall. Normally I would just use __cdcel and be done with it, but the DLL I'm compiling nee... |
Stupid me! All I have to do is use __cdcel and declare the exported functions as __stdcall!
|
I am trying to find a way to test symbol equality in the Ruby C API. Consider the following C function:
```
static VALUE test_symbol_equality(VALUE self, VALUE symbol) {
if (rb_intern("test") == symbol) {
return Qtrue;
} else {
return Qfalse;
}
}
```
From the Ruby point of view, this method does not be... |
You are not comparing the same thing in your example.
rb_internreturns anID, but you are comparing it to theVALUEdirectly. You first have to "unwrap" theVALUE, retrieving theIDit is associated with. Replacing yourifstatement by this should solve your problem:
```
if (rb_intern("test") == SYM2ID(symbol)) {
...
``... |
I just upgraded to Mac OS X Mountain Lion and found out thatvalgrindis still not compatible with Mountain Lion.
I have a 600 line C code that I need to check against memory leaks.
What are possible ways to do it other than valgrind? Can I use Xcode instruments?
|
You could check theclang static analyzer. It's pretty awesome tool for finding bugs in the code.
It's better than valgrind in the fact that it does static analysis rather than running the code — so it can find bugs which you rarely reach. However, it is more likely to trigger false positives as well. And it's not as ... |
I just upgraded to Mac OS X Mountain Lion and found out thatvalgrindis still not compatible with Mountain Lion.
I have a 600 line C code that I need to check against memory leaks.
What are possible ways to do it other than valgrind? Can I use Xcode instruments?
|
You could check theclang static analyzer. It's pretty awesome tool for finding bugs in the code.
It's better than valgrind in the fact that it does static analysis rather than running the code — so it can find bugs which you rarely reach. However, it is more likely to trigger false positives as well. And it's not as ... |
I have two calls to two different methods :
```
void func1()
{
// do something
if (fail)
{
// then set errno to EEXIST
}
}
```
And the second method :
```
void func2()
{
// do something
if (fail)
{
// then set errno to ENOENT
}
}
```
When I set theerrnoto some value , what does it... |
For all practical purposes, you can treaterrnolike a global variable (although it's usually not). So includeerrno.hand just use it:
```
errno = ENOENT;
```
You should ask yourself iferrnois the best error-reporting mechanism for your purposes. Can the functions be engineered to return the error code themselves ?
|
```
// set all values in the hash table to null
for(int i = 0; i < HASH_SIZE; i++)
{
hashtable[i] = NULL;
}
```
I keep getting this error message in response to hashtable[i]:
assignment makes integer from pointer without a cast [-Werror]
Why?
|
Ifhashtableis an array of integers thenhashtable[i]expects an integer andNULLis a pointer.
So you're trying to assign a pointer value to an integer variable(without a cast), this is usually just a warning but since you have-Werrorall warnings turn into errors.
Just use0instead ofNULL.
|
I have a program which does 5 mallocs and 3 frees. I call mtrace() at the start and muntrace() at the end. mtrace will report the missing frees if I run the program normally. If I do:
```
valgrind -v --log-file=val.log --leak-check=full --show-reachable=yes my_program
```
valgrind will report the missing frees but m... |
So I guess you can't use them both together
Correct.
valgrind will override mtrace?
I don't believe Valgrind overridesmtrace, but itdoesoverridemallocandfree, somtracesimply never sees eithermallocoffree.
|
I am trying to write a C program where the input from command line argument is in the form0x1234aabb.
This definitely comes in the program as a char*[].
Now, I want to store this input in the form ofchar a[]={0x12, 0x34, 0xaa, 0xbb}.
Please help.
|
If you know the string is always a fixed length (e.g. 10 characters as in your example), then you can split the string into four equal parts each three characters long (two for the digits and one for the terminator), and then usestrtoulon each part. If the argument is less than ten characters, only fill in the relevan... |
I am looking for an example of C/C++ app that uses the same code to run on Android via JNI and iOS
Ideally some kind of open source github project that I can pick apart, or maybe something part of a tutorial
hoping the collective conscious can at least guide me in the right direction here. we can ask for examples ri... |
In your comments you mention wanting something graphical. Check outCocos2D-X, a C++ game engine with various implementations (iOS and Android being two).
|
How would you divide a number by 3 without using*,/,+,-,%, operators?
The number may be signed or unsigned.
|
This is asimple functionwhich performs the desired operation. But it requires the+operator, so all you have left to do is to add the values with bit-operators:
```
// replaces the + operator
int add(int x, int y)
{
while (x) {
int t = (x & y) << 1;
y ^= x;
x = t;
}
return y;
}
int... |
I'm trying to embed a C# class in a C application using libmono, but the documentation is a bit lacking.
I'm trying to call a method with the prototypevoid MessageToSend(out MessageObject message);
How do i represent the "out parameter"? is it a pointer-to-a-pointer to a MonoObject? Thanks.
PS. as far as libmono is... |
You're right, it's MonoObject**.
Andoutandrefis the same for pretty much everything except the C# compiler.
|
Is it possible to use GTK without a valid X display?
I want to use GTK with Webkit, but for now I'm only interested in using the DOM functions to experiment, so I have no need to actually display anything. It's very convenient for me to do this over an SSH connection on a server that has no display.
But, without aD... |
There is an X server called Xvfb which provides a validDISPLAYand sends the output to a file instead of to graphics hardware. You can run that on the same machine that's running your gtk client, and gtk will be able to do whatever it wants to do without using any of your network bandwidth. As a bonus, you can read Xvf... |
By default OpenMP directive:
opm_get_num_threadsgives number of threads equivalent to processors/cores.
I have an 8 core machine, so it gives me 8 threads. Is that the maximum? Can I get more threads than 8, if I deliberately specify more than 8?
Thanks
|
You can set as many threads as you want with:
```
int threads = 16;
omp_set_num_threads(threads);
```
http://msdn.microsoft.com/en-US/library/e16bady3%28v=vs.80%29
But be sure you are aware of the drawbacks of using more threads than there are logical cores in the system.
|
I have a this code:
```
#include <stdio.h>
#include <conio.h>
void main()
{
int n = 5;
clrscr();
printf("n=%*d", n);
getch();
}
```
The output which I got is:n= 5. Why is there a space? How is it generated? What is the use of*in the code?
|
When in doubt, read thedocs:
*:The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
However, you appear to be using it wrong. The proper way to use it would be like this:
```
printf("n=%*d", 2, n);
```
|
I am using an open source CLI parser (this one ->http://sourceforge.net/projects/cliparser/) to add command line interface to my application and it works really neat on its own, but I am having trouble adding it to my application. The documentation provided is very meager and I have limited experience with makefiles. ... |
When you compile your program, you need to link against the library. If using GCC, this is done via two ways:
You can specify the path to the library:gcc myapp.c /somepath/libparser.aOr, if it is in your standard library directory you should be able to do:gcc myapp.c -l parser
|
I'm trying to append two structures into one
Ex.
```
l1 = add(1, add(2, NULL));
l2 = add(3, add(4, NULL));
myappend(l1,l2) = add(1,add(2,add(3,add(4,NULL))))
```
I tried many other ways that I can think of... but it doesn't work... can anyone help me out?
```
struct list_node {
struct list_node * rest;
int fi... |
```
list myappend(list l1,list l2){
list k = l1;
while (k->rest != NULL)
{
k = k->rest;
}
k->rest = l2;
return l1;
}
```
Should work for you.
|
I have a C program which contains#include <dos.h>header. It shows a compile time error. I know that thedos.hheader file is not valid in Linux.
Is there any other equivalent header fordos.hin Linux?
|
dos.h header file is interface to the DOS operating system. They are not portable to operating systems other than DOS (means not works in Linux). Which functionality in dos.h you are going to use?
|
I know the function below:
```
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
```
It only reads byte by byte, my goal is to be able to read 12 bits at a time and then take them into an array. Any help or pointers would be greatly appreciated!
|
Adding to the first comment, you can try reading one byte at a time (declare a char variable and write there), and then use the bitwise operators >> and << to read bit by bit. Read more here:http://www.cprogramming.com/tutorial/bitwise_operators.html
|
These two flags are often set together. What is the difference between them?
|
FromLinux Device Drivers 3:
IFF_UP
This flag is read-only for the driver. The kernel turns it on when the interface is active and ready to transfer packets....IFF_RUNNINGThis flag indicates that the interface is up and running. It is mostly
present for BSD compatibility; the kernel makes little use of it. Mo... |
Is
```
--foo++;
```
a valid statement in C? (Will it compile/run) And is there any practical application for this?
Sorry for changing the question in an edit but I found something out.
According to my C++ compiler (Visual Studio 2010):
```
--++foo;
```
is a valid command but
```
foo--++;
```
is not. Is there a... |
No, it is not valid because the result of the increment / decrement operators is not a lvalue.
EDIT:the OP edited his question by adding two more examples . So here we go, for the same reason:
```
--++foo;
--foo++;
foo--++;
```
are all invalid expression statements because the result of increment / decrement operat... |
I need to associate textual data with the lines in a source code file. Something like "these lines are to create a Myclass object" -> lines from 20 to 32.
The problem is that this kind of line tracking is highly fragile: it is sufficient that someone adds a newline to break my correspondence between associated text a... |
An easy solution would be to hash (md5is pretty easy and accessible) the lines and store the hash along the data.
You can then check the hash against the possibly modified file. If it matches, great, otherwise begin checking previous/next lines for a match.
|
I have this simple code (part of a project) :
```
void displayFileProperties(struct stat* file,char* outputProperties , char * path)
{
struct tm* time;
// code
// code
time = localtime(&file->st_mtim);
// code
}
```
Where eclipse keeps throwing me a warning :
```
passing ... |
st_mtimis a struct timespec (seconds and nanoseconds). You wantst_mtime.
|
I've had a lot of trouble in getting through buffer overflow exploits from start to finish. I end up with a sigsegv fault instead the intended result. I just downloaded Damn Vulnerable Linux and all I see from reviews about it is 'effective at teaching sql injection..., something, else, buffer overflows'.
However I c... |
http://www.linuxjournal.com/article/2902
This is a working example of a buffer overflow that is from the book, The Art of exploitation' It works I have tried it. Great book by the way
|
I'm trying to copy a .tgz file into memory and sending it elsewhere.
Using fopen I get a NULL pointer which tells me that a .tgz file isn't a binary file, but I was wondering if it is even possible to open, buffer, and pass a .tgz file using C standard libraries and libraries?
|
Q: I was wondering if it is even possible to open, buffer, and pass a
.tgz file using C standard libraries and libraries?
Q: Do you want to copy the binary .tgz file as-is? Sure - piece of cake :)
Or do you want tointerpretthe .tgz file, and then copy itscontents?
If the latter, I'd look at "zlib":
http://www.g... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:“C subset of C++” -> Where not ? examples?
I am aware that C is a subset of C++ (i.e. there does not exist valid C code that is not valid C++ code). My question is whetherg++is completely compatible with all C code. For example, will
``... |
C is not a subset of C++.
Try:
foo.c
```
int main() {
int class = 0;
return 0;
}
```
Anyway have fun here:Where is C not a subset of C++?
|
The output of the following c program is:0.000000
Is there a logic behind the output or is the answer compiler dependent or I am just getting a garbage value?
```
#include<stdio.h>
int main()
{
int x=10;
printf("%f", x);
return 0;
}
```
PS:- I know that to try to print an integer value using %f is stup... |
From the latestC11 draft—§7.16 Variable arguments<stdarg.h>:
§7.16.1.1/2
```
...if type is not compatible with the type of the actual next argument
(as promoted according to the default argument promotions), the behavior
is undefined, except for the following cases:
— one type is a signed integer type, the other t... |
I have a small snippet of code.
When I run this on my DevC++ gnu compiler it shows the following output:
```
main ()
{ char b = 'a';
printf ("%d,", sizeof ('a'));
printf ("%d", sizeof (b));
getch ();
}
```
OUTPUT: 4,1
Why is'a'treated as an integer, whereas asbis treated as only a cha... |
Because character literals are of typeintand notcharin C.
Sosizeof 'a' == sizeof (int).
Note that in C++, a character literal is of typecharand sosizeof 'a' == sizeof (char).
|
Is there an established way to parse a string to a Time structure?
What I would ideally like to do is the reverse ofstrftime(...), where instead of producing a string from a time struct and format string, I get a time struct from a string parsed according to the provided format string.
I would prefer not to add addi... |
The corresponding method for parsing strings tostruct tm *isstrptime.
Unfortunately this isn't part of the standard C runtime library and doesn't exist on e.g. windows, but you can reuse a BSD-licensed version, such asthis one.
|
I found this piece of code somewhere on the net. The output of the program is
string
string
string
Can someone please explain me why the first secon and third printf statements printing the same output even though the arguments for them are different?
```
#include<stdio.h>
int main()
{
char a[2][3][3] = {'s','t','r'... |
Since this is 3 dimensional array (array of array of arrays),*a,a, and**aall refer to the same address. The type isn't correct forprintf()for the first two, however it will be interpreted as a flatchar *string in all cases. If you turn up the warnings on your compiler, you should see some about the format string and... |
I was discussing with some friends a piece of code, and we discussed about using memset function in C, which is the order in Big-O notation for this function if we initialize an array of size N?
|
On a system where you have direct access to the page tables and they're stored in a hierarchical way,memsetcould be implemented inO(log n)by replacing the whole virtual address mapping with copy-on-write references to a single page filled with the given byte value. Note however that if you're going to do any future mo... |
I want to compile my NDK code using gnu libstdc++, any clue how to do this?
|
You should add a line toApplication.mk
```
APP_STL := gnustl_static
```
if you want to link it statically, and
```
APP_STL := gnustl_shared
```
if you want to use it as a shared library.
Here is the example of typicalApplication.mk(it should be placed into the same folder where yourAndroid.mkis located):
```
APP... |
Is there a canonical way to check the size of a file in Windows? Googling brings me bothFindFirstFileandGetFileSizeExbut no clear winner. And must GetLastError always be called too?
|
If you just want the size, theGetFileSizeExis the clear winner. Yes,FindFirstFilewill do the job too, but it's really intended for other purposes, and unless you need to do those other things, its use is likely to mislead or confuse the reader.
|
Im writing this program in C and Im having a big problem when I compile it, once I get to the part were I ask the user if hes under 21, if the answer is yes, I ask more questions about that, but when I compile it, the program basicly answers its self. how can I fix this plz?
heres a screenshot, the orange box, i did n... |
You have forgotten to ask the user for input after each question except the first one. Just doscanf("%c", &a);after each question.
|
I was discussing with some friends a piece of code, and we discussed about using memset function in C, which is the order in Big-O notation for this function if we initialize an array of size N?
|
On a system where you have direct access to the page tables and they're stored in a hierarchical way,memsetcould be implemented inO(log n)by replacing the whole virtual address mapping with copy-on-write references to a single page filled with the given byte value. Note however that if you're going to do any future mo... |
I want to compile my NDK code using gnu libstdc++, any clue how to do this?
|
You should add a line toApplication.mk
```
APP_STL := gnustl_static
```
if you want to link it statically, and
```
APP_STL := gnustl_shared
```
if you want to use it as a shared library.
Here is the example of typicalApplication.mk(it should be placed into the same folder where yourAndroid.mkis located):
```
APP... |
Is there a canonical way to check the size of a file in Windows? Googling brings me bothFindFirstFileandGetFileSizeExbut no clear winner. And must GetLastError always be called too?
|
If you just want the size, theGetFileSizeExis the clear winner. Yes,FindFirstFilewill do the job too, but it's really intended for other purposes, and unless you need to do those other things, its use is likely to mislead or confuse the reader.
|
Im writing this program in C and Im having a big problem when I compile it, once I get to the part were I ask the user if hes under 21, if the answer is yes, I ask more questions about that, but when I compile it, the program basicly answers its self. how can I fix this plz?
heres a screenshot, the orange box, i did n... |
You have forgotten to ask the user for input after each question except the first one. Just doscanf("%c", &a);after each question.
|
How do I reuse a plan with different input / output data in FFTW 3?
I am transforming a large number of small arrays, mostly of the same size, and plan creation is currently the bottleneck.
|
There are two options - either create your original plan with a "scratch" set of input/output arrays that you copy each successive data set into and each result out of, or, use the "guru" interface to execute a plan (which normally contains the addresses of the arrays it was created for) with a different set of arrays... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:#include all .cpp files into a single compilation unit?
I'm working on a project in MSVS where most implementation files (.cpp) are excluded from the build and included in a single source file that is compiled.
```
//a.cpp
#include "b.cpp... |
This is called aunity build.
It's supposed to speed up compilation of the source code.
See a related question here that provides more details:The benefits / disadvantages of unity builds?
|
could someone explain the following code snippet to me please, specifically the third line as it seems to be causing an error in my code:
```
char * (strtok_r)(char *s, const char *delimiters, char **lasts) {
char *sbegin, *send;
sbegin = s ? s : *lasts;
...
```
Im guessing its more like Im passing an in... |
Equivalent to
```
if (s)
sbegin = s;
else
sbegin = *lasts;
```
To get more detail about?:operator, you could readthis.
|
I saw this sample code in an answer toHow do function pointers in C work?
```
#import <stdlib.h>
#define MAX_COLORS 256
typedef struct {
char* name;
int red;
int green;
int blue;
} Color;
Color Colors[MAX_COLORS];
void eachColor (void (*fp)(Color *c)) {
int i;
for (i=0; i<MAX_COLORS; i++)... |
printflives instdio.h, notstdlib.h.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:char [length] initialization and dealing with it
I have:
```
char d[7];
```
What is wrong regarding following:
At this moment no memory allocated for variabled. Now I'm going to initialize it:
```
d="bbbbbb";
```
After this type initi... |
OK if you want to fill your char with 'b' character you CAN do it this way
```
char d[7];
int i;
for (i = 0; i < 7; i++) {
d[i] = 'b';
}
```
|
I tried to do some stuff with scanset in scanf but stuck somewhere.
when I write
```
char s1[250];
scanf("%[A-Z]",s1);
input : AHJHkiuy
Output: AHJH
```
and with this,
```
scanf("%[^\n]",s1);
input: abcd ABCD hie
output: abcd ABCD hie /*that is reading white space also (till \n) */
```
Now My question is,... |
You could expand your example a little bit and achieve your goal.
```
scanf("%[A-Za-z ]", s1);
```
|
I use clearsilver library to write CGI. And before my Apache, I use Haproxy. I can output the real user ip in the apache log using:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{X-Forwarded-For}i\"" common
But I nearly test everything, for example:HTTP.XForwardedFor,HTTP_X_FORWARDED_FORand so on to get the real ip from h... |
Have you triedgetenv("HTTP_X_FORWARDED_FOR")? Judging bycgi.c, clearsilver doesn't copy the X-Forwarded-For header, but you should still be able to pluck it out of the environment, whereapache put it.
|
In C, when is it preferrable to use one over the other?
|
It is really a matter of style and of coding conventions, since in Cp[i]isdefinedto be the same as*(p+i)wherepis a pointer andian integral index. AFAIK you could even writei[p]but that is ugly.
This is not always true in C++ (which gives you the power of definingoperator []etc...).
I personally dislike hand-coding&p... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why does sizeof(x++) not increment x?
```
#include<stdio.h>
int main(void)
{
double num=5.2;
int var=5;
printf("%d\t",sizeof(!num));
printf("%d\t",sizeof(var=15/2));
printf("%d",var);
return 0;
}
```
The program gave an output... |
The expressions
```
!num
var=15/2
```
both evaluate to an int.sizeof(int)is always 4 on your platform.
As for why var is not updated:
sizeof is a compile-time operator, so at the time of compilation sizeof and its operand get replaced by the result value. The operand is not evaluated (except when it is a variable ... |
I have a library that calls C code. It's compile with the -custom, -cclib, -l flags, which is working ok when I compile my code against the library with ocamlc,
but when I use the "ocaml" top level to run a script like:
```
ocaml -I /opt/godi/lib/ocaml/pkg-lib/xxxx xxx.cma myprog.ml
```
it says:
```
Error: The ext... |
You should build your own toplevel using "ocamlmktop":
$ ocamlmktop -custom -I /opt/godi/lib/ocaml/pkg-lib/xxxx xxx.cma -o ocaml_with_xxx
Then, you can use it :
$ ./ocaml_with_xxx -I /opt/godi/lib/ocaml/pkg-lib/xxxx
Note that you still need the -I so that the toplevel can find the interface files of the library t... |
What is the easiest way to generate 5 random numbers from 1 to 200 such that
```
randnum[0] < randnum[1] < randnum[2] < randnum[3] < randnum[4]
```
My code looks like this but it always overflows at randnum[4]
```
limit_upper = 10; // generate random number up to 10 for randnum[0]
limit_lower = 0;
srand((time(0... |
Generate random numbers from 1 to 200, sort them as you go, discard duplicates, until you have 5.
|
I have to read tags from an FLV file and there are three chars that identify the data length. I've read them into chardataLength[3], but I don't know what to do next. It's binary, not ASCII, so it's not as simple as usingatoi()to convertchar xxx[] = "123"into the integer 123. Here is my C struct for the tags:
```... |
```
int length = ((unsigned int)xxx[0]) << 16 + ((unsigned int)xxx[1]) << 8 + ((unsigned int)xxx[2]);
```
Big-endian according tohttp://osflash.org/flv.
|
I have to believe that this question must have been already answered multiple times, but I cannot find it. Using Visual Studio C (not C++ or C#), how do I get a list of directories inside another directory? I've tried searching "get list of directories" and "get list of folders" and "find folders in a directory".
... |
The answer fromNTDLSshould solve your problem:Listing directory contents using C and Windows
You have to change the function so the files would be skipped but that shouldn't be the problem. If you don't want to list all the folders of the subdirectorys: leave out the recursive call in the if statement.
|
Why does this syntax work
```
NSString* newDisplayText = [currentDisplayText stringByAppendingString:digit];
```
while this one, (assigning the digit NSStrin to the new string first, and then sending it a message using the stringByAppendingString method). Does not work?
```
NSString* newDisplayText = digit;
[newD... |
stringByAppendingString:returns anNSStringobject. It does not modify the receiver becauseNSStringis immutable.
In your case, you need to assign the result ofstringByAppendingStringtonewDisplayText.
```
NSString* newDisplayText = digit;
newDisplayText = [newDisplayText stringByAppendingString:currentDisplayText];
```... |
I've found a couple of different styled macros.For header files something like this:
```
#define __HEADER_H__
#define _HEADER_H_
#define _header_h
```
simple macros:
```
#define SOMEMACRO something
#define somemacro something
#define SOME_MACRO something
```
macros with arguments:
```
#define func_macro() somethi... |
Using all capital letters is definitely the way to go for constants. However, I would suggest never using function macros. I recommend writing in-line functions. Function macros used in certain situations can result in logical errors. For example:
```
#define FUNC(x) x + x
int main() {
int a = 1;
b = FUNC(a+... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:how to printf uint64_t?
I want to printu_int64_tin C.
I want to know the format specifier for this?
I am a C user, I want to do aprintf().
|
```
#include <inttypes.h>
#include <stdio.h>
uint64_t t = 42;
printf("%" PRIu64 "\n", t);
```
|
How to get a portion of a string.
For Example, the string is:
Input String: "53 56 4B 00 00 41 41 2F 41 54 43 43 54 52 31 2E 41 54 31 2E 4E 37 38"| |
ptr1 ptr2
ptr1It's always going to be at the 7th position starting from left ... |
If you already have the pointers, this is very simple. Use thestd::stringconstructorthat takes a pointer and a length.
```
std::string result(ptr1, ptr2 - ptr1);
```
Or as pointed out in the comments, since pointers can also be used as iterators you can use the dual iterator constructor:
```
std::string result(ptr1... |
I saw this sample code in an answer toHow do function pointers in C work?
```
#import <stdlib.h>
#define MAX_COLORS 256
typedef struct {
char* name;
int red;
int green;
int blue;
} Color;
Color Colors[MAX_COLORS];
void eachColor (void (*fp)(Color *c)) {
int i;
for (i=0; i<MAX_COLORS; i++)... |
printflives instdio.h, notstdlib.h.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:char [length] initialization and dealing with it
I have:
```
char d[7];
```
What is wrong regarding following:
At this moment no memory allocated for variabled. Now I'm going to initialize it:
```
d="bbbbbb";
```
After this type initi... |
OK if you want to fill your char with 'b' character you CAN do it this way
```
char d[7];
int i;
for (i = 0; i < 7; i++) {
d[i] = 'b';
}
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How to Skin an Win32 Application
I'm trying to learn to design a application, but I'm stuck.
For a example, how would I code/get this kind GUI ( Background image, navigation, the engineering icon in the up left corner, styled minimize and... |
This is called "skinning".
See this article for example:(Flipcode)
All you have to do is to create theHBITMAPobject (load it from Resource or from File) and the use theSelectObjectto choose it as a background.
|
manpage forfsyncsays:
If the underlying hard disk has write caching enabled, then the data
may not really be on permanent storage when fsync() / fdatasync()
return.
Is there any way how to ensure that data was physically written to the disk?
|
No, there is not.
Withfsyncyou tell your OS to write it to disk and as far as the OS is concerned, it has been written to disk.
If disks are faking this then it is not something you can really change unfortunately.
With proper disk systems (i.e. BBU raid setups) you can simply enable/disable write cache to avoid thi... |
Some portion of the C code gets greyed in the IDE. I'm unable to figure out why. This happened in many other sections of the code as well. Some of errors I'm getting show that this code isn't getting recognized by the compiler. Could anyone help me by suggesting what is the cause for greying and also how to resolve it... |
The code editor is sophisticated enough to understand that the_32_preprocessor symbol is left undefined in your current build configuration (and is not defined by previously included code).
To reflect that, it grays out the dependent code to point out that it won't be compiled (or even seen by the compiler).
Platfor... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:determine size of dynamically allocated memory in c
I have astructin my c code, but this question is also valid for all other types so I will useintinstead ofstructI created.
```
int *a = realloc(NULL, 10*sizeof(int) );
printf("%d\n",size... |
Remember thatsizeofis evaluated at compile-time (except with VLA, but it's not your case). Imagine that you take the size ofreallocargument as user's input : it's impossible to the compiler to know the real allocated size. So it returns the size of the pointer.
|
I want to know the reason behind the output of this code. I couldn't come up with an answer.
```
#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)
void main()
{
printf("%s %s",h(f(1,2)),g(f(1,2)));
}
```
PS: output is12 f(1,2). I thought it was12 12orf(1,2) f(1,2).
|
```
h(f(1,2))
```
f(1,2)is substituted fora.ais not the subject of a#or##operator so it's expanded to12. Now you haveg(12)which expands to"12".
```
g(f(1,2))
```
f(1,2)is substituted fora. The#operator applied toaprevents macro expansion, so the result is literally"f(1,2)".
|
I have to calculate speed of my algorithm in base of milliseconds. In C++/C , how can i do this? I need to write smth before input and after output but what exactly??
|
You could useclock()function from<time.h>clock()shows how many ticks have passed since your program started. The macroCLOCKS_PER_SECcontains the number of ticks per second, so you can actually get time.
```
//We start measuring here. Remember what was the amount of ticks in the
//beginning of the part of code you wa... |
I have code that looks like the following:
```
#include <stdio.h>
typedef struct SomeStruct* ptr;
main(){
printf("%lu\n",sizeof(ptr));
}
```
The given code will print the size ofstruct SomeStruct*. However I wantsizeof(struct SomeStruct). If I don't know beforehand the name of the struct, is there a way for me to ... |
If you have a variable with typeptr, you can dereference it:
```
ptr v;
sizeof(*v)
```
|
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.Closed11 years ago.
I downloadedthe source code for Rab... |
I wrote awrapperfor ios5, disabled ARC, and rewrote a few vars definitions. It is all working now. :D I might write a bit more about this problem if I find the time.
|
In an Objective-C project, if I am incorporating some C code, does the environmental variable NSZombieEnabled help me debug accidentally de-allocated region which I've done with C code, or does it only work for the Objective-C part?
|
It only works for Objective-C objects. Instead of dying, the objects turn into zombies which will complain on attempt to send them any message. Since plain memory cannot receive messages, this mechanism makes no sense for it.
You need Valgrind or similar tools for generic memory debugging.
|
Can any one tell me where can I find freeImage.so?I have been trying a lot to find the same and have not been succesfull..any help would be highly appreciated.I have tried to convert freeimage.a to freeImage.so and that also haven't worked yet.
Thanking you in advance.
|
You can compile .so from FreeImage sources yourself. Just addBUILD_SHARED_LIBRARYinto FreeImage'sAndroid.mk. You will also need a correct header file to import functions from .so into your project.
P.S. Why don't you like static library .a?
|
What is the use of width in theprintf()statement? Why is the output 7 in the example below?
Code
```
int add(int x, int y)
{
return printf("%*c%*c", x, '\r', y, '\r');
}
int main()
{
printf("Sum = %d", add(3, 4));
return 0;
}
```
Output
Sum = 7
|
A) this is a totally crazy thing to do with printf. But since you asked...
B) the%*csays to take the next two of printf's arguments, and interpret them as a width and a character. Print that character in a field of the specified width. In this case, print a fieldxwide containing the character\r. Same foryand\r. ... |
I am using a system() to call an executable program(A server) . Now after a certain time I want to terminate this program from my c program itself. Does anyone know how to do this?
OS running:(http://rcn-ee.net/deb/rootfs/precise/ubuntu-12.04-r4-minimal-armhf-2012-07-16.tar.xz)
|
The best way to do this is to use a function that gives you more control over the resulting process thansystem()does. However, this would be platform specific.
For Windows, useCreateProcess()which returns aHANDLEwhich you can use later inTerminateProcess()to kill the process.For Unix, usefork()andexec()which gives yo... |
Consider the following C code:
```
struct Foo
{
short a;
long b;
char c;
void* d;
};
```
I know it is possible to know the size of the entire structure using sizeof. Is it possible to know the size of a subset of this structure, or (stated differently) know the distance between two members? I realize could... |
```
offsetof(Foo, d) - offsetof(Foo, a)
```
offsetofgives you the offset from the beginning ofFooto the member specified.
You'll need#include <stddef.h>
|
I need to code a jailed command executor and it needs to execute linux command, I've tried copying /bin to my new root, but system() (e.g. system("ls")) still doesn't work. I've read about copying libraries, however there are any other ways to execute linux command that doesn't involve copying stuff ?
Moreover (and m... |
Either the binaries you copy in to your chroot environment must be statically linked, or you need to copy in the necessary shared libraries as well (/lib//usr/lib).
Non-root processes can execute in a chroot environment just as root processes can, but only root processes can callchroot()so you will need to have a roo... |
I want to have simple syntax highlighting when I am editing code files of a C like language. I know I can just pick C++ syntax highlighting but the language has a lot of keywords similar to HLSL and I want to color them too.
Do I need to write an VS extension for this? Or is this just a matter of proving a VS specifi... |
you can find a few examples on codeplexhttp://www.codeplex.com/site/search?query=highlight&ac=3. Specifically one of the plugins is for HSLS, GLSL, and CG (http://nshader.codeplex.com/)
|
How can I include into my Visual Studio 2010 C-project langinfo.h. I've tried#include <langinfo.h>, but it seems there is no such header file in the VS 2010 environment. I need to get the starting weekday for the locale, but I now the way only using this library.
So, the question is how to solve my problem: how to inc... |
I think, you should use GetLocaleInfoEx() function.
For example, to get the starting day of a week these calls might be used:
```
# if defined(_WIN32_WINNT_VISTA) && WINVER >= _WIN32_WINNT_VISTA && defined(LOCALE_NAME_USER_DEFAULT)
GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_IFIRSTDAYOFWEEK, wsDay, 4)
# else... |
my code is:-
```
#include<stdio.h>
#include<conio.h>
#define sq(x) x*x*x
void main()
{
printf("Cube is : %d.",sq(6+5));
getch();
}
```
The output is:-
```
Cube is : 71.
```
now please help me out that why the output is 71 and not 1331...
thank you in advance.
|
Always shield your macro arguments with parenthesis:
```
#define sq(x) ((x) * (x) * (x))
```
Consider the evaluation without the parenthesis:
```
6 + 5 * 6 + 5 * 6 + 5
```
And recall that*has a higher precedence than+, so this is:
```
6 + 30 + 30 + 5 = 71;
```
Get to know the precedence rules if you don't alread... |
In a && b , this returns true if both a and b are equal to 1. If a=-1 and b=-1 then also the expression returns true.Similar is the case with a||b,where a=-1 and b=0,it returns true. Can anybody please explain the reason.
|
a && breturns 1 whenbothaandbarenonzero, not just when they're equal to 1. Otherwise it returns 0.
a || breturns 1 whenat least one ofaorbisnonzero, not just when one of them is equal to 1. Otherwise it returns 0.
To give some examples:
```
0 && 0 -> 0
1 && 0 -> 0
1 && 1 -> 1
2 && 1 -> 1
-1 && -1 -> ... |
I have a project which I try to compile with Eclipse-CDT. The project depends on a library with header files and source files. How can I configure the project in Eclipse such that it will compile the needed source files from the library with the project?
With a makefile I use:
```
SRC+=lib_source.c
```
|
You can add linked source file.
Choose project properties and in the left panel choose c++ general.
Under it choose path and symbols.
Now in the right panel tabs choose source location and add linked source folder.
Include you need to define in "include" (under c++ build you will find settings)
|
```
#include<stdio.h>
int main(void){
int *ptr,a,b;
a = ptr;
b = ptr + 1;
printf("the vale of a,b is %x and %x respectively",a,b);
int c,d;
c = 0xff;
d = c + 1;
printf("the value of c d are %x and %x respectively",c,d);
return 0;
}
```
the out put value is
```
the vale of a,b is 57550c90 and 57550... |
Because pointers are designed to be compatible with arrays:
```
*(pointer + offset)
```
is equivalent to
```
pointer[offset]
```
So pointer aritmetic doesn't work in terms of bytes, but in terms ofsizeof(pointer base type)-bytes sized blocks.
|
I have the following code, and the only thing I can physically see it evaluating is line 18 which is the call to printf(). It doesn't go any further.
```
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int cylNum;
double disp, pi, stroke, radius;
pi = 3.14159;
printf("Welcome to the E... |
the variables you're trying to read should be parameters to "scanf()", not the result of scanf():
```
printf("Enter number of cylinders (then press enter): ");
scanf("%d", &cylNum);
...
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
Ruby's for/in loop can have many statement:
```
for a in 1..2 do
expression 1
expres... |
Yes, formally speaking all loop statements in C take onlyonestatement as the loop body. The same is true for branching statements (likeif) and virtually all other statements in C.
However, thatonestatement can be acompoundone. A compound statement begins with{, ends with}and contains an arbitrary number of nested sta... |
My question is regarding the CPP backend, does it serve the same purposes as the C backend?
The C backend was one of my favorite LLVM features, and I'm very upset it was removed.
Whats the real differences?
I' most appreciative of any help.
Reference:The LLVM 3.1 Release Notes"The C backend has been removed ..."
|
The CPP backend creates LLVM API calls to create an AST that represent the equivalent of the LLVM assembly. You can try the CPP backend athttp://llvm.org/demo/by selecting the "LLVM C++ API code"Target.
The C backend creates C code that execute the semantics of the LLVM assembly.
They are fundamentally different.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Difference between format specifiers %i and %d in printf
I just checked the reference, it says both of them indicate signed integer. I thought there must be some difference
|
There is no difference.
From the C99 standard document, section 7.19.6.1:
d, iThe int argument is converted to signed decimal in the style [−]dddd.
The precision specifies the minimum number of digits to appear; if the
value being converted can be represented in fewer digits, it is
expanded with leading zeros. ... |
I have the followingWndProc:
```
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM w, LPARAM l)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_MOUSEMOVE:
return 0;
default:
return DefWindowProc(hWnd, message, w, l);
}
}
``... |
TheWM_MOUSEMOVEmessage is just the window manager telling youthat the mouse has movedand if your application wants to do something with that information it can do so. It isnota mechanism where you can intercept mouse movements and cancel them at will.
|
I try to use CFLocaleCopyCurrent under OSX 10.5.8 but I get weird error:
```
#include <CoreFoundation/CoreFoundation.h>
int main(int argc, char **argv){
setlocale(LC_ALL, "");
CFLocaleRef loc = CFLocaleCopyCurrent();
return 0;
}
Undefined symbols:
"_CFLocaleCopyCurrent", referenced from: _main in ccn51X... |
try/usr/bin/gcc -framework Foundation test.c
|
im working on converting C code to c++ , in one section of the code i have something like
function array in C that looks like:
this is how C looks like :
```
void func1(bool a)
{
..
}
void func2(bool a)
{
..
}
void func3(bool a)
{
..
}
struct func
{
void (*f)(incoming *);
int arg_length;
};
typedef stru... |
You could define a class, and insert a '[]' operator to get pointers to functions, in your case.
|
I have a simple echo server written in C, I would like to stop the server if it received thequitword
```
int n;
char buffer[256];
while(strcmp(buffer,"quit") != 0)
{
n = read(sock,buffer,255);
if (n < 0)
{
perror("ERROR reading from socket");
exit(1);
}
... |
It's likely the buffer isn't 0-terminated so using "string" comparison functions is wrong. You should trystrncmpormemcmpinstead.
Also, in thewhilecondition, you're testing before actually reading intobuffer.
|
I am trying to write raw binary bits at a time to a file.
I have found an example that uses unsigned char ->https://stackoverflow.com/a/2666669/1541965
But the minimum size is 8 bit (because of the unsigned char 0 to 255).
Is there a way to write bits to a file in a more direct way?
Thanks.
|
You haven't said what operating system you're using. But generally the smallest unit you get to write to a file is one 8-bit byte. If you want to write individual bits, you'll need to assemble them into bytes in your own code. I don't know of any OS whose file IO facilities allow writing of individual bits.
|
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 GPL is ok, there'sSECCURE
I haven't used it personally but did stumble upon it couple of months ago when evaluating my options for a pet project.
|
Consider the below program:
```
#pragma startup foo1
#pragma exit foo2
void foo1()
{
printf("Called before main\n");
}
void foo2()
{
printf("Called after main\n");
}
int main()
{
printf("main called\n");
return 0;
}
```
I am getting the output as:http://ideone.com/ooMFI
```
main called
```
Why t... |
Because none of these pragmas are recognized byGCC. In general, stay clear of pragmas if you're trying to write portable code, because they differ per compiler and even per platform within the same compiler family.
|
Well, I would like to initiate my 2D array by a void function. But I obtain a Segmentation Fault...
That's my code :
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void groupeetchoixgen(int*** choixGEN);
void main(int args, char **argv)
{
int** choixGEN;
int i,j... |
On this line:
```
choixGEN=(int**) malloc (sizeof(int*)*2);
```
you are only allocating space for 2int*s, but you access the 3rd element in theforloop.
|
I'm calling a c program using crontab.
If I call the program directly, everything is fine.
If the program is called by cron, my .log files can't be opened.
the program is in a directory
/stuff1/stuff2/stuff3/program
all pathnames in the program are absolute
just to make sure, I chmod 777'd everything in stuff3
ED... |
This'll probably help you get to the bottom of it, since you know at least some C:http://stromberg.dnsalias.org/~strombrg/debugging-with-syscall-tracers.html
|
```
#include <stdio.h>
int main()
{
int *p = (int*) 60; --- Line 1
int *q = (int*) 40; --- Line 2
printf("%d", p-q); //Output is 5
return 0;
}
```
Could anybody please explain to me the output of this program?
|
It means the (implementation-defined) action of assigning an integral value to a pointer happens. This often means thatppoints to the memory address at60andqto the address at40. These memory addresses could be in virtual memory, hardware memory, and many implementations have different conversion routines for these.
S... |
I want to share memory between two processes. One way I know is tommapa shared file. However, I don't want to use a shared file, I want an anonymous mapping in the memory. How can I do that.
|
shm_openis your friend. You can unmap the shared region by usingshm_unlink.
|
In a && b , this returns true if both a and b are equal to 1. If a=-1 and b=-1 then also the expression returns true.Similar is the case with a||b,where a=-1 and b=0,it returns true. Can anybody please explain the reason.
|
a && breturns 1 whenbothaandbarenonzero, not just when they're equal to 1. Otherwise it returns 0.
a || breturns 1 whenat least one ofaorbisnonzero, not just when one of them is equal to 1. Otherwise it returns 0.
To give some examples:
```
0 && 0 -> 0
1 && 0 -> 0
1 && 1 -> 1
2 && 1 -> 1
-1 && -1 -> ... |
I have a project which I try to compile with Eclipse-CDT. The project depends on a library with header files and source files. How can I configure the project in Eclipse such that it will compile the needed source files from the library with the project?
With a makefile I use:
```
SRC+=lib_source.c
```
|
You can add linked source file.
Choose project properties and in the left panel choose c++ general.
Under it choose path and symbols.
Now in the right panel tabs choose source location and add linked source folder.
Include you need to define in "include" (under c++ build you will find settings)
|
```
#include<stdio.h>
int main(void){
int *ptr,a,b;
a = ptr;
b = ptr + 1;
printf("the vale of a,b is %x and %x respectively",a,b);
int c,d;
c = 0xff;
d = c + 1;
printf("the value of c d are %x and %x respectively",c,d);
return 0;
}
```
the out put value is
```
the vale of a,b is 57550c90 and 57550... |
Because pointers are designed to be compatible with arrays:
```
*(pointer + offset)
```
is equivalent to
```
pointer[offset]
```
So pointer aritmetic doesn't work in terms of bytes, but in terms ofsizeof(pointer base type)-bytes sized blocks.
|
I have the following code, and the only thing I can physically see it evaluating is line 18 which is the call to printf(). It doesn't go any further.
```
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int cylNum;
double disp, pi, stroke, radius;
pi = 3.14159;
printf("Welcome to the E... |
the variables you're trying to read should be parameters to "scanf()", not the result of scanf():
```
printf("Enter number of cylinders (then press enter): ");
scanf("%d", &cylNum);
...
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
Ruby's for/in loop can have many statement:
```
for a in 1..2 do
expression 1
expres... |
Yes, formally speaking all loop statements in C take onlyonestatement as the loop body. The same is true for branching statements (likeif) and virtually all other statements in C.
However, thatonestatement can be acompoundone. A compound statement begins with{, ends with}and contains an arbitrary number of nested sta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.