question
stringlengths
25
894
answer
stringlengths
4
863
I am playing around with the pcap library in C. I can filter http traffic using the filter expression "port 80" in the pcap_compile call, but now I'm wondering whether I can filter POST requests specifically. Does anyone know of a filter expression for filtering http POST requests?
The following should match only POSTs: ``` port 80 and tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354 ``` However, a HTTP request is likely to be split in various TCP packets, and thus you may not get the full request.
I have code that is completely parallel, no dependencies, so using pthreads was a natural choice. Unfortunately, there is one shared resource, the log file. We don't want the log to be interleaved line-by-line in any case, so rather than use mutexes on every log call I want to open a separate log file for each threa...
If each thread gets its own log, use pthread_key_create and related functions to maintain a per-thread logger variable.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. Please, could you explain, which te...
Have a look at the APIs standardised by theKhronos Group. They have a well-established convention of defining library interfaces in a concise way. No, they probably don't hold the Guiness record for "Most convenient API", but they indeed could have one for "Most consistent API stanard", "Best legacy API deprecation m...
Are there any builtin equivalents to_countofprovided by other compilers, in particular GCC and Clang? Are there any non-macro forms?
Using C++11, the non-macro form is: ``` char arrname[5]; size_t count = std::extent< decltype( arrname ) >::value; ``` Andextentcan be found in thetype_traitsheader. Or if you want it to look a bit nicer, wrap it in this: ``` template < typename T, size_t N > size_t countof( T ( & arr )[ N ] ) { return std::ex...
I found the following declaration in my c Book, can anyone explain it: ``` char *dic[][40]={ "atlas", "A volume of maps", "car", "a vehicle", "telephone", "a communication device", "", "" } ``` Here what does the 40 means i.e. which dimension this is?
This is actually kind of a weird way to initialize the dictionary. It is a 2D array ofchar*(zero terminated (\0) strings). The dimensions are [rows][columns]. So you have 1 row (determined by the initializer) and 40 columns of strings, where 8 of them are initialized. NOTE: Are you sure it isnt chardic[][40](i.e....
I noticed many mentions ofptyandttyin some open source projects, could someone tell me what do they mean and what is the difference between them?
ttyoriginally meant"teletype"and"pty"means"pseudo-teletype". In UNIX,/dev/tty*is any device that acts like a"teletype", i.e: a terminal. (Called teletype because that's what we had for terminals in those benighted days.) Aptyis apseudotty, a device entry that acts like a terminal to the process reading and writing ...
I have integers which I put in a matrix in order to use them in a specific function in openCV. The matrix that I created is only cvMat and I want to use this matrix in the function. I'm getting an error: error: cannot convert ‘CvMat’ to ‘const CvMat*’ So how can I convert these ints to const in order to create that ...
" error: cannot convert ‘CvMat’ to ‘const CvMat*’ " The important thing there is the asterix at the end. That means the function you are calling wants a pointer. you can just take the address of your matrix and pass that, insteadsomefunction(myMatrix)it needssomefunction(&myMatrix). Don't worry about the const. A...
Suppose there are two threads, the main thread and say thread B(created by main). If B acquired a mutex(say pthread_mutex) and it has called pthread_exit without unlocking the lock. So what happens to the mutex? Does it become free?
nope. The mutex remaines locked. What actually happens to such a lock depends on its type, You can read about thathereorhere
I'm using libsndfile to load the music file and i use jack to play it. how do I resolve issues when the sample rate of the song is lower or higher then the sample rate of my sound card? is there something i can configure in jack or do i need to use libsamplerate to convert the sample rate ? Thanks
jack does not resample. there is a library called libsamplerate that converts from one sample rate to another. I can use it to convert a song to the sound card's sample rate.
I'm trying to compilepythonsource code foo.py to C usingcython. Infoo.py: ``` print "Hello World" ``` The command I'm running iscython foo.py. The problem is that when compiling foo.c usinggcc, I get the error: undefined reference to 'main'.
when converting the code from python to c (using Cython) it converts it to c code which can be compiled into a shared object. in order to make it executable, you should add "--embed" to cython conversion command. this flag adds the 'main' function you need, so you could compile the c code into executable file. please ...
How to count the no of arguments passed to the function in following program: ``` #include<stdio.h> #include<stdarg.h> void varfun(int i, ...); int main(){ varfun(1, 2, 3, 4, 5, 6); return 0; } void varfun(int n_args, ...){ va_list ap; int i, t; va_start(ap, n_args); fo...
You can't. You have to manage for the caller to indicate the number of arguments somehow. You can: Pass the number of arguments as the first variableRequire the last variable argument to be null, zero or whateverHave the first argument describe what is expected (eg. the printf format string dictates what arguments sh...
``` #define BS 1000 XDR *xdrs; char buf1[BS]; xdrmem_create(xdrs,buf1,BS,XDR_ENCODE); ``` I followed what the text book said but whenever I ran my program, it has segmentation fault. I think there is problem with xdrmem_create. Has anybody here been successful when using this function? (I'm using Ubuntu 10.10)
You didn't initialize the pointer. Fix: ``` XDR stream; xdrmem_create(&stream, buf1, BS, XDR_ENCODE); ```
So I'm trying to write a C program that uses inotify. I've used pyinotify before so I understand how it works. However, I'm following some guide and it tells me to include<linux/inotify.h>. The problem is that this header only has macro definitions, not the funciton prototypes. It looks like the functions are prototyp...
sys/inotify.his part of theGNU C library. It exposes the structures and functions that your program will use in order to receive filesystem change notifications. It can be considered as the public API of the notification system. linux/inotify.his part of the Linux kernel. It defines the kernel structures and constant...
When I try to write the file using C;fwritewhich acceptsvoidtype as data, it is not interpreted by text editor. ``` struct index { index(int _x, int _y):x(_x), y(_y){} int x, y; } index i(4, 7); FILE *stream; fopen_s(&stream, "C:\\File.txt", "wb"); fwrite(&i, sizeof(index), 1, stream); ``` but when I try wit...
This is the way to write binary data using a stream in C++: ``` struct C { int a, b; } c; #include <fstream> int main() { std::ofstream f("foo.txt",std::ios::binary); f.write((const char*)&c, sizeof c); } ``` This shall save the object in the same way asfwritewould. If it doesn't for you, please post y...
Given a pointer to structure, can I write a#definethat would access a member of the structure? ``` struct s_block { size_t size; struct s_block *ptr; }; #define SIZER(ptr) // will access size member ???? ```
``` #define SIZER(ptr) (ptr)->size ``` Do note though that you must pass in a pointer to ans_blockfor this to work. Finally, this should be in any reference manual covering the C programming language. I suggest you pick one up.K&Ris very good, even today.
I can't get why the following bit of C code doesn't work: ``` int obtainStringLength(char* str, char c1, char c2) { char* firstOcurrence = strchr(str, c1); char* endOcurrence = strchr(str, c2); return 2+(endOcurrence - firstOcurrence) / sizeof(char*); } ``` The idea is to find how many characters are bet...
Division bysizeof(char*)? That's incorrect - the result of subtracting two pointers is a numerical value (ptrdiff_t) corresponding to the number of values, not a pointer or difference of addresses. There's also the off-by-one error in calculating the length. So that last line should look like: ``` return 1 + (endOcu...
I was reading C Traps and Pitfalls and read that the following code may work on some implementations and won't on others due to an undefined order of = and ++. Is this still true of C? ``` int i = 0; while (i < n) y[i] = x[i++]; ``` If so, that's really incredible.
Nothing incredible. Pretty defined undefined behavior. Read more aboutsequence points. Just writing as: ``` int i = 0; while (i < n) { y[i] = x[i]; i++; } ``` is safer and more readable.
This question already has answers here:Closed12 years ago. Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)Undefined Behavior and Sequence Points(C++ FAQ entry) In C and C++ how is the expressionx+++++yparsed? Asx++ ++ +yor asx++ + ++y?
x+++++yis parsed asx ++ ++ + yand not asx ++ + ++ y. According toMaximal Munch principle"the tokenizer should keep reading characters from the source file until adding one more character causes the current token to stop making sense" x++ ++ +yshould not compile(In C and C++) because the post-increment operator++requi...
I have an array of u_chars and I want to print it using printf. I don't know the size of the array: ``` u_char *ip_p; printf("%s", ip_p); // EXC_BAD_ACCESS D:< ``` I want to print this. How can I do this?
That can't be done. A pointer doesn't magically contain information about the size of the data pointed to. If there's no convention (a terminator byte, or a length encoded somewhere), you can't know how much data is valid, and thus how much to print.
I was trying to figure out something when I wrote this by a mistake ``` printf("string1""string2"); ``` To my surprise it compiled and produced a concatenated string output i.e ``` string1string2 ``` Is this valid C? I am using gccversion 4.4.1 (Ubuntu 4.4.1-4ubuntu9)
Yes it is. Consecutive string literals are concatenated early in the parsing of C. 6.4.5 / 4: In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and wide string literal tokens are concatenated into a single multibyte character sequence. If any of the tokens are ...
Consider this code: ``` typedef int64_t Blkno; #define BLKNO_FMT "%lld" printf(BLKNO_FMT, (Blkno)some_blkno); ``` This works well and fine on x86. On x64, int64_t is actually along, rather than along long, and whilelongandlong longare the same size on x64, the compiler generates an error: src/cpfs/bitmap.c:14: warn...
UsePRId64frominttypes.h. Blknois not a very good type name.BLKNO_FMTcould be replaced byPRIdBLKNO. ``` #include <inttypes.h> #include <stdio.h> typedef int64_t Blkno; #define PRIdBLKNO PRId64 int main(void) { printf("%" PRIdBLKNO "\n", (Blkno)1234567890); return 0; } ```
How can I pass around pointers to structs which have private definitions, without prepending the pointer types withstruct? For example this works: ``` typedef struct Handle { Ino ino; } Handle; bool handle_open(Handle **); ``` But if I move the struct definition into a source file, other source files are force...
You cantypedef struct Handle Handle;. In this case,Handleis an incomplete type (just likestruct Handle).
I have written same lines of code in both C and C++ build environment of visual studio 2008 but C code's object file size is 5.5kb and C++ code file size is 6.17 kb. Why is this difference? Following is the code in both environments: ``` #include <stdio.h> struct S { char c; }; void func() { int i; int ...
It links different C runtime libraries in each case.Check herefor detailed explanation. For instance,libcmt.libvslibcpmt.lib.
Is there an equivalent of fseek for fd? I've been using int fds for a very long time, and want to use fseek... but I know there is no seek function. Thanks in advance!
See the POSIX functionlseek(2): SYNOPSIS#include <unistd.h> off_t lseek(int fildes, off_t offset, int whence);DESCRIPTIONThelseek()function repositions the offset of the file descriptorfildesto the argumentoffset, according to the directivewhence. The argumentfildesmust be an open file descriptor.
What is the difference between the C main function and the Java main function? ``` int main( int argc, const char* argv[] ) ``` vs ``` public static void main(String [] args) ``` How do these main functions relate to each languages creation and what are the benefits or outcomes of each?
They do the same thing -- they're both intended to be the entry point into your program. The difference in the signatures is because Java supports arrays which 'know' what their length is, and C does not. That's why you needargc, which is the count of the number of arguments passed. In C, you return a success or fa...
This is my code: ``` int a1[][3]={{1,2,3,4,5,6},{4,5,6,5}}; int (*q)[3]; q=a1; ``` qis a pointer to an array of 3 integers. Buta1does not comply withq's type. Yet the assignment works and no error comes. Can anyone explain why?
The types do comply.a1is an array of length-3 arrays of ints.qis a pointer to a length-3 array of ints. An array decays to a pointer in most circumstances; this is one of them, so everything's fine!
This question already has answers here:Closed12 years ago. Possible Duplicate:How can I best do source code browsing inside emacs? I have a large base to modify, and I want to be able to follow a function to its definition, the better to read it. Can I do this in emacs?
Yes. Useetags. It will take you to the definition of any symbol.Hereis a cheat sheet full of commands for it. You'll have to generate a TAGS file using theetagsprogram first. I use this on a mixed C/Ada codebase: ``` (find . -name '*.[ch]' find . -name '*.ad[bs]' )|grep -v "CVS/Base" | sort | xargs etags -a ```
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
Garbage. This is due to a programming error: You put only one parameter on the stack (a), but printf takes 2 values from the stack, because of the two percent signs. If you intended to have both outputs, the character and its ordinal value, you should have writtenprintf("%c %d", a, a);
Yes I know you shouldn't use C style casts in C++, but in some cases I really think it's a lot more readable if you do, compare these two for example: ``` d = ((double)i * 23.54) / (d + (double)j); d = (static_cast<double>(i) * 23.54) / (d + static_cast<double>(j)); ``` Which one is more readable? Now on to my mai...
They're all unreadable. You should write: ``` d = (i * 23.54) / (d + j); ```
I'm looking for a way to use JumpLists through plain C or C++ using the Windows API. TheCode Packseems to be only available for .NET. Is there anyway to implement them using C/C++ wothout .NET? I mean how is this possible: http://www.strixcode.com/q7goodies/-> C++http://www.strixcode.com/j7goodies/-> Java
Of course it's available for native developers. You were looking in the wrong place. Here's a link:http://msdn.microsoft.com/en-us/library/dd378460(v=VS.85).aspx#custom_jump_lists
This question already has answers here:Closed10 years ago. Possible Duplicate:The initialization of static variable in C I know that either global variables or static are automatically initialized with zero in C. However, I'm not sure if both or only one of them are initialized. Note that I'mnottalking about variabl...
C FAQ.
I need to find the fastest equivalence of the following C code. ``` int d = 1 << x; /* d=pow(2,x) */ int j = 2*d*(i / d) + (i % d); ``` What I thought is to shift left upper 32 - x bits of i.For example the following i with x=5:1010 1010 1010 1010will become:0101 0101 0100 1010Is there an assembly command for that? ...
divisions are slow: ``` int m = (1 << x) - 1; int j = (i << 1) - (i & m); ``` update: or probably faster: ``` int j = i + (i & (~0 << x)); ```
I want to have two structs that can contain each other. Here is an example: ``` struct a { struct b bb; }; struct b { struct a aa; }; ``` But this code doesn't compile. gcc says: ``` test.c:3: error: field ‘bb’ has incomplete type ``` Is there a way to achieve this?
How is that supposed to work?awould containb, which would containa, which would containb, etc... I suppose you want to use a pointer instead? ``` struct b; struct a { struct b *bb; }; struct b { struct a *aa; }; ``` Even that though is bad coding style - circular dependencies should be avoided if possible.
I'm trying to include plCrashReporter in my iPhone app using the code found here: http://plcrashreporter.googlecode.com/svn/tags/plcrashreporter-1.0/Documentation/API/example_usage_iphone.html My one issue occurs on this line: ``` NSLog(@"Crashed with signal %@ (code %@, address=0x%" PRIx64 ")", report.signalInfo.n...
PRIx64 is a macro for "X".
Yes I know you shouldn't use C style casts in C++, but in some cases I really think it's a lot more readable if you do, compare these two for example: ``` d = ((double)i * 23.54) / (d + (double)j); d = (static_cast<double>(i) * 23.54) / (d + static_cast<double>(j)); ``` Which one is more readable? Now on to my mai...
They're all unreadable. You should write: ``` d = (i * 23.54) / (d + j); ```
I'm looking for a way to use JumpLists through plain C or C++ using the Windows API. TheCode Packseems to be only available for .NET. Is there anyway to implement them using C/C++ wothout .NET? I mean how is this possible: http://www.strixcode.com/q7goodies/-> C++http://www.strixcode.com/j7goodies/-> Java
Of course it's available for native developers. You were looking in the wrong place. Here's a link:http://msdn.microsoft.com/en-us/library/dd378460(v=VS.85).aspx#custom_jump_lists
This question already has answers here:Closed10 years ago. Possible Duplicate:The initialization of static variable in C I know that either global variables or static are automatically initialized with zero in C. However, I'm not sure if both or only one of them are initialized. Note that I'mnottalking about variabl...
C FAQ.
I need to find the fastest equivalence of the following C code. ``` int d = 1 << x; /* d=pow(2,x) */ int j = 2*d*(i / d) + (i % d); ``` What I thought is to shift left upper 32 - x bits of i.For example the following i with x=5:1010 1010 1010 1010will become:0101 0101 0100 1010Is there an assembly command for that? ...
divisions are slow: ``` int m = (1 << x) - 1; int j = (i << 1) - (i & m); ``` update: or probably faster: ``` int j = i + (i & (~0 << x)); ```
I want to have two structs that can contain each other. Here is an example: ``` struct a { struct b bb; }; struct b { struct a aa; }; ``` But this code doesn't compile. gcc says: ``` test.c:3: error: field ‘bb’ has incomplete type ``` Is there a way to achieve this?
How is that supposed to work?awould containb, which would containa, which would containb, etc... I suppose you want to use a pointer instead? ``` struct b; struct a { struct b *bb; }; struct b { struct a *aa; }; ``` Even that though is bad coding style - circular dependencies should be avoided if possible.
I'm trying to include plCrashReporter in my iPhone app using the code found here: http://plcrashreporter.googlecode.com/svn/tags/plcrashreporter-1.0/Documentation/API/example_usage_iphone.html My one issue occurs on this line: ``` NSLog(@"Crashed with signal %@ (code %@, address=0x%" PRIx64 ")", report.signalInfo.n...
PRIx64 is a macro for "X".
The problem is on while loop. I couldn't find what's wrong. ``` #include <stdio.h> #include <stdlib.h> #include <conio.h> typedef struct node { int data; node *next; }; int main(){ node * root= (node *) malloc(sizeof(node)); node * temp = root; for(int i=0;i<10;i++){ temp->data=i...
You never set the last nodes next to null. Puttemp->next = NULL;after the for loop. When you allocate node with malloc, values are not initialized to anything. Sonextpoints to some random place in the memory.
The following line of code, which creates a variable-length array on the stack: ``` char name[length] = {'\0'}; ``` Generates the following compiler diagnostics: ``` error: variable-sized object may not be initialized warning: excess elements in array initializer warning: (near initialization for ‘name’) ``` What ...
Yes, you must write code for the initialisation of VLAs (which could be amemset()like you have described, or any other way that you care to). It is simply a constraint in the C standard (§6.7.8): The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable l...
``` void callback(const unsigned char* data, int len) { unsigned char copydatahere; } ``` data is a pointer-to-const situation, that is allocated in library outside. len is a size of data, guessing it to be sizeof(unsigned char)*N. How I allocatecopydatahereto size oflenand copy the whole memory behinddataincluding...
Usememcpy.bcopyis only supported on some platforms, and is deprecated in newer standards. ``` void callback(const unsigned char* data, int len) { unsigned char* copydatahere = malloc(len); if (!copydatahere) { exit(1); } memcpy(copydatahere, data, len); /* ... */ free(copydatahere); } ```
I am using Swig to wrap a C interface that looks like this: ``` int dosomething(char **str); ``` where str is an output string. For example, from C its called like this: ``` char *str= NULL; int val= dosomething(&str); ... free(str); ``` In Python, I'd like to be able to call it like this: ``` val,str = dosom...
Try this typemap (I'm using SWIG 2.0.0): ``` %include <cstring.i> %cstring_output_allocate(char **str, free(*$1)); ``` Documentation:cstring.i
Trying to compile gearman on Suse 10 and I get this: ``` #:~/src/gearmand-0.14> sudo make make all-am make[1]: Entering directory `/src/gearmand-0.14' CC libgearman/libgearman_libgearman_la-client.lo libgearman/client.c: In function '_client_add_task': libgearman/client.c:986: error: storage size of 'uuid' isn...
storage size of 'uuid' isn't known I guess you're missing an#includein client.c.
I'm using TinyXml to parse some XML that has some HTML Entities embedded in text nodes. I realize that TinyXML is just an XML parser, so I don't expect or even want TinyXML to do anything to the entities. In fact I want it to leave them alone. If I have some XML like this: ``` ... <blah>&uuml;</blah> ... ``` Callin...
If you look at theTinyXML documentationyou'll see that it recognizes only five character entities (&uuml;is not one of them), plus Unicode code point syntax&#xA0;or&#160;.
Can I compare three variables like the following, instead of doingif((x==y)&&(y==z)&&(z=x))? [The if statement should execute if all three variables have the same value. These are booleans.] ``` if(debounceATnow == debounceATlast == debounceATlastlast) { debounceANew = debounceATnow; } else { debounceANew = debounc...
No, it does not. x == yis converted to int, yields0or1, and the result is compared toz. Sox==y==zwill yield true if and only if(x is equal to y and z is 1) or (x is not equal to y and z is 0) What you want to do is ``` if(x == y && x == z) ```
What does the following code fragment (in C) print? ``` int a = 033; printf("%d", a + 1); ```
033is anoctal integer literaland its value is8*3+3 = 27. Your code prints28. An integer literal that starts with a0is octal. If it starts in0xit's hexadecimal. By the way, for an example's sake ``` int x = 08; //error ``` is a compile-time error since8is not an octal digit.
I am a primary windows developer with experience in C#, .NET, Visual C/C++. I want to lean C/C++ development in linux in order to create portable GUI applications which run on both Windows and Linux. I have used Fedora in past (2005). Want your suggestions to know which is the best distribution currently to learn pro...
You can't really go wrong with any of the major ones. Personally I use Debian, but Fedora and OpenSUSE are good choices as well. I would also like to point out that youcanuse C# to create portable GUI applications. Have a look atMonoandGtk#. I have developed quite a few Gtk# apps and they usually run flawlessly on...
This question already has answers here:Closed12 years ago. Possible Duplicate:What does 'unsigned temp:3' means I don't understand this struct definition. It seems illegal to me, but apparently it isn't: ``` typedef struct { unsigned i:1; } my_struct; ``` I believe that marking the variable asunsignedwithout a...
It defines i to be of 1 bit width. If i:x is given then it defines i to be x bits wide.
Have a windows program writtent in C language. But need to sent message to the chat server. I found xSocket which is written in Java, it would be great to have a simple C libraries that is able to sent message to xSocket server port like Port 8090.
Sockets programming using the Berkeley sockets library is so simple that it's probably best to just code something yourself. There are various C++ socket libraries, but they add little value to just writing a few simple functions yourself. There's loads of example code on the internet. Key functions are: socket() - ...
I have to write a C program that uses a linked list. I have created a list and added elements to the list. But I don't know how to print all the elements in the list. The list is a list of strings. I figured I'd somehow increment through the list, printing every string that's there, but I can't figure out a way to do...
There are no stupid questions1. Here's some pseudo-code to get you started: ``` def printAll (node): while node is not null: print node->payload node = node->next printAll (head) ``` That's it really, just start at the head node, printing out the payload and moving to the next node in the list. ...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. I want to convert pointers of any t...
Looks like you want theoffsetofmacro, it's defined in<stddef.h>. Edit: You have changed your example, now you should look atintptr_toruintptr_twhich are instdint.h. Do not, under any circumstances, put an address into a plainint.
I have been using theBitsetclass in Java and I would like to do something similar in C. I suppose I would have to do it manually as most stuff in C. What would be an efficient way to implement? ``` byte bitset[] ``` maybe ``` bool bitset[] ``` ?
CCANhas a bitset implementation you can use:http://ccan.ozlabs.org/info/jbitset.html But if you do end up implementing it yourself (for instance if you don't like the dependencies on that package), you should use an array of ints and use the native size of the computer architecture: ``` #define WORD_BITS (8 * sizeof...
This question already has answers here:Closed12 years ago. Possible Duplicates:Is this a legitimate C++ code?“C subset of C++” -> Where not ? examples ? Could anybody come up with a piece of code that compiles with gcc or any other C compiler, and doesn't compile g++ or any other C++ compiler? UPDATE: I don't mean ...
``` #include <stdlib.h> int main() { char* s = malloc(128); return 0; } ``` This will compile with gcc, but not with g++. C++ requires an explicit cast fromvoid*here, whereas C does not.
I want to use the same variable name with a different datatype in C program without casting. I really wanna do that don't ask why. So how can I do that ?And how can I handle the error if this variable doesn't exist while doingprophylacticunsetting ?
You can't. The closest you can get is creating separate scopes and using the same variable name in them: ``` { int val; // do something with 'val' } { double val; // do something with 'val' } ```
``` #include<stdio.h> int fact(int i); void main() { int j; j=fact(4); printf("%d",j); } int fact(int i){ int x=i;static int tot=1; if(x<1){ tot=x*fact(x-1); } return tot; } ``` Please help me with this code. What is wring in this code?
You do not have a base condition in the fact function. You need to check: ``` if(i == 1){ return 1; }else{ return i * fact(i - 1); } ```
Is there any algorythm to sort an array of float numbers in one cycle?
If you mean one pass, then no. Sorting generally requires either O(N log N). Single-pass implies O(N). Radix sort takes O(N*k) with average key-length k. Even though it's linear time, it requires multiple passes. It is also not usually suitable for sorting floats.
I'am doing a program that deals with connecting to mysql server and accessing or writing data. I am wondering whether to do the connector part using connector for c or c++. I have heard that c connector is more stable than the c++ connector. Please do help me choose.. MySQL Connector/C or MySQL Connector/C++?
Go with the language you're the most comfortable with, and use the connector for that language.
Consider the following code ``` #include <stdio.h> void print(char string[]){ printf("%s:%d\n",string,sizeof(string)); } int main(){ char string[] = "Hello World"; print(string); } ``` and the output is ``` Hello World:4 ``` So what's wrong with that ?
It does return the true size of the "variable" (really, the parameter to the function). The problem is that this is not of the type you think it is. char string[], as a parameter to a function, is equivalent tochar* string. You get a result of4because that is the size, on your system, of achar*. Please read more her...
It can be opensource. I need it because I don't want to install virtual machine. So is there any online, html/flash/js based, free C++ (or at least C) compiler that can compile code simulating ubuntu c/c++ compiler and return built executable file to me? I heard that Mozilla had some cool online editors but I don't kn...
I don't think you clearly understand the difference between an editor and a compiler. An editor cannot compile code. A compiler doesn't help you to edit code. An IDE (Integrated Development Environment) incorporates the features of both an editor and a compiler. Are you asking if anyone knows of an IDE that can comp...
So we have some function like(pow(e,(-a*x)))/(sqrt(x))wherea,eare const floats. we have some float eps=pow (10,(-4)). We need to find out starting from whichxintegral of that function from that x to infinety is less than eps? We can not use functions for special default integration function just standart math like op...
If you perform the u-substitution u=sqrt(x), your integral will become 2 * integral e^(-au^2) du. With one more substitution you can reduce it to a standard normal. Once you have it in standard normal form, this reduces to calculating erf(x). The substitutions can be done abstractly for any a, and the results hardc...
``` strcmp(variable, "constant"); ``` Or do I have to protect it with a mutex?
If variable can be modified by other thread you must protect it. No magic here – higher level languages could do such function call atomically and that is the 'magic' not present in C. Please note that protection (by a single lock) need both the 'variable' pointer value (address of the string in the memory) and the s...
``` #include <stdio.h> #define f(a,b) a##b #define g(a) #a #define h(a) g(a) int main() { printf("%s\n",h(f(1,2))); printf("%s\n",g(f(1,2))); return 0; } ``` Just by looking at the program one "might" expect the output to be, the same for both the printf statements. But on running the progr...
An occurrence of a parameter in a function-like macro, unless it is the operand of#or##, is expanded before substituting it and rescanning the whole for further expansion. Becauseg's parameteristhe operand of#, the argument is not expanded but instead immediately stringified ("f(1,2)"). Becauseh's parameteris notthe o...
It's the same idea as Operating system boot loader. I have a C source code and Assembly source code. I want the assembly code to pass control to the C application. I am working on Linux and using GCC + NASM for compiling. Do I need to compile them in a special way? What's the assembly code used to load the c applicati...
Let gcc and nasm produce object files which you can link together. You have to use the right symbol names, too. In the NASMmanual, you can find a nice explanation including examples. As it is not explained how to compile the examples using gcc and a linker, you can find these things explainedhere.
``` void call(int x,int y,int z) { printf("%d %d %d",x,y,z); } int main() { int a=10; call(a,a++,++a); return 0; } ``` this program is giving different output on different compiler and when i compiled it on linux m/c output was quite weird,any reason.
Because the behaviour is undefined. The compiler is allowed to evaluatea,a++and++ain any order before passing them tocall(). (Technically, because we've invoked undefined behaviour, it actually doesn't have to do anything in particular at this point; it may write whatever code it pleases.) Depending on what order they...
I never saw such awhilestatement before. ``` while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) { .. .. } ``` I read online, that the condition to come out of while loop is the rightmost one [ !feof(stdin) ]. Then, what is the use of the abovewhilestatement as opposed to ``` while(!feof(stdin)) { prin...
The two loops given don't have the same meaning. By using the comma operator in that way, the author was able to specify code that should be executed every iteration, even if the loop itself is never entered. It's more like ado ... while ()loop, or something like the following: ``` printf("> "); fgets(str, 100, stdi...
I'd like to know how to check if a user types the "backspace" character. I'm using thegetch() function i.e. "key = getch()"in my C program and i'd like to check when backspace is pressed. the line: ``` if(key = '\b') { .... ``` doesn't work.
The problem with readingBackspaceis that most terminals are 'cooked' in that keys like backspace are handled by the terminal driver. However, the curses functiongetch()can read the backspace as it's not tied to the terminal. Edit I just noticed your codeisusinggetch()for input. I ran a little test program andgetch...
So my question in C is: what is basically the differences (maybe pros and cons) of using a pthread barrier (init and wait..etc) compared to using the pthread Join in a loop. So say I created 10 threads in a loop, and then later at the place of where I want a barrier, I put a loop to do Join for all the threads. Would...
pthread_join()blocks the calling thread until the joining thread exits. In contrast, a barrier allows the all threads to continue running.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
``` int main(void){ calcuateSphereVolume(radius * radius * radius); return 0; } ``` You spelt 'calculateSphereVolume' incorrectly for one... Also, you need to rethink your formula for the volume of a sphere :Pi
This question already has answers here:Closed12 years ago. Possible Duplicate:How to check whether two file names point to the same physical file How can I know if two hardlinks are connected to one file from C in Linux. Thanks.
Use thestat() or fstat()function for both paths. If in the returned structures both the st_dev and st_ino fields are identical, then the paths refer to the same filesystem object. EDIT: Note thatyou need to check both st_dev and st_ino. Otherwise you run the risk of matching two files in different filesystems that j...
I did the opposite by mistake and now i can't go back to the java enviorment. anyoune knows how? thanks.
There should be a button in the top right corner for changing perspectives. You can also get to it through theWindow > Open Perspectivemenu.
if i had a 5 X 5 multidimensional-array, where all values would be ether 0 or 1, would there be a way to generate a 5 X 5 pixel image where 1 was black and 0 was white? i would like to do this in c. the output image type would not matter. --Thanks chad
If the array is 5x5 then it is 2-dimensional which is more specific than calling it multi-dimensional. Read up on the pbm or the pgm image formats. They are very easy to use and they are easily output by your program.
So how to create a function to return nearest up so nearest to 9 9+ 1 to given int leaving no remainder when divided by 2 int?
To round to the nearest int: ``` number+=(number & 1) ```
I'am doing a program that deals with connecting to mysql server and accessing or writing data. I am wondering whether to do the connector part using connector for c or c++. I have heard that c connector is more stable than the c++ connector. Please do help me choose.. MySQL Connector/C or MySQL Connector/C++?
Go with the language you're the most comfortable with, and use the connector for that language.
Consider the following code ``` #include <stdio.h> void print(char string[]){ printf("%s:%d\n",string,sizeof(string)); } int main(){ char string[] = "Hello World"; print(string); } ``` and the output is ``` Hello World:4 ``` So what's wrong with that ?
It does return the true size of the "variable" (really, the parameter to the function). The problem is that this is not of the type you think it is. char string[], as a parameter to a function, is equivalent tochar* string. You get a result of4because that is the size, on your system, of achar*. Please read more her...
It can be opensource. I need it because I don't want to install virtual machine. So is there any online, html/flash/js based, free C++ (or at least C) compiler that can compile code simulating ubuntu c/c++ compiler and return built executable file to me? I heard that Mozilla had some cool online editors but I don't kn...
I don't think you clearly understand the difference between an editor and a compiler. An editor cannot compile code. A compiler doesn't help you to edit code. An IDE (Integrated Development Environment) incorporates the features of both an editor and a compiler. Are you asking if anyone knows of an IDE that can comp...
So we have some function like(pow(e,(-a*x)))/(sqrt(x))wherea,eare const floats. we have some float eps=pow (10,(-4)). We need to find out starting from whichxintegral of that function from that x to infinety is less than eps? We can not use functions for special default integration function just standart math like op...
If you perform the u-substitution u=sqrt(x), your integral will become 2 * integral e^(-au^2) du. With one more substitution you can reduce it to a standard normal. Once you have it in standard normal form, this reduces to calculating erf(x). The substitutions can be done abstractly for any a, and the results hardc...
``` strcmp(variable, "constant"); ``` Or do I have to protect it with a mutex?
If variable can be modified by other thread you must protect it. No magic here – higher level languages could do such function call atomically and that is the 'magic' not present in C. Please note that protection (by a single lock) need both the 'variable' pointer value (address of the string in the memory) and the s...
``` #include <stdio.h> #define f(a,b) a##b #define g(a) #a #define h(a) g(a) int main() { printf("%s\n",h(f(1,2))); printf("%s\n",g(f(1,2))); return 0; } ``` Just by looking at the program one "might" expect the output to be, the same for both the printf statements. But on running the progr...
An occurrence of a parameter in a function-like macro, unless it is the operand of#or##, is expanded before substituting it and rescanning the whole for further expansion. Becauseg's parameteristhe operand of#, the argument is not expanded but instead immediately stringified ("f(1,2)"). Becauseh's parameteris notthe o...
It's the same idea as Operating system boot loader. I have a C source code and Assembly source code. I want the assembly code to pass control to the C application. I am working on Linux and using GCC + NASM for compiling. Do I need to compile them in a special way? What's the assembly code used to load the c applicati...
Let gcc and nasm produce object files which you can link together. You have to use the right symbol names, too. In the NASMmanual, you can find a nice explanation including examples. As it is not explained how to compile the examples using gcc and a linker, you can find these things explainedhere.
``` void call(int x,int y,int z) { printf("%d %d %d",x,y,z); } int main() { int a=10; call(a,a++,++a); return 0; } ``` this program is giving different output on different compiler and when i compiled it on linux m/c output was quite weird,any reason.
Because the behaviour is undefined. The compiler is allowed to evaluatea,a++and++ain any order before passing them tocall(). (Technically, because we've invoked undefined behaviour, it actually doesn't have to do anything in particular at this point; it may write whatever code it pleases.) Depending on what order they...
I never saw such awhilestatement before. ``` while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) { .. .. } ``` I read online, that the condition to come out of while loop is the rightmost one [ !feof(stdin) ]. Then, what is the use of the abovewhilestatement as opposed to ``` while(!feof(stdin)) { prin...
The two loops given don't have the same meaning. By using the comma operator in that way, the author was able to specify code that should be executed every iteration, even if the loop itself is never entered. It's more like ado ... while ()loop, or something like the following: ``` printf("> "); fgets(str, 100, stdi...
I'd like to know how to check if a user types the "backspace" character. I'm using thegetch() function i.e. "key = getch()"in my C program and i'd like to check when backspace is pressed. the line: ``` if(key = '\b') { .... ``` doesn't work.
The problem with readingBackspaceis that most terminals are 'cooked' in that keys like backspace are handled by the terminal driver. However, the curses functiongetch()can read the backspace as it's not tied to the terminal. Edit I just noticed your codeisusinggetch()for input. I ran a little test program andgetch...
So my question in C is: what is basically the differences (maybe pros and cons) of using a pthread barrier (init and wait..etc) compared to using the pthread Join in a loop. So say I created 10 threads in a loop, and then later at the place of where I want a barrier, I put a loop to do Join for all the threads. Would...
pthread_join()blocks the calling thread until the joining thread exits. In contrast, a barrier allows the all threads to continue running.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
``` int main(void){ calcuateSphereVolume(radius * radius * radius); return 0; } ``` You spelt 'calculateSphereVolume' incorrectly for one... Also, you need to rethink your formula for the volume of a sphere :Pi
This question already has answers here:Closed12 years ago. Possible Duplicate:How to check whether two file names point to the same physical file How can I know if two hardlinks are connected to one file from C in Linux. Thanks.
Use thestat() or fstat()function for both paths. If in the returned structures both the st_dev and st_ino fields are identical, then the paths refer to the same filesystem object. EDIT: Note thatyou need to check both st_dev and st_ino. Otherwise you run the risk of matching two files in different filesystems that j...
I did the opposite by mistake and now i can't go back to the java enviorment. anyoune knows how? thanks.
There should be a button in the top right corner for changing perspectives. You can also get to it through theWindow > Open Perspectivemenu.
I never saw such awhilestatement before. ``` while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) { .. .. } ``` I read online, that the condition to come out of while loop is the rightmost one [ !feof(stdin) ]. Then, what is the use of the abovewhilestatement as opposed to ``` while(!feof(stdin)) { prin...
The two loops given don't have the same meaning. By using the comma operator in that way, the author was able to specify code that should be executed every iteration, even if the loop itself is never entered. It's more like ado ... while ()loop, or something like the following: ``` printf("> "); fgets(str, 100, stdi...
I'd like to know how to check if a user types the "backspace" character. I'm using thegetch() function i.e. "key = getch()"in my C program and i'd like to check when backspace is pressed. the line: ``` if(key = '\b') { .... ``` doesn't work.
The problem with readingBackspaceis that most terminals are 'cooked' in that keys like backspace are handled by the terminal driver. However, the curses functiongetch()can read the backspace as it's not tied to the terminal. Edit I just noticed your codeisusinggetch()for input. I ran a little test program andgetch...
So my question in C is: what is basically the differences (maybe pros and cons) of using a pthread barrier (init and wait..etc) compared to using the pthread Join in a loop. So say I created 10 threads in a loop, and then later at the place of where I want a barrier, I put a loop to do Join for all the threads. Would...
pthread_join()blocks the calling thread until the joining thread exits. In contrast, a barrier allows the all threads to continue running.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
``` int main(void){ calcuateSphereVolume(radius * radius * radius); return 0; } ``` You spelt 'calculateSphereVolume' incorrectly for one... Also, you need to rethink your formula for the volume of a sphere :Pi
This question already has answers here:Closed12 years ago. Possible Duplicate:How to check whether two file names point to the same physical file How can I know if two hardlinks are connected to one file from C in Linux. Thanks.
Use thestat() or fstat()function for both paths. If in the returned structures both the st_dev and st_ino fields are identical, then the paths refer to the same filesystem object. EDIT: Note thatyou need to check both st_dev and st_ino. Otherwise you run the risk of matching two files in different filesystems that j...
I did the opposite by mistake and now i can't go back to the java enviorment. anyoune knows how? thanks.
There should be a button in the top right corner for changing perspectives. You can also get to it through theWindow > Open Perspectivemenu.
if i had a 5 X 5 multidimensional-array, where all values would be ether 0 or 1, would there be a way to generate a 5 X 5 pixel image where 1 was black and 0 was white? i would like to do this in c. the output image type would not matter. --Thanks chad
If the array is 5x5 then it is 2-dimensional which is more specific than calling it multi-dimensional. Read up on the pbm or the pgm image formats. They are very easy to use and they are easily output by your program.
So how to create a function to return nearest up so nearest to 9 9+ 1 to given int leaving no remainder when divided by 2 int?
To round to the nearest int: ``` number+=(number & 1) ```
Is there aplatform-independentway to measure time up to micro seconds using C standard library?
The precision of the measurement depends on the operating system, unfortunately.
i have to write program, which will create two child processes These processes would write something in the file, but both processes are managed by the parent(which process will write) i am not asking you guys for direct solutions, but i need some hints, to know where to start from. I guess i have to create two forks...
You will need the basicfork()usage pattern, which looks like so: ``` pid = fork(); if (pid == 0) { // child process code starts here } else if (pid > 0) { // parent process code continues here } ``` Sounds like you are going to need twofork()s, which means you need to use this pattern nested. That's the basic u...
``` #include <stdio.h> #include <stdlib.h> #include <string.h> void main() { typedef int (FuncPtr)(); char asmFunc[] = {0x90, 0xB8, 0x10, 0x00, 0x00, 0x00, 0xC3}; FuncPtr *cFunc = malloc(7); memmove(cFunc, asmFunc, 7); int result = cFunc(); printf("result = %d\n", result); } ``` Would be awesome if somebody co...
Best way to put assembly code in a C source file would be to use inline assembly. Here's a goodstarting point. Example: ``` int main(void) { int x = 10, y; asm ("movl %1, %%eax;" "movl %%eax, %0;" :"=r"(y) /* y is output operand */ :"r"(x) /* x is input operand */ :"%eax"); /* %eax is clobbered regi...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. Diagram and program code in c is ne...
http://www.codeproject.com/KB/recipes/ReverseLinkedList.aspx It's also on Google.