question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Is there a better way than parsing /proc/self/maps to figure out memory protection?
I have a pointer and I want to check if the referenced memory is readable, writeable and/or executable. How can I do this?
|
You will have to parse the file/proc/self/mapswhich contains memory mappings of your process, and check which of the mappings lie within the value of your pointer (if any). The/proc/self/mapsfile contains the memory protection (read/write/execute).
Seethis questionfor more info about the maps file.
|
I am looking for a way to make a program in C or C++ that detects if there was any files altered, renamed, moved or deleted in a specified directory for Linux systems. Is there a way to do that?
|
You wantinotify(and itsman page.)
|
Given
```
struct S {
SomeType single_element_in_the_struct;
};
```
Is it always true that
```
sizeof(struct S) == sizeof(SomeType)
```
Or it may be implementation dependent?
|
This will usually be the case, but it's not guaranteed.
Any struct may have unnamed padding bytes at the end of the struct, but these are usually used for alignment purposes, which isn't a concern if you only have a single element.
|
Why do the functions displayed in a callstack generated in Solaris always contain 6 parameters?
In most of the cases, the original function will not be having 6 parameters at all. Sometimes I also find, the parameter values displayed are not matching the order in function declaration.
Any pointers or links for understanding these concepts and debugging in Solaris will be helpful.
|
I believe, depending on your version of Solaris (64 bit?), that the calling convention specifies the first 6 parameters of a function be passed by registers. Even if they're not being used, your debugger may just be showing the contents of these 6 registers.
Edit: fromhttp://publib.boulder.ibm.com/httpserv/ihsdiag/get_backtrace.html#pstack
```
Note that pstack doesn't know how many arguments there are so it always displays six. So if you know that some function has only two arguments, ignore whatever pstack displays after the first argument.
```
|
Hello I'd like to list all real users on Linux/*nix and it's data. I probably need to parse/etc/passwdand/etc/shadowand check if user have password.
The problem is that is not cross-platform (on *BSD there is no/etc/shadow). Is there any cross-platform library/command I can use?
|
See man pages for getpwent.
```
The getpwent() function returns a pointer to a structure containing the
broken-out fields of a record from the password database (e.g., the
local password file /etc/passwd, NIS, and LDAP).
```
I will add that if you want to check the passwords, look at getspent, getspnam for listing the shadow password file. The man page says that the getspent etc. functions might not be cross-platform though.
|
I used to think the second argument forinet_ntopshould always be astruct in_addrorstruct in6_addr. But then I looked up thePOSIX definition:
```
const char *inet_ntop(int af, const void *restrict src,
char *restrict dst, socklen_t size);
```
[...] Thesrcargument points to a buffer holding an IPv4 address if theafargument is AF_INET, or an IPv6 address if theafargument is AF_INET6; the address must be in network byte order. [...]
As you can see both the function prototype and the description are vague.
Why is this? And what are allowed/portable choices forsrc?
|
It's a pointer to an IPv4 or IPv6 as stored in the respective headers - so a 4 byte buffer in the case of IPv4, and a 16 byte buffer in the case of IPv6.
struct in_addrandstruct in6_addrare convenient structures for storing such addresses, but you could useunsigned char [4]andunsigned char [16]respectively, if you wanted.
|
On a linux box
is it compulsory to write a program into a file and compile it
cant this be done from command line
```
localhost$gcc "include<stdio.h> int main(){printf('hello world'); return o; }"
```
|
sure you can, but i doubt that that makes sense....
```
$ echo '#include <stdio.h>
int main() { printf("hello world\n"); return 0; }' | gcc -x c -
$ ./a.out
hello world
$
```
gcc options:
```
-o <file> Place the output into <file>
-x <language> Specify the language of the following input files
Permissible languages include: c c++ assembler none
'none' means revert to the default behavior of
guessing the language based on the file's extension
```
|
Whats the difference between aNull pointer& aVoid pointer?
|
Null pointeris a special reservedvalueof a pointer. A pointer of any type has such a reserved value. Formally, each specific pointer type (int *,char *etc.) has its own dedicated null-pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere.
Void pointeris a specific pointertype-void *- a pointer that points to some data location in storage, which doesn't have any specific type.
So, once again,null pointeris avalue, whilevoid pointeris atype. These concepts are totally different and non-comparable. That essentially means that your question, as stated, is not exactly valid. It is like asking, for example, "What is the difference between a triangle and a car?".
|
I thought I read about a C standard library function recently that was able to return a pointer to any extern variable whose name was passed to it as a const char *. I think that it works via linker symbols, if that helps.
|
You could be thinking ofdlsym, which is not part of the C standard library but part of the POSIX API.
|
Can someone please point me to some documentation on the virtual memory maps used for Linux and Windows. By that I mean what virtual addresses, code, writable static data, the stack and the heap (along with other kernel bits) will normally be placed in, in a typical process?
|
Since the advent of ASLR, it's mostly on random virtual addresses.
|
This may be a stupid question but how does the sizeof operator know the size of an array operand when you don't pass in the amount of elements in the array. I know it doesn't return the total elements in the array but the size in bytes, but to get that it still has to know when the array ends. Just curious as to how this works.
|
sizeofis interpreted at compile time, and the compiler knows how the array was declared (and thus how much space it takes up). Callingsizeofon a dynamically-allocated array will likely not do what you want, because (as you mention) the end point of the array is not specified.
|
Not C++, not C#, just plain old C for my computer science class.
I see options for C#, F#, Visual Basic, and Visual C++, but if there's an easy way to get it to work with C, I'm not seeing it.
*"set up as an IDE" in this case, meaning use Visual Studio to compile, debug, and run the written programs via VS2010, just as I've been using it previously for programming in c#.
|
Nothing special is needed. Just write your code in a .c source code file instead of a .cpp file. The project templates create .cpp files, just rename them with right-click + Rename.
|
```
#include<stdio.h>
void f(void)
{
int s = 0;
s++;
if(s == 10)
return;
f();
printf("%d ", s);
}
int main(void)
{
f();
}
```
what is the output of the programme!??
i m segmentation fault ...what is it?
|
Sincesis a local variable, each recursive call tof()gets its own copy of it. So every timeswill be 1 and the you get a stack overflow exception.
|
Simple code:
```
ATOM atom = GlobalAddAtom(L"TestCpp1");
```
It returns 0 and GetLastError returns 0x5 (Access Denied). Nothing on MSDN about it.
This is on Win7. Admin rights make no difference.
Same code works on XP. AddAtom (local) works on Win7.
What's causing this?
|
Is this a GUI or Console application? One thing you might try is to explicity call LoadLibrary("User32") before calling GlobalAddAtom.
Here is a reference to someone that had a similar problem, on XP maybe this is relevant?http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2004-03/0851.html
|
Insome of its API functionMicrosoft use the "multi-string" format to specify a list of strings.
As I understand it, a multi-string is a null-terminated buffer of concatenated null-terminated strings. But this can also be interpreted as a list of strings, separated by a null character and terminated by two null characters.
Here comes an example. A list composed of the following items:
```
"apple", "banana", "orange"
```
Becomes:
```
apple\0banana\0orange\0\0
```
But now I wonder:
How would anempty listbe represented ?
Would it be:
```
\0
```
Or:
```
\0\0
```
I failed to found an accurate documentation that clarifies this. Any clue ?
|
\0
|
My understanding is that C++ reinterpret_cast and C pointer cast is a just
a compile-time functionality and that it has no performance cost at all.
Is this true?
|
It's a good assumption to start with. However, the optimizer may be restricted in what it can assume in the presence of areinterpret_cast<>or C pointer cast. Then, even though the cast itself has no associated instructions, the resulting code is slower.
For instance, if you cast an int to a pointer, the optimizer likely will have no idea what that pointer could be pointing to. As a result, it probably has to assume that a write through that pointer can change any variable. That beats very common optimizations such as storing variables in registers.
|
In C (linux) how will I be able to find out if the squareroot of a number is and integer or a floating point.
I want to write a program using a function pointer which adds up all the Perfect squares
upto the limit sepcified.
|
Here you go. Compile it with-lmon Linux.
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int checkRoot(double n) {
long n_sqrt = (long)(sqrt(n)+0.5);
return n_sqrt*n_sqrt == n;
}
int main() {
double n = 9.0;
if(checkRoot(n)) {
puts("Perfect root.");
}
else {
puts("Not quite.");
}
return EXIT_SUCCESS;
}
```
You should also read this discussion.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago.
gcc 4.4.3 c89
I am just getting started with log4c. However, there is very little documentation out there for how to get started with it.
I am wondering does anyone know of any tutorials, articles on how to get started?
|
If you unpack the tar ball from the project page athttp://log4c.sourceforge.net/there is a doc directory containing examples etc.
Also there is the developer's guide athttp://www.slideshare.net/gzm55/log4-c-developers-guide-presentation.
|
I have a test program which prompts for input from user(stdin), and depending on inputs, it asks for other inputs, which also need to be entered.
is there a way I can have a script do all this work ?
|
There's a program calledexpectthat does pretty much exactly what you want -- you can script inputs and expected outputs and responses based on those outputs, as simple or complex as you need. See also thewikipedia entryfor expect
|
What's the equivalent to Windows'sVirtualAllocin OS X? That is, how can i reserve a contiguous address space without actually commiting it and then commit chunks of it later?
Thanks,
Alex
|
Themmap()function, called withMAP_ANON | MAP_PRIVATE, is very roughly equivalent toVirtualAlloc()with theMEM_RESERVEflag. Memory is then committed by touching each page in the mapping.
|
How do I use pow() and sqrt() function in Ubuntu?
I have included the math.h header file but it still gives me an error.
|
Try adding-lmto your linker command. Most of the math functions live inlibmwhich needs to be explicitly linked in.
|
I have a C array called buf. Here is it's definition:
char buf[1024];
Now, my current code takes fromstdinand usesfgets()to set that array, however I wish to use code to set it instead. Right now the line that sets buf looks like this:
fgets(buf, 1024, stdin);
Basically, I want to replace stdin, with say... "My String". What's the best way to do this?
|
Look forsprintf, for example here:Cpp reference
Edit:
```
sprintf(buf, "My string with args %d", (long) my_double_variable);
```
Edit 2:
As suggested to avoid overflow (but this one is standard C) you can usesnprintf.
|
intelligent people!
Thanks so much for checking out my post.
Right now I'm running this:
```
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/top"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-stats", @"pid,cpu", nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
```
and it is giving me the error:
```
Error opening terminal: unknown.
```
Any clues? Thanks again!
|
It seems as if it was my arguments:
```
arguments = [NSArray arrayWithObjects: @"-s", @"1",@"-l",@"3600",@"-stats",@"pid,cpu,time,command", nil];
```
Thanks!
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Is there a performance difference between i++ and ++i in C++?
In terms of usage of the following, please rate in terms of execution time in C.
In some interviews i was asked which shall i use among these variations and why.
```
a++
++a
a=a+1
a+=1
```
|
Here is whatg++ -Sproduces:
```
void irrelevant_low_level_worries()
{
int a = 0;
// movl $0, -4(%ebp)
a++;
// incl -4(%ebp)
++a;
// incl -4(%ebp)
a = a + 1;
// incl -4(%ebp)
a += 1;
// incl -4(%ebp)
}
```
So even without any optimizer switches, all four statements compile to the exact same machine code.
|
I implemented a function called abs(). I get this error:
Intrinsic function, cannot be defined
What have I done wrong?
I'm using Visual Studio 2005.
|
Intrinsic function, cannot be defined
In this case,intrinsicmeans that the compileralreadyhas an implementation of a function calledabs, and which you cannot redefine.
Solution? Changeyourfunction's name to something else,snakile_absfor example.
Check the MSDN documentation on theabsfunction for more information.
|
I want to find out for how long (approximately) some block of code executes. Something like this:
```
startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);
```
How?
|
You can use theclockmethod intime.h
Example:
```
clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
```
|
As a continuation ofthis questionI'm wondering if I can get some simple sample code as to how tomake use of getrusage. I would like to use it to find thetime CPU used by a process, ideally from thePID.
I'm working in Cocoa, Objective_C and of course C. Any help would be awesome!
Thanks
|
I'm not so sure about OS X, but for what it's worth, if this were on Linux it would be a fairly simple matter of reading from a file underneath/proc/<pid>. OS X doesn't seem to haveprocfs(at least, not standard), though, so this answer will fall into the "any help" category. :)
|
I have written a C based library and for it to work in multi-thread parallely, I create some global mutexes in the init function.
I expect the init function to be called in the main thread before the library APIs are used in multi-thread.
But, if the init function itself is called in multi-thread directly, then it is a problem. Is there a way to protect the init function itself from my library? One way I can think of is to ask the application to create a mutex and protect parallel calls to my init function, but can I protect it from my library itself?
|
You probably want to use teh default entry point functions.
In windows you can useDllMainto create and destroy your mutexes.
On Linux and probably some other Unixes you can use__attribute__((constructor))and__attribute__((destructor))on your entry and exit functions.
In both these case, the functions will be called once on load and unload
|
I take blocks of incoming data and pass them through fftw to get some spectral information. Everything seems to be working, however I think I'm getting some aliasing issues.
I've been trying to work out how to implement a hann window on my blocks of data. Google has failed me for examples. Any ideas or links I should be looking at?
```
double dataIn[2048] > /* windowing here? */ > FFT > double freqBins[2048]
```
Update
Thanks to Oli for pointing out the issue I'm actually trying to fix is spectral-leakage, NOT aliasing...
|
http://en.wikipedia.org/wiki/Hann_function. The implementation follows from the definition quite straightforwardly. Just use thew(n)function as multiplier, loop through all your samples (changingnas you go), and that's it.
```
for (int i = 0; i < 2048; i++) {
double multiplier = 0.5 * (1 - cos(2*PI*i/2047));
dataOut[i] = multiplier * dataIn[i];
}
```
|
I have read few articles about different Windows C entry pooints, wmain and WinMain.
So, if I am correct, these are added to C language compilers for Windows OS. But, how are implemented?
For example, wmain gets Unicode as argv[], but its Os that sends these arguments to program, so is there any special field in the .exe file entry which says to windows to pass arguemnts as unicode? Thanks.
|
Modern versions of Windows internally use UTF-16. Therefore, when you launch an executable, all command line arguments likely are passed as UTF-16 from the onset, and the runtime library linked into the launched application either passes the arguments through unscathed (if usingwmain) or converts them to the local encoding automatically (if usingmain). (Specifically this would be done bywmainCRTStartup/mainCRTStartupwhich are the actual entry points used for console Windows applications.)
|
I am new to writing programs in c++ and i want to know if there is a way to export it to a windows format. Also what is a good way to learn objective-c, is it very different from c++? Thank you in advance.
|
Using mingw32 you can cross compile for windows. Seehttp://www.mingw.org/wiki/LinuxCrossMinGW
|
Hello I was looking around on the internet and I was unable to find anything concrete. I would like to find a good Wiimote API (in C or C++) that also implements usage of the Wii Motion Plus accessory. If anyone knows of any good ones it would be greatly appreciated. Thanks.
|
I useWiiYourself.
You might need to adapt one thing or another, such as the connection timeout, but it works quite well.
Take also a look at WiiBrew'sWiimote pageandWiimote driver page.
|
If I do*ptr[x], is that equivalent to*(ptr[x]), or(*ptr)[x]?
|
*(ptr[x])
See theWikipedia operator precedence table, or, for a more detailed table,this C/C++ specific table.
|
EDIT: An initial "float** floats;" was a typo, corrected. Also, "*floats[0] = 1.0;" does work, but "*floats[1] = 1.0;" segfauls at that point. The array is malloced. Compilation has no warnings on pedantic c99.
This worked:
(pseudo:)
```
void func(int*);
int i;
func(&i);
void func(int* i) {
func2(i);
}
void func2(int* i) {
*i = 2;
}
```
initial value changed to 2.
but this didn't work:
```
void func(float**);
float* floats;
func(&floats);
void func(float** floats) {
func2(floats);
}
void func2(float** floats) {
*floats[1] = 1.0;
}
```
segfault on assignment;
|
because 'floats' is a bad pointer. Sure, you declared the pointer, but you haven't allocated any memory, so wherever it happens to point will be invalid.
Also, the address of a float** is a float***, which is not what your function calls for.
|
I have the below program to obtain current date and time.
```
int main(void)
{
time_t result;
result = time(NULL);
struct tm* brokentime = localtime(&result);
printf("%s", asctime(brokentime));
return(0);
}
```
And the output of the program is as follows :
```
Tue Aug 24 01:02:41 2010
```
How do I retrieve only the hour value say 01 from the above ?Or is there any other system call where the currect hour of the system can be obtained ? I need to take an action based on this.
Thanks
|
```
struct tm* brokentime = localtime(&result);
int hour = brokentime->tm_hour;
```
|
I have an unsorted linked list. I need to sort it by a certain field then return the linked list to its previous unsorted condition. How can I do this without making a copy of the list?
|
When you say "return the linked list to its previous unsorted condition", do you mean the list needs to be placed into a random order or to the exact same order that you started with?
In any case, don't forget that a list can be linked into more than one list at a time. If you have two sets of "next"/"previous" pointers, then you can effectively have the same set of items sorted two different ways at the same time.
|
I am compiling on a 64 bit architecture with the intel C compiler. The same code built fine on a different 64 bit intel architecture.
Now when I try to build the binaries, I get a message "Skipping incompatible ../../libtime.a" or some such thing, that is indicating the libtime.a that I archived (from some object files I compiled) is not compatible. I googled and it seemed like this was usually the result of a 32->64 bit changeover or something like that, but the intel C compiler doesnt seem to support a -64 or some other memory option at compile time. How do I troubleshoot and fix this error?
|
You cannot mix 64-bit and 32-bit compiled code. Config instructions for Linuxare here.
|
What is a good algorithm to fill an array with 0s and 1s combinations.
For example if I have three columns the combinations would be:
(1 1 1)
(0 1 1)
(1 0 1)
(0 0 1)
(1 1 0)
(0 1 0)
(1 0 0)
(0 0 0)
It makes a total of 8 rows (I hope I'm right here).
So how to determine the needed number of rows in advance (depending on the N number of columns) and then how to fill the array out programatically? Any programming language is fine (I tagged C and lisp because of familiarity) it's the algorithm that is needed. Thanks
|
Count up from 0 in base 2
```
0 = 000
1 = 001
2 = 010
...
7 = 111
```
|
Can anybody tell me how to use
```
PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12);
int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca);
```
any documenatation reference will also work.
|
Without error-checking:
```
FILE *p12_file;
PKCS12 *p12_cert = NULL;
EVP_PKEY *pkey;
X509 *x509_cert;
STACK_OF(X509) *additional_certs = NULL;
p12_file = fopen("foo.p12", "rb");
d2i_PKCS12_fp(p12_file, &p12_cert);
fclose(p12_file);
PKCS12_parse(p12_cert, "password", &pkey, &x509_cert, &additional_certs);
```
The private key is now inpkey, the certificate inx509_certand any additional certificates inadditional_certs.
|
I'm trying to write a simple device driver for Windows 7 x64 using the latest Windows Driver Kit that will parse the Interrupt Descriptor Table (IDT) and print the contents. I plan on doing this by using the SIDT (store IDT) assembly instruction, however MSVC does not allow you to use inline asm when compiling for x64. Is there any way to get around this restriction? I checked MSDN and it said to look at the compiler intrinsics, but I don't believe there is an intrinsic available that does what I need.
The code I intended to use:
```
__asm sidt, idt_info // Where idt_info is a suitable struct
```
|
There's an intrinsic available for it,__sidt().
|
Ais anMxKmatrix,Bis a vector of sizeK, andCis aKxNmatrix. What set of BLAS operators should I use to compute the matrix below?
```
M = A*diag(B)*C
```
One way to implement this would be using three for loops like below
```
for (int i=0; i<M; ++i)
for (int j=0; j<N; ++j)
for (int k=0; k<K; ++k)
M(i,j) = A(i,k)*B(k)*C(k,j);
```
Is it actually worth implementing this in BLAS in order to gain better speed efficiency?
|
First computeD = diag(B)*C, then use the appropriate BLAS matrix-multiply to computeA*D.
You can implementdiag(B)*Cusing a loop over elements ofBand calling to the appropriate BLAS scalar-multiplication routine.
|
```
// PWM frequency:
// 0 - 48 kHz
// 1 - 12 kHz
// 2 - 3 kHz
enum { MOTOR_FREQUENCY = 1 };
// Configure Timer 2 w. 250x period.
T2CON = 1 << 2 | MOTOR_FREQUENCY /* << 0 */;
```
Have i understood this right?
11111111 Arithmetic left-shift-by-two of 0 or 1 or 2
Means:
```
T2CON = 1 << 2 | 0 = 1111 1100
T2CON = 1 << 2 | 1 = 1111 1000
T2CON = 1 << 2 | 2 = 1111 0000
```
Kind Regards, Sonite
|
```
1 << 2 = 100b
```
So with the OR:
```
100b | 1 = 101b
100b | 2 = 110b
```
|
I'm working on Windows with the Quicktime-API and I wonder, how to get the start timecode (SMPTE) of a movie file? Can someone post a link or an example how to do that?
|
You'll need to get the timecode track's media handler using {GetMovieIndTrackType(theMovie, 1, TimeCodeMediaType, movieTrackMediaType)}, {GetTrackMedia}, {GetMediaHandler}.
Go to the beginning of the movie, then use {TCGetCurrentTimeCode} and possibly {TCTimeCodeToString} to get the current time code. Alternatively look at {TCFrameNumberToTimeCode} with frame set to the first frame of the movie.
If you have several TC tracks with each not spanning all of the movie, you might have to loop over GetMovieIndTrackType to get the right one.
|
What is the difference between C & C# on the basis of OOP concepts?
|
The difference is in the support of those OOP concepts. C does not support OOP concepts while C# does.
|
I'm using a naive approach to this problem, I'm putting the words in a linked list and just making a linear search into it. But it's taking too much time in large files.
I was thinking in use a Binary Search Tree but I don't know if it works good with strings. Also heard of Skip Lists, didn't really learn it yet.
And also I have to use the C language...
|
You can put all of the words into atrieand then count the number of words after you have processed the whole file.
|
When generating VS2010 targets with CMake, I would like the /LTCG flag turned on (only for release + releasewithdebinfo if possible, but its okay if its on for debug builds). How do I modify the linker flags?add_definitions()doesn't work because that only modifies compiler flags. And yes, I have wrapped it in if(MSVC).
How do I modify the linker flags?
|
You can modify the linker flags in MSC using #pragma comment(linker, ...)
However, if you'd like to do it in the build process with cmake, here are the names you need to know:
CMAKE_EXE_LINKER_FLAGSCMAKE_SHARED_LINKER_FLAGSCMAKE_MODULE_LINKER_FLAGS
(Thanks toCmake.org).
|
I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.
If it is possible, can you give me a link to an example application ? I saw something about libXul, is it needed ? where can i find it ?
TNX, Vertilka
|
I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.
The usual way to create a XUL GUI on top of a C++ application is by writing a XULRunner application with the C++ code wrapped in an XPCOM plugin.
You can make your application "stand-alone" by creating an installer program that copies the XULRunner runtime together with the XPCOM plugin to the user's computer. This is howGStreamerSongBirdworks, for example.
|
I need Mosquittohttp://mosquitto.orgto work with SSL.
I've read several examples with OpenSSL, but as I've never worked with sockets in C, can someone tell me what do I have to change for my existing sockets? (Accept, write, read?)
Thank you very much
|
My understanding is that after you've called accept(), you then have to configure the socket for use with OpenSSL - assuming you've also already configured the library for use as well.
After that, you can use SSL_read() and SSL_write() instead of read() and write().
When you want to close the socket, you need to disable SSL support before calling close().
It's a reasonable undertaking for certain - the socket code isn't really the problem, it's understanding what you need to do to start and stop the TLS support and ensuring that you don't miss something out which could lead to vulnerabilities.
|
I am thinking about usingCRC-32orSHA-1, possibly both in a C program I develop on Linux (Ubuntu).
Are there any easy way to use libraries for either? Cutting and pasting a CRC-32 algorithm into the source code of my program seems simple enough, but doing the same for SHA-1 feels slightly shaky. Are there any easy way to use libraries, preferably in Ubuntu but not necessarily?
I am using C, but C++ would be OK if I had to.
|
The OpenSSL interface is pretty simple:
```
#include <openssl/sha.h>
unsigned char *SHA1(const unsigned char *d, unsigned long n, unsigned char *md);
```
dis a pointer to the input to be hashed, with lengthn.mdis a pointer toSHA_DIGEST_LENGTHbytes where the SHA1 hash will be stored.
|
I have code written using GNU Pth (http://www.gnu.org/software/pth/) and I want to move to Pthreads because I want it to be cross-platform (Unix, Mac, Windows).
Are there and caveats I should watch out for while going about switching from Pth to Pthreads, or is it mostly just a matter of realigning arguments and variable types?
|
Just to let people know: it is a fairly easy transition. Some of the naming is different, and there are slight differences in argument number and order but they are very similar overall.
Just look up the api docs for both and look up what they do and then compare it to the other api docs.
|
How to analyze these two following lines of code?
```
w += /* 28 + */ y % 4 == 0 && (y % 100 || y % 400 ==0);
```
and
```
w += 30 + (i % 2 ^ i >= 8);
```
|
The first one looks for leap years and adds 1 to w if it is. (every four year except ones divisible by 100 except ones divisible by 400.)
The second one looks for months that are 31 days. (Every every month except for months greater than 8, which repeats one month.)
Whoever wrote this code is just trying to be confusing and fancy. You should rewrite it to be more readable.
|
I have binary array in c, I want to compress the array, kindly suggest me algorithm which compress binary array. I have used Lempel–Ziv–Welch (LZW) algorithm but its not suitable for me because there is no repetition in my data.
|
Why not just to use thelibz'sdeflate? As added bonus, libz is available on pretty much every existing platform.
Or newerLZMA? It beats thebzip2on binary data compression.
|
```
int main()
{
int i,j;
i='c';
scanf("%d",&j); // I will read 'c' here
printf("%d %d",i,j);
}
```
Output is not same.'j'takes garbage value and'i'takes ascii value of'c'. Can anybody tell what could be the reason ?
|
Youscanfsays:
```
scanf("%d", &j);
```
With this sentencescanfwill try to parse (convert) the 'c' character you are using as input to the function into a number. That's way you getgarbage. C doesn't know how to turn 'c' into a number, becausescanfis expecting digits.
Try changing that to:
```
scanf("%c", &j);
```
If yourprintfcall is like this:
```
printf("%d %d", i, j);
```
You should get the same value, both times: ASCII value of 'c' character.
|
I have written a C program to get all the possible combinations of a string. For example, forabc, it will printabc,bca,acbetc. I want to get this output in a separate file. What function I should use? I don't have any knowledge of file handling in C. If somebody explain me with a small piece of code, I will be very thankful.
|
Using functionfopen(andfprintf(f,"…",…);instead ofprintf("…",…);wherefis theFILE*obtained fromfopen) should give you that result. You mayfclose()your file when you are finished, but it will be done automatically by the OS when the program exits if you don't.
|
hello i got a problem with comparing two char* variables that contains numbers for examplechar1 = "999999"andchar2="11111111"when i am using thestrcmpfunction it will return that char1 variable is greater than char2
even tho its wrong.
(i know that i can compare with using the atoi function till 9 chars inside the string but i need to use 10 so it cuts this possibility).
|
A slightly more cumbersome way, that avoidsatoiand friends, is to prefix the shorter of the two strings with zeroes. Or, assuming there are no prefixing zeroes, simply first comparing the length (since shorter strings must have a lower value), then running a lexiographic comparison:
```
int numerical_strcmp(const char* a, const char* b) {
return (strlen(a) != strlen(b)) ? ((strlen(a) > strlen(b)) ? 1 : -1) : strcmp(a, b);
}
```
Oh, and this requires the strings to contain non-negative numbers.
|
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.Closed13 years ago.
I want to write a program to add all the digits of the entered number. For example, when I enter 54496 the output must be 5 + 4 + 4 + 9 + 6 = 28.
|
This is homework, so this is just a (quick maybe buggy) hint.
1) Initialize sum in 0;
sum := 0
2) take the reminder of the division by 10 of the number and add it to sum.
```
`sum:= sum + number mod 10`
```
3) update number to the result number divided by 10.
```
`number := number div 10`
```
4) if number > 1 goto 2
```
`if (number greater than 1) goto 1`
```
sum:= sum + number
|
Is it possible? i.e. compile .c with dmc and .d with dmd and then link them together, will this work? Will I be able to call D functions from C code, share globals etc? Thanks.
|
Yes it is possible. In fact this is one of the main feature of dmd. To call a D function from C, just make that functionextern(C), e.g.
```
// .d
import std.c.stdio;
extern (C) {
shared int x; // Globals without 'shared' are thread-local in D2.
// You don't need shared in D1.
void increaseX() {
++ x;
printf("Called in D code\n"); // for some reason, writeln crashes on Mac OS X.
}
}
```
```
// .c
#include <stdio.h>
extern int x;
void increaseX(void);
int main (void) {
printf("x = %d (should be 0)\n", x);
increaseX();
printf("x = %d (should be 1)\n", x);
return 0;
}
```
SeeInterfacing to Cfor more info.
|
I want to write a program for finding out the sum of first and the last digit of any number entered through keyboard. For example, I entered 52264. Output must be5+4 = 9.
Yes, this is an assignment.
|
Well, the last digit's easy enough to figure out, right?
```
int lastDigit = input % 10;
```
As for the first digit, I'm not sure about the most efficient way to get that. The first thought that immediately springs to my mind is:
```
int firstDigit = input;
while (firstDigit >= 10)
{
firstDigit /= 10;
}
```
So, with 52264 for example:
```
int lastDigit = 52264 % 10; // 52264 % 10 = 4
int firstDigit = 52264;
firstDigit /= 10; // 5226
firstDigit /= 10; // 522
firstDigit /= 10; // 52
firstDigit /= 10; // 5 -- less than 10
```
|
I am trying to develop a project in C (on Dev-Cpp IDE) using SQLite for data storage, on Windows Vista. I am trying to run this code :Sqlite with C
I moved sqlite3.h in the /lib path. But when I am trying to run the program, I get lots of linker errors, saying "undefined reference to sqlite3_open" ,etc.
Google gives me Linux commands, which cant be used here :( Can somone please guide me through the whole process of using sqlite with C , I am very new to such things. Where do I put the sqlite3.exe ??
Thanks a lot !!
|
I finally figured out my answer through :http://source.online.free.fr/Windows_HowToCompileSQLite
The above link creates a .dll which has to be put in the /bin, and one .a file which has to be passed as an option to the linker !
Thanks David !!
|
I have inherited a pure C project that uses GNU Pth (http://www.gnu.org/software/pth/) and I was hoping that there was a Windows port/implementation so I wouldn't have to stick a whole bunch (more) conditionals into my code.
I know I am being hopeful, but is there anything that provides the exact same function signatures and functionality?
If not, is there any good pure C cross-platform multi-threading library (even if it is different than Pth)?
Edit:
I just foundhttp://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Threadsand it sounds like that might be the way to go. Opinions on NSPR?
|
You have pthread on windowshttp://sourceware.org/pthreads-win32/which is quite stable and the performances are good. This is what we use to port our threaded unix code to windows.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:what is the difference between #include <filename> and #include “filename”
Why do we use Quotation Marks ("...") for custom build classes and braces for built in classes(<...>)?
|
It's to denote that the header isn't system-wide.
This is a convention, not a requirement.
By the way, those aren't inverted commas, they're quotation marks. There is a difference in the field of typography.
|
I have tried a lot to learn linked list.But all my efforts were wasted.Please can some one help me understand linked list by providing his/her own code?Thanks in advance.
|
A linked list is simply a list of elements (usually called nodes) where each node has a reference (or pointers, in C) to the next node:
http://img837.imageshack.us/img837/5613/ll1s.png
You keep track of the list by having a pointer to the first node (the "head"), and by having the last node point tonull
Linked lists where each element points to both the next and previous nodes are called doubly-linked lists.
By following these references, you can traverse the list and get any node.
A common advantage of linked lists over arrays is that you can insert and remove the elements in O(1) (constant) time. The disadvantage is that you have O(N) random-access.
SeeWikipediafor more.
|
In C, when we accessa[i][j]using pointers why do we need the second*in*(*(a + i) + j)? Usingprintf()I seea + iand*(a + i)print the same value.
|
a + iis a pointer to thei'th subarray. If you dereference it, you get an lvalue to thei'th subarray, which decays to a pointer to that array's first element. The address of an array's first element and that of its array is the same.
The dereference is needed to make+ jcalculate with the correct element byte-width. If you would not dereference, then instead of gettingT*you would get aT(*)[J]pointer that you addjto, which together withiadvances into memory pointing to(a + i + j)instead (advancing bysizeof(T[J])instead ofsizeof(T)).
|
gcc 4.4.4 c89
I am just wondering is there any standard that should be followed when creating types.
for example:
```
typedef struct date
{
} date_t;
```
I have also seen people put a capital like this:
```
typedef struct date
{
} Date;
```
Or for variables
```
typedef unsigned int Age;
```
or this
```
typedef unsigned int age_t;
```
Is there any standard that should be followed. Personally I prefer post fixing with a _t.
Many thanks for any suggestions,
|
If you are working on a platform that follows POSIX standards you should be aware that any identifier ending in_tis reserved for POSIX defined types so it is not advisable to follow the same convention for your own types.
|
I'm using a naive approach to this problem, I'm putting the words in a linked list and just making a linear search into it. But it's taking too much time in large files.
I was thinking in use a Binary Search Tree but I don't know if it works good with strings. Also heard of Skip Lists, didn't really learn it yet.
And also I have to use the C language...
|
You can put all of the words into atrieand then count the number of words after you have processed the whole file.
|
When generating VS2010 targets with CMake, I would like the /LTCG flag turned on (only for release + releasewithdebinfo if possible, but its okay if its on for debug builds). How do I modify the linker flags?add_definitions()doesn't work because that only modifies compiler flags. And yes, I have wrapped it in if(MSVC).
How do I modify the linker flags?
|
You can modify the linker flags in MSC using #pragma comment(linker, ...)
However, if you'd like to do it in the build process with cmake, here are the names you need to know:
CMAKE_EXE_LINKER_FLAGSCMAKE_SHARED_LINKER_FLAGSCMAKE_MODULE_LINKER_FLAGS
(Thanks toCmake.org).
|
I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.
If it is possible, can you give me a link to an example application ? I saw something about libXul, is it needed ? where can i find it ?
TNX, Vertilka
|
I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.
The usual way to create a XUL GUI on top of a C++ application is by writing a XULRunner application with the C++ code wrapped in an XPCOM plugin.
You can make your application "stand-alone" by creating an installer program that copies the XULRunner runtime together with the XPCOM plugin to the user's computer. This is howGStreamerSongBirdworks, for example.
|
I need Mosquittohttp://mosquitto.orgto work with SSL.
I've read several examples with OpenSSL, but as I've never worked with sockets in C, can someone tell me what do I have to change for my existing sockets? (Accept, write, read?)
Thank you very much
|
My understanding is that after you've called accept(), you then have to configure the socket for use with OpenSSL - assuming you've also already configured the library for use as well.
After that, you can use SSL_read() and SSL_write() instead of read() and write().
When you want to close the socket, you need to disable SSL support before calling close().
It's a reasonable undertaking for certain - the socket code isn't really the problem, it's understanding what you need to do to start and stop the TLS support and ensuring that you don't miss something out which could lead to vulnerabilities.
|
I am thinking about usingCRC-32orSHA-1, possibly both in a C program I develop on Linux (Ubuntu).
Are there any easy way to use libraries for either? Cutting and pasting a CRC-32 algorithm into the source code of my program seems simple enough, but doing the same for SHA-1 feels slightly shaky. Are there any easy way to use libraries, preferably in Ubuntu but not necessarily?
I am using C, but C++ would be OK if I had to.
|
The OpenSSL interface is pretty simple:
```
#include <openssl/sha.h>
unsigned char *SHA1(const unsigned char *d, unsigned long n, unsigned char *md);
```
dis a pointer to the input to be hashed, with lengthn.mdis a pointer toSHA_DIGEST_LENGTHbytes where the SHA1 hash will be stored.
|
I have code written using GNU Pth (http://www.gnu.org/software/pth/) and I want to move to Pthreads because I want it to be cross-platform (Unix, Mac, Windows).
Are there and caveats I should watch out for while going about switching from Pth to Pthreads, or is it mostly just a matter of realigning arguments and variable types?
|
Just to let people know: it is a fairly easy transition. Some of the naming is different, and there are slight differences in argument number and order but they are very similar overall.
Just look up the api docs for both and look up what they do and then compare it to the other api docs.
|
How to analyze these two following lines of code?
```
w += /* 28 + */ y % 4 == 0 && (y % 100 || y % 400 ==0);
```
and
```
w += 30 + (i % 2 ^ i >= 8);
```
|
The first one looks for leap years and adds 1 to w if it is. (every four year except ones divisible by 100 except ones divisible by 400.)
The second one looks for months that are 31 days. (Every every month except for months greater than 8, which repeats one month.)
Whoever wrote this code is just trying to be confusing and fancy. You should rewrite it to be more readable.
|
I have binary array in c, I want to compress the array, kindly suggest me algorithm which compress binary array. I have used Lempel–Ziv–Welch (LZW) algorithm but its not suitable for me because there is no repetition in my data.
|
Why not just to use thelibz'sdeflate? As added bonus, libz is available on pretty much every existing platform.
Or newerLZMA? It beats thebzip2on binary data compression.
|
```
int main()
{
int i,j;
i='c';
scanf("%d",&j); // I will read 'c' here
printf("%d %d",i,j);
}
```
Output is not same.'j'takes garbage value and'i'takes ascii value of'c'. Can anybody tell what could be the reason ?
|
Youscanfsays:
```
scanf("%d", &j);
```
With this sentencescanfwill try to parse (convert) the 'c' character you are using as input to the function into a number. That's way you getgarbage. C doesn't know how to turn 'c' into a number, becausescanfis expecting digits.
Try changing that to:
```
scanf("%c", &j);
```
If yourprintfcall is like this:
```
printf("%d %d", i, j);
```
You should get the same value, both times: ASCII value of 'c' character.
|
I have written a C program to get all the possible combinations of a string. For example, forabc, it will printabc,bca,acbetc. I want to get this output in a separate file. What function I should use? I don't have any knowledge of file handling in C. If somebody explain me with a small piece of code, I will be very thankful.
|
Using functionfopen(andfprintf(f,"…",…);instead ofprintf("…",…);wherefis theFILE*obtained fromfopen) should give you that result. You mayfclose()your file when you are finished, but it will be done automatically by the OS when the program exits if you don't.
|
hello i got a problem with comparing two char* variables that contains numbers for examplechar1 = "999999"andchar2="11111111"when i am using thestrcmpfunction it will return that char1 variable is greater than char2
even tho its wrong.
(i know that i can compare with using the atoi function till 9 chars inside the string but i need to use 10 so it cuts this possibility).
|
A slightly more cumbersome way, that avoidsatoiand friends, is to prefix the shorter of the two strings with zeroes. Or, assuming there are no prefixing zeroes, simply first comparing the length (since shorter strings must have a lower value), then running a lexiographic comparison:
```
int numerical_strcmp(const char* a, const char* b) {
return (strlen(a) != strlen(b)) ? ((strlen(a) > strlen(b)) ? 1 : -1) : strcmp(a, b);
}
```
Oh, and this requires the strings to contain non-negative numbers.
|
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.Closed13 years ago.
I want to write a program to add all the digits of the entered number. For example, when I enter 54496 the output must be 5 + 4 + 4 + 9 + 6 = 28.
|
This is homework, so this is just a (quick maybe buggy) hint.
1) Initialize sum in 0;
sum := 0
2) take the reminder of the division by 10 of the number and add it to sum.
```
`sum:= sum + number mod 10`
```
3) update number to the result number divided by 10.
```
`number := number div 10`
```
4) if number > 1 goto 2
```
`if (number greater than 1) goto 1`
```
sum:= sum + number
|
Is it possible? i.e. compile .c with dmc and .d with dmd and then link them together, will this work? Will I be able to call D functions from C code, share globals etc? Thanks.
|
Yes it is possible. In fact this is one of the main feature of dmd. To call a D function from C, just make that functionextern(C), e.g.
```
// .d
import std.c.stdio;
extern (C) {
shared int x; // Globals without 'shared' are thread-local in D2.
// You don't need shared in D1.
void increaseX() {
++ x;
printf("Called in D code\n"); // for some reason, writeln crashes on Mac OS X.
}
}
```
```
// .c
#include <stdio.h>
extern int x;
void increaseX(void);
int main (void) {
printf("x = %d (should be 0)\n", x);
increaseX();
printf("x = %d (should be 1)\n", x);
return 0;
}
```
SeeInterfacing to Cfor more info.
|
I want to write a program for finding out the sum of first and the last digit of any number entered through keyboard. For example, I entered 52264. Output must be5+4 = 9.
Yes, this is an assignment.
|
Well, the last digit's easy enough to figure out, right?
```
int lastDigit = input % 10;
```
As for the first digit, I'm not sure about the most efficient way to get that. The first thought that immediately springs to my mind is:
```
int firstDigit = input;
while (firstDigit >= 10)
{
firstDigit /= 10;
}
```
So, with 52264 for example:
```
int lastDigit = 52264 % 10; // 52264 % 10 = 4
int firstDigit = 52264;
firstDigit /= 10; // 5226
firstDigit /= 10; // 522
firstDigit /= 10; // 52
firstDigit /= 10; // 5 -- less than 10
```
|
I am trying to develop a project in C (on Dev-Cpp IDE) using SQLite for data storage, on Windows Vista. I am trying to run this code :Sqlite with C
I moved sqlite3.h in the /lib path. But when I am trying to run the program, I get lots of linker errors, saying "undefined reference to sqlite3_open" ,etc.
Google gives me Linux commands, which cant be used here :( Can somone please guide me through the whole process of using sqlite with C , I am very new to such things. Where do I put the sqlite3.exe ??
Thanks a lot !!
|
I finally figured out my answer through :http://source.online.free.fr/Windows_HowToCompileSQLite
The above link creates a .dll which has to be put in the /bin, and one .a file which has to be passed as an option to the linker !
Thanks David !!
|
I have inherited a pure C project that uses GNU Pth (http://www.gnu.org/software/pth/) and I was hoping that there was a Windows port/implementation so I wouldn't have to stick a whole bunch (more) conditionals into my code.
I know I am being hopeful, but is there anything that provides the exact same function signatures and functionality?
If not, is there any good pure C cross-platform multi-threading library (even if it is different than Pth)?
Edit:
I just foundhttp://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Threadsand it sounds like that might be the way to go. Opinions on NSPR?
|
You have pthread on windowshttp://sourceware.org/pthreads-win32/which is quite stable and the performances are good. This is what we use to port our threaded unix code to windows.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:what is the difference between #include <filename> and #include “filename”
Why do we use Quotation Marks ("...") for custom build classes and braces for built in classes(<...>)?
|
It's to denote that the header isn't system-wide.
This is a convention, not a requirement.
By the way, those aren't inverted commas, they're quotation marks. There is a difference in the field of typography.
|
I have tried a lot to learn linked list.But all my efforts were wasted.Please can some one help me understand linked list by providing his/her own code?Thanks in advance.
|
A linked list is simply a list of elements (usually called nodes) where each node has a reference (or pointers, in C) to the next node:
http://img837.imageshack.us/img837/5613/ll1s.png
You keep track of the list by having a pointer to the first node (the "head"), and by having the last node point tonull
Linked lists where each element points to both the next and previous nodes are called doubly-linked lists.
By following these references, you can traverse the list and get any node.
A common advantage of linked lists over arrays is that you can insert and remove the elements in O(1) (constant) time. The disadvantage is that you have O(N) random-access.
SeeWikipediafor more.
|
I have code written using GNU Pth (http://www.gnu.org/software/pth/) and I want to move to Pthreads because I want it to be cross-platform (Unix, Mac, Windows).
Are there and caveats I should watch out for while going about switching from Pth to Pthreads, or is it mostly just a matter of realigning arguments and variable types?
|
Just to let people know: it is a fairly easy transition. Some of the naming is different, and there are slight differences in argument number and order but they are very similar overall.
Just look up the api docs for both and look up what they do and then compare it to the other api docs.
|
How to analyze these two following lines of code?
```
w += /* 28 + */ y % 4 == 0 && (y % 100 || y % 400 ==0);
```
and
```
w += 30 + (i % 2 ^ i >= 8);
```
|
The first one looks for leap years and adds 1 to w if it is. (every four year except ones divisible by 100 except ones divisible by 400.)
The second one looks for months that are 31 days. (Every every month except for months greater than 8, which repeats one month.)
Whoever wrote this code is just trying to be confusing and fancy. You should rewrite it to be more readable.
|
I have binary array in c, I want to compress the array, kindly suggest me algorithm which compress binary array. I have used Lempel–Ziv–Welch (LZW) algorithm but its not suitable for me because there is no repetition in my data.
|
Why not just to use thelibz'sdeflate? As added bonus, libz is available on pretty much every existing platform.
Or newerLZMA? It beats thebzip2on binary data compression.
|
```
int main()
{
int i,j;
i='c';
scanf("%d",&j); // I will read 'c' here
printf("%d %d",i,j);
}
```
Output is not same.'j'takes garbage value and'i'takes ascii value of'c'. Can anybody tell what could be the reason ?
|
Youscanfsays:
```
scanf("%d", &j);
```
With this sentencescanfwill try to parse (convert) the 'c' character you are using as input to the function into a number. That's way you getgarbage. C doesn't know how to turn 'c' into a number, becausescanfis expecting digits.
Try changing that to:
```
scanf("%c", &j);
```
If yourprintfcall is like this:
```
printf("%d %d", i, j);
```
You should get the same value, both times: ASCII value of 'c' character.
|
I have written a C program to get all the possible combinations of a string. For example, forabc, it will printabc,bca,acbetc. I want to get this output in a separate file. What function I should use? I don't have any knowledge of file handling in C. If somebody explain me with a small piece of code, I will be very thankful.
|
Using functionfopen(andfprintf(f,"…",…);instead ofprintf("…",…);wherefis theFILE*obtained fromfopen) should give you that result. You mayfclose()your file when you are finished, but it will be done automatically by the OS when the program exits if you don't.
|
hello i got a problem with comparing two char* variables that contains numbers for examplechar1 = "999999"andchar2="11111111"when i am using thestrcmpfunction it will return that char1 variable is greater than char2
even tho its wrong.
(i know that i can compare with using the atoi function till 9 chars inside the string but i need to use 10 so it cuts this possibility).
|
A slightly more cumbersome way, that avoidsatoiand friends, is to prefix the shorter of the two strings with zeroes. Or, assuming there are no prefixing zeroes, simply first comparing the length (since shorter strings must have a lower value), then running a lexiographic comparison:
```
int numerical_strcmp(const char* a, const char* b) {
return (strlen(a) != strlen(b)) ? ((strlen(a) > strlen(b)) ? 1 : -1) : strcmp(a, b);
}
```
Oh, and this requires the strings to contain non-negative numbers.
|
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.Closed13 years ago.
I want to write a program to add all the digits of the entered number. For example, when I enter 54496 the output must be 5 + 4 + 4 + 9 + 6 = 28.
|
This is homework, so this is just a (quick maybe buggy) hint.
1) Initialize sum in 0;
sum := 0
2) take the reminder of the division by 10 of the number and add it to sum.
```
`sum:= sum + number mod 10`
```
3) update number to the result number divided by 10.
```
`number := number div 10`
```
4) if number > 1 goto 2
```
`if (number greater than 1) goto 1`
```
sum:= sum + number
|
Is it possible? i.e. compile .c with dmc and .d with dmd and then link them together, will this work? Will I be able to call D functions from C code, share globals etc? Thanks.
|
Yes it is possible. In fact this is one of the main feature of dmd. To call a D function from C, just make that functionextern(C), e.g.
```
// .d
import std.c.stdio;
extern (C) {
shared int x; // Globals without 'shared' are thread-local in D2.
// You don't need shared in D1.
void increaseX() {
++ x;
printf("Called in D code\n"); // for some reason, writeln crashes on Mac OS X.
}
}
```
```
// .c
#include <stdio.h>
extern int x;
void increaseX(void);
int main (void) {
printf("x = %d (should be 0)\n", x);
increaseX();
printf("x = %d (should be 1)\n", x);
return 0;
}
```
SeeInterfacing to Cfor more info.
|
I want to write a program for finding out the sum of first and the last digit of any number entered through keyboard. For example, I entered 52264. Output must be5+4 = 9.
Yes, this is an assignment.
|
Well, the last digit's easy enough to figure out, right?
```
int lastDigit = input % 10;
```
As for the first digit, I'm not sure about the most efficient way to get that. The first thought that immediately springs to my mind is:
```
int firstDigit = input;
while (firstDigit >= 10)
{
firstDigit /= 10;
}
```
So, with 52264 for example:
```
int lastDigit = 52264 % 10; // 52264 % 10 = 4
int firstDigit = 52264;
firstDigit /= 10; // 5226
firstDigit /= 10; // 522
firstDigit /= 10; // 52
firstDigit /= 10; // 5 -- less than 10
```
|
I am trying to develop a project in C (on Dev-Cpp IDE) using SQLite for data storage, on Windows Vista. I am trying to run this code :Sqlite with C
I moved sqlite3.h in the /lib path. But when I am trying to run the program, I get lots of linker errors, saying "undefined reference to sqlite3_open" ,etc.
Google gives me Linux commands, which cant be used here :( Can somone please guide me through the whole process of using sqlite with C , I am very new to such things. Where do I put the sqlite3.exe ??
Thanks a lot !!
|
I finally figured out my answer through :http://source.online.free.fr/Windows_HowToCompileSQLite
The above link creates a .dll which has to be put in the /bin, and one .a file which has to be passed as an option to the linker !
Thanks David !!
|
I have inherited a pure C project that uses GNU Pth (http://www.gnu.org/software/pth/) and I was hoping that there was a Windows port/implementation so I wouldn't have to stick a whole bunch (more) conditionals into my code.
I know I am being hopeful, but is there anything that provides the exact same function signatures and functionality?
If not, is there any good pure C cross-platform multi-threading library (even if it is different than Pth)?
Edit:
I just foundhttp://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Threadsand it sounds like that might be the way to go. Opinions on NSPR?
|
You have pthread on windowshttp://sourceware.org/pthreads-win32/which is quite stable and the performances are good. This is what we use to port our threaded unix code to windows.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:what is the difference between #include <filename> and #include “filename”
Why do we use Quotation Marks ("...") for custom build classes and braces for built in classes(<...>)?
|
It's to denote that the header isn't system-wide.
This is a convention, not a requirement.
By the way, those aren't inverted commas, they're quotation marks. There is a difference in the field of typography.
|
I have tried a lot to learn linked list.But all my efforts were wasted.Please can some one help me understand linked list by providing his/her own code?Thanks in advance.
|
A linked list is simply a list of elements (usually called nodes) where each node has a reference (or pointers, in C) to the next node:
http://img837.imageshack.us/img837/5613/ll1s.png
You keep track of the list by having a pointer to the first node (the "head"), and by having the last node point tonull
Linked lists where each element points to both the next and previous nodes are called doubly-linked lists.
By following these references, you can traverse the list and get any node.
A common advantage of linked lists over arrays is that you can insert and remove the elements in O(1) (constant) time. The disadvantage is that you have O(N) random-access.
SeeWikipediafor more.
|
In C, when we accessa[i][j]using pointers why do we need the second*in*(*(a + i) + j)? Usingprintf()I seea + iand*(a + i)print the same value.
|
a + iis a pointer to thei'th subarray. If you dereference it, you get an lvalue to thei'th subarray, which decays to a pointer to that array's first element. The address of an array's first element and that of its array is the same.
The dereference is needed to make+ jcalculate with the correct element byte-width. If you would not dereference, then instead of gettingT*you would get aT(*)[J]pointer that you addjto, which together withiadvances into memory pointing to(a + i + j)instead (advancing bysizeof(T[J])instead ofsizeof(T)).
|
gcc 4.4.4 c89
I am just wondering is there any standard that should be followed when creating types.
for example:
```
typedef struct date
{
} date_t;
```
I have also seen people put a capital like this:
```
typedef struct date
{
} Date;
```
Or for variables
```
typedef unsigned int Age;
```
or this
```
typedef unsigned int age_t;
```
Is there any standard that should be followed. Personally I prefer post fixing with a _t.
Many thanks for any suggestions,
|
If you are working on a platform that follows POSIX standards you should be aware that any identifier ending in_tis reserved for POSIX defined types so it is not advisable to follow the same convention for your own types.
|
I'm learning queues from a book. The author explains the operation of inserting an element in queue using the following code.
```
#define MAX 100
char *p[MAX];
int spos = 0; // spos: holds the index of the **next free** storage location
int rpos = 0;// rpos: holds the index of the next item to retrieve
void qstore(char *q)
{
if(spos==MAX) {
printf("List Full\n");
return;
}
p[spos] = q;
spos++;
}
```
So according to the above code, a queue is full ifspos=100 i.e the last element in the array. Now, sincesposholds the index of thenext freestorage location, then whenspos=100, the last position in the array is empty. So why is it explained asList full? Shouldn't this code be modified such that it allows the last position in the array to be filled or am I missing something very obvious?
Thanks.
|
p[100]allocates 100 slots, at indexes 0 through 99. There is no position 100.
|
When I compile or run a file from VIM all error references are opened in the last active buffer regardless if the file is open already in another vim tab. This behavior is very annoying.
Is there any way to force vim to behave like ':tab drop' on compile errors?
(Seehttp://vim.wikia.com/wiki/Edit_a_file_or_jump_to_it_if_already_open)
Thanks a lot for any hints!
|
You're looking for the'switchbuf'option. If youset switchbuf=useopen,usetab,newtab, then any window/tab that is already displaying the buffer with the error will be focused. If there isn't a window/tab displaying the buffer, then a new tab will be created in which to display it.
|
What does the code(10%2)mean?
|
%is themodulusoperator.
So this essentially says - what is the remainder of 10 divided by 2?
```
10 % 2 == 0
10 % 5 == 0
10 % 7 == 3
10 % 3 == 1
```
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.