question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
```
int findNumber(char *exp,int i,int *num)
{
int k=i;
char *p;
p=exp[i]; //<-- here
while(*p>='0'&&*p<='9')
{
(*num)=(*num)*10+(*p);
k++;
p++;
}
return k;
}
```
i keep getting that error in line: (p=exp[i];)
Im trying to send a char array, an... |
pis achar*so you need to assign a pointer to it butexp[i]returns a singlecharelement from an array. Try
```
p = &exp[i];
```
or
```
p = (exp + i);
```
instead.
|
```
int f(int n)
{
int i, c = 0;
for (i=0; i < sizeof(int)*8; i++, n >>= 1)
c = (n & 0x01)? c+1: c;
return c;
}
```
It's an exercise I found on my book, but I really don't get It!
|
It counts the number of bits set in the passed in parametern(assuming your machine has 8-bit bytes). I'll comment inline with your code (and fix the terrible formatting):
```
int f(int n)
{
int i; // loop counter
int c = 0; // initial count of set bits is 0
// loop for sizeof(int) * 8 bits (probably... |
I have gcc 4.7.2-3 and I get this following error:
main.c:5:6: error: array size missing in ‘fname’
main.c:6:6: error: array size missing in ‘lname’
when initializing this:
```
int fname[];
int lname[];
```
Is this no longer possible using higher versions of gcc? Because I am certain I have used this before...
E... |
You can only declare an array with no size if you are initializing it right away
```
int myarr[] = {1, 2, 3};
```
or if it is the last member in a structure
```
struct foo {
int something;
int somethingelse;
char emptyarr[];
};
```
|
For C/C++ applications in Windows(non GUI), what should be the proper list of error codes for different failures? I have seen various lists such as from IBM and others, but I was wondering if there was some consensus on typical error codes given to the user when the program exits.
|
There are three portable values for the argument toexit:0,EXIT_FAILURE, andEXIT_SUCCESS.0is equivalent toEXIT_SUCCESS.
|
The code is self-explanatory, but it gives me segmentation fault, why? :\
```
#include <stdio.h>
int main(void)
{
char *c = "Hella";
*(c+4) = 'o';
printf("%s\n",c);
}
```
|
How to avoid it?
Don't modify a string literal!
```
char *c = "Hella";
```
Declares a pointercto a string literal "Hella" stored in implementation defined read only memory.You are not allowed to modify this literal. An attempt to do so results inUndefined Behavior.
You are lucky that your program crashes, an Undef... |
I am tryling to learn C and now i am a floats. I know all values have different sizes on different machines. But i am trying to learn the concept.
Lets say a float is saved in 4 bytes. I read that the first bit is the sign bit, which decide if the number is positve or negative. Then the next 7 bits is the exponent an... |
I wrote this a few years ago.I think it should help you understand how floating point numbers are represented:
http://www.eosgarden.com/en/articles/float/
Basically, the formula for normalized numbers is:-1^S * 1.M * 2^( E - 127 )whereSis the sign,Mthe mantissa, andEthe exponent. But everything is explained in detai... |
I'm sending many TCP packets each of size 50 bytes over the network. Later I found it out TCP aggregates a few 50 byte packets into a single TCP packet. My question is, is there a way to avoid TCP aggregation in 'C' program?
|
Packing multiple sent packets into a single TCP packet is handled using an algorithm known asNagle's algorithm. To disable it,set theTCP_NODELAYoption on your socket:
```
int flag = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
```
Note that this decreases the efficiency of your network, and shou... |
I am developing a cross-platform library, and am trying to test on Android. I have compiled my library with ndk-build, and am trying to compile and run a command-line test fixture we have for the library.
I useadb pushto put the test fixture and .so in/data/local/tmpandchmodboth to 777.
Then I useadb shellto run the... |
I found I can add the path/data/local/tmptoLD_LIBRARY_PATHand it will work, however when usingadb shellcommands in a script, each "adb shell" is a new instance, soLD_LIBRARY_PATHis reset
|
I am writing a small console-like program in C, along with implementations for ls, tac and dir.
I use execvp() function to override the forked children of the process, but when the user inserts one of the above 3 commands, I have to execute my own version, not the one from the system.
I know that execvp() uses the s... |
You can changePATHwithsetenv-- but mind you, it might be simpler to just check for those commands explicitly before doing theexec.
|
What does the C/C++-Standard guarantee about the minimum significant decimal digits of adouble?
The C++ standard actually says in a footnote of § 18.3.2.4/10 this is equivalent toDBL_DIGas defined in the C standard. But I can't find anything about a minimum value in the C standard.
So, what is the minimum value of ... |
You won't find it in the C++ standard, because C++ defers to the C standard on this one. For decimal digits, the minimum values are:
```
FLT_DIG 6
DBL_DIG 10
LDBL_DIG 10
```
So, 6 digits forfloat, and 10 fordoubleandlong double. (This is the number of digits for which it is guaranteed that a conversion from tex... |
I'm sending many TCP packets each of size 50 bytes over the network. Later I found it out TCP aggregates a few 50 byte packets into a single TCP packet. My question is, is there a way to avoid TCP aggregation in 'C' program?
|
Packing multiple sent packets into a single TCP packet is handled using an algorithm known asNagle's algorithm. To disable it,set theTCP_NODELAYoption on your socket:
```
int flag = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
```
Note that this decreases the efficiency of your network, and shou... |
I am developing a cross-platform library, and am trying to test on Android. I have compiled my library with ndk-build, and am trying to compile and run a command-line test fixture we have for the library.
I useadb pushto put the test fixture and .so in/data/local/tmpandchmodboth to 777.
Then I useadb shellto run the... |
I found I can add the path/data/local/tmptoLD_LIBRARY_PATHand it will work, however when usingadb shellcommands in a script, each "adb shell" is a new instance, soLD_LIBRARY_PATHis reset
|
I am writing a small console-like program in C, along with implementations for ls, tac and dir.
I use execvp() function to override the forked children of the process, but when the user inserts one of the above 3 commands, I have to execute my own version, not the one from the system.
I know that execvp() uses the s... |
You can changePATHwithsetenv-- but mind you, it might be simpler to just check for those commands explicitly before doing theexec.
|
What does the C/C++-Standard guarantee about the minimum significant decimal digits of adouble?
The C++ standard actually says in a footnote of § 18.3.2.4/10 this is equivalent toDBL_DIGas defined in the C standard. But I can't find anything about a minimum value in the C standard.
So, what is the minimum value of ... |
You won't find it in the C++ standard, because C++ defers to the C standard on this one. For decimal digits, the minimum values are:
```
FLT_DIG 6
DBL_DIG 10
LDBL_DIG 10
```
So, 6 digits forfloat, and 10 fordoubleandlong double. (This is the number of digits for which it is guaranteed that a conversion from tex... |
I realise this is a strange question perhaps, but if say I have a program which can send commands to system like:
```
system(command);
```
The program can run and send commands to other programs via parameters like "ls -l".
However, if I have a program that requires interactive input e.g. make use of scanf, is ther... |
is there a straightforward approach to enabling my C program to
effectively interact with it.
Yes, you're probably looking forpopen(3). It lets you run a command and gives you aFILE *attached to itsstdin/stdout.
Sadly, on Linux it's one-way: stdinorstdout, not both at the same time. At least one other implementati... |
I have this struct in a file "vector.c":
```
struct Vector
{
int * m_items;
int m_size;
int m_extSize;
int m_numItems;
};
```
On "main.c" I'm trying to check if the value m_items of a certain vector is NULL :
```
if (! vec->m_items)
printf("not fail\n");
```
I do it after initializing "vec" with values - t... |
You have to move the entire definition ofVectorto a header file and include it in both vector.c and main.c.
Adding atypedef struct Vector Vector;is not enough. That merely tells the compiler that there is a typeVectorand is defined elsewhere, so, it is incomplete. It lets you declare pointers to it because it doesn't... |
I have 3 console programs (.exe), and I want to run them from one console application without showing the windows of the 3 console programs.
All programs are written in VC++.
Any suggestions about how I can do this?
|
You can use ShellExecute command to run the other application
|
My system is a x86-64 Linux, and I try to execute the code in the stack or data segment on the system. In detail, I first placed a piece of binary instructions into an integer array(I tried to place the array in either stack or data segment) , then replaced normal function return address with the array address. Every ... |
Almost all modern general purpose architectures have a way to prevent you from executing certain memory regions. It depends on the operating system if the operating system uses those facilities. Linux disables execution on the stack and most data on the architectures where it's easy to do. x86_64 is one of those.
|
If I have something like this
```
if(pointer!=NULL&&(*pointer)==x) { ... }
```
Will it segfault if pointer is NULL? If it is compiler specific, I'd like to know how it is in GCC.
|
No, because ofshort circuit evaluation.
If the LHS isfalse, then the RHS won't be evaluated. Therefore, if it's aNULLpointer, it will never hit the RHS and attempt to dereference it.
|
I have a project in C that I need to modify and run. At some point, in a source file I have
```
#ifndef THE_FLAG
// declare important stuff
#endif
```
but, I don't know whereTHE_FLAGis#included from. It isnotdefined in my project, and it is hidden somewhere in external library.
I triedgcc -Mbut it shows the headers... |
Try compiling withgcc -E. This will tell gcc to stop at the preprocessing stage. As part of that, it will tell you where all the#defines came from.
Note that this will create a text file, not a.ofile.
|
IIRC, there are two flavours of XML parsers: DOM, and SAX. SAX is required to parse the XML document from top-to-bottom without any form of reordered (and is event-based), whilst DOMI believeis allowed to reordered.
Is that correct? And would reading thexmlDocPtrreturned fromxmlReadFilepotentially be out of order (I'... |
libxml2 supports both DOM and SAX parsing. Its DOM parser is actually built on top of its SAX parser. So the DOM output would maintain document order. I have never heard of a DOM parser reordering XML nodes.
|
Hi I have written a decibel level meter in C which reads Linux alsa constantly and output decibel levels numbers in STDOUT.
Now I would like to view via HTTP and streaming live data to clients, with proper js+html decoration, it behaves as a noise meter, with graph and needles.
Therefore I would like to know if some... |
You can use several C libraries. Some C libraries provide HTTP server abilities, e.g.libonionorlibmicrohttpd. Other libraries provide HTTP client abilities, e.g.libcurl
All are using some event loop, e.g.libev,libeventor at least some multiplexing syscall likepoll(2)
You could also make your application a FASTCGI ap... |
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
SVGAlibmight be what you're looking for - a C graphics library that works without X11.
|
When writing a non-blocking program (handling multiple sockets) which at a certain point needs to open files using open(2), stat(2) files or open directories using opendir(2), how can I ensure that the system calls do not block?
To me it seems that there's no other alternative than using threads or fork(2).
|
As Mel Nicholson replied, for everything file descriptor based you can useselect/poll/epoll. For everything else you can have a proxy thread-per-item (or a thread pool) with thesmall stackthat would convert (by means of the kernel scheduler) any synchronous blocking waits to select/poll/epoll-able asynchronous events ... |
If I have something like this
```
if(pointer!=NULL&&(*pointer)==x) { ... }
```
Will it segfault if pointer is NULL? If it is compiler specific, I'd like to know how it is in GCC.
|
No, because ofshort circuit evaluation.
If the LHS isfalse, then the RHS won't be evaluated. Therefore, if it's aNULLpointer, it will never hit the RHS and attempt to dereference it.
|
I have a project in C that I need to modify and run. At some point, in a source file I have
```
#ifndef THE_FLAG
// declare important stuff
#endif
```
but, I don't know whereTHE_FLAGis#included from. It isnotdefined in my project, and it is hidden somewhere in external library.
I triedgcc -Mbut it shows the headers... |
Try compiling withgcc -E. This will tell gcc to stop at the preprocessing stage. As part of that, it will tell you where all the#defines came from.
Note that this will create a text file, not a.ofile.
|
IIRC, there are two flavours of XML parsers: DOM, and SAX. SAX is required to parse the XML document from top-to-bottom without any form of reordered (and is event-based), whilst DOMI believeis allowed to reordered.
Is that correct? And would reading thexmlDocPtrreturned fromxmlReadFilepotentially be out of order (I'... |
libxml2 supports both DOM and SAX parsing. Its DOM parser is actually built on top of its SAX parser. So the DOM output would maintain document order. I have never heard of a DOM parser reordering XML nodes.
|
Hi I have written a decibel level meter in C which reads Linux alsa constantly and output decibel levels numbers in STDOUT.
Now I would like to view via HTTP and streaming live data to clients, with proper js+html decoration, it behaves as a noise meter, with graph and needles.
Therefore I would like to know if some... |
You can use several C libraries. Some C libraries provide HTTP server abilities, e.g.libonionorlibmicrohttpd. Other libraries provide HTTP client abilities, e.g.libcurl
All are using some event loop, e.g.libev,libeventor at least some multiplexing syscall likepoll(2)
You could also make your application a FASTCGI ap... |
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
SVGAlibmight be what you're looking for - a C graphics library that works without X11.
|
When writing a non-blocking program (handling multiple sockets) which at a certain point needs to open files using open(2), stat(2) files or open directories using opendir(2), how can I ensure that the system calls do not block?
To me it seems that there's no other alternative than using threads or fork(2).
|
As Mel Nicholson replied, for everything file descriptor based you can useselect/poll/epoll. For everything else you can have a proxy thread-per-item (or a thread pool) with thesmall stackthat would convert (by means of the kernel scheduler) any synchronous blocking waits to select/poll/epoll-able asynchronous events ... |
I want to implement an algorithm that:
takes database objects from a Ruby on Rails application as inputs,performs calculations on the inputs,queries the Rails database based on the calculations,and produces an ordered set of results based on the queries.
I am going to write the algorithm in C (maybe Objective-C?) fo... |
You can use RubyInline[1] to write C code within Ruby code. You could also create an extension [2].
[1]http://rubyinline.rubyforge.org/RubyInline/
[2]http://blog.jcoglan.com/2012/07/29/your-first-ruby-native-extension-c/
|
How does the process of building (compiling and linking) source code in D differ from C/C++ especially with regards to inline functions, D's module system (instead of headers) and build tools. How are template instantiations reused in D?
|
it doesn't differ that much, each module gets compiled to its own obj file which then gets linked together which IIRC isn't that different from C/C++ process
the main difference however lie in that the imports aresymbolicinstead of C's whole file#includewhich eliminates the need to headerfiles (though the option for ... |
I need to know what it means when a function has avoid *parameter. For example:
```
function(void * param){}
```
|
It is a function that receives avoid*. This may be used to pass any kind of pointer in C.
A good example is thepthread_createfunction, and the pthread start routine.
Note, however, that if no return type is specified, it defaults to return anint, which it does not in your example.
|
I need to encode a few instructions like
```
mov eax, edx
inc edx
```
to the corresponding x86_64 opcodes. Is there any library (not an entire asm compiler) to accomplish that easily?
|
You could take open sourceFASMorNASMand use their parser.
|
I was reading through the aircrack-ng source code and noticed many different uses of struct.
For example:
struct option {...} opt;typedef struct {...} vote;
I thought that the general format of struct was
struct var {...};
or
typedef struct var {...} foo;
What is the purpose ofoptand how comevotedoesn't have typ... |
typedefcreates a type alias. With:
```
typedef struct { /* ... */ } vote;
```
We create ananonym structure, from whichvoteis an alias.
```
struct option { /* ... */ } opt;
```
It declares the typestruct option, and a variableoptof typestruct option.
|
So I have a char array in C...for example:
```
uchar arr[3] = { 0x34, 0x45, 0xFF }
```
I am looking for a fast way to add an integer to it (like its 0x3445FF) so for example if I add 2 to arr I get:
```
{ 0x34, 0x46, 0x01 }
```
|
The easiest and best way will be to convert to int, add, and then convert back. Also, you need to decide on the byte-order since it's never clear.
This code assumes big-endian, i.e. the array initially holds the number 0x3445ff:
```
uint8_t arr[] = { 0x34, 0x45, 0xff };
uint32_t x = (arr[0] << 16) | (arr[1] << 8] |... |
I'm having some trouble reading anunknownamount of bytes (raw data,may contain NULLs) from a device using c in Linux. How can I read the device for "as long as it's ready to be read"? (hopefully without reading 1 byte at a time).
|
Well if you're usingreadyou'll either block if there's no data, or succeed if there was data to read. If there was data to read you'll get either the amount you wanted, or an amount less if there's no more to read. Look at the return value of read to determine how much you have. You could make it non-blocking but the ... |
I have a code, that is split into multiple files, and which has to use a lot of constant strings(hundreds), and many of them have to be accessed from functions located in several files, what is the most convenient way to do this?
|
You can make a header called e.g.,global.hand put your constants on it and include where the constants is needed(in fact,you will include for context,because you need to useinclude guardsfor avoid redefinition error)
|
I am trying to affinitise the completion of CompleteRequest to the CPU that originally issued the request. Is there a way to retrieve the CPU that issued the request during FdoDeviceControl or any onother way to see where the request came from before it entered the dispatch queue?
|
Once you are in a DPC routine it's too late to tell where the request originated. You need to call KeGetCurrentProcessorNumberEx() before you queue the request to a DPC queue. I assume the request is an IRP...?
|
I want to block the user to backup files to optical discs, so I have to determine if a CDROM drive is writable.
How to do under Windows?
|
The drive index (0 = A, 1 = B, etc) for the Windows CD burner can be found in the registry atHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CD Burning\DriveIndex.
|
I was going through the linux kernel sources and found this function definition.
```
function(struct net * const *pnet)
```
Can somebody explain what does this mean. Is it a net* or net** or const net* or const net**?
Thanks
|
pnet is a pointer to a const point to a struct net (in a case like this, you just read from right to left from the name of the variable to the name of the type, reading*as "pointer).
|
The following code is used to print anint. How can I modify it to print along long int? Please explain.
Forpc, readputchar_unlocked
```
inline void writeInt (int n)
{
int N = n, rev, count = 0;
rev = N;
if (N == 0) { pc('0'); pc('\n'); return ;}
while ((rev % 10) == 0) { count++; rev /= 10;}
rev ... |
There's nothing specific about int in the code. Just replace both occurrences of "int" by "long long int", and you're done.
(I find the "optimization" of *10 via shift and add quite ridiculous with all the divisions that remain. Any decent C compiler will do that (and much more) automatically. And don't forget to pro... |
I need to useerl_interfacein my C-program. There is Erlang R15B01 on Debian Wheezy.
I just do the following (for example).
```
// main.c
#include <ei.h>
#include <erl_interface.h>
int main() {
erl_init(NULL,0);
return 0;
}
```
Then i say:
```
cc -I/usr/lib/erlang/lib/erl_interface-3.7.7/include -L/usr/lib... |
Newest versions of the GNU toolchain require that the object files and libraries be specified in the same order their symbols depend on each other. So you should generallyput the library flags to the end of the invocation,like this:
```
gcc -o prog main.c -L<libdir> -I<includedir> -lerl_interface -lei
```
|
I have an array of char arrays in C (not C++). The type is char**. I know it's length, but the lengths of the elements are unknown.
and I have another char* array.
Need to append this char* to my char**, as the last element.
|
char* arr1[]; //known length with some already filled elements
each element of the above array is a pointer to character array.
char *new = "lastElem" // this is the string you have to append
let us say, arr1 has n elements(each a string). Then,
arr1[++n] = new; // this should do it, provided space exists in arr1... |
I understand that-D_FILE_OFFSET_BITS=64causesoff_tto be 64bits. So what does-D_LARGEFILE_SOURCEdo that isn't already done by-D_FILE_OFFSET_BITS=64? What do these definitions do exactly?
|
The GLIBCFeature test macrosdocumentation states:
_LARGEFILE_SOURCEIf this macro is defined some extra functions are available which rectify a few shortcomings in all previous standards. Specifically, the functions fseeko and ftello are available. Without these functions the difference between the ISO C interface (fs... |
```
typedef struct all{
int x;
int ast[5];
}ALL;
ALL x[5];
int main(void){
ALL y[5];
// ...
}
```
How will I be able to set a constant value toast[5]so that all array variables will have the same value ofast[]?
|
```
typedef struct all {
int x;
int ast[5];
} ALL;
ALL x[5];
ALL constast = {0, {1, 2, 3, 4, 5}};
int main(void) {
ALL y[5] = {[0] = constast, [1] = constast, [2] = constast,
[3] = constast, [4] = constast};
// ...
}
```
|
I am currently coding a program for an assignment involving customer orders... So far everything has been coded correct but now i have a problem when it comes to reading user input.. 2 lines are appearing on the screen without giving the user time to enter the order quantity.. This is because i am using scanf.. i trie... |
You can try usinggetchar()afterscanf()
|
We all know this famous macro example:
```
#define max(a,b) ((a) > (b) ? (a) : (b))
```
And, since it usesaandbtwice, it becomes inaccurate when we do something like:
```
max(x, y++); // because this gets translated to...
((x) > (y++) ? (x) : (y++)); // y is incremented twice
```
InEffective C++, Scott Meyers pres... |
In case of GCC you can usetypeofextension, like this:
```
#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; })
```
|
I was just wondering if a variable declared and defined inside a structure can be initialized to a certain value, was planning on using function pointers to mimic the classes in OOP.
Example COde:
```
typedef struct{
int x;
int (*manipulateX)(int) = &manipulateX;
}x = {0};
void main()
{
getch();
}
int manipula... |
Starting with C99, you can usedesignated initializersto set fields of structures to values, as follows:
```
struct MyStruct {
int x;
float f;
};
void test() {
struct MyStruct s = {.x=123, .f=456.789};
}
```
|
What is the most portable way to access locale information?
I'm interested in time locale data, such as month names, day of week names, local time format etc.
Ideally I'd like a POSIX interface, but if it doesn't exist, glibc-specific one will do.
If possible, getting the information about the locale X shouldn't re... |
nl_langinfois a POSIX-standard interface for returning that information and appears to have available all of the things that you're looking for. Sadly, it does require that you callsetlocalebefore calling it. I don't see an interface that lets you query an arbitrary locale without first making it the current locale.... |
Here is my code:
```
void a_simple_func_with_variable_argument(int, ...);
void a_simple_func_with_variable_argument(int start, ...) {
va_list pa;
char ch;
va_start(pa, start);
while(ch = va_arg(pa, char)) {
printf("%c, ", ch);
}
printf("End\n");
va_end(pa);
}
...
//call the func above in somewhere
... |
You need to be careful withchar; it's automatically promoted tointin a variadic function. You will need to passintas the second arg tova_arg.
|
I want to get the transition time for DST
Under Linux with giving time zone or TZ env.
My way is stupid, giving the start of the year and try every hour then check tm_isdst value of local time to get the transition time.
Is there some simple way to do this?
|
There is the source code in glibc, which you can browse here:http://sourceware.org/git/?p=glibc.git;a=tree;f=timezone
Or you can use the timezone database here:ftp://ftp.iana.org/tz/releases/tzdata2012c.tar.gz
Since you haven't given a particular timezone/location, I can't look up and give you the exact information ... |
Here is an extract of the FreeRTOS api-referencehttp://www.freertos.org/a00122.htmlregarding the xSemaphoreTake() function:
```
// See if we can obtain the semaphore. If the semaphore is not available
// wait 10 ticks to see if it becomes free.
if( xSemaphoreTake( xSemaphore, ( portTickType ) 10 ) == pdTRUE )
{
// We... |
As of the example you link to, within the if (...) body the semaphore is taken. If you're copy-pasting from that example, it's up to you to ensure that you have both xSemaphoreTake and xSemaphoreGive in your program.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:How to know a process is 32-bit or 64-bit programmatically
I'm writing an app that injects a dll into other applications. In order for this to work properly, I need to know if the other application is running in 32 or 64 bit mode. Is the... |
Try the code from this page, it takes the size of an int to check, if you want this in C#.
How to determine programmatically whether a particular process is 32-bit or 64-bit
Or perhaps this in C++.
How can I dynamically get the system architecture?
|
I write a server/client TCP application in C .Many clients can be connected to the server at the same time. How can a client be disconnected after 10 seconds he called close()?
|
Callcloseon the socket 10 seconds after youacceptit.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:How to avoid press enter with any getchar()
I need to get keyboard pressed key in console Objective-C app without pressing 'Enter' button
This code reads pressed key code only after I press 'Enter'
```
int key;
key=getchar();
NSLog(@"%i"... |
By default, consoles are in 'canonical' mode which does a load of processing on the input and doesn't pass it to a process's open file descriptor until a new line is encountered. You want to putstdininto 'noncanonical' mode, to get the bytes as they arrive:
```
#include <termios.h>
struct termios terminal_info;
tcge... |
How can i save the id of p_thread to an array?
```
int i;
pthread_t t[N];
float arrayId[N];
for (i = 0; i < N; i++) {
pthread_create(&t[i], NULL, f, (void *) &i);
printf("creato il thread id=%lu\n", t[i]);
arrayId[i] = t[i];
printf("a[%d]=%f\n", i, arrayId[i]);
}
```
I can print it, but i'm not abl... |
All threads will receive the same value foribecause you are passing it by value (the same address).
This should fix it:
```
int i;
pthread_t t[N];
float arrayId[N];
int indexes[N];
for (i = 0; i < N; i++) {
indexes[i] = i;
pthread_create(&t[i], NULL, f, (void *) &indexes[i]);
printf("creato il thread id... |
When declaring arrays in C they can be declared normally like:
```
int arr[10]
```
or they can also be declared inside a structure like:
```
struct structArr{
int sArr[10];
}s1;
```
Will there be any memory or space tradeoff when usings1.sArr[]instead ofarr[], if so why?Is any one form more efficient and faster... |
I wouldn't expect there to be any difference, no.
The compiler "knows" that the offset of thesArrfield from the base address ofs1is 0, so I would guess that accesses can be done using the exact same sequence of instructions.
Of course, wrapping the array in a structure makes it possible to assign and pass/return it ... |
I'd like to know what the difference is between the values 0x7FFF and 32767. As far as I know, they should both be integers, and the only benefit is the notational convenience. They will take up the same amount of memory, and be represented the same way, or is there another reason for choosing to write a number as0xvs... |
The only advantage is that some programmers find it easier to convert between base 16 and binary in their heads. Since each base 16 digit occupies exactly 4 bits, it's a lot easier to visualize the alignment of bits. And writing in base 2 is quite cumbersome.
|
I'm new to embedded programming but I have to debug a quite complex application running on an embedded platform. I use GDB through a JTAG interface.
My program crashes at some point in an unexpected way. I suppose this happens due to some memory related issue. Does GDB allow me to inspect the memory after the system ... |
It depends on your setup a bit. In particular, since you're using JTAG, you may be able to set your debugger up to halt the processor when it detects an exception (for example accessing protected memory illegally and so forth). If not, you can replace your exception handlers with infinite loops. Then you can manual... |
I wrote a small program in C where I opened a file successfuly, then called sleep for 20 sec. In that 20 sec I deleted the open file using rm from shell. After sleep the program reads the data successfully and prints it on screen.
```
int bytes_read;
FILE *fp = fopen("/tmp/file", "r");
sleep(20);
bytes_read = fread(b... |
In linux and other POSIX systems you don't delete files. You just remove an inode from a directory. As long as there is a file descriptor open on a file it will not be deleted. Only when the last link to the inode and the last open file descriptor went away.
|
I need to ask the user for an ID Number, and then use the functionfseek()to find the position of the ID Number entered by the user, and then be able to modify the records. I have something like this:
```
printf("Enter ID Card Number: \n");
scanf("%s", editCust.idNumber);
fseek(custFile, (editCust.idNumber -1)*sizeof(... |
No.
First, substitute:
scanf("%s", editCust.idNumber);
for
scanf("%d", &editCust.idNumber);
%s is for string values and %d is for decimal values.
A good source of formats can be foundhere.
|
I'm trying to use this code to read values between 0 to 255 (unsigned char).
```
#include<stdio.h>
int main(void)
{
unsigned char value;
/* To read the numbers between 0 to 255 */
printf("Please enter a number between 0 and 255 \n");
scanf("%u",&value);
printf("The value is %u \n",value);
re... |
The%uspecifier expects an integer which would cause undefined behavior when reading that into aunsigned char. You will need to use theunsigned charspecifier%hhu.
|
I have for example a function as follows:
```
int func(int a, int b, int c){...}
```
Now I want to use the GMP library. So how do I have to change the above code? Maybe something like:
```
int func(mpz_t a, mpz_t b, mpz_t c){...}
```
|
Take a look at different function types here , and check the sample code for writing a function in GMP library. I hope this answers you question :-
http://gmplib.org/manual/
and also check this link for low level functions:-
http://gmplib.org/manual/Low_002dlevel-Functions.html#Low_002dlevel-Functions
|
I am writing a Qt GUI application (for doing XSL transformations). To print error messages to a file I am using a call like:
```
freopen("my-error-file.txt", "w", stderr);
// call to libxslt function, which possibly prints to stderr
fclose(stderr);
```
The problem I'm having is that while my-error-file.txt is create... |
I'm a goober. I was calling fflush before fclose, but the function was returning before those functions were called.
|
I've removed "use precompiled header" option fromcrypto.c.
How to resolve this error properly?
|
You need to declare thacrypt()function asextern "C"in its header file, like this:
```
#ifdef __cplusplus
extern "C" {
#endif
void crypt(unsigned int *, unsigned int, unsigned int *);
#ifdef __cplusplus
}
#endif
```
If you don't, C++ compilers will treat it as a function with C++ (as opposed to C) linkage and will ... |
I'm working with Cortex M3, Stellaris® LM3S6965 Evaluation Board. I want to display the time of a NTP server on my oled screen.
I searched and found that a server NTP server sends you timestamps.
These timestamps are stored as seconds since January 1, 1900.
32 bits for the number of seconds, and 32 bits for the frac... |
What you are looking for is the NTP (Network Time Protocol). You should be able to find a library for that protocol in C.
If there is no library available, you will have to implement it yourself. More info here:http://en.wikipedia.org/wiki/Network_Time_Protocol
Pay attention to the references to the RFCs.
I also fo... |
Looking for recommendations and some reference code for encrypting byte array in C. The problem is that I have to fit into1KBytememory along with other routines and MCU is only 8MHz. So the size and speed is the key. I've checked Rijndael but it has huge tables for my MCU. Basically I am going to encrypt intel hex for... |
A very simple encryption algorithm that I saw being used in the embedded world isXXTEA
|
I'd like to know what the difference is between the values 0x7FFF and 32767. As far as I know, they should both be integers, and the only benefit is the notational convenience. They will take up the same amount of memory, and be represented the same way, or is there another reason for choosing to write a number as0xvs... |
The only advantage is that some programmers find it easier to convert between base 16 and binary in their heads. Since each base 16 digit occupies exactly 4 bits, it's a lot easier to visualize the alignment of bits. And writing in base 2 is quite cumbersome.
|
I'm new to embedded programming but I have to debug a quite complex application running on an embedded platform. I use GDB through a JTAG interface.
My program crashes at some point in an unexpected way. I suppose this happens due to some memory related issue. Does GDB allow me to inspect the memory after the system ... |
It depends on your setup a bit. In particular, since you're using JTAG, you may be able to set your debugger up to halt the processor when it detects an exception (for example accessing protected memory illegally and so forth). If not, you can replace your exception handlers with infinite loops. Then you can manual... |
I wrote a small program in C where I opened a file successfuly, then called sleep for 20 sec. In that 20 sec I deleted the open file using rm from shell. After sleep the program reads the data successfully and prints it on screen.
```
int bytes_read;
FILE *fp = fopen("/tmp/file", "r");
sleep(20);
bytes_read = fread(b... |
In linux and other POSIX systems you don't delete files. You just remove an inode from a directory. As long as there is a file descriptor open on a file it will not be deleted. Only when the last link to the inode and the last open file descriptor went away.
|
I need to ask the user for an ID Number, and then use the functionfseek()to find the position of the ID Number entered by the user, and then be able to modify the records. I have something like this:
```
printf("Enter ID Card Number: \n");
scanf("%s", editCust.idNumber);
fseek(custFile, (editCust.idNumber -1)*sizeof(... |
No.
First, substitute:
scanf("%s", editCust.idNumber);
for
scanf("%d", &editCust.idNumber);
%s is for string values and %d is for decimal values.
A good source of formats can be foundhere.
|
I'm trying to use this code to read values between 0 to 255 (unsigned char).
```
#include<stdio.h>
int main(void)
{
unsigned char value;
/* To read the numbers between 0 to 255 */
printf("Please enter a number between 0 and 255 \n");
scanf("%u",&value);
printf("The value is %u \n",value);
re... |
The%uspecifier expects an integer which would cause undefined behavior when reading that into aunsigned char. You will need to use theunsigned charspecifier%hhu.
|
I have for example a function as follows:
```
int func(int a, int b, int c){...}
```
Now I want to use the GMP library. So how do I have to change the above code? Maybe something like:
```
int func(mpz_t a, mpz_t b, mpz_t c){...}
```
|
Take a look at different function types here , and check the sample code for writing a function in GMP library. I hope this answers you question :-
http://gmplib.org/manual/
and also check this link for low level functions:-
http://gmplib.org/manual/Low_002dlevel-Functions.html#Low_002dlevel-Functions
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:What are important points when designing a (binary) file format?
I am going to develop a program which will store data in file.
The file can be big. The data in the file is basically made up with variable length records. And I need random... |
You might findhttp://decoy.iki.fi/texts/filefd/filefduseful. It's a general starting point to the techniques to consider.
Also look at this question here on SO:What are important points when designing a (binary) file format?
|
I am followingthiscode to work with FFmpeg library in C. FFmpeg library has very little documentation and it is difficult to understand what each function exactly does.
I understand the code (what is being done). But I am lacking clarity. Can anyone help me out please?
Q1) A **struct AVFrameContext **** andfilename(... |
The main things that gets done in file_open are
Allocate memory for AVFormatContext.Read the probe_size about of data from the file (input url)Tries to guess the input file format, codec parameter for the input file. This is done by calling read_probe function pointer for each of the demuxerAllocate the codec context... |
i am trying to detect an empty string or a string with just white spaces such as " ".
It is a c application and usesregcompandregexec.
For empty string"^$"works fine.
But for string with just whitespaces i am getting a problem. So far, i have come up with
"[\\s]*(?![A-za-z0-9])$"
Is there a better way to expr... |
To test string for only white spaces, its Reg-Ex will be...
^\s*$
REF:helpful
How to test to see if a string is only whitespace in perl
|
I recently updated Ubuntu from 10.04 to 12.04 this changed the linux Kernel from 2.6.35-30-server to 3.0.0-29-server. After the update I am currently getting an error when I am compiling my driver code.
error: implicit declaration of function 'semaphore_init' [-Werror=implict-function-declaration].
How do I resolve ... |
Unlesssemaphore_initis a function of your own making, I think you'll wantsema_initinstead.
|
I've got a project and a part of it is incorporating encryption into a FAT file system.
The goal of the project is not the encryption, so I'm free to use open-source pre-done libraries.
Ideally what I'm after is a C library which uses RSA, that already has the methods for computing keys and encrypting/decrypting fil... |
You might want to check outNaCl(pronounced as "salt"), especially since this is for an embedded system.
It has CPU-specific tunings and doesn't require any dynamic memory allocation.
As for licensing, the page (linked above) says "All of the NaCl software is in the public domain".
|
I am just starting out with C and now I am at the part where I want to learn about Makefiles. I am starting out small but already failing ;)
I have a very simple Makefile which just compiles the main.c to a main.o and then to an executable. But I get an error saying I have a syntax error. I useg++.
The command tha... |
To run make on the Makefile (the default name), invoke the make command:
```
$ make
```
Don't try to call g++ with the makefile, the compiler knows nothing about makefiles.
EDIT: You say you don't have the make command, in a comment. Then you need to get it. :) There are several versions of make for Windows,here is... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
```
int main()
{
int a=1;
printf("%d %d %d",a,a++,++a);
return 0;
}
```
The above code is giving output 3 2 3 why????
|
It actuallyundefined in c and c++.
Undefined: modifying a scalar value twice between sequence points, which is what your code is doing.f(i++, ++i)is undefined behaviour because it modifiesitwice without an intervening sequence point.
A good list of definitions
|
How can I alter the program so that the functionsfunction_delayed_1andfunction_delayed_2were performed only once and concurrently:
```
int main(int argc, char *argv[]) {
printf("message 1.\n");
fork();
function_delayed_1();
function_delayed_2();
printf("message 2.\n");
}
```
|
Read themanpage of fork, and google some examples offork();,, your code should be like as follows:
```
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
pid_t pid; // process ID
printf("message 1.\n");
pid = fork();
if (pid < 0) {
perror("fork");
return;... |
As per C99, there maybe padding bits insigned intorunsigned intrepresentation . So I wonder are there still any implementations having such outdated things?
|
FromThe New C Standard:
On some Cray processors the type short has 32 bits of precision but is held in 64 bits worth of storage. The Unisys A Series unsigned integer type contains a padding bit that is treated as a sign bit in the signed integer representation....The Harris/6 computer represented the type long using ... |
It comes when I want to write my own quicksort for educational purpose. This is what I got:
```
qsort(void* array, int count, int size, int(*compare)(const void*, const void*));
```
And I have size of each element in array, and pointer to the first element in array. How can I get each individual element in that arra... |
If size was generated with thesizeofoperator, it is a multiple ofsizeof(char)(which is 1 by definition). So cast thevoid*into achar*, and movesize"characters" at a time.
```
(((char*)array) + i*size)
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I am using code block and gcc for m... |
Following should work on most systems:
```
system("clear");
```
or
```
system("tput clear");
```
|
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... |
Take a look atlibcsv, which is a CSV library written in ANSI C89.
|
I have some C code that is wrapped in a preprocessor directive:
```
#if defined(TEST)
// do stuff
#endif
```
and I need to executedo stufffrom Python via ctypes - is there any way I can defineTEST?
|
This has nothing at all to do withctypesor python. ctypes only deals with already compiled libraries and allows you to call functions in them. If you want to execute a function that is only conditionally defined you'll have to compile the library with the right directives set.
In gcc that would be something likegcc -... |
When you assign a string literal such as "ABC" to char a[] ex.
```
char a[] = "ABC";
```
it has the effect of doing
```
char a[4] = {'A','B','C','0'};
```
does this same thing apply when you pass it to a function parameter
ex.
```
int f(char a[]);
```
vs.
```
int f(char *a);
```
|
does this same thing apply when you pass it to a function parameter
No; in general, in C you can't pass arrays directly by value; every array parameter to a function is actually interpreted by the compiler as a pointer parameter, i.e. when you write
```
int f(char a[]);
```
the compiler sees
```
int f(char *a);
``... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
```
int main()
{
int a=1;
printf("%d %d %d",a,a++,++a);
return 0;
}
```
The above code is giving output 3 2 3 why????
|
It actuallyundefined in c and c++.
Undefined: modifying a scalar value twice between sequence points, which is what your code is doing.f(i++, ++i)is undefined behaviour because it modifiesitwice without an intervening sequence point.
A good list of definitions
|
How can I alter the program so that the functionsfunction_delayed_1andfunction_delayed_2were performed only once and concurrently:
```
int main(int argc, char *argv[]) {
printf("message 1.\n");
fork();
function_delayed_1();
function_delayed_2();
printf("message 2.\n");
}
```
|
Read themanpage of fork, and google some examples offork();,, your code should be like as follows:
```
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
pid_t pid; // process ID
printf("message 1.\n");
pid = fork();
if (pid < 0) {
perror("fork");
return;... |
As per C99, there maybe padding bits insigned intorunsigned intrepresentation . So I wonder are there still any implementations having such outdated things?
|
FromThe New C Standard:
On some Cray processors the type short has 32 bits of precision but is held in 64 bits worth of storage. The Unisys A Series unsigned integer type contains a padding bit that is treated as a sign bit in the signed integer representation....The Harris/6 computer represented the type long using ... |
It comes when I want to write my own quicksort for educational purpose. This is what I got:
```
qsort(void* array, int count, int size, int(*compare)(const void*, const void*));
```
And I have size of each element in array, and pointer to the first element in array. How can I get each individual element in that arra... |
If size was generated with thesizeofoperator, it is a multiple ofsizeof(char)(which is 1 by definition). So cast thevoid*into achar*, and movesize"characters" at a time.
```
(((char*)array) + i*size)
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I am using code block and gcc for m... |
Following should work on most systems:
```
system("clear");
```
or
```
system("tput clear");
```
|
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... |
Take a look atlibcsv, which is a CSV library written in ANSI C89.
|
I have some C code that is wrapped in a preprocessor directive:
```
#if defined(TEST)
// do stuff
#endif
```
and I need to executedo stufffrom Python via ctypes - is there any way I can defineTEST?
|
This has nothing at all to do withctypesor python. ctypes only deals with already compiled libraries and allows you to call functions in them. If you want to execute a function that is only conditionally defined you'll have to compile the library with the right directives set.
In gcc that would be something likegcc -... |
When you assign a string literal such as "ABC" to char a[] ex.
```
char a[] = "ABC";
```
it has the effect of doing
```
char a[4] = {'A','B','C','0'};
```
does this same thing apply when you pass it to a function parameter
ex.
```
int f(char a[]);
```
vs.
```
int f(char *a);
```
|
does this same thing apply when you pass it to a function parameter
No; in general, in C you can't pass arrays directly by value; every array parameter to a function is actually interpreted by the compiler as a pointer parameter, i.e. when you write
```
int f(char a[]);
```
the compiler sees
```
int f(char *a);
``... |
This question already has an answer here:C99 Variable Length Array Max sizes and sizeof Function(1 answer)Closed8 years ago.
I have some c code to concatenate a string.
```
char str_cat[strlen(str1) + strlen(str2) + 1];
```
How do I check the sizeof str_cat in gdb? Right now it reports 0 with:
```
print sizeof(str... |
char str_cat[strlen(str1) + strlen(str2) + 1];How do I check the sizeof str_cat in gdb? Right now it reports 0 with:
str_catis a variable length array. Apparentlygdbdoes not how to deal with variable length arrays.
There is an open ticket here regarding this issue:http://sourceware.org/bugzilla/show_bug.cgi?id=9663
... |
I need two file pointers (FILE *) to operate alongside each other. One is to apply append operations and another is for reading and overwriting.
I need appends to the file from one pointer to be recognised by the other file pointer so that the other file pointer can both correctly read and overwrite this appended dat... |
You should be able to do that with one pointer (and thus not having to sync unnecessarily). Just usefseek(f, SEEK_END, 0);when you want to add at the end. Use "rb+" to make the file readable and writeable.
As long as you don't use multiple threads to access the file, this should work just fine.
|
I have a string as below
```
char row[]="11/12/1999 foo:bar some data..... ms:12123343 hot:32";
```
I want insert 'ms' val to int variable by using sscanf.
But I don't know how to configure ssscanf to ignore first data in row.
I try blow but don't do the job.
```
int i;
sscanf(row,".*ms:%d",i);
```
|
I think, rather than using sscanf() to ignore data, your best bet is to use another function to get the part of the string you want.
I suggeststrstr().
For example
```
#include <stdio.h>
#include <string.h>
int main(void) {
char row[] = "11/12/1999 foo:54654 some data..... ms:12123343 hot:32";
char *ms;
... |
I am trying to measure my code coverage utilization on a C project consist of several libraries, and main program.
Is there a utility that can help me find which function I dont use from both libraries and main program.
I want to build list of functions (public functions) that are not used by my main program, in ord... |
If you are using gcc you compile your code withoption:
```
-Wunused-function
```
Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.