question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
In C, I know I can make an array like this
```
int myarray[5] = {a,b,c,d,e};
```
However, imagine the array was already initialised like
```
int myarray[5];
```
and then at some point afterwards, I wanted to set/change all the values without going
```
myarray[0] = a;
myarray[1] = b;
myarray[2] = c;
myarray[3] = d;
myarray[4] = e;
```
but rather, something more like
```
myarray = {a,b,c,d,e};
```
The reason why I ask this is because if I declare my array on the heap, I will initialise the array like:
```
int* myarray = malloc(5*sizeof(int));
```
Then I would like to be able to enter in all the values in one line (mostly to make my code look cleaner)
|
```
memcpy(myarray, (int [5]){a,b,c,d,e}, 5*sizeof(int));
```
|
I am trying to debug a file that has had its symbols stripped. I have headers for the file, with offsets for each function, and was wondering if it was possible to create a DSYM file using these headers. I cannot set breakpoints on the offsets because the file is a plugin, so the functions are mapped to a different location in memory.
|
Simply put, it is not.
|
Sorry if my question is trivial.
I am using select() in my server program to look for new connections as well as for data on exisitng connections. However, when I get data on one connection/socket, my program reads the data and store it, in an array. Here, The server will not reply back to client [ though client is in recv() mode ] . Now, when server goes back to select() call, it is getting stuck there. Not sure why. My intention is that, server should come out of select [ if there is no data ]. I kept timeout on the select() as well.
Any suggestions in this regards, would be of great help.
|
I got it resolved. Seems the timeout was not working fine earlier. I have fixed it. It is working fine now. Thanks to all. If i have any doubts, will ping back you all.
|
```
struct{
Vector3* centers;
float* radii;
float* colors;
unsigned int size;
}Spheres;
```
versus
```
struct Sphere{
Vector3 center;
float radius;
float color;
};
struct{
struct Sphere* spheres;
unsigned int size;
}Spheres;
```
usage example
```
void spheres_process(){
int i;
for(i = 0; i < Spheres.size; ++i){
// do something with this sphere
}
}
```
I'm thinking that the second case has better spatial locality since all data is interleaved and should be loaded into the cache at the same time. In both cases I will be processing all spheres at the same time. Any input?
|
May I suggest trying both with your dataset under cachegrind or some other cache profiler? That might be more effective than theorising on spatial locality etc. Depending on the access patterns of your code you might come up with some surprising results.
|
Say we have a function that does not interfere with other data and runs independently. However, I heard a method to do it is to make the whole app in to a section and that alone a section. Can it be done instead with the main app spawning it into a thread and ensuring that the main app will not wait for it to end?
e.g. pseudo code:
```
int main (void) {
<do stuff on thread 0>
<do stuff on thread 0>
<spawn independent function on thread 1 with no waiting>
<do stuff on thread 0>
<do stuff on thread 0>
}
```
EDIT: Can it be done with another philosophy completely? (no OpenMP)
|
This isn't OpenMP's prime goal: it was built for parallel processing, not concurrent programming. Check your local thread library and look for something called "daemon threads", "detached threads" or similar.
|
Say we have a serial application that stops normally for a while 'till a completely independent function is computed. How can one use OpenMP to spawn that function only to a thread and only printf its result when it ends? [without stopping the main application]
EDIT: Can it be done if the independent function is run inside the main app?
|
You can useparallel sections.
```
#pragma omp parallel sections
{
#pragma omp section
YourMainApp ();
#pragma omp section
YourIndepFunction ();
}
```
|
I am writing an application in C which used a global variable (a logfile structure). In my application I am loading shared libraries dynamically at runtime and I want to use a global variable pointing at the the same logfile structure to do logging in the shared library.
This doesn't seem to be possible in the easy approach:
declaring the global variable as extern will not work because dlopen() sais that the global variable is an undefined symboldefining the global variable again will work but the "new" variable will not be the same as the "original" one in the executable
Any hint how to fix this would be great.
Thank you!
|
You need to compile your main application with-rdynamicflag (eg:gcc -g -rdynamic -o main main.c, and to declare the global variable in your dynamic library withextern.
|
I am working with graphics in C. I find thinking about the pixel locations terrible and I am in need of a tool where I can draw images and it gives me the pixel location of that point. Please guide me.
|
Paint that comes with Windows provides pixel locations in its status bar.
|
How to find out, how much RAM and CPU "eats" certain process in Linux? And how to find out all runned processes (including daemons and system ones)? =)
UPD: using C language
|
Usetoporps.
For example,ps auxwill list all processes along with their owner, state, memory used, etc.
EDIT:To do that with C under Linux, you need to read the process files in theprocfilesystem. For instance,/proc/1/statuscontains information about yourinitprocess (which always hasPID 1):
```
char buf[512];
unsigned long vmsize;
const char *token = "VmSize:";
FILE *status = fopen("/proc/1/status", "r");
if (status != NULL) {
while (fgets(buf, sizeof(buf), status)) {
if (strncmp(buf, token, strlen(token)) == 0) {
sscanf(buf, "%*s %lu", &vmsize);
printf("The INIT process' VM size is %lu kilobytes.\n", vmsize);
break;
}
}
fclose(status);
}
```
|
I noticed that there was (at least on Mac OS X) both a<string.h>header and a<strings.h>header.man 3 stringreveals that they contain different functions. Is there any reason for this?
|
strings.h comes from the BSD branch in the unix evolution. Its content has been standardized by POSIX, but most of it is marked as legacy and can be easily replaced with other functions:
```
int bcmp(const void *, const void *, size_t); /* LEGACY, see memcmp */
void bcopy(const void *, void *, size_t); /* LEGACY, see memcpy, memmove */
void bzero(void *, size_t); /* LEGACY, see memset */
int ffs(int);
char *index(const char *, int); /* LEGACY, see strchr */
char *rindex(const char *, int); /* LEGACY, see strrchr */
int strcasecmp(const char *, const char *);
int strncasecmp(const char *, const char *, size_t);
```
|
How to print the environment variables in a C program usingenviron.
```
extern char **environ
```
|
```
#include <unistd.h>
#include <stdio.h>
extern char **environ;
//...
int i = 0;
while(environ[i]) {
printf("%s\n", environ[i++]); // prints in form of "variable=value"
}
```
|
Having a problem here with creating a child window with c++ and win32 api.
If i check the getLastError function its returning "87" but i dont know what that means.
For what i know my code does not contain errors, can someone take a look at my code and help me figure out whats wrong with it.
(This is in the WinProc WM_CREATE section.)
```
HWND hChildWindow = CreateWindowEx(WS_EX_CLIENTEDGE,0,NULL,WS_OVERLAPPEDWINDOW|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,hwnd,0,GetModuleHandle(0),NULL);
if(!hChildWindow)
{
char text[256];
int errormsg = (int)GetLastError();
sprintf(text,"Error# %i",errormsg);
MessageBox(0,text,"Error",MB_OK|MB_ICONEXCLAMATION);
return false;
}
```
|
87 = Invalid Parameter- be aware that you can useFormatMessageto get a string message from an error code.
|
Common programs like gcc, rm, cp etc. seem to follow a pattern in reporting their errors like this:
program: error
For instance:
```
$ gcc
gcc: no input files
```
Is there some standard function or macro I should call from within my own C programs to report errors in a standard fashion?
|
There are no macros (that I know of). But, here's the relevantstandardfor formatting error output.
|
It seems to have modified the original string that I wanted to split specifying tokens.
how does it return back a substring if it can't copy from memory?
I'm also looking for an alternative that accepts aconst char*Or doesn't modify the orignal string.
Or is it safe to justconst_castthe string to remove the const property and let it be handled bystrtok_s(char*, const char*, char**).?
|
strtok_set aldomodify the strings passed in, so no, you can't pass in aconst_castd constant string. What it does is if it finds a delimiter, it replaces that delimiter with a NUL terminator to separate the string into two pieces. It then returns a pointer to the first part, which is now the desired null-terminated token.
|
Hi I wanted to know how to use MATLAB as an external solver from a C program. Specifically in my code I wish
to solve several linear systems of the form Ax=b.
I have heard that to go the other way namely Calling C functions in a MATLAB routine one uses MEX files.But I am not really sure how to use Mex files either.
Thank you
|
Actually, MEX files allow you to include C code in Matlab programs, for example if you want to use external C libraries in Matlab.
What you want to do is use the Matlab Engine:http://www.mathworks.com/help/techdoc/matlab_external/f29148.html
As an alternative, you could use linear algebra libraries that are written purely in C, such as LAPACK and BLAS. ( www.netlib.org )
|
Consider this simple code:
```
int myvar = 0;
int main() {
if (fork()>0) {
myvar++;
} else {
// father do nothing
}
}
```
When child increments myvar, is the value shared with the father (like pthread)?
|
No and yes.
No, they are not shared in any way which is visible to the programmer; the processes can modify their own copies of the variables independently and they will change without any noticable effect on the other process(es) which are fork() parents, siblings or descendents.
But yes, the OS actually does share the pages initially, because fork implements copy-on-write which means that provided none of the processes modifies the pages, they are shared. This is, however, an optimisation which can be ignored.
If you wanted to have shared variables, put them in an anonymous shared mapping (see mmap()) in which case they really will get shared, with all the caveats which come with that.
|
I am trying to understand a C code. In some part there is:
```
for ...{
if condition{
a=1;
break;
}
}
```
which in a later version is changed to:
```
for ...{
if condition{
goto done;
}
}
done: a=1;
```
From my point of view, both vesions should give the same result, but it does not happen. Do you know why?
CORRECTION: The fix is:
```
for ...{
if condition{
goto done;
}
}
goto notdone;
done:
ok=0;
notdone:
```
|
It depends on whether the for-loop has any other exit conditions.
In the first example,a=1only happens for that specific exit condition in the if-statement.In the second example,a=1happens inallscenarios that exit the loop. It can only be circumvented using areturnstatement, or anothergotostatement.
|
I am trying to listen on two devices with libpcap but I still cant find out how to do the trick. I tried to set device to "any" but it isnt working. I am trying to write dhcp relay agent so i need to listen on eth0 and eth1.
I tried to create two pcap_loops, each with different device and handler, but only first pcap_loop works, second one is ignored.
Is there any way how to do this or should I leave libpcap and try to do it with raw sockets?
|
You'll need to run your pcap_loop() in separate threads, one for each interface, we do that, and it works.
Some parts of libpcap, isn't thread safe though, atleast pcap_setfilter(), so provide your own locking around that.
If you do no want to use threads, you'll have to provide an event loop yourself, where you monitor the file descriptors of each device with select/poll or similar. You can get the file descriptor for a device handle with pcap_get_selectable_fd().
|
A friend of mine has told me that on x86 architecture DMA controller can't transfer between two different RAM locations. It can only transfer between RAM and peripheral (such as PCI bus).
Is this true?
Because AFAIK DMA controllershouldbe able between arbitrary devices that sit on BUS and have an address. In particular I see no problem if both source and destionation addresses belong to the same physical device.
|
ISA (remember? ;-) DMA chips certainly have aFetch-and-Deposittransfer type.
However, from theMASM32 forums:
Hi,Checking in "The Undocumented PC",
he says memory to memory DMA is
possible. He then goes on to say that
there can be problems, limitations,
and that the CPU can do the copy
faster than the DMA hardware anyway
(MOVSD on 386+).So it seems to be a yes you can,
but who cares, kind of thing.Regards,Steve N.
|
I'm a real beginner and I'm programming in C++ using Visual Studio.
I've a simple cpp code that recalls some functions written in a .c and .h file. I included that file by means of #include directive and the IDE "sees" the function.
When I compile, I get this
Error 7 error LNK2019: unresolved external symbol _IMUsendAccelToFIFO referenced in function _main D:\Cprojects\Pencil\Pencil\Pencil.obj Pencil
What am I missing here?
Thank you all!
|
It is a linker error, not a compiler error. The compiler is happy, it saw the declaration of function in the .h file. The linker isn't, it cannot find thedefinitionof the function.
Add the .c file to your project.
|
I have a file called "main.c". Whats the simplest Makefile I can have to compile this file into an executable that I can run like./blah?
|
```
all:
gcc -o blah main.c
```
You don't need makefile here, simple shell script is OK.
|
I am doing a project on Windows and the "winsock2.h" file is causing issues during compilation (I have an underlying queue library that has function like "send", "receive" etc and it is complaining about the "winsock2.h" also having a "send" function).
I am just including "windows.h", so is there a way I canEXCLUDEthe inclusion of "winsock2.h" so that my application can compile?
Thanks for the help ;-)
Lynton
|
If you#define WIN32_LEAN_AND_MEANbefore including windows.h, you get a lot fewer headers automatically pulled in.
Though on my system, windows.h includes winsock.h, not winsock2.h, so you may have to double-check it's actually due to including windows.h.
|
What are the advantages and disadvantages of each? If I'm implementing a hash table where fast lookup time is crucial, it seems like I should use immediate, because that would occur only on insertions and deletions, whereas incremental would slow down lookup as well. Does that make sense?
I'm doing this in C, if it matters.
|
Unless you have tight time constraints on every hash table operation, resizing immediately probably makes the most sense. As you say, it will improve lookup times over incremental resizing, and just generally amortize the cost of insertion and deletion. Incremental resizing is more applicable to cases wherealloperations have to proceed in a fixed and strictly bounded amount of time.
|
Can anyone please help me? I need to remove the first character from achar *in C.
For example,char * contentscontains a'\n'character as the first character in the array. I need to detect and eliminate this character, modifying the original variable after its been "sanitized".
Can anyone help me with the code? I'm completely new to C, and just can't seem to figure it out.
|
```
if (contents[0] == '\n')
memmove(contents, contents+1, strlen(contents));
```
Or, if the pointer can be modified:
```
if (contents[0] == '\n') contents++;
```
|
I was wondering if there were any tools that allow me to see roughly how long it takes to run through a function or program. Such as it would tell you that your typical merge sort alogrithim ran ~nlogn or took x time per n or to complete. Stuff like that.
It seems like Visual Studio Ultimate and Team has something that does stuff like that for you but I don't have that so looking for alternatives.
|
You mean a performance profilerWhat's the best free C++ profiler for Windows?
|
I have been looking through the Lua source code, and I think that is how it works.
|
Lua and C use a stack to exchange arguments. Many script languages use this way to communicate with C program.
|
In C, I know I can make an array like this
```
int myarray[5] = {a,b,c,d,e};
```
However, imagine the array was already initialised like
```
int myarray[5];
```
and then at some point afterwards, I wanted to set/change all the values without going
```
myarray[0] = a;
myarray[1] = b;
myarray[2] = c;
myarray[3] = d;
myarray[4] = e;
```
but rather, something more like
```
myarray = {a,b,c,d,e};
```
The reason why I ask this is because if I declare my array on the heap, I will initialise the array like:
```
int* myarray = malloc(5*sizeof(int));
```
Then I would like to be able to enter in all the values in one line (mostly to make my code look cleaner)
|
```
memcpy(myarray, (int [5]){a,b,c,d,e}, 5*sizeof(int));
```
|
I am trying to debug a file that has had its symbols stripped. I have headers for the file, with offsets for each function, and was wondering if it was possible to create a DSYM file using these headers. I cannot set breakpoints on the offsets because the file is a plugin, so the functions are mapped to a different location in memory.
|
Simply put, it is not.
|
Sorry if my question is trivial.
I am using select() in my server program to look for new connections as well as for data on exisitng connections. However, when I get data on one connection/socket, my program reads the data and store it, in an array. Here, The server will not reply back to client [ though client is in recv() mode ] . Now, when server goes back to select() call, it is getting stuck there. Not sure why. My intention is that, server should come out of select [ if there is no data ]. I kept timeout on the select() as well.
Any suggestions in this regards, would be of great help.
|
I got it resolved. Seems the timeout was not working fine earlier. I have fixed it. It is working fine now. Thanks to all. If i have any doubts, will ping back you all.
|
```
struct{
Vector3* centers;
float* radii;
float* colors;
unsigned int size;
}Spheres;
```
versus
```
struct Sphere{
Vector3 center;
float radius;
float color;
};
struct{
struct Sphere* spheres;
unsigned int size;
}Spheres;
```
usage example
```
void spheres_process(){
int i;
for(i = 0; i < Spheres.size; ++i){
// do something with this sphere
}
}
```
I'm thinking that the second case has better spatial locality since all data is interleaved and should be loaded into the cache at the same time. In both cases I will be processing all spheres at the same time. Any input?
|
May I suggest trying both with your dataset under cachegrind or some other cache profiler? That might be more effective than theorising on spatial locality etc. Depending on the access patterns of your code you might come up with some surprising results.
|
Say we have a function that does not interfere with other data and runs independently. However, I heard a method to do it is to make the whole app in to a section and that alone a section. Can it be done instead with the main app spawning it into a thread and ensuring that the main app will not wait for it to end?
e.g. pseudo code:
```
int main (void) {
<do stuff on thread 0>
<do stuff on thread 0>
<spawn independent function on thread 1 with no waiting>
<do stuff on thread 0>
<do stuff on thread 0>
}
```
EDIT: Can it be done with another philosophy completely? (no OpenMP)
|
This isn't OpenMP's prime goal: it was built for parallel processing, not concurrent programming. Check your local thread library and look for something called "daemon threads", "detached threads" or similar.
|
Say we have a serial application that stops normally for a while 'till a completely independent function is computed. How can one use OpenMP to spawn that function only to a thread and only printf its result when it ends? [without stopping the main application]
EDIT: Can it be done if the independent function is run inside the main app?
|
You can useparallel sections.
```
#pragma omp parallel sections
{
#pragma omp section
YourMainApp ();
#pragma omp section
YourIndepFunction ();
}
```
|
I am writing an application in C which used a global variable (a logfile structure). In my application I am loading shared libraries dynamically at runtime and I want to use a global variable pointing at the the same logfile structure to do logging in the shared library.
This doesn't seem to be possible in the easy approach:
declaring the global variable as extern will not work because dlopen() sais that the global variable is an undefined symboldefining the global variable again will work but the "new" variable will not be the same as the "original" one in the executable
Any hint how to fix this would be great.
Thank you!
|
You need to compile your main application with-rdynamicflag (eg:gcc -g -rdynamic -o main main.c, and to declare the global variable in your dynamic library withextern.
|
I am working with graphics in C. I find thinking about the pixel locations terrible and I am in need of a tool where I can draw images and it gives me the pixel location of that point. Please guide me.
|
Paint that comes with Windows provides pixel locations in its status bar.
|
How to find out, how much RAM and CPU "eats" certain process in Linux? And how to find out all runned processes (including daemons and system ones)? =)
UPD: using C language
|
Usetoporps.
For example,ps auxwill list all processes along with their owner, state, memory used, etc.
EDIT:To do that with C under Linux, you need to read the process files in theprocfilesystem. For instance,/proc/1/statuscontains information about yourinitprocess (which always hasPID 1):
```
char buf[512];
unsigned long vmsize;
const char *token = "VmSize:";
FILE *status = fopen("/proc/1/status", "r");
if (status != NULL) {
while (fgets(buf, sizeof(buf), status)) {
if (strncmp(buf, token, strlen(token)) == 0) {
sscanf(buf, "%*s %lu", &vmsize);
printf("The INIT process' VM size is %lu kilobytes.\n", vmsize);
break;
}
}
fclose(status);
}
```
|
I noticed that there was (at least on Mac OS X) both a<string.h>header and a<strings.h>header.man 3 stringreveals that they contain different functions. Is there any reason for this?
|
strings.h comes from the BSD branch in the unix evolution. Its content has been standardized by POSIX, but most of it is marked as legacy and can be easily replaced with other functions:
```
int bcmp(const void *, const void *, size_t); /* LEGACY, see memcmp */
void bcopy(const void *, void *, size_t); /* LEGACY, see memcpy, memmove */
void bzero(void *, size_t); /* LEGACY, see memset */
int ffs(int);
char *index(const char *, int); /* LEGACY, see strchr */
char *rindex(const char *, int); /* LEGACY, see strrchr */
int strcasecmp(const char *, const char *);
int strncasecmp(const char *, const char *, size_t);
```
|
How to print the environment variables in a C program usingenviron.
```
extern char **environ
```
|
```
#include <unistd.h>
#include <stdio.h>
extern char **environ;
//...
int i = 0;
while(environ[i]) {
printf("%s\n", environ[i++]); // prints in form of "variable=value"
}
```
|
Having a problem here with creating a child window with c++ and win32 api.
If i check the getLastError function its returning "87" but i dont know what that means.
For what i know my code does not contain errors, can someone take a look at my code and help me figure out whats wrong with it.
(This is in the WinProc WM_CREATE section.)
```
HWND hChildWindow = CreateWindowEx(WS_EX_CLIENTEDGE,0,NULL,WS_OVERLAPPEDWINDOW|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,hwnd,0,GetModuleHandle(0),NULL);
if(!hChildWindow)
{
char text[256];
int errormsg = (int)GetLastError();
sprintf(text,"Error# %i",errormsg);
MessageBox(0,text,"Error",MB_OK|MB_ICONEXCLAMATION);
return false;
}
```
|
87 = Invalid Parameter- be aware that you can useFormatMessageto get a string message from an error code.
|
Common programs like gcc, rm, cp etc. seem to follow a pattern in reporting their errors like this:
program: error
For instance:
```
$ gcc
gcc: no input files
```
Is there some standard function or macro I should call from within my own C programs to report errors in a standard fashion?
|
There are no macros (that I know of). But, here's the relevantstandardfor formatting error output.
|
It seems to have modified the original string that I wanted to split specifying tokens.
how does it return back a substring if it can't copy from memory?
I'm also looking for an alternative that accepts aconst char*Or doesn't modify the orignal string.
Or is it safe to justconst_castthe string to remove the const property and let it be handled bystrtok_s(char*, const char*, char**).?
|
strtok_set aldomodify the strings passed in, so no, you can't pass in aconst_castd constant string. What it does is if it finds a delimiter, it replaces that delimiter with a NUL terminator to separate the string into two pieces. It then returns a pointer to the first part, which is now the desired null-terminated token.
|
Hi I wanted to know how to use MATLAB as an external solver from a C program. Specifically in my code I wish
to solve several linear systems of the form Ax=b.
I have heard that to go the other way namely Calling C functions in a MATLAB routine one uses MEX files.But I am not really sure how to use Mex files either.
Thank you
|
Actually, MEX files allow you to include C code in Matlab programs, for example if you want to use external C libraries in Matlab.
What you want to do is use the Matlab Engine:http://www.mathworks.com/help/techdoc/matlab_external/f29148.html
As an alternative, you could use linear algebra libraries that are written purely in C, such as LAPACK and BLAS. ( www.netlib.org )
|
I saw this function in thelua.cfile calleddotty(). I have a feeling that it takes line-by-line input, is this correct?
|
That's correct, it's basically theREPL.
That function technically works on a chunk-by-chunk basis. Theloadlinefunction does the actual line-by-line input, until it gets a complete chunk to execute.
|
ulimit -s shows the defaultstacksizelimit.
Is there a startup defaultheapsize ?
|
no
in 32-bit Linux, every process see a continuous 4GB space. most of it isn't mapped to real RAM, but gets mapped on usage.
in 64-bit it's similar but much bigger.
|
I have a packet inside a packet a.k.a tunneling. So it's of the form [IP HEADER 1][IP HEADER 2][PAYLOAD]. After reading the first header(done by a library) I will get the packet with [ IP HEADER 2] at the INPUT chain of the iptables. I want to re-inject the packet to the starting of the iptables i.e. in the PREROUTING chain. Ultimate aim is to forward the packet to a remote host (that's why I want the packet to be in the PREROUTING chain). I have read something about the libipq but I am not really sure that it is the best way to do it.
|
Although there may be some add-on target to do this. My gut feeling is that you would use theMARKtarget to mark this packet then useiproute2to set up the routing of where you want it to go.
Something like:
```
iptables -t mangle -A INPUT -s 192.168.1.2 -j MARK --set-mark 0xAA
```
ip rule add fwmark 0xAA table Reroute_Tunnel
Then it's up to you to add and decide what theReroute_Tunneltable does
|
I am studying for an OS quiz and I did not understand what output
```
if(fork())
fork()
```
will produce. Can someone explain?
I didn't understand this line:
```
if(fork())
```
Edit:
What I meant with "output" is how many processes will be there if this code was executed.
Sorry I'm a bit dizzy after studying.
|
Here's a hint:if (fork())is just a short way of writingif (fork() != 0).
|
How do I get the output from the following:
```
lua_pushstring(L,"print(i)");
lua_call(L,0,0);
```
|
If you want to run arbitrary Lua code from C, what you need to use isluaL_dostring, as in this question:C & Lua: luaL_dostring return value
Edit: please note that Lua's defaultprintfunction will still print its output straight to the console. You will need to redirect stdout in some way (probably to a pipe) if you want to capture its output.
|
I am using Xcode (mac) and I want to import my own header file inside of a C project. How do I do this?
|
With your project open, go to theProjectmenu, chooseAdd to Project..., browse to the header file you want to add, on the next dialog click thecopy into destination group's folder(assuming the file is NOT within your project's path), then click theAddbutton. The file will now appear within your project.
|
In my programming project I want to parse command line attributes using flex/bison. My program is called like this:
```
./prog -a "(1, 2, 3)(4, 5)(6, 7, 8)" filename
```
Is it possible to parse this string using flex/bison without writing it to a file and parsing that file?
|
See this questionString input to flex lexer
|
I am aware thatfoo[bar]is equal to*(foo + bar), but what is*foo[bar]equal to, such as accessing*argv[2]? I am somewhat confused in understanding this, I assumed maybe something like*(*(foo) + bar)but am unsure..
I apologize if this is a simple answer.
|
*a[b]is equivalent to*(a[b])due to C and C++ precedence rules. so*a[b]is equivalent to**(a+b)
|
So I created simple Consol app: FFmpeg RTSP Video stream reader (using only general FFmpeg C API) But while ffmpeg reads from RTSP it shows lots of info. I did not asked for if... At least not all of it... So how can I filter what ffmpeg is outputing? I mean in all he talls user-developer there is only one important line something like:missing picture in acsess unitso how to put some filter mechanism for ffmpeg not to output all it wants and for me developer to catch the moment when message I want appeares? (In my project I write in C++ under visual studio using Boost libs)
|
Use av_log_set_callback, to set your function as callback:
```
static void avlog_cb(void *, int level, const char * szFmt, va_list varg) {
//do nothing...
}
av_log_set_callback(avlog_cb);
```
or, you may also use
```
av_log_set_level(AV_LOG_ERROR);
```
to print error messages only.
|
I'm working on a C project with Eclipse and MinGW. When running a debug build of this project, gdb always breaks on enteringmain(). I can see why this could be useful, but for my current project I don't want that to happen.
I've read that there is a command
```
(gdb) break main
```
which will accomplish the same behavior when running from the command line.
At the moment I do NOT have a .gdbinit file.
At the moment gdb doesn't stop on entering main when running from the command line, but it does when running from Eclipse.
How do I make GDB stop breaking on entering main by default within Eclipse?
|
Make sure you are in the c++ perspective, then go to menuRun->Debug Configurations. Make sure your application is chosen in the left pane, press theDebuggertab, and uncheckStop on startup at:checkbox.
EDIT: you can see a screen-shot here:Method/Function Breakpoints in Eclipse CDT
|
I want to build one network system which can make client communicate thought NAT? any suggestion ?
|
RFC 1701 can be implemented using ifconfig and route. You don't really need C code AFAIK. I do not know of open source to create what you specified.
The qnx site has an example:
```
http://www.qnx.com/developers/docs/6.4.0/neutrino/technotes/gre.html
```
A linux example:
```
http://tier.cs.berkeley.edu/drupal/howto/ip-tunnel-using-gre-on-linux
```
|
I am working on a university assignment, based largely around IPC and shared memory. The problem is, as a complete noob to C, I've been happily testing my app (which usesshmgetandshmatobviously) for hours. As you can probably guess, I've not been cleaning up after myself, and now I can't run my app, because (I assume)shmgetcant allocate anymore resources.
My question is: how can I get this resource back without restarting OSX, and is there a GUI tool or something I can use to monitor/manage this shared memory I am creating?
|
Perhaps a bit late, but there are cmdline tools available to do exactly this.
ipcs and ipcrm
take a look at their man pages.
|
I am writing a C app and I use malloc to create data on the heap. Now while the application is active, this data is always persistant, so I never "free" the Malloc data.
My question is: will this memory be automatically freed when the application terminates, or must I execute free() manually at the completion of my application?
|
This is implementation-defined. Strictly following the C standard, you shouldfreeeverything you'vemalloc'd before the application terminates.
Any modern general-purpose operating system, however, will clean up after you, so this is only relevant in some embedded, old-fashioned, or otherwise exotic environments.
As a point of style, do try tofreeevery allocated block. It gets you in the habit of writing clean code and preventing memory leaks.
|
Is it possible for a program written in C (or assembly) and is linked with c stdlib using gcc to print the address of its entry? (Since the _start symbol denotes the program entry actually i ask if its possible to print the address of that symbol from inside the main function without using parsing of ELF executable file.)?
|
I question why you need to do this, but have you tried usingdlsymfor your purposes?
|
Well, this is not actually a question..
I have just occasionally found out that there's an interesting way to declare local variables inside a switch/case block. Instead of using braces inside every case block, you can write:
```
switch (action) {
int res;
int value;
case ACTION_OPEN:
res = open(...);
...
break;
case ...
}
```
So, I just wonder what C/C++ compilers besides gcc support this construction? It looks like a common fall-through. Any comments on this construction are welcome!
|
The switch body is just a normal statement (in your case a compound statement, looking like{ ... }) which can contain any crap. Including case labels.
This switch philosophy is abused byDuffs device.
Many people don't realize that even something likeswitch(0) ;is a valid statement (instead of having a compound statement, it has a null statement as body), although quite useless.
|
I have a program I am writing for uni in C, and when my code reaches this line:
```
strcat("md5 ", "blah");
```
I am getting a EXC_BAD_ACCESS error, and my app crashes. As far as I can tell, there isn't anything wrong with it, so I thought a fresh pair of eyes might solve my problem. Any ideas?
|
You're trying to modify a constant string. The first argument ofstrcatis also the destination string and in your case it is a constant string. You should use something like:
```
char s[100];
strcpy(s, "md5 ");
strcat(s, "blah");
```
|
Let's say I open a file withopen(). Then Ifork()my program.
Will father and child now share the same offset for the file descriptor?
I mean if I do a write in my father, the offset will be changed in child too?
Or will the offsets be independent after thefork()?
|
Fromfork(2):
* The child inherits copies of the parent’s set of open file descrip-
tors. Each file descriptor in the child refers to the same open
file description (see open(2)) as the corresponding file descriptor
in the parent. This means that the two descriptors share open file
status flags, current file offset, and signal-driven I/O attributes
(see the description of F_SETOWN and F_SETSIG in fcntl(2)).
|
```
float jk = 7700; float ck = 8000; - if i do int jk; I get rim=0;
printf (asin(jk/10500)) = 1.57897 - for example
printf (asin(ck/9500)) = 0.87868 - for example
float rim;
rim= asin(jk/10500)+ asin(ck/9500);
printf("\n%f", rim) = nan
```
Why i get nan?
|
I don't believe your "for example". Because I don't believe in magic. If you have two valid floats both pretty small, then their sum is not a nan. So, my guess is this:
either|jk| > 10500or|ck| > 9500. So you make asin with an invalid ( > 1.0 or < -1.0) argument and thus get a nan.
Or you have made another error. Please post a compilable runnable example which will print NAN
|
Would anyone know any pointers to information about multicore programming in C? I apologize if the question has been asked before, after a "bona fide" search, I couldn't find it. I'd be happy to delete if someone points me to it.
|
C1Xis the unofficial name of the planned new standard for the C programming language.
Multithreading support (_Thread_local
storage-class specifier,
header including thread
creation/management functions, mutex,
condition variable and thread-specific
storage functionality, as well as the
_Atomic type qualifier and for uninterruptible
object access)
|
Many compilers seem to be keeping only 0 or 1 in bool values, but I'm not sure this will always work:
```
int a = 2;
bool b = a;
int c = 3 + b; // 4 or 5?
```
|
Yes:
In C++ (§4.5/4):
An rvalue of type bool can be
converted to an rvalue of type int,
with false becoming zero and true
becoming one.
In C, when a value is converted to_Bool, it becomes 0 or 1 (§6.3.1.2/1):
When any scalar value is converted to
_Bool, the result is 0 if the value compares equal to 0; otherwise, the
result is 1.
When converting toint, it's pretty straight-forward.intcan hold 0 and 1, so there's no change in value (§6.3.1.3).
|
I want to define a constant string containing non printable characters in C. For e.g - Let say I have a string
```
char str1[] ={0x01, 0x05, 0x0A, 0x15};
```
Now I want to define it like this
```
char *str2 = "<??>"
```
What should I write in place of<??>do define an string equivalent tostr1?
|
You can use"\x01\x05\x0a\x15"
|
in the spirit ofgraphics.stanford.edu/~seander/bithacks.htmlI need to solve the following problem:
```
int x;
int pow2; // always a positive power of 2
int sgn; // always either 0 or 1
// ...
// ...
if(sgn == 0)
x -= pow2;
else
x += pow2;
```
Of course I need to avoid the conditional. So far the best I came up with is
```
x -= (1|(~sgn+1))*pow2
```
but that involves a multiplication which I also would like to avoid. Thanks in advance.
EDIT: Thanks all,
```
x -= (pow2^-sgn) + sgn
```
seems to do the trick!
|
I would try
```
x -= (pow2 ^ (~sgn+1)) + sgn
```
or, as suggested by lijie in the comments
```
x -= (pow2 ^ -sgn) + sgn
```
Ifsgnis0,~sgn+1is also0, sopow2 ^ (~sgn+1) == pow2. Ifsgnis1,(~sgn+1)is0xFFFFFFFF, and(pow2 ^ (~sgn+1)) + sgn == -pow2.
|
I wanted to know whether there is a way to parallelize a"for loop"having data dependency problem usingOpenMP.
here is thefor loopwhich I like to parallelize
```
int k = 0;
int A[100][100];
for(i = 0; i < 100; i++) {
for(j = 0; j < 100; j++) {
A[i][j] = k;
k++;
}
}
```
Do anyone have a solution for this...
|
You don'treallyhave a data dependency problem there, becausekcan be computed fromiandj:
```
int A[100][100];
for(i = 0; i < 100; i++) {
for(j = 0; j < 100; j++) {
A[i][j] = i * 100 + j;
}
}
```
If you can give a more realistic example of what you're trying to do, we may be able to help you more.
|
I made 2 files which are different from the program above
one is temp1.h and another is temp2.c to understand how extern is used.
So here is temp1.h
```
#include<stdlib.h>
typedef struct node * bond;
extern int jk;
```
and temp2.c is
```
#include<stdio.h>
#include<temp1.h>
struct node {
int data;
};
int main ()
{
bond t1;
t1=(bond)malloc(sizeof(bond));
t1->data=23;
printf("the data is %d\n",t1->data);
jk=0;
printf("The variable jk = %d\n",jk);
}
```
and when I compile these ascc -I ./ temp2.cthen I get
```
/tmp/ccdeJCat.o: In function `main':
temp2.c:(.text+0x3c): undefined reference to `jk'
temp2.c:(.text+0x46): undefined reference to `jk'
collect2: ld returned 1 exit status
```
I had declared jk in temp1.h as an extern int so why can I not initialize it in temp2.c?
|
```
int jk;
```
The above declaration must be made somewhere in the code. Also,jkmust be global.
|
I made 2 files which are different from the program above
one is temp1.h and another is temp2.c to understand how extern is used.
So here is temp1.h
```
#include<stdlib.h>
typedef struct node * bond;
extern int jk;
```
and temp2.c is
```
#include<stdio.h>
#include<temp1.h>
struct node {
int data;
};
int main ()
{
bond t1;
t1=(bond)malloc(sizeof(bond));
t1->data=23;
printf("the data is %d\n",t1->data);
jk=0;
printf("The variable jk = %d\n",jk);
}
```
and when I compile these ascc -I ./ temp2.cthen I get
```
/tmp/ccdeJCat.o: In function `main':
temp2.c:(.text+0x3c): undefined reference to `jk'
temp2.c:(.text+0x46): undefined reference to `jk'
collect2: ld returned 1 exit status
```
I had declared jk in temp1.h as an extern int so why can I not initialize it in temp2.c?
|
```
int jk;
```
The above declaration must be made somewhere in the code. Also,jkmust be global.
|
Where to search for free C/C++ libraries?
|
trySourceforge
avoidGPL, as they aren't really free and are spreading like a virus through the rest of your project
useLGPL
|
Hey all, I need to compare a double inside an if statement. If the double has no value/is equal to zero, it should do nothing. Otherwise it should do something.
My if statement if (doubleNameHere > 0) doesn't work.
Obviously I'm missing something fundamental here, any ideas?
|
Sorry all, it turns out that it wasn't set to zero, it was equal to another blank double value. I started it at zero and it was fine.
|
How would I load a chunk of Lua code as acharand run it using this function? If not, what other function can I use and how doeslua_load()work?
|
UseluaL_dofileandluaL_dostringto load and run Lua code. Read their definitions inlauxlib.hto see how these are implemented in terms of lower-level primitives.
To learn howlua_loadworks, read the code ofluaL_loadfileandluaL_loadstring.
|
I am trying to compile a program in c/c++, but am getting the error message:
fpu_control.h: No such file or directory
From google, I have found out that this problem is about the way floating point precision is handled. I read that not all distributions of gcc include fpu_control.h.
This is the only thing I can find out. I have searched extensively and cannot find anywhere to download this fpu_control.h. Can anyone help?
Thank you all.
|
Apple doesn't support setting the FPU flags, anddoing so isn't needed. The reason is thatthey don't even use the i387 coprocessor for float and double, but SSE. The last reference also explains how to revert that approach, and how to perform FPU control using inline assembly.
|
If I define a function in filefunc1.c, and I want to call it from filecall.c. How can I accomplish this task?
|
You would put a declaration for the function in the filefunc1.h, and add#include "func1.h"incall.c. Then you would compile or linkfunc1.candcall.ctogether (details depend on which C system).
|
How do I generate all possible permutations of a list of numbers in C?
As an example,[1, 8, 12]would generate
```
[1, 12, 8],
[12, 8, 1],
[12, 1, 8], ...
```
|
Have a look at thisJohnson-Trotter Algorithmand applet it is exactly what you want.
|
In my code:
```
scanf("%s", &text);
printf("%s\n", text);
```
Input:
```
hi how are you
```
Output:
```
hi
```
and not
```
hi how are you
```
what can I do to fix it?
|
Look atfgets
The fgets() function reads at most one
less than the number of characters
specified by n from the given stream
and stores them in the string
s.Reading stops when a newline
character is found, at end-of-file or
error. The newline, if any, is
retained. If any characters are read
and there is no error, a `\0'
character is appended to end the
string.
|
A common way to measure elapsed time is:
```
const clock_t START = clock();
// ...
const clock_t END = clock();
double T_ELAPSED = (double)(END - START) / CLOCKS_PER_SEC;
```
I know this is not the best way to measure real time, but I wonder if it works on a system with a variable frequency CPU. Is it just wrong?
|
There are system architectures that change the frequency of the CPU but have a separate and constant frequency to drive a system clock. One would think that aclock()function would return a time independent of the CPU frequency but this would have to be verified on each system the code is intended to run on.
|
Hey everyone.
I have an exe file that runs a console program that was programmed in C.
during the run of the program the user is asked to enter numbers (using the scanf function).
and the output is being printed to the screen by printf.
The thing is this. I want to make my own txt file with inputs and I want the program to use those inputs.
I also want that the output will be printed to a different txt file - and not in the command window (or in addition to the command windows - I don't care if it's both).
how can I do that, in c#? or can I create a *.bat file that will do that? - that would be best.
Another question:
Is there a way to create a *.bat file that will check if two txt files are the same?
Thanks!
|
Assuming that the program was written to read fromstdin(standard input) and write tostdout(standard output), you should be able to use the following command line:
```
program.exe < input.txt > output.txt
```
|
I'm confused in this program how the value of x=320 ...
```
#include<stdio.h>
int a=5;
int main(){
int x;
x=~a+a&a+a<<a;
printf("%d",x);
return 0;
}
```
http://codepad.org/UBgkwdYl
hoping for quick and positive response..
|
This is evaluated like this:
```
x = ((~a) + a) & ((a + a) << a);
```
You should review the C operator precedence tables.
|
would it make any difference if i use c-style functions to search an array or cstring?
|
In a character string (cstring), the NULL character at the end acts as a sentinel, to signify the end of the search.
If it's an array of characters without the terminating NULL character, then you had better know the length of the string, to avoid overflow.
|
What doesconst structmean? Is it different fromstruct?
|
Theconstpart really applies to the variable, not the structure itself.
e.g. @Andreas correctly says:
```
const struct {
int x;
int y;
} foo = {10, 20};
foo.x = 5; //Error
```
But the important thing is that variablefoois constant, not thestructdefinition itself.
You could equally write that as:
```
struct apoint {
int x;
int y;
};
const struct apoint foo = {10, 20};
foo.x = 5; // Error
struct apoint bar = {10, 20};
bar.x = 5; // Okay
```
|
XL Compiler of AIX seems to have the-qfuncsectoption which places each function in a seperate object control section with the effect that when the final executable is created it helps in removing unwanted functions.
Is there an equivalent option for the same in gcc? I am unable to find the same.
|
```
-ffunction-sections
-fdata-sections
```
http://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/Optimize-Options.html
|
```
enum FileOpenFlags
{
FileOpenFlags_Create = 1,
FileOpenFlags_Truncate = 2,
};
FileOpenFlags flags = FileOpenFlags_Create | FileOpenFlags_Truncate;
```
Is it true the return type ofenum |is alsoenum??
|
No, the above expression will have the typeint. However, sinceenums convert to and fromintwithout problems, it's then implicitly converted back toenumfor the store.
See alsothis comp.lang.c FAQ entry.
|
I found a lot of Optimization Optionshere
While going through them I found some of them have side-effects (like makes debugging impossible). In my experience I have found the -O1 to -O3 and -Os most commonly used. But, what are the other options which are commonly used in your projects?
|
-ffast-mathcan have a significant performance impact on floating point intensive software.
Also, compiling specific for the target processor using the appropriate-march=option may have a slight performance impact, but strictly speaking, this is not an optimizing option.
|
I am trying to implement backtrace functionality for a large framework, which is used for different platforms and OS'es. In some of them, it is linked against glibc, while in the other, something different (eg. uclibc) is used. backtrace() function exists only in the former.
Is there any way to tell whether glibc is used? Any #define? I was unable to find an answer in glibc manual. I know I can't have linking-time information during compilation, but I guess include files have to differ. At least backtrace have to be declared somewhere.
I would like to check it without being forced to pass explicit flags to the compiler.
|
Include features.h, it contains the macros you need, e.g.
```
#define __GNU_LIBRARY__ 6
/* Major and minor version number of the GNU C library package. Use
these macros to test for features in specific releases. */
#define __GLIBC__ 2
#define __GLIBC_MINOR__ 4
```
|
So we have an image. We want to draw a line that must definitely be seen. So how to draw a lines with colors that are inverted relatively to the surface it should be drawn on in each point?
|
The XOR trick is trivially different. It's not visually the most distinct, though, if only because it entirely ignores how human eyes work. For instance, on light greys, a saturated red color is visually quite distinct.
You might want to convert the color to HSV and check the saturation S. If low (greyscale), draw a red pixel. If the saturation is high, the hue is quite obvious, and a white or black pixel will stand out. Use black (V=0) if the the original pixel had a high V; use white if the original pixel had a low V (dark saturated color)
You can use the LineIterator method as suggested earlier.
(BTW, the XOR trick has quite bad cases too. 0x7F ^ 0xFF = 0x80. That's bloody hard to see)
|
What's the difference between the 2 definitions below:
```
#define DEFINE_BIT_MASK_ENUM_AND_OR(Type) \
inline Type EnumBitMaskOr(Type lhs, Type rhs) { return lhs | rhs; } \
#define DEFINE_BIT_MASK_ENUM_AND_OR(Type) \
Type EnumBitMaskOr(Type lhs, Type rhs) { return lhs | rhs; } \
```
|
The word "inline" signals to some compilers that the function should be inlined if possible, i.e. the code from the function's body should be "copy pasted" into the call site, rather than generated as a stand-alone function.
This can save time, since if the work being done is smaller than the work in doing the call itself, it's a net win to remove it. It can also slow things down, by bloating the code and killing the cache.
|
```
struct ethernet_header
{
u_char ether_dhost[ ETHER_ADDR_LEN];
u_char ether_shost[ETHER_ADDR_LEN];
u_short ether_type;
};
for(i = 0;i <6; i++)
printf("dest ether:%x",ethernet->ether_dhost);
```
How to print the Ethernet address in proper readable form with spaces after each byte? The o/p I get is in hex. Here Ethernet is the pointer to the structureethernet_header.
|
How about:
```
printf("%02x:%02x:%02x:%02x:%02x:%02x",
(unsigned)ethernet->ether_dhost[0],
(unsigned)ethernet->ether_dhost[1],
(unsigned)ethernet->ether_dhost[2],
(unsigned)ethernet->ether_dhost[3],
(unsigned)ethernet->ether_dhost[4],
(unsigned)ethernet->ether_dhost[5]);
```
|
How do I inspect a string a pointer is pointing to when stepping through a program using GDB?
I can see the a pointer is pointing to0x82c6e10. I know it is a string. How do I print it?
Usingprintf("%s\n", 0x82c6e10)givesBad format string, missing '"'.The fact that gdb does not complain of unknown command tells me that the solution is some variation of what I am doing. Am I right? I tried escaping the quotes but that did not help.
|
Usexrather thanp:
```
x /s 0x82c6e10
```
|
I am usinglibcurlto create an http connection to anamfphpserver. Do I have to set the content type to any specific format? I noticed there is a option calledAMFPHP_CONTENT_TYPEin PHP cURL but I couldn't find a corresponding value inC.
|
Found it. I have to addContent-type: application/x-amfto thePOSTheader.
|
I can't find any information about making a tcp/ip packet logger in a book. can someone point me in right direction or a book reference would be helpful.
|
If you simply need a program to log tcp packets, have a look at Wireshark. If you actually want to write your own logger, you can use thelibpcaplibrary. It is implemented in C and there are lots of tutorials / examples on the website. If you working in windows, you should have a look atWinPcap.Hereis a nice easy tutorial for libpcap.
|
I have a problem with some C code I am writing as part of a University assignment. Consider the code:
```
printf("%s\n", argv[1]);
if ((argv[1] == "--verbose") || (argv[1] == "-v")) {
printf("%d\n", argc);
}
```
now:printf("%s\n", argv[1]);prints "--verbose" so I knowargv[1] == "--verbose"should be true, but the lineprintf("%d\n", argc);never executes. And I cant workout why. Any ideas?
|
Use thestrcmpfunction:
```
strcmp(argv[1], "--verbose") == 0
```
==checks that two pointers have the same address, which is not what you want.
|
I'm interested in reviewing some of the functions included in the string library for c, but I can't find the source code (literally, i.e. functions and all) online and I have no idea where to find it.
Thanks.
EDIT:
thelink provided by pmgshows those functions divided into c files, so it's about what I needed. Thanks.
|
Take a look atredhat glibc. It appears to be somewhat current.
|
Say you have a C code like this:
```
#include <stdio.h>
int main(){
printf("Hello, world!\n");
printf("%d\n", f());
}
int f(){
}
```
It compiles fine with gcc, and the output (on my system) is:
Hello, world!14
But.. but.. how is that possible? I thought that C won't let you compile something like that because f() doesn't have a return statement returning an integer. Why is that allowed? Is it a C feature or compiler omission, and where did 14 come from?
|
The return value in this case, depending on the exact platform, will likely be whatever random value happened to be left in the return register (e.g.EAXon x86) at the assembly level. Not explicitly returning a value is allowed, but gives an undefined value.
In this case, the 14 is the return value fromprintf.
|
What is the difference betweenfork()andvfork()? Doesvfork()return likefork().
|
The intent ofvforkwas to eliminate the overhead of copying the whole process image if you only want to do anexec*in the child. Becauseexec*replaces the whole image of the child process, there is no point in copying the image of the parent.
```
if ((pid = vfork()) == 0) {
execl(..., NULL); /* after a successful execl the parent should be resumed */
_exit(127); /* terminate the child in case execl fails */
}
```
For other kinds of uses,vforkis dangerous and unpredictable.
With most current kernels, however, including Linux, the primary benefit ofvforkhas disappeared because of the wayforkis implemented. Rather than copying the whole image whenforkis executed, copy-on-write techniques are used.
|
I have a 3d scene drawn out in Opengl, the camera is allowed to pan around the scene. How do I go about adding 2d shapes to the window that will be unaffected by the camera moving?
|
Generally this is done by drawing in two steps. Assuming that you would like the 2D shapes to always be "on top" of scene like a GUI, I would render your 3D scene, then useglOrtho2Dand draw your shapes. You'll probably want to also disable depth testing. Be sure to set back up for your 3D each frame.
|
I want to save an integer variable, so that it can be retained even after the C program is restarted.
The way is to store it in a file.
But it is just an integer variable. In the file if I write 1000 first and replace it with 12, it saves as 1200, how can I delete the old value which was there in the file and write the new one?
Or some other way other than files exist?
Thanks
Pradeep
|
When you callfopento open the file stream, use the"w"mode; this opens the file for writing and truncates it.
|
I am writing a c application in Visual Studio 2008, and need to grab some information from the executable to send to another application.
The info I need is what you get when you right click on an executable->Properties->Details
How can you get the "Product version" and "File version" information from .exe file in c?
and also can you set such values from Visual Studio 2008? if so how?
Specifically interested in Product version and File Version, though other version info (Product Name, etc) would be helpful as well.
|
GetFileVersionInfoSize,GetFileVersionInfo, andVerQueryValueshould at least give you a good start.
|
Can anyone give me an example forrecvfromepolled, nonblocking socket in edge-triggered mode? I ask because I have some troubles.
|
The man page, for EPOLLET set-up has:
The suggested way to use epoll as an Edge Triggered ( EPOLLET ) interface is below, and possible pitfalls to avoid follow.
```
i
with non-blocking file descriptors
ii
by going to wait for an event only after read(2) or write(2)
return EAGAIN
```
Edit:
You can also call recv() or read() for x number of bytes until you receive less than x bytes.
If you don't do this you can create a starved situation where data remains in the socket buffer and prevents the ET activity on the socket.
What problem are you having?
|
is it possible to call c# methods written in managed code (maybe in a class or a library) from a native c code (and how)?
thx
edit: with "c#" i mostly refer to mono or even portable.net and the OS is Linux
|
Your C code can define functions to register callbacks. The C# code can P/Invoke these functions, and pass managed delegates as arguments. The marshalling code will transparently transform these to C function pointers.
Alternatively, approaching it from the C side, you can use the Mono embedding API to load assemblies, look up MonoMethods, and invoke them.
Using the embedding API is much more complicated. If your entry point is in C, you'll have to use the embedding API, but it's likely easier to simply write a managed method to do the callback registration and any other managed setup, then you only have to load and invoke that single method from C code.
|
Can you tell me what is the meaning of " Java-class-file loader library in C"?
It's a homework assignment and I am not sure how I should approach it.
Update:I just found out a link ongithubwhich exactly defines the topic but I still need some help to figure out what exactly this means?
|
I suppose it's about a C library which provides an API for loading Java .class files. This should be possible usingJNI.
|
Is there a simply way how to get the virt size of the Linux process from the C/C++ code? Thanks
|
If you want to find out your the virtual size of own process you simply need to read/proc/self/statusand find there the VmSize field
```
FILE* handle = fopen("/proc/self/status","r");
// and then read its conttent find the VmSize string and its value
```
If you want to know the virtual size of an arbitrary process then open"/proc/<process-id>/status"for the process and find there the VmSize field.
|
In C, at least every positive value except for 0 is treated as a boolean true. But what about a negative value? I did some tests and it seems that also negative values are treated as a boolean true. Is this a defined behaviour or implementation specific?
(I came to think about this when I saw in a question, someone promoting declaring "true" and "false" in an enum as 1 and 0.)
|
This is defined behavior. I'll look for the C99 standard paragraph stating as such
§ 6.3.1.2When any scalar value is converted to _Bool, the result is 0 if
the value compares equal to 0;
otherwise, the result is 1.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.