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 thread. But currently, all through the code, there is a global variable logger.
I currently have two solutions, neither of which makes me happy.
Implement a hash on the thread id: pthread_self().Pass the parameter from the thread creation to every function it calls (very invasive).
I'd love some clever way to make it look like I have a global variable in each thread, something with very little overhead.
|
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 technique is common for developing API for C/C++ programs?
One example is sockets. And what else?
Thanks...
|
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 model" or something of those sorts.
One example of such API is theOpenGL's.
|
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::extent< T[ N ] >::value;
}
```
And then it becomes:
```
char arrname[5];
size_t count = countof( arrname );
char arrtwo[5][6];
size_t count_fst_dim = countof( arrtwo ); // 5
size_t count_snd_dim = countof( arrtwo[0] ); // 6
```
Edit:I just noticed the "C" flag rather than "C++". So if you're here for C, please kindly ignore this post. Thanks.
|
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., a list of strings of max-length 40) ?
|
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 there, but is managed by something else. They first appeared (as I recall) for X Window and screen and the like, where you needed something that acted like a terminal but could be used from another program.
|
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 matrix as const CvMat i.e how to change CvMat to const CvMat?
|
" 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 pointer can always be converted to a const pointer implicitly.
|
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 notice you'll need the python.soruntime libraries in order to run the exec.
|
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);
for(i=0;t = va_arg(ap, int);i++){
printf("%d", t);
}
va_end(ap);
}
```
This program's output over my gcc compiler under ubuntu 10.04:
```
234561345138032514932134513792
```
so how to find how many no. of arguments actually passed to the function?
|
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 should follow)
|
```
#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 prototyped in<sys/inotify.h>.
My question is what's the difference betweenlinux/inotify.handsys/inotify.h? Why are there both?
|
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 constants used to implement the notification system itself. You shouldn't include that file unless you're writing something like a kernel module, because it's Linux-specific and thus not portable.
|
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 with C++; ofstreamwritein binary mode, it is readable. why doesn't it come up same as written usingfwrite?
|
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 your code with streams - we'll see what's wrong.
|
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 betweenc1andc2:
```
printf("%d\n", obtainStringLength("abc def ghi", 'a', 'i')); //should yield 11
```
Unfortunately, this is always printing 1. What is the problem? Shouldn'tstrchrwork like C#'sstring.IndexOf()?
|
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 + (endOcurrence - firstOcurrence);
```
|
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++requires anlvalueas an argument and returns anrvalue.
|
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 wide string literal tokens, the resulting multibyte character sequence is treated as a wide string literal; otherwise, it is treated as a character string literal.
|
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: warning: format ‘%lld’ expects type ‘long long int’, but argument 6 has type ‘Blkno’
How can I tellprintfthat I'm passing a 64bit type?Is there some better way to standardize specs for user types than using a#definelikeBLKNO_FMTas above?
|
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 forced to usestruct Handle *, instead ofHandle *.
|
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 j;
printf("%d", i);
}
int main()
{
struct S s;
return 0;
}
```
|
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 failure code to the shell by using thereturnkeyword, along with an integral value. In Java, you do it by calling System.Exit(code) with a return code. Two different ways of doing the same thing.
This guy hasquite the write-upon the topic!
|
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 center.Closed10 years ago.
```
#include<stdio.h>
int main()
{
char a='x';
printf("%c %d",a);
return 0;
}
```
Output:
x 134513696
What is 134513696?
|
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 main question. Obviously I prefer the upper one, but there is one way to make it even more readable in my opinion:
```
d = (double(i) * 23.54) / (d + double(j));
```
My question here is, will this be less efficient? Will the compiler create more doubles in this case than if they were casted with the other methods, or is it clever enough not to? Is this more or less bad than typical C-style casts?
|
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 variables defined in functions but globally in the .c file.
So which of the following variables are automatically initialized with zero?
```
static struct mystruct var1;
struct mystruct var2;
static struct { int x; int y; } var3;
```
|
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? How can I perform this operation fast?
|
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.name,
report.signalInfo.code, report.signalInfo.address);
```
with the error:
```
error: expected `)' before 'PRIx64'
```
I tried searching around but can't find anything on this. Thoughts? report.signalInfo.address is an 64-bit unsigned int so why don't they just use %u?
Thanks!
|
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 main question. Obviously I prefer the upper one, but there is one way to make it even more readable in my opinion:
```
d = (double(i) * 23.54) / (d + double(j));
```
My question here is, will this be less efficient? Will the compiler create more doubles in this case than if they were casted with the other methods, or is it clever enough not to? Is this more or less bad than typical C-style casts?
|
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 variables defined in functions but globally in the .c file.
So which of the following variables are automatically initialized with zero?
```
static struct mystruct var1;
struct mystruct var2;
static struct { int x; int y; } var3;
```
|
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? How can I perform this operation fast?
|
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.name,
report.signalInfo.code, report.signalInfo.address);
```
with the error:
```
error: expected `)' before 'PRIx64'
```
I tried searching around but can't find anything on this. Thoughts? report.signalInfo.address is an 64-bit unsigned int so why don't they just use %u?
Thanks!
|
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*10;
temp->next=(node *) malloc(sizeof(node));
temp=temp->next;
}
temp =root;
while(temp){ //infinite loop
printf("\n%d",temp->data);
temp=temp->next;
}
getch();
return 0;
}
```
|
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 options are available to me for initializing VLAs? Am I forced to use a line such as:
```
memset(name, 0, sizeof(name));
```
Instead?
|
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 length array type.
|
```
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 null bytes, string termination chars and anything other that has byte representation? What would be the difference between bcopy and memcpy in this situation?
Addition:memcpy(pointer+offset, sourcedata, size);that's how you can do 'memcpy append' guys. Thank you all!
|
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 = dosomething()
```
However, python keeps reporting
```
TypeError: dosomething() takes exactly 1 arguments (0 given)
```
I've tried using OUTPUT in a typemap, but to no avail. Any ideas?
|
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't known
libgearman/client.c:1002: warning: implicit declaration of function 'uuid_generate'
libgearman/client.c:1003: warning: implicit declaration of function 'uuid_unparse'
libgearman/client.c:986: warning: unused variable 'uuid' [-Wunused-variable]
make[1]: *** [libgearman/libgearman_libgearman_la-client.lo] Error 1
make[1]: Leaving directory `/src/gearmand-0.14'
make: *** [all] Error 2
```
Here is the source file in question:
http://bazaar.launchpad.net/~gearman-developers/gearmand/trunk/annotate/head:/libgearman/client.c
|
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>ü</blah>
...
```
Calling Value() on the TiXmlText instance I get:
```
"uuml;"
```
So TinyXml always seems to remove the ampersand. Is there any way I can get it to leave it alone so it comes out unchanged?
Appreciate any ideas..
|
If you look at theTinyXML documentationyou'll see that it recognizes only five character entities (üis not one of them), plus Unicode code point syntax or .
|
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 = debounceAOld;
}
```
|
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 programming in linux.
|
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 Windows and Linux, with very little work on my part. It might not be a bad introduction to coding on Linux, as you will be able to use a familiar language.
|
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 type is the same as marking it asunsigned int. However, I'm completely baffled by the colon. What does it do? My guess is that it's some sort of initializer, but I haven't a clue what it means. Off the top of my head, the only place that I'd expect a colon in C is in the ternary operator, which this obviously isn't. So, this appears to be a construct with which I am not familiar. Can anyone explain what the purpose of the colon is in this struct definition? What exactly does the declarationunsigned i:1;mean?
|
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() - creates a socket.
connect() - makes a connection.
send() - take a guess ;)
recv() - read data from socket.
If you just search something like "socket c example" on Google you should be fine.
|
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 this.
Short: How to I print alinked list?
|
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.
Once that next node is the end of the list, stop.
1Well, actually, there probablyare,but this isn't one of them :-)
|
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 type tointin C and C++. The code must be the same for both C and C++. The following program works for C but not for C++.
```
int main(void)
{
long long a;
int b = (int)&a;
return 0;
}
```
How can I get it working for C++?
|
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(unsigned int))
unsigned int * bitarray = (int *)calloc(size / 8 + 1, sizeof(unsigned int));
static inline void setIndex(unsigned int * bitarray, size_t idx) {
bitarray[idx / WORD_BITS] |= (1 << (idx % WORD_BITS));
}
```
Don't use a specific size (e.g. with uint64 or uint32), let the computer use what it wants to use and adapt to that using 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 just keywords
UPDATE2:
Thank you All for answers. Apparently moderators were less enthusiastic than I was about subtle differences between C and C++.
UPDATE3:
to moderators: could you merge it with my previous question on the topic, as you suggested? It makes perfect sense to keep these two question together.
|
```
#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 here:http://c-faq.com/aryptr/index.html
|
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 know if they have compilation options.
|
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 compile for Ubuntu?
What platform do you want it to run on?
|
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 operators. point is to achive max evaluetion speed.
|
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 hardcoded for simplicity and speed.
|
```
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 string itself (note: it could be referenced by other pointer too). If the string is modified while 'strcmp' is running you could get false result or a buffer overflow and a segmentation fault.
|
```
#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 program you get it as:
```
bash$ ./a.out
12
f(1,2)
bash$
```
Why is it so?
|
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 operand of#nor##, the argument is first expanded (12), then substituted (g(12)), then rescanning and further expansion occurs ("12").
|
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 application and start it ?
|
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're evaluated in, the results differ.
|
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))
{
printf("> ");
fgets(str, 100, stdin);
...
...
}
```
Also,whilestatement takes an expression, so is 1,1,1 a valid expression in C?
|
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, stdin);
while(!feof(stdin)) {
..
..
printf("> ");
fgets(str, 100, stdin);
}
```
|
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()returns 127 when you hit backspace. Therefore try:
```
if (key == 127 || key == 8) { ... /* Checks for both Delete or Backspace */
```
Also note that your sample code uses theassignmentoperator=when it should be using theequalityoperator==
|
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. Wouldn't that act as a Barrier too?
Please clarify. Thanks!
|
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 center.Closed10 years ago.
New to C can someone tell me what is wrong with this program.
```
#include <stdio.h>
float volume = 0.00;
float radius = 10.00;
float calculateSphereVolume(float radiusCubed){
volume = 4.0f/3.0f * radiusCubed;
printf("%.2f", volume);
return volume;
}
int main(void){
calcuateSphereVolume(radius * radius * radius);
return 0;
}
```
|
```
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 just happen to have the same inode number. You may be able to see this if you runstaton two mountpoints:
```
$ stat / /boot | grep Device
Device: 903h/2307d Inode: 2 Links: 23
Device: 902h/2306d Inode: 2 Links: 3
```
You can clearly see the identical inode numbers in the output.
|
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 here:http://c-faq.com/aryptr/index.html
|
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 know if they have compilation options.
|
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 compile for Ubuntu?
What platform do you want it to run on?
|
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 operators. point is to achive max evaluetion speed.
|
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 hardcoded for simplicity and speed.
|
```
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 string itself (note: it could be referenced by other pointer too). If the string is modified while 'strcmp' is running you could get false result or a buffer overflow and a segmentation fault.
|
```
#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 program you get it as:
```
bash$ ./a.out
12
f(1,2)
bash$
```
Why is it so?
|
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 operand of#nor##, the argument is first expanded (12), then substituted (g(12)), then rescanning and further expansion occurs ("12").
|
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 application and start it ?
|
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're evaluated in, the results differ.
|
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))
{
printf("> ");
fgets(str, 100, stdin);
...
...
}
```
Also,whilestatement takes an expression, so is 1,1,1 a valid expression in C?
|
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, stdin);
while(!feof(stdin)) {
..
..
printf("> ");
fgets(str, 100, stdin);
}
```
|
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()returns 127 when you hit backspace. Therefore try:
```
if (key == 127 || key == 8) { ... /* Checks for both Delete or Backspace */
```
Also note that your sample code uses theassignmentoperator=when it should be using theequalityoperator==
|
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. Wouldn't that act as a Barrier too?
Please clarify. Thanks!
|
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 center.Closed10 years ago.
New to C can someone tell me what is wrong with this program.
```
#include <stdio.h>
float volume = 0.00;
float radius = 10.00;
float calculateSphereVolume(float radiusCubed){
volume = 4.0f/3.0f * radiusCubed;
printf("%.2f", volume);
return volume;
}
int main(void){
calcuateSphereVolume(radius * radius * radius);
return 0;
}
```
|
```
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 just happen to have the same inode number. You may be able to see this if you runstaton two mountpoints:
```
$ stat / /boot | grep Device
Device: 903h/2307d Inode: 2 Links: 23
Device: 902h/2306d Inode: 2 Links: 3
```
You can clearly see the identical inode numbers in the output.
|
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))
{
printf("> ");
fgets(str, 100, stdin);
...
...
}
```
Also,whilestatement takes an expression, so is 1,1,1 a valid expression in C?
|
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, stdin);
while(!feof(stdin)) {
..
..
printf("> ");
fgets(str, 100, stdin);
}
```
|
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()returns 127 when you hit backspace. Therefore try:
```
if (key == 127 || key == 8) { ... /* Checks for both Delete or Backspace */
```
Also note that your sample code uses theassignmentoperator=when it should be using theequalityoperator==
|
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. Wouldn't that act as a Barrier too?
Please clarify. Thanks!
|
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 center.Closed10 years ago.
New to C can someone tell me what is wrong with this program.
```
#include <stdio.h>
float volume = 0.00;
float radius = 10.00;
float calculateSphereVolume(float radiusCubed){
volume = 4.0f/3.0f * radiusCubed;
printf("%.2f", volume);
return volume;
}
int main(void){
calcuateSphereVolume(radius * radius * radius);
return 0;
}
```
|
```
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 just happen to have the same inode number. You may be able to see this if you runstaton two mountpoints:
```
$ stat / /boot | grep Device
Device: 903h/2307d Inode: 2 Links: 23
Device: 902h/2306d Inode: 2 Links: 3
```
You can clearly see the identical inode numbers in the output.
|
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 at start and then manage it through case, or something like that
thanks
|
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 usage, all the rest is up to your application.
|
```
#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 could fix the assembler part on a intel i7 pc because it result in a segfault on my ubuntu :)
Is this the best way to put assembler code in a c program?
|
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 register */
}
```
|
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 necessary.
|
http://www.codeproject.com/KB/recipes/ReverseLinkedList.aspx
It's also on Google.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.