question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I would like to have the equivalent of
```
void print3( char a, uint8_t b, int8_t c )
{
printf("%c %" PRIu8 " %" PRIi8 "\n", a, b, c);
}
```
using thewritesyscall. The problem is, I don't know how to print an integer usingwrite. Only commands from ANSI C are allowed and usingsprintfto format strings is forbidden... |
Consider the number155, if you divide by100then there's1hundred and the remainder is55, divide by10you get510s and the remainder is5, divide that by1you get5. now concatenate those numbers 1-5-5 you get the final number.This should get you started.
|
c99standard says that result of modulo operation has same sign as first operand. So-9 % 7 = -2and9 % -7 = 2.
I read in one book that c89 standard depends on implementation. So-9 % 7could yield-2or5??? How remainder of-9 / 7could be5?
|
Consider two numbersaandb.
The quotientq=a/band remainderr=a%bsatisfy the equationa == q*b + r.
An (hypothetical) implementation of C89 in which -9 % 7 produces 5 is an implementation in which -9 / 7 is computed as -2.
The mathematical (Euclidian) division constrainsrto be positive and smaller thanb. C99 constrains... |
I want to know if there is a way of calling in a .c assembly code?
I want to put this code in my .c file
The assembly code i want to execute in .c file to return the address
```
1. mov eax, 0x2d
2. mov ebx, 0
3. int 0x80
```
I know the answer is put eax.
This is the part of .c file:
```
1. void function(void)
2. ... |
The ability to do this is compiler-specific. Gcc allows thisusing itsasmkeyword extension, while Visual studio implements adifferent extension.
Note that, beside the obvious problem with non-portability to other architectures, including any inline assembly can reduce performance because the compiler is unable to anal... |
```
uint8_t * const LCDMem = (uint8_t *) &LCDM3;
```
This code is used in msp430fg4618 trainer kit for lcd configuration.
Could any one please explain the meaning of the above mentioned code?
It allows use ofarray LCDMem[]? I don't know how.
|
LCDMem is not arrray, it is a pointer. This code assigns to LCDMem new address - LCDM3's, so after execution LCDMem will point to LCDM3. Can't say how many bytes allocated for LCDM3, may be array, may be just one.
|
What is a short illustrative C program that demonstrates the difference between volatile and non-volatile in the disassembly?
ie
```
int main()
{
volatile int x;
???
}
```
vs
```
int main()
{
int x;
???
}
```
What can we replace both???with such that the generated code is different?
|
for example:
```
x = 0;
```
Ifxis notvolatile, the compiler will see that it's unused and will probably eliminate it (either thex = 0;statement or even the variable itself) completely from the generated code as an optimization.
However, thevolatilekeyword isexactly for preventing the compiler from doing this.It bas... |
I am trying to compile a C++ project in Visual Studio 2010.
It contains many C++ files and it also has a couple of C files.
Because it is a C++ project and the warning level is set to /W4 I am getting a lot of warnings on the C source code.
Is there a way to select the C compiler for C source code and the C++ compil... |
Normally, the file extension will be used to hint a default compilation mode. If for some reason the compilation mode was overriden, you can set it manually:
Go to properties of your C file. Inside: Configuration Properties --> C/C++ --> Advanced --> Compile As --> Compile as C code.
|
I have a program where I am printing to a file, and I would like to print my columns in steady columns.
You can see here by looking at the output of my file what I am trying to say
Output:http://nopaste.dk/p15072
Here is what I wrote:
```
int func1(int n) {
if(n==0){return(6);}
return ((int)log2(n));
}... |
Make changes in the following lines and it should work.
```
fprintf(fp,"%8s%8s%4d%2c",tString+11,log->file,log->line,levelStrings[func1(log->ssMask%64)]);
```
|
I need to print 2 vector in openGL but I cannot sent a pointer with the functionglutDisplayFunc.
glutDisplayFunc(graphfunct)I have this once the window is created but I need send the 2 pointers with the address of vector to set the coordinates.
|
You cannot pass parameters to the function you register withglutDisplayFunc. You must use a globally-accessible variable instead.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
IsBoost - Compressed Sparse Matrixan alternative for you?
EDIT:
Pure C-Library:CSparse
|
In the code I'm writing, I have been told to define a variable in a header file in the following way:
```
#define CLR_BLACK 0x0000
```
and since this is the only example I've been given, I was wondering whether all variables defined in a header file with the #define command need to be in caps. For example, would the... |
No.You can use any combination of alphanumeric characters and underscores. Don't start with a number.
However a variable name likevideoBufferwould be difficult to distinguish from regular variables (without syntax coloring). That's why most people either use all caps for preprocessor macros or start them with a lower... |
```
int main()
{
const int STRIDE=2,SIZE=8192;
int i=0;
double u[SIZE][STRIDE];
#pragma vector aligned
for(i=0;i<SIZE;i++)
{
u[i][STRIDE-1]= i;
}
printf("%lf\n",u[7][STRIDE-1]);
return 0;
}
```
The compiler uses xmm registers here. There is stride 2 access and I want to m... |
A masked store with a mask value as0xAA(10101010)
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
What is meant by1<<20?
A 1, shifted to the left by 20 places, also known as 2^20 = 1048576.<<is the bit-shift operator that shifts to the left.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:maximum memory which malloc can allocate!
How can I know the maximum size of the heap I can occupy bymalloc().
I use MS Visual Studio 2010.
|
There are operating system-dependent ways of finding out how much virtual memory is available for your process, but I do not know how to do this on windows. You can, however, find it out by doing a hunt+halving search, caling malloc with ever larger arguments until it fails, and then homing in on the value it balks at... |
What are some possible ways if any to execute a web browser on someone else's computer? I have a server and now when I use Process.Start. When someone executes that code from another computer the browser will show up on the server only.
What are some ways to have the browser open in their computer instead?
|
In effect you're asking how to execute code remotely. This is done by using some form ofRPC. There are many RPC frameworks out there, so no definite answer can be given. Pick an RPC framework suitable for your situation and them you could ask a more specific question pertaining to that particular framework.
If, on th... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:How to convert integer to string in C?
I would like to calculate the length of the string and pass the value to a function as a string.
```
char* s="abcd";
int i = strlen(s);
char* lengthAsString = ????(i);
```
|
```
char* s = "abcd";
int i = strlen(s);
char lengthAsString[50];
sprintf(lengthAsString, "%d", i);
// now you can use lengthAsString to pass it to a function
```
|
I need to print 2 vector in openGL but I cannot sent a pointer with the functionglutDisplayFunc.
glutDisplayFunc(graphfunct)I have this once the window is created but I need send the 2 pointers with the address of vector to set the coordinates.
|
You cannot pass parameters to the function you register withglutDisplayFunc. You must use a globally-accessible variable instead.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
IsBoost - Compressed Sparse Matrixan alternative for you?
EDIT:
Pure C-Library:CSparse
|
In the code I'm writing, I have been told to define a variable in a header file in the following way:
```
#define CLR_BLACK 0x0000
```
and since this is the only example I've been given, I was wondering whether all variables defined in a header file with the #define command need to be in caps. For example, would the... |
No.You can use any combination of alphanumeric characters and underscores. Don't start with a number.
However a variable name likevideoBufferwould be difficult to distinguish from regular variables (without syntax coloring). That's why most people either use all caps for preprocessor macros or start them with a lower... |
```
int main()
{
const int STRIDE=2,SIZE=8192;
int i=0;
double u[SIZE][STRIDE];
#pragma vector aligned
for(i=0;i<SIZE;i++)
{
u[i][STRIDE-1]= i;
}
printf("%lf\n",u[7][STRIDE-1]);
return 0;
}
```
The compiler uses xmm registers here. There is stride 2 access and I want to m... |
A masked store with a mask value as0xAA(10101010)
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
What is meant by1<<20?
A 1, shifted to the left by 20 places, also known as 2^20 = 1048576.<<is the bit-shift operator that shifts to the left.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:maximum memory which malloc can allocate!
How can I know the maximum size of the heap I can occupy bymalloc().
I use MS Visual Studio 2010.
|
There are operating system-dependent ways of finding out how much virtual memory is available for your process, but I do not know how to do this on windows. You can, however, find it out by doing a hunt+halving search, caling malloc with ever larger arguments until it fails, and then homing in on the value it balks at... |
What are some possible ways if any to execute a web browser on someone else's computer? I have a server and now when I use Process.Start. When someone executes that code from another computer the browser will show up on the server only.
What are some ways to have the browser open in their computer instead?
|
In effect you're asking how to execute code remotely. This is done by using some form ofRPC. There are many RPC frameworks out there, so no definite answer can be given. Pick an RPC framework suitable for your situation and them you could ask a more specific question pertaining to that particular framework.
If, on th... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:How to convert integer to string in C?
I would like to calculate the length of the string and pass the value to a function as a string.
```
char* s="abcd";
int i = strlen(s);
char* lengthAsString = ????(i);
```
|
```
char* s = "abcd";
int i = strlen(s);
char lengthAsString[50];
sprintf(lengthAsString, "%d", i);
// now you can use lengthAsString to pass it to a function
```
|
What are some possible ways if any to execute a web browser on someone else's computer? I have a server and now when I use Process.Start. When someone executes that code from another computer the browser will show up on the server only.
What are some ways to have the browser open in their computer instead?
|
In effect you're asking how to execute code remotely. This is done by using some form ofRPC. There are many RPC frameworks out there, so no definite answer can be given. Pick an RPC framework suitable for your situation and them you could ask a more specific question pertaining to that particular framework.
If, on th... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:How to convert integer to string in C?
I would like to calculate the length of the string and pass the value to a function as a string.
```
char* s="abcd";
int i = strlen(s);
char* lengthAsString = ????(i);
```
|
```
char* s = "abcd";
int i = strlen(s);
char lengthAsString[50];
sprintf(lengthAsString, "%d", i);
// now you can use lengthAsString to pass it to a function
```
|
How do I find a substring from the string path "/user/desktop/abc/post/" using C/C++? I want to check if folder "abc" is present or not in that path.
Path is character pointerchar *ptr = "/user/desktop/abc/post/";
|
Usestd::stringandfind.
```
std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;
```
|
I want to make an array of my struct type, but it is not defined in sequence, e.g, randomly I can doarray[3] = mystruct_t;array[5] = mystruct_t(3and5is defined at run-time by user input). I had tried:
it's the "ideal", but can't hold null-pointers:
```
static struct mystruct_t foo_inputs[SIZE];
```
So, I tried:
``... |
Combine the two. In the first, you can't (shouldn't) assignNULLto a non-pointer. In the second, you have one uninitialized pointer. What you want is an array of pointers:
```
static struct mystruct_t *foo_inputs[SIZE];
foo_inputs[x] = NULL;
```
|
Is there a way to get kernel previous debug information after kernel crash occurs.
I am trying to develop a kernel module which basically captures IP packets in the IP layer inside the kernel network stack and after some modification I have to send the same packet back to the NIC for transmission.
During all these ... |
Actually, the/var/log/dmesgfile contains the current boot print message log. The/var/log/kern.logfile contains your previous boot kernel print message log inUbuntu. In other Linux flavours it will contain in the/var/log/messagesfile in Fedora, etc..
|
Just a fast question:
I'm trying to test if a variable is not greater than or equal to another variable.
I have it coded as such:
```
if (f!>=i){
print ("True");}
```
but my c compiler won't recognize it. I can't find it online, is it possible?
|
Just change it to(f < i)which is!(f >= i).
Note: this is not the case if eitherforiisNaN. This is becausef >= iwill evaluate tofalseif either isNaNleading to!(f >= i)evaluating totruewheref < ievaluates tofalse.
|
I have a problem with C programming. I want to reach large numbers of fibonacci sequence but program, 47 Number of minutes to give the error. Here is the preview.
```
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
35245... |
Looks like you rolled over the limit for a 32 bit integer. Try using a 64 bit integer.
|
I need to statically link glibc to my project, because the target platform supports only a very old one ( but it works with statically linked glibc from my toolchain, I have checked it)
Unfortunately, this application has to make use of pthread library, but statically linked libpthread takes too much space.
I would ... |
There is a-static-libgccif that may help
|
I am writing a simple C program to check if a File F is a usable SQLite3 database.
I tried writing gibberish into a filetest.db, butsqlite3_open("test.db", &db)returned 0.
I suppose eithersqlite3_status()orsqlite3_db_status()do what I want, but the documentation states something different.
|
Check out thisthread.
It looks likesqlite3_openwill return SQLITE_OK even if the file is not a database. However, when you try execute a statement you will get SQLITE_NOTADB. Instead of reading the header, you could just do something likeSELECT * FROM sqlite_master;after opening the database and check if SQLITE_NOT... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
```
#include <stdio.h>
#define NUM_MARKS 3
int main()
{
int marks[NUM_MARKS];
/* marks contains all undefined data */
int counter=0;
int i;
for (i = 0; i < NUM_MARKS; i++){
printf("%d\n", marks[i]);
counter++;
}
return 0;
}
```
|
What is the difference betweenstatic constandconst?
For example:
```
static const int a=5;
const int i=5;
```
Is there any difference between them?
When would you use one over the other?
|
staticdetermines visibility outside of a function or a variables lifespan inside. So it has nothing to do withconstper se.
constmeans that you're not changing the value after it has been initialised.
staticinside a function means the variable will exist before and after the function has executed.
staticoutside of a... |
I have a C code that runs on Linux that creates a certain amount of threads. In one of the threads, I want it so that if it runs into a certain condition, it should terminate the entire process. I looked up the exit() command but didn't really understand how to use it.
|
There's little not to understand aboutexit(). Just do:
```
exit(EXIT_FAILURE);
```
and gone's your process.
EXIT_FAILUREbecomes the exit status of your program; this is the same as returning a value frommain().
|
I want to get information about the battery in C on linux. Idon'twant to read or parseanyfile! Is there any low-level interface to acpi/the kernel or any other module to get the information I want to have?
I already searched the web, but every question results in the answer "parse /proc/foo/bar". I really don't want ... |
The /proc filesystem does not exist on a disk. Instead, the kernel creates it in memory. They are generated on-demand by the kernel when accessed. As such, your concerns are invalid -- the/procfiles will change as quickly as the kernel becomes aware of changes.
Checkthisfor more info about/procfile system.
In any ca... |
Do sockets in C offer any kind of way to limit the number of incoming connections to the socket based on the IP?
For example, to prevent one client IP from spamming connections, is there a way to limit the number of times an IP can connect to a socket?
Or does something like this have to be custom made?
|
I feel the real intention you are talking about is throttling i.e. for a particular client / connection, allowing only a fixed number of packets in a given time. This sounds like a more realistic usage scenario than allowing / disallowing more connections.
Most of modern languages provide some kind of support such as... |
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
Searching google I have found the following that support taint analysis for C programs:
http://code.google.com/p/tanalysis/http://www.cs.umd.edu/~jfoster/cqual/-- see their printf format string example
|
Of the following, which is the preferred way of doing things, and why? Are there any specific situations in which it makes any difference,assuming that the function bar() does not take the value zero at any time?
Case 1: Test the truth value of both conditions
```
if ((foo = bar()) && foo < 0)
error();
```
Case... |
The preferred way is to separate them:
```
foo = bar();
if (foo < 0)
error();
```
Edit: This is better way for both readability and avoiding bugs, such as in your first case:
```
if (foo = bar() && foo < 0)
error();
```
That should probably be:
```
if ((foo = bar()) && foo < 0)
error();
```
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
I would like to know which infinite loop is more preferable:
```
for(;;) {
// Do some stuff
}
```
or
```
#define TRUE 1
while(TRUE) {
// Do some stuff
}
```... |
From a performance point of view it doesn't matter. The compiler will optimize both into the same assembly code. From a "coding standards" point of view, for(;;) is more terse, which is nice. Although while(TRUE) is a bit clearer, for(;;) is so common that clarity in this case is not much of an issue (in fact, the ubi... |
How can I make an automatic updater for my visual studio 2010 c++ application ? I do not want any kind of advanced features.
Any free application that can provide a notification that "A new version 1.2.2 is available" ?
Actually right now I just want only notification to the user not download the software or somethi... |
I don't know Windows, but....
You could use some HTTP client library, perhapslibcurl, to issue aGETHTTP request to yourhttp://www.site.com/update.txtURL.
But don't overwrite magically the binary executable.
|
I was wondering... suppose I've dynamically allocated an array like
```
array = calloc(n, sizeof(float));
```
or something similar. And also if n is a really large number, (~ 1 million, for arguments sake), how long would Linux take to clear the heap memory if I didn'tfree()it at the end? I know any OS would go arou... |
If a process is terminated (either voluntarily or by force), all its heap memory will be reclaimedimmediatelyby an operating system including Windows, Linux and OS X.
|
I'm opening several files , and want to add to my struct the creation time of the file and the last write time. Is there a way I can do it?
|
You can usefstatto read the last write time (seestat.st_mtime).
I'm not aware of a portable way to read creation time. On Windows you could useGetFileTime
|
I don't understand the meaning of
The original Java AWT was implemented by having widgets written in Java which delegated to peer classes that were written in C
The"peer classes that were written in C"part:
It means Java classes included native code?
|
Hotspot Java has substantial parts of the runtime system written in C / C++. At one point, this included the AWT peer classes. (And it still may do ... )
The native code is not "in" the Java. Rather, the Java typically hasnativemethod declarations that typically get bound to a native implementation when the corres... |
I need to find the time taken to execute a single instruction or a few couple of instructions and print it out in terms of milli seconds. Can some one please share the small code snippet for this.
Thanks.. I need to use this measure the time taken to execute some instructions in my project.
|
```
#include<time.h>
main()
{
clock_t t1=clock();
printf("Dummy Statement\n");
clock_t t2=clock();
printf("The time taken is.. %g ", (t2-t1));
```
Please look at the below liks too.What’s the correct way to use printf to print a clock_t?
http://www.velocityreviews.com/forums/t454464-c-get-time-in-milliseconds.html
|
I'd like to parse C header files in Javascript. Is there any such library available? Otherwise, any tips to help me get started?
Update:My ultimate goal is to automatically build interfaces fornode-ffi. The parser doesn't necessarily have to be in Javascript as long as it can spit out a format understandable by Javas... |
You should check outclang.
For a simple command-line invocation, you can try this:
```
clang -cc1 -ast-dump-xml myfile.h
```
Or you can build your own tool usingclangreasonably-well-documentedparser library, which will build an AST for you, and let you walk it as you see fit (perhaps for output in JSON).
|
The compiler is gcc and I'm using an old version of linux
```
typedef struct strlist strlist;
struct strlist
{
char *data;
time_t *timestamp;
struct strlist *next;
}
strlist * list_directory(char *dirname)
{
//do something
}
```
The error message is:
```
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attr... |
```
struct strlist
{
char *data;
time_t *timestamp;
struct strlist *next;
};
^^^
|
```
You are missing the;at the end of structure declaration.
|
```
#include <stdio.h>
int main(void)
{
fork();
fork();
printf("ppid %d pid %d\n", getppid(), getpid());
return 0;
}
```
The above code sometimes prints
```
$ ./a.out
ppid 3389 pid 3883
ppid 3883 pid 3885
ppid 1 pid 3884
ppid 3884 pid 3886
```
Why is process 3884's ppid 1? Doesn't it supposed to b... |
I'd guess the parent process had already completed running and exited by the time the third child checked for the parent's PID. That would have caused the child to be re-parented underinit, which has process ID 1.
|
I'm want to try using look up table (cvLUT) to check whether it is fast than the current way that I'm doing right now. The question is I don't really understand how look up table works if I have different set of values Eg.
```
if(mean < 50)
//do gamma correction
else if(mean > 50 && mean < 100)
// do gamma correcti... |
I don't think a lookup table is appropriate for what you are doing since the transformation is dependent on information in the local window. A lookup table is good if you want a transformation on all pixels that only depends on the pixel value and doesn't depend on the value of other pixels.
|
I am trying to do a function that will store in a char array some information to print on it:
```
int offset = 0;
size_t size = 1;
char *data = NULL;
data = malloc(sizeof(char));
void create(t_var *var){
size_t sizeLine = sizeof(char)*(strlen(var->nombre)+2)+sizeof(int);
size = size + sizeLine;
realloc(... |
Without knowing the specific valgrind errors, the standout one is:
realloc(data, size);should bedata = realloc(data, size);
|
Only once, when a new connection is created, I want to peek into the stream to determine whether or not the connection is an SSL connection. To do this I use recv() with the MSG_PEEK flag. The problem is that for connections which are not SSL connections and dont have any initial incoming data the recv blocks for a fe... |
If you don't want the call to block, you can supply theMSG_DONTWAITflag as well (not POSIX, but widely implemented) - but how would you tell the difference between an SSL connection where the initial data just hasn't arrived yet and a non-SSL connection?
It seems that to do this reliably you will need to wait for the... |
I open a file using the system callopen().
```
if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT ), 0666) == -1)
DieWithError("open() failed");
```
My file which is FTP_track.log is created without any problem. The problem is although i have mode0666, which is read and write for all, I can not open the file in... |
The problem with your line is that the parenthesis don't match up. Your expression is parsed asfd2 = open(), 0666. In C the expressionexpr1, expr2has the valueexpr2so yourifstatement basically saysfd2 = 0666.
|
For my assignment I need to read some strings coming from a serial port.
This has to be done in a kernel module, so I can't use stdio library.
I'm trying in this way:
```
#include <linux/module.h>
#include <linux/unistd.h>
#include <asm/io.h>
#include <asm/fcntl.h>
#define SERIAL_PORT "/dev/ttyACM0"
void myfun(void)... |
You want to use thefilp_open()function, it is pretty much a helper to open a file in kernelspace. You can find the man on ithere
The file pointer fromfilp_open()is of typestruct fileand don't forget to close it with filp_close() when you're done:
```
#include <linux/fs.h>
//other includes...
//other code...
st... |
I'm trying to measure some activity in C (Matrix multiplying) and noticed that I should do something like this:
```
clock_t start = clock();
sleep(3);
clock_t end = clock();
double elapsed_time = (end - start)/(double)CLOCKS_PER_SEC;
printf("Elapsed time: %.2f.\n", elapsed_time);
```
The output is:
```
Elapsed time... |
clockestimates the CPU time used by your program; that's the time the CPU has been busy executing instructions belonging to your program.sleepdoesn't perform any work, so it takes no noticeable CPU time (even if it takes wallclock time).
If you want to measure wallclock time, usetime:
```
time_t start = time(NULL);
... |
Here is my problem, I wrote a programa.exe, it can take several options, like"r:e:m:".r:andm:can't appear together, which means they run totally different tasks insidea.exe. Ande:is an optional option, if it shows up, then it should be withr:.
How should I implement this logic withgetopt?
|
You have to manually check for incompatible options. For example, when you see the-roption you set a flag saying "-ris found", if you then see the-moption you check to see if the "-ris found" flag is set, and print an error message telling the user about it.
|
```
char * return_buffer()
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s", "test");
return buffer;
}
```
buffer is created in the function, can I return the buffer directly? after the function returns, the buffer would disappear?
|
You are creating a statically allocated buffer, which means that it is being created on the stack. When the function returns, it will give you an address on the stack that is no longer in use. So if you make more function calls, the data it stores will likely corrupt.
It is much better to allocate it to the heap by c... |
```
void func(char a, int num)
{
printf("%c",a);
}
int main()
{
func("a", 6); //not func('a',6);
printf("\n");
func("b", 2); //not func('b',6);
}
```
I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?
|
It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.
|
After commenting Line 2 "Hello" is printed nine times but commenting Line 1 outputs "Hello" more than nine times. My question is what's the role of '\n' in this?
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int tmp[10], i, n=0;
for(i=0;i<9;i++)
{
tmp[i]=fork();
if(tmp[i]>0)
... |
\n also flushes the standard output buffer. If it is not present, it is possible that you have previously entered data in it. Flushing also means it forces printf to print on the screen as soon as \n is processed. Otherwise it is buffered output and you can never predict how long would OS buffer your output and when p... |
Incrementing integer pointer will increase the address by size of integer.
What will happen if we increment a function pointer?
|
Just as withvoid *pointers and pointers to incomplete types, arithmetic is not allowed on pointers to functions.
For example, C99 §6.5.6 on Additive operators says:
For addition, either both operands shall have arithmetic type, or one
operand shall be a pointer to an object type and the other shall have
integer ... |
I'm working on a puzzle right now....trying to writeif (x==5 || x==7)With bitwise operations (in C). Been working on it for a while....can't figure it out.
Any help would be appreciated! Thanks
Ps this isn't homework...trying to study for a test.
EDIT so the format would be something likeif (x _ _)with a bitwise op... |
7d = 111b and 5d = 101b
So bit 0 must be on, bit 1 is don't care, bit 2 must be on and bits 3-31 must be off.
So, mask out bit 1 and test for 101b
so your test becomes ((x & ~2) == 5)
Then ask Bing or wikipedia about "Karnaugh Maps" so you can do your own expression reduction.
Tom's answer below is also correct an... |
For my assignment I need to read some strings coming from a serial port.
This has to be done in a kernel module, so I can't use stdio library.
I'm trying in this way:
```
#include <linux/module.h>
#include <linux/unistd.h>
#include <asm/io.h>
#include <asm/fcntl.h>
#define SERIAL_PORT "/dev/ttyACM0"
void myfun(void)... |
You want to use thefilp_open()function, it is pretty much a helper to open a file in kernelspace. You can find the man on ithere
The file pointer fromfilp_open()is of typestruct fileand don't forget to close it with filp_close() when you're done:
```
#include <linux/fs.h>
//other includes...
//other code...
st... |
I'm trying to measure some activity in C (Matrix multiplying) and noticed that I should do something like this:
```
clock_t start = clock();
sleep(3);
clock_t end = clock();
double elapsed_time = (end - start)/(double)CLOCKS_PER_SEC;
printf("Elapsed time: %.2f.\n", elapsed_time);
```
The output is:
```
Elapsed time... |
clockestimates the CPU time used by your program; that's the time the CPU has been busy executing instructions belonging to your program.sleepdoesn't perform any work, so it takes no noticeable CPU time (even if it takes wallclock time).
If you want to measure wallclock time, usetime:
```
time_t start = time(NULL);
... |
Here is my problem, I wrote a programa.exe, it can take several options, like"r:e:m:".r:andm:can't appear together, which means they run totally different tasks insidea.exe. Ande:is an optional option, if it shows up, then it should be withr:.
How should I implement this logic withgetopt?
|
You have to manually check for incompatible options. For example, when you see the-roption you set a flag saying "-ris found", if you then see the-moption you check to see if the "-ris found" flag is set, and print an error message telling the user about it.
|
```
char * return_buffer()
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s", "test");
return buffer;
}
```
buffer is created in the function, can I return the buffer directly? after the function returns, the buffer would disappear?
|
You are creating a statically allocated buffer, which means that it is being created on the stack. When the function returns, it will give you an address on the stack that is no longer in use. So if you make more function calls, the data it stores will likely corrupt.
It is much better to allocate it to the heap by c... |
```
void func(char a, int num)
{
printf("%c",a);
}
int main()
{
func("a", 6); //not func('a',6);
printf("\n");
func("b", 2); //not func('b',6);
}
```
I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?
|
It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.
|
After commenting Line 2 "Hello" is printed nine times but commenting Line 1 outputs "Hello" more than nine times. My question is what's the role of '\n' in this?
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int tmp[10], i, n=0;
for(i=0;i<9;i++)
{
tmp[i]=fork();
if(tmp[i]>0)
... |
\n also flushes the standard output buffer. If it is not present, it is possible that you have previously entered data in it. Flushing also means it forces printf to print on the screen as soon as \n is processed. Otherwise it is buffered output and you can never predict how long would OS buffer your output and when p... |
Incrementing integer pointer will increase the address by size of integer.
What will happen if we increment a function pointer?
|
Just as withvoid *pointers and pointers to incomplete types, arithmetic is not allowed on pointers to functions.
For example, C99 §6.5.6 on Additive operators says:
For addition, either both operands shall have arithmetic type, or one
operand shall be a pointer to an object type and the other shall have
integer ... |
I'm working on a puzzle right now....trying to writeif (x==5 || x==7)With bitwise operations (in C). Been working on it for a while....can't figure it out.
Any help would be appreciated! Thanks
Ps this isn't homework...trying to study for a test.
EDIT so the format would be something likeif (x _ _)with a bitwise op... |
7d = 111b and 5d = 101b
So bit 0 must be on, bit 1 is don't care, bit 2 must be on and bits 3-31 must be off.
So, mask out bit 1 and test for 101b
so your test becomes ((x & ~2) == 5)
Then ask Bing or wikipedia about "Karnaugh Maps" so you can do your own expression reduction.
Tom's answer below is also correct an... |
```
char * return_buffer()
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s", "test");
return buffer;
}
```
buffer is created in the function, can I return the buffer directly? after the function returns, the buffer would disappear?
|
You are creating a statically allocated buffer, which means that it is being created on the stack. When the function returns, it will give you an address on the stack that is no longer in use. So if you make more function calls, the data it stores will likely corrupt.
It is much better to allocate it to the heap by c... |
```
void func(char a, int num)
{
printf("%c",a);
}
int main()
{
func("a", 6); //not func('a',6);
printf("\n");
func("b", 2); //not func('b',6);
}
```
I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?
|
It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.
|
After commenting Line 2 "Hello" is printed nine times but commenting Line 1 outputs "Hello" more than nine times. My question is what's the role of '\n' in this?
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int tmp[10], i, n=0;
for(i=0;i<9;i++)
{
tmp[i]=fork();
if(tmp[i]>0)
... |
\n also flushes the standard output buffer. If it is not present, it is possible that you have previously entered data in it. Flushing also means it forces printf to print on the screen as soon as \n is processed. Otherwise it is buffered output and you can never predict how long would OS buffer your output and when p... |
Incrementing integer pointer will increase the address by size of integer.
What will happen if we increment a function pointer?
|
Just as withvoid *pointers and pointers to incomplete types, arithmetic is not allowed on pointers to functions.
For example, C99 §6.5.6 on Additive operators says:
For addition, either both operands shall have arithmetic type, or one
operand shall be a pointer to an object type and the other shall have
integer ... |
I'm working on a puzzle right now....trying to writeif (x==5 || x==7)With bitwise operations (in C). Been working on it for a while....can't figure it out.
Any help would be appreciated! Thanks
Ps this isn't homework...trying to study for a test.
EDIT so the format would be something likeif (x _ _)with a bitwise op... |
7d = 111b and 5d = 101b
So bit 0 must be on, bit 1 is don't care, bit 2 must be on and bits 3-31 must be off.
So, mask out bit 1 and test for 101b
so your test becomes ((x & ~2) == 5)
Then ask Bing or wikipedia about "Karnaugh Maps" so you can do your own expression reduction.
Tom's answer below is also correct an... |
I figure usingfgetsis the best option, but apparently it takes input from stdin? How do I generate a random number usingrand(), and store it?
|
You can usesprintf():
```
char buf[11];
int r = rand();
sprintf(buf, "%d", r);
```
A more robust option is to usesnprintf()if your runtime library offers it:
```
snprintf(buf, sizeof(buf), "%d", r);
```
Usingsnprintf()in this way ensures that the resulting string will not overflow the bounds ofbuf.
|
I'm trying to create a file and copy to it a random chars of 256 MB sizes all by System Calls operations and I just can't understand how should I do that.
Obviously I need the file to be txt file so when I tried to use thecreatfunction with O_RDWR flag but it didn't creat a txt file, it was something unknown which I ... |
The second argument ofcreat()is not the same as ofopen().
The constantO_RDWRis defined as 2 and is misinterpreted as the file mode bits, which means you can't read the file.
|
I had a program that worked properly with Mac OS 10.6 but inexplicably fails in 10.8. The gist of it is that sendto is now returning -1 and setting errno to EINVAL (22). What's going wrong?
|
The address I was giving sendto came from the first result of getaddrinfo. Turns out that first result is now an IPV6 result (using sockaddr_in6). sendto on OS 10.8 (at least for now) only seems to work with sockaddr_in address. Make sure to pass a hint to getaddrinfo that says you only want ipv4 addresses, i.e.
```... |
I need to include a#defineat the top of around 300 .c files. I would prefer not to change the code as it is open source code but if I have to I will just write a script to modify all the files. Is there a way using gcc to add a#defineor header file include to the top of every source file during compilation? The#def... |
You can pass-Dmalloc=MYmallocto thegccoptions.
For more information about the-Doption:
http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html
Note that if you want to modify the behavior ofmallocfunction for debugging purposes, you may also be interested inglibcmallochooks:
http://www.gnu.org/software/libc/ma... |
Why this code isn't working ? (This is not the actual code, but a simplified version)
```
#include <stdio.h>
#define NUMBER 5
int function( int NUMBER );
int main (void)
{
function( NUMBER );
return 0;
}
int function( int NUMBER )
{
printf("Hi %d\n", NUMBER);
return 0;
}
```
|
```
#define NUMBER 5
int function( int NUMBER );
```
#defineis a pre-processor macro, simple text replacement. So, let's look at what you are really trying to compile:
```
int function( int 5 );
```
Which makes no sense. This part is fine:
```
int main (void)
{
function( NUMBER );
return 0;
}
```
Be... |
Here is the situation:
A process has two pages vp1 and vp2. These two pages are mapped to 2 physical pages or 2 pages in the swap. Let's call these physical (or in swap) pages pp1 and pp2. The mapping is:
vp1->pp1
vp2->pp2
Now, if I want to change the mapping to:
vp1->pp2
vp2->pp1
That means, reading from vp2 b... |
Yes, but you have to do some work first. One way to accomplish this is to create two shared memory objects. Then you can map and unmap the shared memory objects in the process address space. See the system callsshmat,shmdt,shmget, andshmctlfor details.
Mapping and unmapping is likely to take considerable time, so it ... |
For a college assignment we have to add a system call to the Linux kernel. I have "Hello, World" done no problem. In terms of adding a more complicated call, I know (or at least think) I can't use C functions like malloc, but I'm wondering can I use syscall() to use other system calls?
|
The kernel has its own specific calls for pretty much everything. You don't have access to system calls or<sys/xxxx.h>header files.
For your exmaple, yes, you can't usemalloc()but you can usekmalloc()
In older versions of the kernel (2.4) you could usesyscall()via:syscallN()macros. I'm pretty sure that's been remove... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:what does “%.*s” mean in printf in c
I know this question has for sure been asked elsewhere, but searching "%.*s" yields nothing meaningful on SO. Could someone please explain the following line to me?
printf("%.*s", len, buffer);
|
It limits the output to at mostlencharacters. The.starts the 'precision'; the*says 'use anintfrom the argument list to determine the precision'. Note that the 'string' (buffer) does not even have to be null terminated if it is longer thanlen.
All this is easily found in the manual page forprintf().
|
I know thatFILETIMEstructure formed datetime value in 100 nanosecond step from 1st of Jan 1601. But what does meandwLowDateTime's value that less then 0???
|
It means you are viewing it as an int rather than an unsigned int and hence it can show negative.
As Matteo Italia says you are better off placing it in a ULARGE_INTEGER as follows:
```
ULARGE_INTEGER uli;
uli.LowPart = ft.dwLowDateTime;
uli.HighPart = ft.dwHighDateTime;
__int64 filetime64 = uli.QuadPart;
```
You ... |
I am unable to understand what this macro does. These are defined inlinux-kernelbut my doubt is independent of that. I am unable to understand what does(((x)+(mask))&~(mask))line does.
```
#define ALIGN(x,a) __ALIGN_MASK(x,(typeof(x))(a)-1)
#define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask))
```
Any ... |
Say you have a number:0x1006
For some reasons you want to align it to a4bytes boundary.
With a 4-byte boundary, you know aligned values are0x1000,0x1004,0x1008, etc.
You then also know the aligned value of0x1006is0x1008.
How would you get0x1008? The alignment mask for alignment value4is(4 - 1) = 0x03
Now0x1006 + 0... |
I wish to bind a texture on a cube (creating cube using GlutSolidCube and not glvertex) but the whole texture is bound. In the image file I have all textures together (for speed and because the teacher requested) and I only want part of the texture to be bound. How can I do that????
|
Textures are the unit of texture binding. If you want to "cut out" part of a texture, you do so by adjusting the texture coordinates that you use.
Instead of using the full range of 0..1, use smaller values that match the sub-texture's location inside the texture.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Double comparison
```
int x=-1;
if(0<=x<=9)
std::cout<< "Without Logical operator";
if (0<=x && x<=9)
std::cout<< "With Logical operator";
```
I know about 2ndifIt's working fine.
What's happening here in the 1stifcondition .... |
In C, boolean values are just plain integers. In boolean context,0is false, and all other values are true. In this case,
```
(0 <= x <= 9) ==
((0 <= x) <= 9) == // the (0 <= x) evaluates to 0, which is false in boolean context
(0 <= 9) ==
1 (true)
```
|
I have this piece of code that produces some output with printf statements on the console. I want to somehow collect the data into a .txt file when I run this code multiple times with different variables, for example if my program is called "produce", I want to get the outputs of:
```
./produce 0
./produce 1
./produc... |
You can write a simple shell script for this.
```
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "Output of produce for $i" >> output.txt
./produce $i >> output.txt
done
```
Put the above code in a file like test.sh. And then run the commandsh test.shon the console and you should be seeing the file output.txt getting created... |
Does Python change my string??
The related question isI was using a little shellcode in my python but failed
PS: I was doubting what's is the end charecter of Python String or C string, if the string have the end charecter, how to deal with it? Does this related to this question?
|
```
>>> chr(int('49', 16))
'I'
```
Actually,\x49isI.
A word of explanation about this:
\x49means "Char with code 49 in hex. 49 in hex isint('49', 16):73.73is the ASCII character code forI, which you can verify with:ord('I'):73.
|
We can pass an array as a variable in a C/C++ function header, as in
```
int func(int arr[]) { ... }
```
I'm wondering: Is it ever possible that something goes inside the[]in a variable that's passed into the function header, or is it always empty?
|
For any (non-reference) typeT, the function signaturesR foo(T t[])andR foo(T t[123])(or any other number) are identical toR foo(T * t), and arrays are passed by passing the address of the first element.
Note thatTmay itself be an array type, such asT = U[10].
|
```
HANDLE pipe = CreateFile( L"\\\\.\\pipe\\my_pipe",
GENERIC_READ, // only need read access
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NOR... |
Windows doesn't follow the UNIX philosophy "everything is a file", so the named objects you create with the kernel APIs aren't files, but are objects in various NT objects namespaces. You can see them with tools likeWinObj.
You may want to have a look at the article about theobject managerin Windows.
|
I'm trying to create a file and copy to it a random chars of 256 MB sizes all by System Calls operations and I just can't understand how should I do that.
Obviously I need the file to be txt file so when I tried to use thecreatfunction with O_RDWR flag but it didn't creat a txt file, it was something unknown which I ... |
The second argument ofcreat()is not the same as ofopen().
The constantO_RDWRis defined as 2 and is misinterpreted as the file mode bits, which means you can't read the file.
|
I had a program that worked properly with Mac OS 10.6 but inexplicably fails in 10.8. The gist of it is that sendto is now returning -1 and setting errno to EINVAL (22). What's going wrong?
|
The address I was giving sendto came from the first result of getaddrinfo. Turns out that first result is now an IPV6 result (using sockaddr_in6). sendto on OS 10.8 (at least for now) only seems to work with sockaddr_in address. Make sure to pass a hint to getaddrinfo that says you only want ipv4 addresses, i.e.
```... |
I need to include a#defineat the top of around 300 .c files. I would prefer not to change the code as it is open source code but if I have to I will just write a script to modify all the files. Is there a way using gcc to add a#defineor header file include to the top of every source file during compilation? The#def... |
You can pass-Dmalloc=MYmallocto thegccoptions.
For more information about the-Doption:
http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html
Note that if you want to modify the behavior ofmallocfunction for debugging purposes, you may also be interested inglibcmallochooks:
http://www.gnu.org/software/libc/ma... |
Why this code isn't working ? (This is not the actual code, but a simplified version)
```
#include <stdio.h>
#define NUMBER 5
int function( int NUMBER );
int main (void)
{
function( NUMBER );
return 0;
}
int function( int NUMBER )
{
printf("Hi %d\n", NUMBER);
return 0;
}
```
|
```
#define NUMBER 5
int function( int NUMBER );
```
#defineis a pre-processor macro, simple text replacement. So, let's look at what you are really trying to compile:
```
int function( int 5 );
```
Which makes no sense. This part is fine:
```
int main (void)
{
function( NUMBER );
return 0;
}
```
Be... |
Here is the situation:
A process has two pages vp1 and vp2. These two pages are mapped to 2 physical pages or 2 pages in the swap. Let's call these physical (or in swap) pages pp1 and pp2. The mapping is:
vp1->pp1
vp2->pp2
Now, if I want to change the mapping to:
vp1->pp2
vp2->pp1
That means, reading from vp2 b... |
Yes, but you have to do some work first. One way to accomplish this is to create two shared memory objects. Then you can map and unmap the shared memory objects in the process address space. See the system callsshmat,shmdt,shmget, andshmctlfor details.
Mapping and unmapping is likely to take considerable time, so it ... |
For a college assignment we have to add a system call to the Linux kernel. I have "Hello, World" done no problem. In terms of adding a more complicated call, I know (or at least think) I can't use C functions like malloc, but I'm wondering can I use syscall() to use other system calls?
|
The kernel has its own specific calls for pretty much everything. You don't have access to system calls or<sys/xxxx.h>header files.
For your exmaple, yes, you can't usemalloc()but you can usekmalloc()
In older versions of the kernel (2.4) you could usesyscall()via:syscallN()macros. I'm pretty sure that's been remove... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:what does “%.*s” mean in printf in c
I know this question has for sure been asked elsewhere, but searching "%.*s" yields nothing meaningful on SO. Could someone please explain the following line to me?
printf("%.*s", len, buffer);
|
It limits the output to at mostlencharacters. The.starts the 'precision'; the*says 'use anintfrom the argument list to determine the precision'. Note that the 'string' (buffer) does not even have to be null terminated if it is longer thanlen.
All this is easily found in the manual page forprintf().
|
I know thatFILETIMEstructure formed datetime value in 100 nanosecond step from 1st of Jan 1601. But what does meandwLowDateTime's value that less then 0???
|
It means you are viewing it as an int rather than an unsigned int and hence it can show negative.
As Matteo Italia says you are better off placing it in a ULARGE_INTEGER as follows:
```
ULARGE_INTEGER uli;
uli.LowPart = ft.dwLowDateTime;
uli.HighPart = ft.dwHighDateTime;
__int64 filetime64 = uli.QuadPart;
```
You ... |
I am unable to understand what this macro does. These are defined inlinux-kernelbut my doubt is independent of that. I am unable to understand what does(((x)+(mask))&~(mask))line does.
```
#define ALIGN(x,a) __ALIGN_MASK(x,(typeof(x))(a)-1)
#define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask))
```
Any ... |
Say you have a number:0x1006
For some reasons you want to align it to a4bytes boundary.
With a 4-byte boundary, you know aligned values are0x1000,0x1004,0x1008, etc.
You then also know the aligned value of0x1006is0x1008.
How would you get0x1008? The alignment mask for alignment value4is(4 - 1) = 0x03
Now0x1006 + 0... |
I wish to bind a texture on a cube (creating cube using GlutSolidCube and not glvertex) but the whole texture is bound. In the image file I have all textures together (for speed and because the teacher requested) and I only want part of the texture to be bound. How can I do that????
|
Textures are the unit of texture binding. If you want to "cut out" part of a texture, you do so by adjusting the texture coordinates that you use.
Instead of using the full range of 0..1, use smaller values that match the sub-texture's location inside the texture.
|
I'm developing a C++ application which needs to connect to MySQL server for some information but my app doesn't run queries frequently. So As C++ connector uses C API behind the scenes... I got this doubt.I'm in dilemma whether to go with C API or C++ API??
|
From my experience it doesn't make that much of a difference. The C++ API just wraps the C API – so you're left with an additional function call using the C++ API. Most of the time the compiler can optimize that out and a function call does not have a real perceivable overhead.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.