question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
For instance if I called WriteFile to the end of a file, and later I wanted to delete the written bytes, how could I do this? Do I have to read the file's contents into a buffer, re-create the file, and write the desired bytes, or is there an easier way?
|
Seekto the file position you want to truncate from (if you're not already there), then call the aptly-namedSetEndOfFile()function.
|
How can I understand the parsing of expressions like
```
a = b+++++b---c--;
```
in C?
I just made up the expression above, and yes, I can check the results using any compiler, but what I want to know is theground rulethat I should know to understand the parsing of such expressions in C.
|
From the standard 6.2(4):
If the input stream has been parsed into preprocessing tokens up to a given character, the
next preprocessing token is the longest sequence of characters that could constitute a
preprocessing token.
They even add the example:
EXAMPLE 2 The program fragment x+++++y
is parsed as x ++ ++ + y, which
violates a constraint on increment
operators, even though the parse x ++
+ ++ y might yield a correct expression.
So your statement:
```
a = b+++++b---c--;
```
Is equivalent to:
```
a = b ++ ++ + b -- - c -- ;
```
|
I'm trying to encode and transfer raw video frames over LAN (100 Mbps) connection (frames captured by a web cam). What video/image encoding format is recommended for fast compression (with not much regard for the compression ratio) ?
Thanks,
|
If you need individual frames to be independent of one another, use mjpeg (which is equivalent to encoding each frame as a jpeg). It's simple and you have plenty of tools with which to manipulate it.
Otherwise, as long as you have a remotely modern cpu and the resolution isn't insanely high, just use a simple mpeg4 asp or even h264 profile. Encoding 320x240 video with the simplest profile should take less than 5% cpu on a current low-end machine.
|
Is there a way to set the blending parameters so the whole scene renders in grayscale? (without using GLSL, only pipeline functions)
Thanks
|
No, all colors are separated. You need a pixel shader for that
|
We're using Redis for monitoring on a high traffic web application.
The app is written in c and uses the credis client
library.
We're seeing enormous numbers of TIME_WAIT connections left over from
our communications with Redis:
$ netstat -a | grep 6379 | grep TIME_WAIT | wc -l
15865
Any idea what's going on here?
"
rh = credis_connect(NULL, 6379, 2000);credis_incr(rh, "hhhh2",NULL);credis_close(rh);
|
SeeSO question #337115for approaches to this problem.
(I prefer making the client close the connection so the client ends up in the TIME_WAIT state.)
|
I have aC-program(an Apache module, i.e. the program runs often), which is going towrite()a 0-terminated string over a socket, so I need to know its length.
The string is #defined as:
```
#define POLICY "<?xml version=\"1.0\"?>\n" \
"<!DOCTYPE cross-domain-policy SYSTEM\n" \
"\"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\n" \
"<cross-domain-policy>\n" \
"<allow-access-from domain=\"*\" to-ports=\"8080\"/>\n" \
"</cross-domain-policy>\0"
```
Is there please a way, better than usingstrlen(POLICY)+1at the runtime (and thus calculating the length again and again)?
A preprocessor directive, which would allow settingPOLICY_LENGTHalready at compile time?
|
Usesizeof(). e.g.sizeof("blah")will evaluate to5at compile-time (5, not 4, because the string literal always includes an implicit null-termination character).
|
I have some vars live:
```
int foo1;
int foo2;
..
```
and I want to reach them from:
```
for (int i = 1;i<=2;i++)
{
// howto get foo1 and foo2?
}
```
how to get them?
EDIT, end what when it will be no int but a Opject *pointer;?
|
You can't; you need an array of some kind. e.g.:
```
int foo[2]; /* Two elements, foo[0] and foo[1] */
for (int i = 0; i < 2; i++)
{
foo[i] = i;
}
```
or:
```
int foo1;
int foo2;
int *p[] = { &foo1, &foo2 }; /* Array of pointers */
for (int i = 0; i < 2; i++)
{
*p[i] = i; /* Changes foo1 or foo2 */
}
```
I don't fully understand your last question, but if you mean that you want the data types to beObject *rather thanint, then all you need to do is substituteObject *forintinto my code examples above (other than forint i = 0, obviously).
|
I have a process that continuously needs to write information. Furthermore, there is a second process which sometimes connects to the "information channel" of the writing process and should read the information that are written since it's connected. This process might also deconnect and reconnect several times again.
I am currently realizing this with a named pipe, by using mkfifo() in my c++ program. Unfortunately if I call open() on this fifo it blocks until a process opens the fifo for reading. This is quite normal for named pipes, but I need this open command to be non-blocking.
Do you know an alternative to mkfifo in this case?
Heinrich
|
You could use Unix-domain sockets, or regular TCP sockets on loopback interface.
|
I need to use natural cubic spline interpolation in an iPhone app. Does anyone know of a class for Obj C or C that resembles this:http://www.ee.ucl.ac.uk/~mflanaga/java/CubicSpline.html
"performing an interpolation within a one dimensional array of data points, y = f(x), using a cubic spline."
|
Look at thisarticleThis is a sample for Curve Fitting. It uses Cubic Spline Interpolation, and Bezier Spline Curve.
|
```
#include<stdio.h>
int main(void)
{
char c = 0x80;
printf("%d\n", c << 1);
return 0;
}
```
The output is-256in this case. If I writec << 0then the output is-128.
I don't understand the logic behind this code.
|
charmay be signed on your platform, in which case0x80represents -128 (assuming two's complement).
When acharis used as an operand with the<<operator, it is promoted toint(still -128). So when you apply the left-shift, you get -256. Technically, shifting negative values isimplementation-definedundefined, but what you see is typical behaviour.
|
I have a C source file having comments in//(C++) style. I want to change all the comments to the old/* */(C) style. Is there a way to do this using an existing script?
|
A substitution with you favorite editor and a regular expression likes#//(.*)#/*\1 */#should do it...
|
How do I cause a thread to respond topthread_cancel()if it is blocked on asem_wait()?
|
You can set a signal handler, let's says for SIGUSR1, for the thread that will be blocking then, from another thread, you callpthread_cancel(tid)andpthread_kill(tid, SIGUSR1). The thread will be canceled oncesem_wait()is interrupted by the signal.
|
Many times I see in open source code that a call to a C function is cast to void.
For example, in the source code forls(http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/ls/ls.c) I see the following.
```
(void) setlocale(LC_ALL, "");
```
Why is this good practice?
|
It explicitly means you ignore the return value, and did not just forget it.
|
I am looking for a automated finite state machine generator for C? I have seen a few over the internet but unable to decide which one to use. If anybody worked with any such tool then help me to find the right one.
Thanks,
Ravi Gupta
|
Ragelis fairly powerful.
|
I know that C strings are char[] with a '\0' in the last element. But how are the chars encoded?
Update: I found this cool link which talks about many other programming languages and their encoding conventions:Link
|
All the standard says on the matter is that you get at least the 52 upper- and lower-case latin alphabet characters, the digits 0 to 9, the symbols! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~, and the space character, and control characters representing horizontal tab, vertical tab, form feed, alert, backspace, carriage return, and new line.
The only thing it says about numeric encoding is that all of the above fits in one byte, and that the value of each digit after zero is one greater that the value of the previous one.
The actual encoding is probably inherited from your locale settings. Probably something ASCII-compatible.
|
I would like to model an event-driven finite state machine in C as proposed here :http://en.wikipedia.org/wiki/Event-driven_finite_state_machine
But I would also like the 'external' events to be handled in various threads.
Can I find such a code somewhere ? Or advices ?
|
Message queues are a way to solve your problem.
If you want to feed your state machine with external events from other threads, they can write these events in a message queue that will be read by your state machine.
If you want that other threads trigger on actions from your state machine, it can write to various message queues each associated to a thread that will read from its MQ.
One drawback is that events get sorted in chronological order. If your state machine is not in the mood of handling the event it just read from the queue, you have to decide what to do with this event: destroy it, put it back to the queue, remember it for future use...
|
I am taking a file path from a user. I need to then access that file, and create it if it does not exist. I also need to create any intermediate directories if they don't exist as well.
For example, if my directory looks like:
```
mydir
|
+---subdir
| |
| +-- FileA
|
+---File1
```
I might receive mydir/subdir/FileA and would then access the relevant file. However, I might also receive mydir/NewDir/FileB.
How can I do this using Unix system calls in C? I have tried using open() with the (O_RDWR | O_CREAT) flags, but this didn't work out.
|
I think this answer covers your question:
Recursive mkdir() system call on Unix
In short, you must create the subdirs yourself.
|
So... I will have a project which will be tested on Win 7 and some Linux server. It will be a web service that will use HSQLDB, Hibernate, Spring, Blaze DS and Flash (Flex RIA) as front end. I need to implement into it some image filtering\editing functionality which will be implemented in cross-platform C++ code (It will use Open-CV) wrapped in Java.
I need some kind of tutorial how to create cross-platform Java projects that use C/C++ libs *(most of all I am intrested in crossplatform compiling issue and what IDEs support such things)
|
It sounds like you'll benefit from the Java Native Interface. If you've got existing C and C++ code that you'd like to use from Java you may want to seriously consider something likeGlueGen. It will save you a lot of time generating the code to access your C code.
You can have a look at the official Java JNI Exampleshere
|
I'm Interested in writing gedit-plugins in C. I've checkedGedit/NewMDIPluginHowTo...but haven't had any luck with it.
How can I get more information about writing gedit plugins in C?
|
If you're willing to use Python instead,hereis a tutorial for writing gedit plugins in Python.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago.
I'm looking for interesting programming puzzles, problems or challenges suitable for a class of chemistry majors learning C as their first programming language. Do you have any recommendations?
|
Project Euleris pretty good. They have some simple challenges that may be suitable.
These won't really do much to teach them C, though. Text books are much better for that.
Additionally, you could have them write a program to balance chemical reaction equations. That would be good for I/O and simple math.
|
I have astaticvariable in source filetest_1.cdeclared as:
```
static char var1 = 0;
```
I need to access the current value of this variable from source filetest_2.c. So, I did something like:
In test_1.c
```
static char var1 = 0;
volatile char var_another = var1;
```
and intest_2.c, I declare the variablevar_anotherasexternand access it:
```
extern volatile char var_another;
```
Is this the right way to do it?
|
staticandexternare mutually exclusive. If you want to access yourstatic char var1from a different file, you'll have to remove thestaticand just make it a regular global. You don't needvolatileat all.
Alternatively, you can make an accessor function that returns the value ofstatic char var1and use that from your other module.
Side note: externs and exported function prototypes should generally go in header files.
|
I have#include<math.h>,
and I tried to use pow(x, y) and powf(x, y).
but it seems neither of them are under c99 standard.
and I use the commandgcc -std=c99 test.c -o testto compile.
what function there exists I can use?
|
Forhistericalreasons, the math library is not bundled in with the rest of the Standard Library. You have to manually add it to the compilation with the-lmoption to gcc.
```
gcc -std=c99 test.c -o test -lm
```
|
My c/c++ skills are non-existent
and
there's some custom string array data that needs to be returned from an old C dll
fyi - The C/C++ code can be modified as needed
|
Without more information about your specific case, it's impossible to say how you'd marshal the return value. Perhaps this page of interop marshaling samples will help:http://msdn.microsoft.com/en-us/library/e765dyyy.aspx
The above link no longer works. TryMarshaling Data with Platform Invoke.
|
I am looking for a automated finite state machine generator for C? I have seen a few over the internet but unable to decide which one to use. If anybody worked with any such tool then help me to find the right one.
Thanks,
Ravi Gupta
|
Ragelis fairly powerful.
|
I know that C strings are char[] with a '\0' in the last element. But how are the chars encoded?
Update: I found this cool link which talks about many other programming languages and their encoding conventions:Link
|
All the standard says on the matter is that you get at least the 52 upper- and lower-case latin alphabet characters, the digits 0 to 9, the symbols! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~, and the space character, and control characters representing horizontal tab, vertical tab, form feed, alert, backspace, carriage return, and new line.
The only thing it says about numeric encoding is that all of the above fits in one byte, and that the value of each digit after zero is one greater that the value of the previous one.
The actual encoding is probably inherited from your locale settings. Probably something ASCII-compatible.
|
I would like to model an event-driven finite state machine in C as proposed here :http://en.wikipedia.org/wiki/Event-driven_finite_state_machine
But I would also like the 'external' events to be handled in various threads.
Can I find such a code somewhere ? Or advices ?
|
Message queues are a way to solve your problem.
If you want to feed your state machine with external events from other threads, they can write these events in a message queue that will be read by your state machine.
If you want that other threads trigger on actions from your state machine, it can write to various message queues each associated to a thread that will read from its MQ.
One drawback is that events get sorted in chronological order. If your state machine is not in the mood of handling the event it just read from the queue, you have to decide what to do with this event: destroy it, put it back to the queue, remember it for future use...
|
I am taking a file path from a user. I need to then access that file, and create it if it does not exist. I also need to create any intermediate directories if they don't exist as well.
For example, if my directory looks like:
```
mydir
|
+---subdir
| |
| +-- FileA
|
+---File1
```
I might receive mydir/subdir/FileA and would then access the relevant file. However, I might also receive mydir/NewDir/FileB.
How can I do this using Unix system calls in C? I have tried using open() with the (O_RDWR | O_CREAT) flags, but this didn't work out.
|
I think this answer covers your question:
Recursive mkdir() system call on Unix
In short, you must create the subdirs yourself.
|
So... I will have a project which will be tested on Win 7 and some Linux server. It will be a web service that will use HSQLDB, Hibernate, Spring, Blaze DS and Flash (Flex RIA) as front end. I need to implement into it some image filtering\editing functionality which will be implemented in cross-platform C++ code (It will use Open-CV) wrapped in Java.
I need some kind of tutorial how to create cross-platform Java projects that use C/C++ libs *(most of all I am intrested in crossplatform compiling issue and what IDEs support such things)
|
It sounds like you'll benefit from the Java Native Interface. If you've got existing C and C++ code that you'd like to use from Java you may want to seriously consider something likeGlueGen. It will save you a lot of time generating the code to access your C code.
You can have a look at the official Java JNI Exampleshere
|
I'm Interested in writing gedit-plugins in C. I've checkedGedit/NewMDIPluginHowTo...but haven't had any luck with it.
How can I get more information about writing gedit plugins in C?
|
If you're willing to use Python instead,hereis a tutorial for writing gedit plugins in Python.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago.
I'm looking for interesting programming puzzles, problems or challenges suitable for a class of chemistry majors learning C as their first programming language. Do you have any recommendations?
|
Project Euleris pretty good. They have some simple challenges that may be suitable.
These won't really do much to teach them C, though. Text books are much better for that.
Additionally, you could have them write a program to balance chemical reaction equations. That would be good for I/O and simple math.
|
I have astaticvariable in source filetest_1.cdeclared as:
```
static char var1 = 0;
```
I need to access the current value of this variable from source filetest_2.c. So, I did something like:
In test_1.c
```
static char var1 = 0;
volatile char var_another = var1;
```
and intest_2.c, I declare the variablevar_anotherasexternand access it:
```
extern volatile char var_another;
```
Is this the right way to do it?
|
staticandexternare mutually exclusive. If you want to access yourstatic char var1from a different file, you'll have to remove thestaticand just make it a regular global. You don't needvolatileat all.
Alternatively, you can make an accessor function that returns the value ofstatic char var1and use that from your other module.
Side note: externs and exported function prototypes should generally go in header files.
|
I have#include<math.h>,
and I tried to use pow(x, y) and powf(x, y).
but it seems neither of them are under c99 standard.
and I use the commandgcc -std=c99 test.c -o testto compile.
what function there exists I can use?
|
Forhistericalreasons, the math library is not bundled in with the rest of the Standard Library. You have to manually add it to the compilation with the-lmoption to gcc.
```
gcc -std=c99 test.c -o test -lm
```
|
My c/c++ skills are non-existent
and
there's some custom string array data that needs to be returned from an old C dll
fyi - The C/C++ code can be modified as needed
|
Without more information about your specific case, it's impossible to say how you'd marshal the return value. Perhaps this page of interop marshaling samples will help:http://msdn.microsoft.com/en-us/library/e765dyyy.aspx
The above link no longer works. TryMarshaling Data with Platform Invoke.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed12 years ago.
Can any one suggest me a Best IDE for C programming ( With auto completion feature)?
|
use vim with plugins like snipMate, c-support etc.
|
I've downloaded Eclipse C/C++ IDE . I need to run a simple c program in this(To print welcome).
While trying to run the program its popping up an error message like"Launch failed: Binary not found" .
Need i install any compiler package. ?
Please help me to do this.
|
Yes, you have to install a compiler, Eclipse is only an IDE. You can get MinGWhere.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?
This is C code sample of a reference page.
```
signed int _exponent:8;
```
What's the meaning of the colon before '8' and '8' itself?
|
It's a bitfield. It's only valid in astructdefinition, and it means that the system will only use 8 bits for your integer.
|
Just more a general question I can't seem to find a definite answer on.
But what is a good SQL wrapper for C++ that allows me to call queries?
I'm used to Oracle, but i've used MYSQL before aswell.
And how would you call something such as an insert statement (for example) in one?
|
Personally I loveSOCI, simple and easy to use, just follow the link for easy example code and a much better explanation of what SOCI is all about then I could put in this answer. I use this for all of my C++ SQL development work.
|
I recently read a sample job interview question:
Write a function to convert an integer
to a string. Assume you do not have
access to library functions i.e.,
itoa(), etc...
How would you go about this?
|
fast stab at it: (edited to handle negative numbers)
```
int n = INT_MIN;
char buffer[50];
int i = 0;
bool isNeg = n<0;
unsigned int n1 = isNeg ? -n : n;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf(buffer);
```
|
Is there an easy way to check if a line is empty. So i want to check if it contains any white space such as \r\n\t and spaces.
Thanks
|
You can use theisspacefunction in a loop to check if all characters are whitespace:
```
int is_empty(const char *s) {
while (*s != '\0') {
if (!isspace((unsigned char)*s))
return 0;
s++;
}
return 1;
}
```
This function will return 0 if any character is not whitespace (i.e. line is not empty), or 1 otherwise.
|
I have a value thats 5 bits in length. 4 bits determine the number and the 5th bit determines the sign, there by holding any value between -16 and +15. How can I accomplish sign extending from a constant bit width in C#? I know in C, I can use something like the follow to accomplish this:
```
int x; // convert this from using 5 bits to a full int
int r; // resulting sign extended number goes here
struct {signed int x:5;} s;
r = s.x = x;
```
How can I do something similar to this in C#?
|
It's not really clear what you mean, but itcouldbe as simple as:
```
int fiveBits = normal & 0x1f;
```
and for the reverse:
```
int normal = fiveBits < 16 ? fiveBits : fiveBits | -32;
```
If you could suggest some original input and desired output, that would help.
|
I am trying to observe if software can damage hardware today or not.For that I choose that choosing to shut the computer fans would be a nice idea(else I would have preferred crashing the harddisk).I need to know the following:
Is it possible to do that anyone's computer?Can this be dangerous to the hardware?Choosing C is a good choice or should I go for Assembly language?
Thanks in advance.
|
First of all, the fans spin for a reason: complex electronics overheat rather quickly. It would be easier to look into a specialized tool that does this, such as SpeedFan for Windows.
On the other hand, if youreallywant to do it, there are ways - however, they are mostly vendor- and product-specific. For Acer laptops on Linux, see e.g.this- note that it's very low-level (involves BIOS calls) and if it breaks, you get to keep both parts.
|
For regular expression \w+\d, in many script language such as perl/python it can be written literally. But in C/C++, I must write it as:
```
const char *re_str = "\\w+\\d";
```
which is ugly to eye.
Is there any method to avoid it? MACRO are also acceptable.
|
Just as an FYI, the next C++ standard (C++ 0x) will have something calledraw string literalswhich should let you do something like:
```
const char *re_str = R"(\w+\d)";
```
However until then I think you're stuck with the pain of doubling up your backslashes if you want the regex to be a literal in the source file.
|
printfconversion specifications are%followed by flags, width, precision, length modifier and conversion specifier. Is there practical limit to size of a conversion specification?
I.e.%sis 2 chars long, while%08.2fis 6 chars long. My question is, what is the length of the maximal single specification in a format string that can be created, according to C99 standard?
|
There is no such conversion specification of maximum length. If you think you've found such a spec, I can come up with one that is one char longer.
For example, consider field width and precision. The standard says they are decimal integers but does not specify their range. Therefore you can write conversion specifiers with arbitrarily large integers as field width or precision.
|
```
# include <stdio.h>
int x = 5;
int main(void)
{
int x = 7;
printf("output = %d\n", x);
}
```
The above program shows output as7.
How to print5inc?
thanx...
|
So you're asking how to access a global that's shadowed by a local? You can't in that scope, but something like this should work
```
# include <stdio.h>
int x = 5;
int get_global_x()
{
return x;
}
int main(void)
{
int x = 7;
printf("output = %d\n", get_global_x());
}
```
|
My input data is 16-bit data, and I need to find a median of 3 values using SSE2 instruction set.
If I have 3 16-bits input values A, B and C, I thought to do it like this:
```
D = max( max( A, B ), C )
E = min( min( A, B ), C )
median = A + B + C - D - E
```
C functions I am planing to use are :
max - _mm_max_epi16min - _mm_min_epi16addition - _mm_add_epi16subtract - _mm_sub_epi16
Can anyone suggest a better way?
|
Your idea is quite clever but you can do it with fewer operations just using max and min.
```
t1 = min(A, B)
t2 = max(A, B)
t3 = min(t2, C)
median = max(t1, t3)
```
This will be just 4 SSE instructions compared with 8 in your original implementation.
Note that this is actually just a prunedsorting networkfor N = 3.
|
I want to read in a string and parse it with sscanf. Although i don't want to read in any spaces in the beginning.
Sample string.
```
@a Bear Tiger
sscanf(strLine, "@%1s %64s %64s", dir, name1, name2);
```
I have that.
Problem is if the line goes in as say
```
@a Bear Tiger
```
Should be:
```
@a Bear Tiger
```
that it will want to read in the spaces up to the @ character. How can i skip over white-space and read from the @ character.
Thanks.
|
```
sscanf(strLine, " @%1s %64s %64s", dir, name1, name2);
```
This is necessary becausescanfonly skips whitespace for (most) conversion specifications. But@is an "ordinary character", not a conversion specification, so there is no skip. However, adding whitespace to the format string forces input whitespace to be skipped.
|
I was trying to develop a chat application using C programmable sockets. I need to check whether the stdin buffer has some value in it to send the message to the client/server and receive it. But I don't know how to check the stdin buffer for values.
Please help.
|
You wantselect(2,3p).
|
Is there a way to find out if a socket is already in Non-Blocking mode in Windows?
I know this can be done in case of Linux, but, I am unable to find any way for this Windows.
All my coding is in 'C' language. Is there a way?
|
The only way you can check this is by doing something illegal on a nonblocking socket and checking that it fails in an expected way. Hardly the most robust design.
The socket will be blocking unless you explicitly set it nonblocking usingWSAIoctlorioctlsocketwithFIONBIO. That cannot be too hard to check in your code, I would have thought. If you have to track this at runtime, a flag per socket as suggested by @jweyrich is the way to go.
|
Many times I need to do things TWICE in a for loop. Simply I can set up a for loop with an iterator and go through it twice:
```
for (i = 0; i < 2; i++)
{
// Do stuff
}
```
Now I am interested in doing this as SIMPLY as I can, perhaps without an initializer or iterator? Are there any other, really simple and elegant, ways of achieving this?
|
This is elegant because it looks like a triangle; and triangles are elegant.
```
i = 0;
here: dostuff();
i++; if ( i == 1 ) goto here;
```
|
```
struct stats
{
char top : 1;
char bottom : 1;
char side : 2;
} MyStat;
```
I have seen this format with integers but how does the above char bit field work and what does it represent?
Thank You.
|
Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.
|
I'm trying to compile the following code using the MPLAB C18 v3.36 compiler.
Compiler returns a syntax error on 'char rij;'.
But when i put char rij; a line earlier (before TRISA = ...), it compiles ...
```
void setup(void)
{
TRISD = 0b00000000;
TRISA = 0b00000000;
char rij;
for (rij = 0; rij<ROWS; rij++)
{
red_byte_array[rij]=0;
green_byte_array[rij]=0;
blue_byte_array[rij]=0;
}
}
```
|
Although I'm not familiar with this compiler I would guess that it follows C89 semantics which forbid mixing declarations with statements. Therefore you can only declare variables on the beginning of the block.
|
```
void clearscreen ( void )
{
char a = 'a' ;
fflush ( stdout );
do{
a = getc( stdin ) ;
if ( isspace ( (int ) a ) )
{
getc ( stdin );
}
}while ( a != EOF );
}
```
Iwantwrite function which is capable of cleaning the screen, while doing its job itmusterase all characters including especiallywhitespacecharacters.
But I could not write it, so are there any one can help me to write such a function
|
If you're working with a ANSI-compliant terminal (which is probably the case if you're under Linux), then you can useescape sequences.
|
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.
```
char* fun(char *s) {
char buffer[50];
int i=0;
while(*s){
if(isdigit(*s)){
buffer[i++]=*s;
}
s++;
}
buffer[i]='\0';
return buffer;
}
int main(){
char *s="o34";
char *p="off";
p=fun(s);
while(*p){
printf("%c",p);
p++;
}
//printf("%s",fun(&s[0]));
//puts(fun(s));
getchar();
}
```
|
Two problems:
You are returning a pointer to the
character array that islocalto
the function.Inprintf("%c",p);it should be*p
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:C : How do you simulate an 'exception' ?
Hi, I know that exception handling is available in C++ but not in C. But I also read that exception handling is provided from OS side, so isnt there any function for C invoking the same behavior from OS as try catch and throw? Thanks.
|
The C language itself has no support for exception handling. However a means of exception handling for C does exist on a platform + compiler specific basis.
In windows for example C programs can use SEH exception handling.
http://www.microsoft.com/msj/0197/Exception/Exception.aspx
I've seen arguments in the past that the C function pairsetjmpandlongjmpis exception handling in C. I consider it closer to the ejection pattern but it's worth investigating
http://msdn.microsoft.com/en-us/library/aa272905(VS.60).aspx
|
I'm wondering if my implementation should expect that reentrant mutex's are supported or not. The code is supposed to portable/platform independent. I'm wondering if mutex recursion is common enough that it shouldn't be a concern.
|
It's usually a distinct option, available through a different function call. Even then it isn't "detected" it's just "permitted".
Sometimes, you WANT the lock to be recursive. Sometimes, you DON'T want the lock to be recursive. Any solution you come up with without explicitly allowing both conditions will not work universally for every mutex solution available without you imposing some contraints that don't exist in the libraries you'll be wrapping.
|
I would like to parse a html page and extract the meaningful text from it. Anyone knows some good algorithms to do this?
I develop my applications on Rails, but I think ruby is a bit slow in this, so I think if exists some good library in c for this it would be appropriate.
Thanks!!
PD: Please do not recommend anything with java
UPDATE:
I found thislink text
Sadly, is in python
|
UseNokogiri, which is fast and written in C, for Ruby.
(Using regexp to parse recursive expressions like HTML isnotoriously difficult and error proneand I would not go down that path. I only mention this in the answer as this issue seems to crop up again and again.)
With a real parser like for instance Nokogiri mentioned above, you also get the added benefit that the structure and logic of the HTML document is preserved, and sometimes you really need those clues.
|
With reference to the semaphore implementation of semaphore.h in Linux, does an uninitialized semaphore sem_t default to 0?
I just discovered that I had forgotten to initialize my semaphores to 0. Even so, the program worked fine without sem_init.
(To all the purists, I completely agree that doing so is a bad practice.)
|
It will depend on how/where the semaphore is defined.
If it is defined as (part of) a global variable, then the compiler must initialise it to 0 if you don't specify any valueThis is also true when it is (part of) a block-scope variable declared asstatic.If it is (part of) a non-staticblock-scope variable, then it will start out with whatever value has been previously stored in that memory location.
|
Is there a way to find out if a socket is already in Non-Blocking mode in Windows?
I know this can be done in case of Linux, but, I am unable to find any way for this Windows.
All my coding is in 'C' language. Is there a way?
|
The only way you can check this is by doing something illegal on a nonblocking socket and checking that it fails in an expected way. Hardly the most robust design.
The socket will be blocking unless you explicitly set it nonblocking usingWSAIoctlorioctlsocketwithFIONBIO. That cannot be too hard to check in your code, I would have thought. If you have to track this at runtime, a flag per socket as suggested by @jweyrich is the way to go.
|
Many times I need to do things TWICE in a for loop. Simply I can set up a for loop with an iterator and go through it twice:
```
for (i = 0; i < 2; i++)
{
// Do stuff
}
```
Now I am interested in doing this as SIMPLY as I can, perhaps without an initializer or iterator? Are there any other, really simple and elegant, ways of achieving this?
|
This is elegant because it looks like a triangle; and triangles are elegant.
```
i = 0;
here: dostuff();
i++; if ( i == 1 ) goto here;
```
|
```
struct stats
{
char top : 1;
char bottom : 1;
char side : 2;
} MyStat;
```
I have seen this format with integers but how does the above char bit field work and what does it represent?
Thank You.
|
Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.
|
I'm trying to compile the following code using the MPLAB C18 v3.36 compiler.
Compiler returns a syntax error on 'char rij;'.
But when i put char rij; a line earlier (before TRISA = ...), it compiles ...
```
void setup(void)
{
TRISD = 0b00000000;
TRISA = 0b00000000;
char rij;
for (rij = 0; rij<ROWS; rij++)
{
red_byte_array[rij]=0;
green_byte_array[rij]=0;
blue_byte_array[rij]=0;
}
}
```
|
Although I'm not familiar with this compiler I would guess that it follows C89 semantics which forbid mixing declarations with statements. Therefore you can only declare variables on the beginning of the block.
|
```
void clearscreen ( void )
{
char a = 'a' ;
fflush ( stdout );
do{
a = getc( stdin ) ;
if ( isspace ( (int ) a ) )
{
getc ( stdin );
}
}while ( a != EOF );
}
```
Iwantwrite function which is capable of cleaning the screen, while doing its job itmusterase all characters including especiallywhitespacecharacters.
But I could not write it, so are there any one can help me to write such a function
|
If you're working with a ANSI-compliant terminal (which is probably the case if you're under Linux), then you can useescape sequences.
|
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.
```
char* fun(char *s) {
char buffer[50];
int i=0;
while(*s){
if(isdigit(*s)){
buffer[i++]=*s;
}
s++;
}
buffer[i]='\0';
return buffer;
}
int main(){
char *s="o34";
char *p="off";
p=fun(s);
while(*p){
printf("%c",p);
p++;
}
//printf("%s",fun(&s[0]));
//puts(fun(s));
getchar();
}
```
|
Two problems:
You are returning a pointer to the
character array that islocalto
the function.Inprintf("%c",p);it should be*p
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:C : How do you simulate an 'exception' ?
Hi, I know that exception handling is available in C++ but not in C. But I also read that exception handling is provided from OS side, so isnt there any function for C invoking the same behavior from OS as try catch and throw? Thanks.
|
The C language itself has no support for exception handling. However a means of exception handling for C does exist on a platform + compiler specific basis.
In windows for example C programs can use SEH exception handling.
http://www.microsoft.com/msj/0197/Exception/Exception.aspx
I've seen arguments in the past that the C function pairsetjmpandlongjmpis exception handling in C. I consider it closer to the ejection pattern but it's worth investigating
http://msdn.microsoft.com/en-us/library/aa272905(VS.60).aspx
|
I'm wondering if my implementation should expect that reentrant mutex's are supported or not. The code is supposed to portable/platform independent. I'm wondering if mutex recursion is common enough that it shouldn't be a concern.
|
It's usually a distinct option, available through a different function call. Even then it isn't "detected" it's just "permitted".
Sometimes, you WANT the lock to be recursive. Sometimes, you DON'T want the lock to be recursive. Any solution you come up with without explicitly allowing both conditions will not work universally for every mutex solution available without you imposing some contraints that don't exist in the libraries you'll be wrapping.
|
I would like to parse a html page and extract the meaningful text from it. Anyone knows some good algorithms to do this?
I develop my applications on Rails, but I think ruby is a bit slow in this, so I think if exists some good library in c for this it would be appropriate.
Thanks!!
PD: Please do not recommend anything with java
UPDATE:
I found thislink text
Sadly, is in python
|
UseNokogiri, which is fast and written in C, for Ruby.
(Using regexp to parse recursive expressions like HTML isnotoriously difficult and error proneand I would not go down that path. I only mention this in the answer as this issue seems to crop up again and again.)
With a real parser like for instance Nokogiri mentioned above, you also get the added benefit that the structure and logic of the HTML document is preserved, and sometimes you really need those clues.
|
With reference to the semaphore implementation of semaphore.h in Linux, does an uninitialized semaphore sem_t default to 0?
I just discovered that I had forgotten to initialize my semaphores to 0. Even so, the program worked fine without sem_init.
(To all the purists, I completely agree that doing so is a bad practice.)
|
It will depend on how/where the semaphore is defined.
If it is defined as (part of) a global variable, then the compiler must initialise it to 0 if you don't specify any valueThis is also true when it is (part of) a block-scope variable declared asstatic.If it is (part of) a non-staticblock-scope variable, then it will start out with whatever value has been previously stored in that memory location.
|
i want to write a program using multi-threading, raw sockets, to scan the ports in python
i have a C code for injection of raw socket. i want to perform a ACK scan so need a raw socket.
So please help me.
thank you
|
Please check outCython. It makes it very easy to wrap C code.
This is adapted from thedocumentation on calling external C functions:
```
cdef extern from "math.h":
double sin(double)
def pysin(x):
return sin(x)
```
You could then callpysinfrom the compiled module like a normal Python module.
|
Is there a way to put a breakpoint on any function in Visual Studio, sort of likebm kernel32!LoadLib*in WinDbg?
I know one way is to break at application start, find the required DLL load address, then add offset to required function you can get via Depends, and create a breakpoint on address. But that's really slow, and switching to WinDbg and back is also pretty annoying.
Maybe there is a better way?
|
Go to "Debug / New breakpoint / Break at function..." and paste the function name.
For APIs, this can be tricky, as the name of the function as seen by the debugger is different from its real name.Examples:
```
{,,kernel32.dll}_CreateProcessW@40
{,,user32.dll}_NtUserLockWindowUpdate@4
```
See this blog post to find the right name:Setting a Visual Studio breakpoint on a Win32 API function in user32.dll
|
If the following pieces of code execute in the order in which I have put them, can I be sure that thread 1 is awoken first by thread 3, later followed by thread 2?
```
main:
sem_init(&x,0,0);
thread 1:
sem_wait(&x);
thread 2:
sem_wait(&x);
thread 3:
sem_post(&x);
```
|
There is no reason to make such an assumption. It depends on when thread 1 and thread 2 are invoquing sem_wait(), i.e., on what they do before and how the scheduler gives them CPU for running. If you want that thread 1 be awoken before thread 2, you need another semaphore:
```
main:
sem_init(&x,0,0);
sem_init(&y,0,0);
thread 1:
sem_wait(&x);
sem_post(&y);
thread 2:
sem_wait(&y);
thread 3:
sem_post(&x);
```
|
I have executed a process using CreateProcess, but I want to fetch or dump the memory area allocated to the process, preferably in real time. Unfortunately I do not know how to recieve the pointer to the memory are after creating the process. I've been searching around, but I have not found any useful answers so far.
If anyone could help me out, I'd be very grateful. Language does not really matter, anything will do. (However, preferably C/C++/Delphi etc.)
|
TryVirtualQueryEx()to see what memory pages are used, andReadProcessMemory()to read them.
|
In the following code, I get a warning that there is an implicit declaration of function getpgid. I know its only a warning, but its for a class and the professor wants us to treat warnings as errors. So, help please.
I have included the appropriate header file as well so I have no idea whats wrong:
```
#include <unistd.h>
pid_t pid, pgid;
if ((pgid = getpgid(pid)) < 0) {
app_error("Failure to get process group ID");
}
```
|
From theman page:
Feature Test Macro Requirements for glibc (seefeature_test_macros(7)):getpgid():
_XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
|| /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L
|
I have a simple C/CPP process running on a linux system. This is a.out.
Another process is capable to start a.out inside its code. This is b.out.
What code do I need inside a.out to understand that it is executed from the command line?
Eg ./a.out
Is there a way a process to know if it started from the cmd or started from another process?
|
You can't find out in general whether a program was started "from the command line" (by a user's explicit command), but you can find out whether its standard input and output are talking to a terminal/command window:
```
#include <unistd.h>
isatty(fileno(stdin))
```
andstdoutreturn whether standard input/standard output are terminals.
If you need to know what process starting your program, use thegetppidsystem call to get the parent's process ID (ppid), then read the pseudo-file/proc/ppid/cmdline.
|
I would like to enable tabbing for my application. And so far it seems I could use a tab control. The problem with it is, though, that it creates a border around the client area. What I want, is more like a FireFox tab control, that only takes up a row in the application and doesn't create any frames around client area.
Does anyone know if it is possible with the default control?
I'm using MFC, but that shouldn't change things much I hope.
|
I'm pretty sure the tab control consists of two parts - the tab headers and the tab page. So you should be able to use the tab header only. It will take more work, but I think you can get what you want.
Look at CTabCtrl and CHeaderCtrl - will those do it? I've never customized them, but it seems possible.
|
I have multiple threads, and I want each thread to wait for every others to complete at certain point in the code before proceeding as following:
```
void *run() {
for (i=0;i<1000;i++){
do_1st();
// sync() all stop here wait for all then resume
do_2nd();
}
}
```
I tried to use pthread_cond_wait.. but It seems very complicated.
Is there any easy wait to do this ?
Thank you
|
You can use apthread_barrier, initialize it before you start your threads, and set thecountto the no. of threads that's running your loop. e.g. if you have 8 threads:
```
pthread_barrier_init(&my_barrier,NULL,8);
```
The thread loop now becomes
```
void *run() {
for (i=0;i<1000;i++){
do_1st();
pthread_barrier_wait(&my_barrier);
do_2nd();
}
}
```
|
there is someone that know if exist a XSD code generator for C source code?
I have a lot of xsd files and I need to generate C struct and relative function fromXml and toXml.
Thanks.
|
For C++ generation there ishttp://sourceforge.net/projects/xxsd2code/
|
This post is edited and the original post here is asking the implementation of _malloc_r which is not a good move to use.
My question now is there any other malloc implementation or alternative function for malloc and free functions?
Please advice.
Many thanks.
|
Give up on trying to have a reentrantmalloc. It's a bad idea. If you really need to allocate memory from signal handlers, usemmap, but even that is a bad design.
|
Is the address returned by malloc a virtual address or is it the actual physical address where the memory is allocated?
Edit:
I read somewhere "In some implementations, calling free() releases the memory back to the system and in others it is released back to the process". Does "releasing back to the system" imply that the memory is the actual physical memory and "releasing back to the process" mean it is virtual memory?
|
It's an address valid in the current process. Whether it's virtual address or physical address depends on the underlying platform.
|
I am using C programming language in Linux platform and my question is how can I know how much I allocated in heap memory and other useful information such as peak usage in the heap memory. Is there a standard C function for this implementation?
Please advice.
Many thanks.
|
Since you're working on Linux, I am assuming you're using the GNU C Compiler. A little searching on Google revealed these websites...
GNU malloc statistics
Summary of malloc related functions
...that give information about the heap stats, which hopefully should contain the data you're looking for.
Good luck!
|
After reading a series of man pages and searching through google, I decided to post this question to the bright folks of stack overflow.
I'm working on a basic Unix Shell and one of the requirements is that I have to implement a command to echo out the shell's pid in base 10 ASCII... Before I read this requirement, I had assumed that process id's were already base 10 numbers. Does anyone know if this is true?
|
Technically speaking, the numbers that are returned bygetpid()are in base two. :-)
Seriously speaking, the requirement probably just means that the number should be displayed as a decimal number as opposed to, for example, a hexadecimal number. I would ask for clarification of that requirement though, since you had to ask.
|
Have a problem with fscanf() - it does not skip to the next word after reading 10 characters from the file
```
while(fscanf(TEXT_FILE,"%10s", str) != EOF) // reads up to 10 char into str
```
If it find the word that is greater than 10 characters, it will read 10 characters, store them into str, continue in the same word reading up to 10 characters.
How would I specify to read up to 10 char and skip to the next word ?Is there an alternative ?
Thanks !
|
You're probably better off usingfgets()andstrtok(), or writing a little loop aroundfgetc()to do what you want.fscanf()is flexible, but doesn't solve every problem.
|
I understand that the fastest and the most lightweight binary at windows generate only msvc compiler
Express edition of msvc is freehttp://www.microsoft.com/express/windows/
but how to use cl.exe instead of g++.exe?
is it possible in common by using GNU make variables produce makefiles which will works with cl.exe and g++?
for examplehttp://msdn.microsoft.com/en-us/library/19z1t1wy(v=VS.80).aspx
```
export CC = path/to/cl.exe
export COMPILE_WITHOUT_LINKING = /c
export OBJECT_FILE = /Fo
```
or is conception of cl and g++ very different?
|
Of course you can.cl.exeis just another command line tool. However, the two compilers differ in more advanced usage, so it might be difficult to usecl.exeas a drop-in replacement forg++.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Why is sizeof an operator?
Why issizeofsupposed to be anoperatorin C, & not afunction?
Its usage seems similar to that of a function call, as insizeof(int).
Is it supposed to be some kind of a pseudo-function?
|
Because it's not a function; it's not possible to write a function that can take a type as an argument and return its size! Note also thatsizeofis implemented at compile-time, and that the parentheses aren't necessary if you're using it on a variable.
|
I have a .bin file that contains records in CSV format what I want to do is assign each record in the bin file a sequence number. So the first record in the bin file would be assigned 0 and so on. These will be placed into a bianry index file such as (username, seq #).
If I have the bin file already created with records in it, how do I go through the bin file and index each record? Thanks for any help!
|
You would read lines from file A, and write lines to file B. Keep a count of each line you read and use that to generate the sequence number column when writing to file B.
To be honest, I would probably use Excel or a spreadsheet app if the file is already in CSV format
|
How does one begin writing drivers for Windows? Is there some sort of official DDK "Hello World" example out there?
While I'm sure it will be way above my head at first, eventually I would like to create a simple MIDI driver, much like theMaple Virtual MIDI Cablewhere the MIDI messages come from a user application rather than a physical device.
(The trouble with using the off-the-shelf MIDI loopback drivers is that the existence of an input and output end is often confusing for the user. My application generates MIDI output that gets sent to the MIDI input of other programs, so if I could create a fake driver that connects to my program rather than hardware, it would eliminate this confusion.)
Thank you for your time.
|
You could take a look at my virtualMIDI-driver:
www.tobias-erichsen.de/virtualMIDI.html
This one does exactly what your are looking for.
Tobias
|
I'm working on broadcast, and I'm failing pretty badly at even getting the thing to work. I know I have to do the setsockopt() call, but what is needed before that to ensure that the broadcast will go to every box on the network? I vaguely remember something about complementing the network address or something like that. I appreciate the help.
|
You don't need to use setsockopt(). A UDP packet sent to the special address 255.255.255.255 will be sent to all addresses on the local network.
If the network you want to broadcast to is not local you need to use the broadcast address of that network (as per ivymike's comment), which by convention is normally (but not always) the last IP in the subnet.
Bear in mind that broadcast addresses are used in a number of DOS attacks and are likely to be filtered.
|
var1 must hold a string whether it is empty or not or my program will segfault. But gcc complains that the empty string literal is constant while var1 is not. The following is an example of what I am talking about.
How can I fix this ?
warning: assignment discards qualifiers from pointer target type
```
char *var1 = NULL;
if(var1 == NULL)
{
var1 = malloc(strlen(var2) + 1);
strcpy(var1, var2);
}else{
var1 = ""; // warning points here
}
```
EDIT:
String literals are not modifiable so I use this flag to warn me:
-Wwrite-strings
|
To assign a empty string, do something like this:
```
var1 = malloc(1); /* 1 byte */
var1[0] = '\0';
```
|
I want to open port 5555 on my machine using UPnP to the world. Could you please provide me with such Java sample for any sutable Opensource library. I need A CODE SAMPLE like one I can give you for C# usingthis lib
```
using TCMPortMapper;
private void Form1_Load()
{
PortMapper.SharedInstance.Start();
PortMapping pm = new PortMapping(localPort, publicPort,
PortMappingTransportProtocol.TCP);
PortMapper.SharedInstance.AddPortMapping(pm);
}
private void Form1_FormClosing()
{
PortMapper.SharedInstance.StopBlocking();
}
```
|
Have you tried googling for "java upnp library"?
My first hit was oneUPNPLibthat looks reasonable.sample for UPNP mappingwith same.
there are also others:
weupnpcling
|
I ran into this question while typingman 2 open. It says that there are two kinds of open, one with two args, and one with three! last time i checked we could not overload functions in C. How did they do this? did they write in C++?
```
int open(const char * pathname, int flags);
int open(const char * pathname, int flags, mode_t mode);
```
|
No, they just used variadic function.
```
int open(const char * pathname, int flags, ...);
```
This makes the last argumentmodeoptional. The prototypes only show how the function should be used, not the actual interface.
Of course, unlike real overloading, the compiler cannot type-check themodeargument, so the user have to be extra careful to ensure only 2 or 3 arguments are passed, and the 3rd argument must be amode_t.
BTW, if you check theman 2 openfor BSD (including OS X) it shows thecorrect prototype as above.
|
I want to create a simple 3D editor program, and I don't like C++ windows programming. But I don't want to mess with managed code when using OpenGL, either. So, it is possible to create in native C++ a control which will host the OpenGL 3D drawing surface, with no other controls, and also with an interface (methods and properties), and use it as a control in a WinForms, or even better, WPF application?
|
It is also possible to use managed C++. I created a simple OpenGL control for WinForms which suits your requirements. You can find more info about ithere.
|
I'm writing a simple application in ANSI C. I am using GCC in a Unix environment.
I have the following sample application:
```
//main.c
#include "foo.h"
int main()
{
int result;
result = add(1,5);
return0;
}
```
Header:
```
//foo.h
#ifndef FOO_H_INCLUDED
#define FF_H_INCLUDED
int add(int a, int b);
#endif
```
Implementation:
```
//foo.c
int add(int a, int b)
{
return a+b;
}
```
I am compiling my program with the following command:
```
cc main.c -o main.o
```
The compiler complains that 'reference toaddis undefined'. Is this a linking problem? How do properly make use of my header?
Thanks!
|
You need to compile both your source files together:
```
cc main.c foo.c -o main
```
Also, in this case,-oproduces an executable, so calling itmain.ocan be misleading.
Yet another tidbit, though unrelated to the question: the#ifndefand#defineinfoo.hdon't match.
|
Why is it that I'm finding the size of int and long int are shown to be 4 bytes? Is it that the int is by default long int?
|
```
sizeof(short) <= sizeof(int) <= sizeof(long)
```
That's all you can count on. The rest is completely up to the implementation. In the olden days of DOS, 16 bit compilers usually has sizeof(int) == sizeof(short) == 2. On 32 bit systems, sizeof(int) is usually equal to sizeof(long) == 4. As a rule of thumb,intis the type the processor can work with the fastest. No rule without exceptions...
EDIT: Removed the second rule,sizeof(short) < sizeof(long), which is NOT part of the C standard. On some platforms,sizeof(short)may actually be equal tosizeof(long).
|
Not sure if it is a duplicate. Given a data structure having firstNintegers and nextNchars.A = i1 i2 i3 ... iN c1 c2 c3 ... cN. I need an in-place algorithm to rearrange the elements asA = i1 c1 i2 c2 ... iN cN.
|
Your problem is equivalent to transposing a 2xN matrix in-place. You can read the theory here:http://en.wikipedia.org/wiki/In-place_matrix_transposition
Maybe in the special case of 2xN matrix a simpler algorithm exists, however I can't think of any. The general idea is to follow the cycles of the permutation.
|
I declared a Normal Structure In C:
```
typedef struct arr_struct{
int* original;
int size;
int first[size/2];
int second[size-(size/2)];
};
```
when compile it gives me:
test.c:11: error: ‘size’ undeclared here (not in a function)
any explanation?
|
You can't define arrays based on a variable size. The size has to be known at compile time. You'll need to makefirstandsecondpointers and dynamically allocate them oncesizeis known.
|
Can local message-based sockets transfer messages up to the SO_SNDBUF/SO_RCVBUF limits, or where can the so-called 'fixed maximum length' be determined for a descriptor created withsocket(PF_UNIX, SOCK_SEQPACKET, 0)orsocket(PF_UNIX, SOCK_DGRAM, 0)?
|
fromman unix
The SO_SNDBUF socket option does have an effect for Unix domain sock‐
ets, but the SO_RCVBUF option does not. For datagram sockets, the
SO_SNDBUF value imposes an upper limit on the size of outgoing data‐
grams. This limit is calculated as the doubled (see socket(7)) option
value less 32 bytes used for overhead.
|
I have C program I compile withmingwon Windows. It works fine but requiresMSVCRT.DLL. I want to link that statically (like I can do in Visual Studio). Is this possible?
I tried-staticflag togccand it didn't make any change.
What about C++ program using also standard C++ library?
|
I believe that MinGW doesn't use the static runtime library for copyright reasons.
You can maybe try to use newlib (http://sourceware.org/newlib/) to create an executable that doesn't link tomsvcrt.dll
|
Should I put the includes in the header file or the source file? If the header file contains the include statements, then if I include that header file in my source, then will my source file have all of the included files that were in my header? Or should I just include them in my source file only?
|
Only put includes in a header if the header itself needs them.
Examples:
Your function returns typesize_t. Then#include <stddef.h>in theheaderfile.Your function usesstrlen. Then#include <string.h>in thesourcefile.
|
I have a program like this
```
int main(){
char c;
int i; /* counter */
double d;
return 0;
}
```
if I want to comment out char, int and double, and just have return uncommented, can I do it? the comment that's already there stops the comment..
Is there an easy/fast way to comment that out?
|
```
int main(){
#if 0
char c;
int i; /* counter */
double d;
#endif
return 0;
}
```
Not strictly a comment, but the effect is what you want and it's easy to revert.
This also scales well to larger code blocks, especially if you have an editor that can match the start and end of the#if..#endif.
|
Seems all compilers can deal with both c and c++,like gcc ,msvc...
Is it because these 2 languages are exactly very much alike?
|
Actually, GCC (GNU Compiler Collection) has two different front-ends,gccandg++. To specify C++, you can also use a .cpp (or a few others) extension, or-x c++, when executinggcc. However, this requires extra options (like linking in the C++ standard library).
cl, Microsoft's C++ compiler, does not support modern C. However, it will compile C source files as a variant of C89, and you can specify this explicitly with/TC.
For both, you are correct that there's a lot of shared code, regardless of which front-end is used (GCC also has many more). However, the languages do have significant differences, which are discussed elsewhere (this questionamong others).
|
What is the correct way to work out how many bytes an int is? and how do I write an int to a file descriptor?
Here is a mock code sample which might make clear what I am trying to achieve:
```
char *message = "test message";
int length = strlen(message);
int fd = open(file, O_CREAT|O_RDWR);
write(fd, length??, ??); // <--- what goes here
write(fd, message, length);
```
I dont care about platform independence and byte order, just that it can compile on as many platforms as possible.
|
sizeof(length)goes in the field.
It is preferable over usingsizeof(int)in case you ever change the type oflengthin the future.
sizeofexpresses the, well, size of a data type in multiples ofsizeof(char), which is always 1.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.