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... |
```
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 lo... |
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 i... |
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(){
... |
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.... |
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 ... |
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 a... |
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];
unsign... |
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); /* LEGAC... |
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... |
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 p... |
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 t... |
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.
... |
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 ... |
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... |
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 doe... |
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... |
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 mon... |
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 particu... |
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 ... |
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 _IMUsend... |
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 canEXCLUDEth... |
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 m... |
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 wherealloperatio... |
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 c... |
```
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 th... |
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... |
```
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 lo... |
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 i... |
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(){
... |
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.... |
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 ... |
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 a... |
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];
unsign... |
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); /* LEGAC... |
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... |
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 p... |
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 t... |
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.
... |
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 ... |
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... |
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 Rerou... |
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 studyi... |
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 wa... |
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 l... |
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 be... |
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/ho... |
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 assum... |
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 ... |
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... |
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 fi... |
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(...);
...
... |
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 state... |
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... |
```
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. Pl... |
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 qual... |
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; oth... |
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 cam... |
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 ... |
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 ()
{
b... |
```
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 ()
{
b... |
```
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 fi... |
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 ... |
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 pro... |
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... |
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 ... |
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 ... |
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 i... |
```
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 ... |
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 th... |
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 tutor... |
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 ... |
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. Thank... |
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 th... |
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 exec... |
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 ... |
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... |
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(... |
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 assemblie... |
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 t... |
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 p... |
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.