question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I have to retrieve first bit from 1 byte.
For this i stored whole 1 byte in unsigned char Array. Now i retrieved first bit as per below code:
```
unsigned char byteArray[100];
.....
.....//some code to store 1 byte in byte array
//now 1st bit will be:
int bit=(int) byteArray[0];
```
I just wanted to confirm that step involved in retrieving 1st bit is right or not? Is there any better way to retrieve single bit from unsigned char array(byte array) in C.
|
How (and why) do you store a byte in a byte array for this purpose? Its not necessary.
In any case, if you want to retrieve the first bit of a byte, all you have to do is one bit operation.
```
unsigned char byte = <some random value>; // your byte containing the value.
unsigned int first_bit = byte & 1; // for Least significant bit
```
The operationbyte & 1is abitwise AND operation.
|
I am working on a C project and can not figure out how to pass command line arguments to my main function in Visual Studio 2010 Express Edition. I want to debug - how do these command line arguments work?
|
Right click your project in Solution Explorer and select Properties from the menuGo to Configuration Properties -> DebuggingSet the Command Arguments in the property list.
|
I had some questions about puttingfnext to literal values. I know it defines it as afloatbut do I really need it?
Is this2.0f * 2.0fany faster or compiled any different than2.0 * 2.0? Is a statement likefloat a = 2.0;compiled differently thanfloat a = 2.0f;?
|
Sometimes you need it to explicitly have typefloat, like in the following case
```
float f = ...;
float r = std::max(f, 42.0); // won't work; (float, double).
float r = std::max(f, 42.0f); // works: both have same type
```
|
In C, can I say a white space in a string has a NULL type, or something else?In C, which character represents the termination of a string?
|
Thenull character(ASCII value 0,'\0'as a character literal) terminates a string in C. This character isnotusually regarded as a whitespace character.
The space in the middle of this string for example:"Hello world"is the character with ASCII value 32. This is not the same as NULL or\0.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago.
Is there software that can help create flow charts, class diagrams etc to help software development planning.
Thanks
|
You can create all kinds of charts and diagrams with something like Microsoft Visio or the open-sourceDia.
If you want to auto-generate things like this, take a look at using a UML-based tool. A list of some UML tools is availablehere.
|
why do i get error: 'strcmp': identifier not found in visual studio 2010 C++ Express
```
#include <string.h>
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d",(int)strcmp( "str1", "str2" ));
return 0;
}
```
Thanks
|
```
:( #include <string.h> :(
#include "stdafx.h"
```
Fun quirk of the MSVC compiler, it generates the exact same error when you compile it like that. Yes, not a lot of 'fun'. It skips everything to find the stdafx.h precompiled header include directive. The string.h doesn't actually get included. Fix:
```
#include "stdafx.h"
#include <string.h>
```
Always put the stdafx.h include first.
|
which visual studio project type should i choose that will best for c basic library(uni studies).
the problem in visual studio 2010 express that its gives _tmain instead int main().
Thanks
|
I usually select "Win32 Console Application" and then "Empty project". Add a new source file and type in the main() by hand.
I have no idea what R is talking about with his absurd comment.
|
I have the following files:a.h,a.c,b1.c,b2.cand in both b1 and b2 I have some macro definitions which are identical.
Is it ok if I move them ina.hor is it more common to leave them in the file where they are being used ? Which way is the proper way to do it in C ?
|
It is common to move macro definitions which are shared between files into a header which both of those files include. You should make sure that the file you move that definition into is a sensible file for it to be in; don't move it into a completely unrelated header just because it's included in both files. If there is no logical related header file for bothb1.candb2.c, perhaps you ought to create ab.hto be shared between them.
|
Recently I reviewed some C code and found something equivalent to the following:
```
struct foo {
int some_innocent_variables;
double some_big_array[VERY_LARGE_NUMBER];
}
```
Being almost, but not quite, almost entirely a newbie in C, am I right in thinking that this struct is awfully inefficient in its use of space because of the array member? What happens when this struct gets passed as an argument to a function? Is it copied in its entirety on the stack, including the full array?
Would it be better in most cases to have adouble *some_pointerinstead?
|
If you pass by value yes it will make a copy of everything.
But that's why pointers exist.
```
//Just the address is passed
void doSomething(struct foo *myFoo)
{
}
```
|
Suppose you have 2 numbers:
```
int x = 1;
int y = 2;
```
Using bitwise operators, how can i representx-y?
|
When comparing the bits of two numbersAandBthere are three posibilities. The following assumes unsigned numbers.
A == B: All of the bits are the sameA > B: The most significant bit that differs between the two numbers is set inAand not inBA < B: The most significant bit that differs between the two numbers is set inBand not inA
Code might look like the following
```
int getDifType(uint32_t A, uint32_t B)
{
uint32_t bitMask = 0x8000000;
// From MSB to LSB
for (bitMask = 0x80000000; 0 != bitMask; bitMask >>= 1)
{
if (A & bitMask != B & bitMask)
return (A & bitMask) - (B & bitMask);
}
// No difference found
return 0;
}
```
|
Under Linux what would be the best way for a program to restart itself on a crash by catching the exception in a crashhandler (for example on a segfault)?
|
simplest is
```
while [ 1 ]; do ./program && break; done
```
basically, you run program until it is return 0, then you break.
|
I've got a Nvidia Tesla s2050; a host with a nvidia quadro card.CentOS 5.5 with CUDA 3.1
When i run cuda app, i wanna use 4 Tesla c-2050, but not including quadro on host in order not to lagging the whole performance while split the job by 5 equally.any way to implement this?
|
I'm assuming you have four processes and four devices, although your question suggests you have five processes and four devices, which means that manual scheduling may be preferable (with the Tesla devices in "shared" mode).
The easiest is to use nvidia-smi to specify that the Quadro device is "compute prohibited". You would also specify that the Teslas are "compute exclusive" meaning only one context can attach to each of these at any given time.
Runman nvidia-smifor more information.
|
```
wprintf(L"Selecting Audio Input Device: %s\n",
varName.bstrVal);
if(0 == wcscmp(varName.bstrVal, L"IP Camera [JPEG/MJPEG]"))
{
...
}
hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, (void **)&pGrabberF);
```
The above is from a .cpp file ,but as you see its content is quite c-style.
Will you call it a c or c++ project?
|
It simply depends how you compile it.
Some code will compile as both, it's considered C++ code if it gets compiled by a C++ compiler.
C is NOT an exact subset of C++by the way.
Often you can deduce with a fast glance simply by the file's extension, although it's possible to put C code in a .cc extension or .cpp extension and you can also put C++ code in a .c extension, but that would be pretty rare.
|
I may miss the obvious, but how/is it possible to retrieve interrupt counters for a specific interrupt without manually parsing/proc/interruptsfrom inside a C/C++ program?
Thanks in advance!
Best regards, Martin
|
/proc/interruptsand/proc/statobtain their data by calling the kernel functionkstat_irqs_cpu(). The only way to read it without opening the files in /proc is, I think, writing your own kernel driver which would call the same function and return the results via ioctl() or some other way.
|
Why does++x || ++y && ++zcalculate++xfirst, even though the precedence of operator&&is higher than||?
|
Huh?
If you're saying that&&binds tighter than||(which is true), the expression is then equivalent to
```
++x || (++y && ++z)
```
Since||short-circuits, it needs to evaluate the left-hand side first.
If you mean that it ought to be equivalent to
```
(++x || ++y) && ++z
```
The same is still true, since&&also short-circuits, meaning the||needs to be evaluated first, which in turn makes++xthe first thing to evaluate.
|
I've a program which links to many libraries.g++, by default, prefers to link to shared libraries, even if the corresponding archive exists.
How can I change this preference to prefer static archives over dynamic libraries, if a static archive exists?
Note, I used-staticoption, but it tries to find static archive for all libraries which is not what I want.
|
```
g++ -Wl,-Bstatic -lz -lfoo -Wl,-Bdynamic -lbar -Wl,--as-needed
```
Will linkzlibandlibfooas static, andlibbaras dynamic .--as-neededwill drop any unused dynamic library.
|
I have to retrieve first bit from 1 byte.
For this i stored whole 1 byte in unsigned char Array. Now i retrieved first bit as per below code:
```
unsigned char byteArray[100];
.....
.....//some code to store 1 byte in byte array
//now 1st bit will be:
int bit=(int) byteArray[0];
```
I just wanted to confirm that step involved in retrieving 1st bit is right or not? Is there any better way to retrieve single bit from unsigned char array(byte array) in C.
|
How (and why) do you store a byte in a byte array for this purpose? Its not necessary.
In any case, if you want to retrieve the first bit of a byte, all you have to do is one bit operation.
```
unsigned char byte = <some random value>; // your byte containing the value.
unsigned int first_bit = byte & 1; // for Least significant bit
```
The operationbyte & 1is abitwise AND operation.
|
I am working on a C project and can not figure out how to pass command line arguments to my main function in Visual Studio 2010 Express Edition. I want to debug - how do these command line arguments work?
|
Right click your project in Solution Explorer and select Properties from the menuGo to Configuration Properties -> DebuggingSet the Command Arguments in the property list.
|
I had some questions about puttingfnext to literal values. I know it defines it as afloatbut do I really need it?
Is this2.0f * 2.0fany faster or compiled any different than2.0 * 2.0? Is a statement likefloat a = 2.0;compiled differently thanfloat a = 2.0f;?
|
Sometimes you need it to explicitly have typefloat, like in the following case
```
float f = ...;
float r = std::max(f, 42.0); // won't work; (float, double).
float r = std::max(f, 42.0f); // works: both have same type
```
|
In C, can I say a white space in a string has a NULL type, or something else?In C, which character represents the termination of a string?
|
Thenull character(ASCII value 0,'\0'as a character literal) terminates a string in C. This character isnotusually regarded as a whitespace character.
The space in the middle of this string for example:"Hello world"is the character with ASCII value 32. This is not the same as NULL or\0.
|
Suppose you have the following C code.
```
unsigned char a = 1;
printf("%d\n", ~a); // prints -2
printf("%d\n", a); // prints 1
```
I am surprised to see -2 printed as a result of ~1 conversion:
The opposite of 0000 0001 is 1111 1110. That is anything but -2.
What am I missing here?
|
It is two's complement.
In two's complement representation, if a number x's most significant bit is 1, then the actual value would be −(~x + 1).
For instance,
```
0b11110000 = -(~0b1111 + 1) = -(15 + 1) = -16.
```
This is a natural representation of negative numbers, because
```
0000001 = 1
0000000 = 0
1111111 = -1 (wrap around)
1111110 = -2
1111101 = -3 etc.
```
Seehttp://en.wikipedia.org/wiki/Two%27s_complementfor detail.
BTW, to print an unsigned value, use the%hhuor%hhxformat. Seehttp://www.ideone.com/YafE3.
|
NULL in C programming can anyone tell me how NULL is handled in C?
And the output of this program is 3, how with NULL concept?
```
#include <stdio.h>
int main(void) {
int i;
static int count;
for(i = NULL; i <= 5;) {
count++;
i += 2;
}
printf("%d\n",count);
return 0;
}
```
|
For C, "NULL" is traditionally defined to be (void *)0 - in other words, it's a pointer alias to address 0. For C++, "NULL" is typically defined to be "0". The problem with NULL in C++ and C is that it's not type safe - you can build bizarre constructs like the one you included in your code sample.
For C++, the language designers fixed this in C++0x by adding a new "nullptr" type which is implicitly convertable to any pointer type but which cannot be converted to an integer type.
|
I was wondering what I needed to know in terms of C to move onto Objective-C. I would be uber-grateful if you could let me know what you think is sufficient to move on Objective-C.
Thanks,
~Daniel
|
If you're looking to learn C before moving on to Objective-C (which, in my opinion, is a great idea), I would recommend to you Steve Kochan's 'Programming in Objective-C 2.0'. Very similar to his 'Programming in C' book, it will contain all the C you're going to need to use Objective-C, and it's a great primer for learning both languages.
If you're not looking to read a book, though, or you already have one, I would assume that after learning pointers, you will have covered most of the important parts of the C language (of course, it will depend on the order of material in the book, but pointers are usually sufficiently advanced to move on). Good luck!
|
i have written a C programme which prints itself n times, but i can't get how to reverse print the same n times.E.g, if the sample programme is :
```
hello
```
then the required output should be"olleh" for n=1.
Here's my quine programme,
```
#include <stdio.h>
int main()
{
int n;
char c;
FILE *f;
f=fopen(__FILE__,"r");
scanf("%d",&n);
while(n--)
{
while((c=getc(f))!=EOF)
putchar(c);
fseek(f,0,0);
}
return 0;
}
```
|
This is not a pure quine. Seethe Quine article in Wikipedia:
A quine takes no input. Allowing input
would permit the source code to be fed
to the program via the keyboard,
opening the source file of the
program, and similar mechanisms.
|
The question is how to get the length of dynamically allocated 2D Arrays in C? I thought the code below should get the number of rows, but it doesn't.
```
char** lines;
/* memory allocation and data manipulation */
int length; //the number of rows
length = sizeof(lines)/sizeof(char*);
```
Any thoughts on this?
|
You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.
In your test case abovesizeofis returning the size of the type oflines, and thus your length calculation is equivalent tosizeof(char**)/sizeof(char*)and is likely to have the trivial result of1, always.
|
I have some knowledge in C/C++ but only using the Console. I'd like to start programming some graphical interfaces, but I don't have the minimal idea where to start.
I've heard of GUI applications and DirectX applications. I'd like to know which is the best for start programming?
Which libraries also is good to use and some tutorials if possible.
|
What's your platform?
If you only care about Windows and don't mind an outdated technology, you can go to MFC way.
If you want a cross-platform GUI toolkit; there are several:
GTKWxWidgetQt
If you want something more about drawing, instead of boring GUI forms; then you can learn either:
OpenGL (cross-platform)DirectX (Windows-only)
For simple uses, and if you're in Windows, you can use GDI+, which is also rather outdated.
Newer .NET platforms have GUI technologies with fancy names, though I'm not quite acquaintanced with them to suggest anything.
|
I am currently working on a project about setting process to one core in linux environment. I use sched_setaffinity to do this job and I wonder whether there are some functions provided by linux to get which core the process is running on. I use top command and find it could get this info using j option. So i am sure there are some ways to get this info in user space.
|
You probably wantsched_getcpu(). If you are running an older version of glibc, you can read the 39th field of/proc/[pid]/statfor the appropriate pid -- see theproc(5)man page for more details.
|
Does C allow to place a string terminator at the end of read bytes full of garbage or is it only guaranteed if the read bytes are chars ?
I need to read something like this from stdin but I do not know how many chars to read and EOF is not guaranteed:
```
Hello World!---full of garbage until 100th byte---
```
```
char *var = malloc(100 + 1);
read(0, var, 100); // read from stdin. Unfortunately, I do not know how many bytes to read and stdin is not guaranteed to hold an EOF. (I chose 100 as an educated guess.)
var[100] = '\0'; // Is it possible to place a terminator at the end if most of the read bytes are garbage ?
```
|
read()returns the number of characters that were actually read into the buffer (or <0 in the case of an error). Hence the following should work:
```
int n;
char *var = malloc(100 + 1);
n = read(0, var, 100);
if(n >= 0)
var[n] = '\0';
else
/* error */
```
|
Dolfind/lsearchperform better than a typical looping solution that checks each item until it matches? Is there any special sauce/reason that these functions exist?
|
Probably they are not more efficient that a homebrew version, maybe even a bit less since the comparison function can't be inlined.
But this is certainly not the point with them. They complete the API of the other search functions, in particularbsearchandtsearch.
|
i have written a C programme which prints itself n times, but i can't get how to reverse print the same n times.E.g, if the sample programme is :
```
hello
```
then the required output should be"olleh" for n=1.
Here's my quine programme,
```
#include <stdio.h>
int main()
{
int n;
char c;
FILE *f;
f=fopen(__FILE__,"r");
scanf("%d",&n);
while(n--)
{
while((c=getc(f))!=EOF)
putchar(c);
fseek(f,0,0);
}
return 0;
}
```
|
This is not a pure quine. Seethe Quine article in Wikipedia:
A quine takes no input. Allowing input
would permit the source code to be fed
to the program via the keyboard,
opening the source file of the
program, and similar mechanisms.
|
The question is how to get the length of dynamically allocated 2D Arrays in C? I thought the code below should get the number of rows, but it doesn't.
```
char** lines;
/* memory allocation and data manipulation */
int length; //the number of rows
length = sizeof(lines)/sizeof(char*);
```
Any thoughts on this?
|
You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.
In your test case abovesizeofis returning the size of the type oflines, and thus your length calculation is equivalent tosizeof(char**)/sizeof(char*)and is likely to have the trivial result of1, always.
|
I have some knowledge in C/C++ but only using the Console. I'd like to start programming some graphical interfaces, but I don't have the minimal idea where to start.
I've heard of GUI applications and DirectX applications. I'd like to know which is the best for start programming?
Which libraries also is good to use and some tutorials if possible.
|
What's your platform?
If you only care about Windows and don't mind an outdated technology, you can go to MFC way.
If you want a cross-platform GUI toolkit; there are several:
GTKWxWidgetQt
If you want something more about drawing, instead of boring GUI forms; then you can learn either:
OpenGL (cross-platform)DirectX (Windows-only)
For simple uses, and if you're in Windows, you can use GDI+, which is also rather outdated.
Newer .NET platforms have GUI technologies with fancy names, though I'm not quite acquaintanced with them to suggest anything.
|
I am currently working on a project about setting process to one core in linux environment. I use sched_setaffinity to do this job and I wonder whether there are some functions provided by linux to get which core the process is running on. I use top command and find it could get this info using j option. So i am sure there are some ways to get this info in user space.
|
You probably wantsched_getcpu(). If you are running an older version of glibc, you can read the 39th field of/proc/[pid]/statfor the appropriate pid -- see theproc(5)man page for more details.
|
Does C allow to place a string terminator at the end of read bytes full of garbage or is it only guaranteed if the read bytes are chars ?
I need to read something like this from stdin but I do not know how many chars to read and EOF is not guaranteed:
```
Hello World!---full of garbage until 100th byte---
```
```
char *var = malloc(100 + 1);
read(0, var, 100); // read from stdin. Unfortunately, I do not know how many bytes to read and stdin is not guaranteed to hold an EOF. (I chose 100 as an educated guess.)
var[100] = '\0'; // Is it possible to place a terminator at the end if most of the read bytes are garbage ?
```
|
read()returns the number of characters that were actually read into the buffer (or <0 in the case of an error). Hence the following should work:
```
int n;
char *var = malloc(100 + 1);
n = read(0, var, 100);
if(n >= 0)
var[n] = '\0';
else
/* error */
```
|
Dolfind/lsearchperform better than a typical looping solution that checks each item until it matches? Is there any special sauce/reason that these functions exist?
|
Probably they are not more efficient that a homebrew version, maybe even a bit less since the comparison function can't be inlined.
But this is certainly not the point with them. They complete the API of the other search functions, in particularbsearchandtsearch.
|
How isstruct sockaddrdifferent fromstruct sockaddr_un?
I know that we use these structures in client-server modules, for binding the socket to the socket address. And we use a cast operator for it to accept structsockaddr_un.
I want to know how different/similar they are, and why the cast operator?
|
"struct sockaddr" is a generic definition. It's used by any socket function that requires an address.
"struct sockaddr_un" (a "Unix sockets" address) is a specific kind of address family.
The more commonly seen "struct sockaddr_in" (an "Internet socket" address) is another specific kind of address family.
The cast is what allows the sockets APIs to accept a common parameter type that will actually be any one of several different actual types.
Here's a good link that shows several different address family definitions:
http://www.cas.mcmaster.ca/~qiao/courses/cs3mh3/tutorials/socket.html
|
I have this float which is a rotation angle.
```
Camera.roty += (float) diffx * 0.2;
```
where diff is the change in mouse position.
In OpenGL it will wrap it if it exceeds 360 or is below 0, but how could I do this if I want to verify if the angle is between 0 and 180?
Thanks
|
If I understand your question correctly you're basically looking for something like this?:
```
float Wrap( const float Number, const float Max, const float Min ) {
if( Number > 0.0f ) {
return fmod( Number, Max ) + Min;
}
else {
return Max - fmod( abs( Number ), Max ) + Min;
}
}
```
|
I'm writing some C and I have a lookup table of ints. I'm a little rusty... where do I declare and initialize the array so that I can use it in multiple C files? Can I declare it in an H file and initialize it in a C file?
|
Globals should be declared in a .h file and should be declared asextern, and then they should be defined in a .c file. SeeWhat's the best way to declare and define global variables and functions?from the comp.lang.c FAQ.
For arrays, some extra care might be necessary. SeeQ1.24from the comp.lang.c FAQ too.
|
I would like to have a function written in C, but callable from C++ which takes a restricted pointer. This is only available in c99, so g++ doesn't like it, even inextern "C"blocks. How can I get around this limitation?
|
```
#ifdef __cplusplus
# ifdef __GNUC__
# define restrict __restrict__ // G++ has restrict
# else
# define restrict // C++ in general doesn't
# endif
#endif
```
|
I read that pointers passed by malloc() & calloc() get allocated memory dynamically from the heap.
```
char *Name="Ann";
```
In this case, is the static string {'A','n','n','\0'} also stored in the heap?Can I modify the string using the pointer?
|
No, the string is allocated statically. (C99, §6.4.5/5)Attempting to modify a string literal gives undefined behavior. (§6.4.5/6)
|
I have a function
```
void add_car(char *car) {
park.buffer[park.size] = car;
park.size ++;
}
```
car is a string like "XYZ". Atm, It seems to assign the carpark buffer array element to an address. Thus if I fill the array with 10 cars, I get back 10 cars, but each of them is the latest one, since the address of car was overwritten. How do I fill my carpark.buffer with the actual value of a car.
Total mindblank atm
|
Assumingpark.bufferis an array ofchar*, you may want to use
```
park.buffer[park.size] = strdup(car);
```
Note that, inevitably, this makes acopy(indispensable, if you don't want further changes tocarto affectpark.buffer!)ownedbypark(meaning that, when done, you'll have tofreeit from there, becausestrdupimplicitly does amalloc[and astrcpytoo of course;-)]).
BTW, you'll need to#include <string.h>at the top of your file (if you're not already doing so) in order to usestrdup.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:How do you set, clear and toggle a single bit in C?
Can some one help me how to toggle a bit at ith position.
One way is to do((n>>i) ^ 1) << i. Are there any other ways ?
|
n ^= 1U << iis easy enough, isn't it?
|
Can I do floating point operations in interrupt handler ? (x86 or 64) Also I would like know can I use print function inside the interrupt handler ?
|
Inside an interrupt handler, don't use anything that can block. That means don't use print functions unless they are non-blocking. Ideally, your ISR should do the bare minimum needed to clear the interrupt and then launch a normal thread to do the rest of the processing. If you need the print statements for debugging, then consider having the non-ISR part of your program declare a global, volatile buffer and have your ISR write your debug data into it. Your non-ISR code can check the buffer andprintfthe data from it if needed.
You should avoid floating-point operations inside an ISR (and in kernel code in general) as well.
|
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 answered with facts and citations.Closed8 years ago.Improve this question
I'm just wondering if anyone has already created a tool that will take a given JSON string and write the code for an identical struct in C along with the parser code specific to that struct.
I'm about to do this myself using JSON-C, but I thought I'd ask first.
|
I thinkprotobufis my best bet. A guy on the NodeJS list led me on to this.
protobuf-cnode-protobufprotobuf-js
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed13 years ago.
So, I'm wondering if there's a good marker to choose in C, apart from the common0xDEADBEEFor the less appealing (for proper code)0x0BADA550.
What's your favorite?
Is there any reason to choose one particular value or another?
|
Wikipedia has awhole pageon this subject; it provides a lot of examples and famous software in which they are used.
Anyway, if you are working on x86 you should consider following @torak's suggestion, memory filled withint 3saved me several times. If you feel creative, you may make it more recognizable and useCC90CC90, which translates to alternatedint 3andnop.
|
I need to write my 4-5 .cpp and .h file to c code. In C++ code we have defined a class, constructor, destructor, function.
How to convert them in C code?
Can somebody give me example of it so that i can implement it or provide link so that I can better explore it to my C code?
How to implement all the functionality i mean constructor,destructor,functions of class in C ?
|
convert all classes to data structures (typedefs)replace constructors and destructors with functions that use malloc/calloc and free and return/take pointers to your typedef'd structureseliminate polymorphism; if this is not possible then implement a message-dispatching function for each typedef (a big switch statement) and represent messages as constant integersalter all functions to take a pointer to the appropriate typedef
Note that typedefs do not support subtyping, so all inheritance will have to be converted to composition.
|
in my C file I call luaL_dostring like this:
```
luaL_dostring(L, "return 'somestring'");
```
How do I read this return value in C after this line?
Thanks.
Edit:
Thanks for the help.
I'd like to add that to remove the element after retrieving it, you use:
```
lua_pop(L, 1);
```
|
The value is left on the Lua stack. In order to retrieve the value, use one of thelua_toXXXXfunctions, with -1 as the index argument (-1 refers to the top of the stack). Alternatively, uselua_gettop()to get the size of the stack.
In your case, use this:
```
luaL_dostring(L, "return 'somestring'");
const char * str = lua_tostring(L, -1);
```
|
in a C program I need to define
```
float (*d_i)[3];
```
but later I realized that I need to define NMAX variables of this type. I tried with
```
float (*d_i)[3][NMAX];
```
but it does not work.
what would be the right syntax?
Thanks
|
Don't guess. Just use atypedef.
```
typedef float (*someType)[3];
someType d_i[NMAX];
```
(In case you really don't want thetypedef,
```
float (*d_i[NMAX])[3];
```
)
|
I've inherited some code which, to initialise some hardware, writes a few bytes and then waits for a return. To do this it calls the_writefunction fromio.h. From my testing, it looks like it's locking up at that point. So my questions are as follows:
Is that function a blocking function?Is there a way of setting a timeout?Is there an alternative non-blocking function I could use instead?
|
If you want to do async I/O on Windows then either use the Win32 APIs directly (look at docs for WriteFileEx/ReadFileEx, which contain pointers to general background on async I/O vs sync) or consider boost::asio.
|
For example, I have:
```
void(temperature, pressure,time)
{
int i;
double results[10];
for (i = 0 ; i <= 9 ; i++)
{
fx(temperature, pressure, time);
results[i]=fx[i];
}
}
```
(P/S: above is the simplified version of my real problem)
fx by itself is of course another ste of codes with equations for calculations that will give results in fx[i].
I was just wondering if I can call another function like that in a 'void' function. Just a curious question, Thanks!
|
Yes you can, as long as you give the outer function a name. (This is C, or similar, right?)
|
I have a C code written. When I compile it on Linux then in the header file it says the
following error:storage class specified for parameter i32 , i8and so on
```
typedef int i32;
typedef char i8;
```
|
Chances are you've forgotten a semicolon in a header file someplace. Make sure each line ends in;
|
I am confused by a program mentioned in K&R that usesgetchar(). It gives the same output as the input string:
```
#include <stdio.h>
main(){
int c;
c = getchar();
while(c != EOF){
putchar(c);
c = getchar();
}
}
```
Why does it print the whole string? I would expect it to read a character and ask again for the input.
And, are all strings we enter terminated by an EOF?
|
In the simple setup you are likely using,getcharworks withbufferedinput, so you have to press enter before getchar gets anything to read. Strings are not terminated byEOF; in fact,EOFis not really a character, but a magic value that indicates the end of the file. ButEOFis not part of the string read. It's whatgetcharreturns when there is nothing left to read.
|
I know the differences between the two. One notable thing is that abort() sends SIGABRT signal, so it may be relevant when your software relies on them. But for a typical application exit() seems to be more safe version of abort()...? Are there any other concerns to use abort() instead of exit()?
|
Usingabortwill dump core, if the user has core dumps enabled. So as a rule of thumb, I'd useabortif you're so unsure about what's gone wrong that the only way to get useful information about it is by analysing a core dump.
If you can safelyexitfrom any given point, and don't need the core dump, then exit is a nicer approach.
|
```
typedef int (fc_name) (void);
```
Herefc_nameis any valid C symbol.
How different is this from a function pointertypedef?
|
It's atypedefto a function type. The intent is to use it for function pointers, but in this case the syntax to use it would be:
```
int bar(void);
fc_name* foo = bar; /* Note the * */
```
Update:
As mentioned in the comments toJonathan Leffler's answer, thetypedefcan be used to declare functions. One use could be for declaring a set of callback functions:
```
typedef int (callback)(int, void*);
callback onFoo;
callback onBar;
callback onBaz;
callback onQux;
```
|
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 answered with facts and citations.Closed8 years ago.Improve this question
I'm just wondering if anyone has already created a tool that will take a given JSON string and write the code for an identical struct in C along with the parser code specific to that struct.
I'm about to do this myself using JSON-C, but I thought I'd ask first.
|
I thinkprotobufis my best bet. A guy on the NodeJS list led me on to this.
protobuf-cnode-protobufprotobuf-js
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed13 years ago.
So, I'm wondering if there's a good marker to choose in C, apart from the common0xDEADBEEFor the less appealing (for proper code)0x0BADA550.
What's your favorite?
Is there any reason to choose one particular value or another?
|
Wikipedia has awhole pageon this subject; it provides a lot of examples and famous software in which they are used.
Anyway, if you are working on x86 you should consider following @torak's suggestion, memory filled withint 3saved me several times. If you feel creative, you may make it more recognizable and useCC90CC90, which translates to alternatedint 3andnop.
|
I need to write my 4-5 .cpp and .h file to c code. In C++ code we have defined a class, constructor, destructor, function.
How to convert them in C code?
Can somebody give me example of it so that i can implement it or provide link so that I can better explore it to my C code?
How to implement all the functionality i mean constructor,destructor,functions of class in C ?
|
convert all classes to data structures (typedefs)replace constructors and destructors with functions that use malloc/calloc and free and return/take pointers to your typedef'd structureseliminate polymorphism; if this is not possible then implement a message-dispatching function for each typedef (a big switch statement) and represent messages as constant integersalter all functions to take a pointer to the appropriate typedef
Note that typedefs do not support subtyping, so all inheritance will have to be converted to composition.
|
in my C file I call luaL_dostring like this:
```
luaL_dostring(L, "return 'somestring'");
```
How do I read this return value in C after this line?
Thanks.
Edit:
Thanks for the help.
I'd like to add that to remove the element after retrieving it, you use:
```
lua_pop(L, 1);
```
|
The value is left on the Lua stack. In order to retrieve the value, use one of thelua_toXXXXfunctions, with -1 as the index argument (-1 refers to the top of the stack). Alternatively, uselua_gettop()to get the size of the stack.
In your case, use this:
```
luaL_dostring(L, "return 'somestring'");
const char * str = lua_tostring(L, -1);
```
|
in a C program I need to define
```
float (*d_i)[3];
```
but later I realized that I need to define NMAX variables of this type. I tried with
```
float (*d_i)[3][NMAX];
```
but it does not work.
what would be the right syntax?
Thanks
|
Don't guess. Just use atypedef.
```
typedef float (*someType)[3];
someType d_i[NMAX];
```
(In case you really don't want thetypedef,
```
float (*d_i[NMAX])[3];
```
)
|
I've inherited some code which, to initialise some hardware, writes a few bytes and then waits for a return. To do this it calls the_writefunction fromio.h. From my testing, it looks like it's locking up at that point. So my questions are as follows:
Is that function a blocking function?Is there a way of setting a timeout?Is there an alternative non-blocking function I could use instead?
|
If you want to do async I/O on Windows then either use the Win32 APIs directly (look at docs for WriteFileEx/ReadFileEx, which contain pointers to general background on async I/O vs sync) or consider boost::asio.
|
For example, I have:
```
void(temperature, pressure,time)
{
int i;
double results[10];
for (i = 0 ; i <= 9 ; i++)
{
fx(temperature, pressure, time);
results[i]=fx[i];
}
}
```
(P/S: above is the simplified version of my real problem)
fx by itself is of course another ste of codes with equations for calculations that will give results in fx[i].
I was just wondering if I can call another function like that in a 'void' function. Just a curious question, Thanks!
|
Yes you can, as long as you give the outer function a name. (This is C, or similar, right?)
|
I have a C code written. When I compile it on Linux then in the header file it says the
following error:storage class specified for parameter i32 , i8and so on
```
typedef int i32;
typedef char i8;
```
|
Chances are you've forgotten a semicolon in a header file someplace. Make sure each line ends in;
|
I am confused by a program mentioned in K&R that usesgetchar(). It gives the same output as the input string:
```
#include <stdio.h>
main(){
int c;
c = getchar();
while(c != EOF){
putchar(c);
c = getchar();
}
}
```
Why does it print the whole string? I would expect it to read a character and ask again for the input.
And, are all strings we enter terminated by an EOF?
|
In the simple setup you are likely using,getcharworks withbufferedinput, so you have to press enter before getchar gets anything to read. Strings are not terminated byEOF; in fact,EOFis not really a character, but a magic value that indicates the end of the file. ButEOFis not part of the string read. It's whatgetcharreturns when there is nothing left to read.
|
I know the differences between the two. One notable thing is that abort() sends SIGABRT signal, so it may be relevant when your software relies on them. But for a typical application exit() seems to be more safe version of abort()...? Are there any other concerns to use abort() instead of exit()?
|
Usingabortwill dump core, if the user has core dumps enabled. So as a rule of thumb, I'd useabortif you're so unsure about what's gone wrong that the only way to get useful information about it is by analysing a core dump.
If you can safelyexitfrom any given point, and don't need the core dump, then exit is a nicer approach.
|
```
typedef int (fc_name) (void);
```
Herefc_nameis any valid C symbol.
How different is this from a function pointertypedef?
|
It's atypedefto a function type. The intent is to use it for function pointers, but in this case the syntax to use it would be:
```
int bar(void);
fc_name* foo = bar; /* Note the * */
```
Update:
As mentioned in the comments toJonathan Leffler's answer, thetypedefcan be used to declare functions. One use could be for declaring a set of callback functions:
```
typedef int (callback)(int, void*);
callback onFoo;
callback onBar;
callback onBaz;
callback onQux;
```
|
In the following code.Amutexis initialized.what is the significance ofNULL.
```
pthread_mutex_init(&a->monitor,NULL);
```
I want to know why we pass NULL as the second parameter.
|
The second argument is a pointer to apthread_mutexattr_tstructure, which lets you tweak the behavior of the mutex; NULL means "no special options here, use the default mutex behavior."
Most mutex options are useful only in edge cases (avoiding priority-inversion deadlocks, sharing a mutex between processes rather than threads) and the more useful ones (e.g. recursion control) were only standardized in the 2008 revision of POSIX, which means you can't yet rely on their existence cross-platform. paxdiablo's answer has a comprehensive list.
|
What's the best method to print out time in C in the format2009‐08‐10
18:17:54.811?
|
Usestrftime().
```
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer;
char buffer[26];
struct tm* tm_info;
timer = time(NULL);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
return 0;
}
```
For milliseconds part, have a look at this question.How to measure time in milliseconds using ANSI C?
|
I've been doing PHP for a long time now and I'd like to make some desktop applications on my Mac. I've never used C before but I installed xcode and I could do some basic things with some terminal apps.
I'd like to make an application with a GUI. I don't know how to add libraries or frameworks in xcode though and I don't know how to install the GTK library/framework so I can start using it when I code.
|
You can find a popular GTK framework that works with Xcode GTK-OSX, athttp://gtk-osx.sourceforge.net/
|
InC++C: Output: "1610612736"
```
#include <math.h>
#include <stdio.h>
int main(int argc, char** argv)
{
printf("%d\n", fmodf(5.6f, 6.4f));
getchar();
}
```
In C#: Output: "5.6"
```
using System;
static class Program
{
public static void Main(string[] args)
{
Console.WriteLine(5.6f % 6.4f);
Console.Read();
}
}
```
Clearly not the same output. Suggestions?
|
Try withprintf("%f\n", fmodf(5.6f, 6.4f))instead.
|
I read that \n consists of CR & LF. Each has their own ASCII codes.
So is the \n in C represented by a single character or is it multi-character?
Edit:Kindly specify your answer, rather than simply saying"yes, it is"or"no, it isn't"
|
In a C program, it's a single character,'\n'representing end of line. However, some operating systems (most notably Microsoft Windows) use two characters to represent end of line in text files, and this is likely where the confusion comes from.
It's the responsibility of the C I/O functions to do the conversions between the C representation of'\n'and whatever the OS uses.
In C programs, simply use'\n'. It is guaranteed to be correct. When looking at text files with some sort of editor, you might see two characters. When a text file is transferred from Windows to some Unix-based system, you might get"^M"showing up at the end of each line, which is annoying, but has nothing to do with C.
|
I am running System Verilog inside of an ASIC simulator. SV has an import/export mechanism to call C functions from SV, and for SV functions to be called from within C.
I'd like to send realtime-ish (a very slow stream) data from the simulation to a charting program that I will write in Java. What is the best way to call the Java with periodic updates from the simulator/C program?
|
After a quick glance here :http://java.sun.com/docs/books/jni/html/invoke.html, ...
Then consider this:
The simplest way is to write the data to a file, and write a java program
to read from the file as it grows. See this answer:Java IO implementation of unix/linux "tail -f"
Start them both separately, or usesystem()to start the java program from your plugin, passing the filename as an argument.
|
Google officially provides a C++ implementation of Google Protocol buffers,
but I'm looking for a C implementation.
I will not be using it myself, but my hope is that I can use this tool to generate
C code for our Google Protocol Buffer definitions which I can then hand of to the C developers.
I'm not looking for any RPC functionality, simply encoding and decoding of Google Protocol Buffer messages.
|
Useprotobuf-c(now at Github asprotobuf-c).
From their official site:
This package provides a code generator and runtime libraries to use
Protocol Buffers from pure C (not C++).It uses a modified version ofprotoccalledprotoc-c.
|
Looking at MSDN documentaion forGetTokenInformation()and theGetting the Logon SIDexample, GetTokenInformation() needs to be called twice. The first call is to get the buffer size.
So, buffer size of what? Just say I use TokenUser as its second parameter, I see that the dwReturnLength returned by first call is not the size of TOKEN_USER structure.
Thanks in advance
|
TheTOKEN_USERstructure contains pointers (in particular, a pointer to aSIDthat itself has variable length). Those pointers have to point somewhere. The API function will expect a buffer big enough to hold not only the theTOKEN_USERstructure, but also all the things that structure points to. The function tells you how much memory it needs foreverything. It will all reside in adjacent memory.
|
I am trying to write a function in C that will shift out the individual bits of a byte based on a clock signal. So far I have come up with this...
```
void ShiftOutByte (char Data)
{
int Mask = 1;
int Bit = 0;
while(Bit < 8)
{
while(ClkPin == LOW);
DataPin = Data && Mask;
Mask = Mask * 2;
Bit++;
}
}
```
where DataPin represents the port pin that I want to shift data out on and ClkPin is the clock port pin.
I want the device to shift out 8 bits, starting on the LSB of the byte. For some reason my output pin stays high all the time. I am certain that the port pins are configured properly so it is purely a logical issue.
|
You want to use &, not &&. && is the logical and, whereas & is the bitwise and.
|
What function should I use to escape strings for shell command argument in C?
I have a string:This is a string with () charactersThis will be error:echo This is a string with () charactersThese are OK:echo "This is a string with () characters"echo This is a string with \(\) characters
Is there a predefined function convert #2 to #3 in C?
|
Replacing all instances of'with'\''then enclosing the whole string in single quotes (') is one safe way. This works even with embedded newlines. Another method would be to insert\before each character, except that then you have to do some special treatment for newlines since\followed by a newline is ignored by the shell, not treated as a literal newline. You'd have to surround newlines with'(single quotes).
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Where do I find the current C or C++ standard documents?
Where can I read C99 official language standard manual/reference/specification online?
|
The standard itself ishere(a)(with TC1, 2 and 3 included), the rationale document ishere.
(a)Actually, it's the final draft but is still useful because:
the changes from final draft to published standard are usually minimal to none; andit's free unlike theactualstandards :-)
|
I am trying to display currently running process in Ubuntu.
Right now I am using system() function to print running process in the terminal. Code:
```
system("ps -A");
```
This function displays all running process in the terminal.
But I want to this functionality using a POSIX function. I am not looking for a ready made code.
Can some one point me to the function name or any manual ?
|
psis a POSIX command.
popenis a POSIX API for reading output from a command.
If you want a pure POSIX approach (maybe you want it portable to some OS that does not provide/proc), you should runpswith POSIX-only options and fetch the output frompopen.
So, for example, maybe you want to callpopen("ps -A -o pid=", "r");and then read through the list of PIDs.
|
I have just come to Mac world from Linux world and I love my way around in Mac environment. I want to write and practice simple C programs in mac and I was searching for the tools I require. Most (All) of the resources in the web ask me to use XCode as IDE to do programming in C on Mac. XCode, for my purpose seems to be an overkill. I am in no way interested in developing iPhone or Mac GUI application. All I want is
enter C programs using a text editor,compile it ,and get the output in a Console.
How can I do it ?
Thanks.
|
the 3 steps you give are simply the answer already:
use text editor of choiceuse eg Terminal and compile on command line (simply using gcc, or cmake/make or so for more complex programs)run program on console
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
Is there any way to write a C program without a main function? If so, how can that be achieved?
|
C defines the entry point in a hosted environment to bemain. In a "freestanding" environment, however, the entry point can have some other name. That's about the only latitude the language (at least officially) allows in that particular respect.
|
GDB normally stops all threads if a breakpoint is reached (or Ctrl+C is pressed in the GDB shell). I'm aware that commands like scheduler-locking and schedule-multiple exists, but I see no possibility to let a defined thread run in the background while another is debugged.
|
You can useset target-async onto enable asynchronous mode, if your target supports it. Then, you can specify background execution with commands. For example,
```
continue&
```
can be used to run a single thread, and
```
interrupt [-a]
```
to suspend execution of a single thread, or the whole program.
In conjunction with non-stop mode, you can examine a single thread while others continue to run in the background:
```
# If using the CLI, pagination breaks non-stop.
set pagination off
# Finally, turn it on!
set non-stop on
# Before debugging is started!
```
|
I am unable to figure out the exact difference between character devices vs Terminal devices vs Streams. Any help is very much appreciated.
Thanks & Regards,
Mousey.
|
Character devices are those which transmit one character at a time and are used for "stream" based I/O. Examples are modems, keyboards, mouse etc. They do not allow random access on data.
Streams - It is the communication framework of unix. it provides full-duplex mode of communication. Character special files, named pipes, and sockets are actually streams and not files.
Terminal devices - Not sure what you mean by "terminal devices". But I think you are refering to TTYs or tele-typewritters or computer terminals (monitors). Please be clear on this.
|
how to compare two strings in C? Help me, I am beginner@@
```
char *str1 = "hello";
char *str2 = "world";
//compare str1 and str2 ?
```
|
You may want to usestrcmp:
```
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
int v;
const char *str1 = "hello";
const char *str2 = "world";
v = strcmp(str1, str2);
if (v < 0)
printf("'%s' is less than '%s'.\n", str1, str2);
else if (v == 0)
printf("'%s' equals '%s'.\n", str1, str2);
else if (v > 0)
printf("'%s' is greater than '%s'.\n", str1, str2);
return 0;
}
```
Result:
```
'hello' is less than 'world'.
```
|
I'm using GL_FOG, but it only fogs up my geometry. I would like to find a way for the fog to feel like it encumbers an area, not just fog up my geometry, sort of like a box of fog...
Is there a way to do this? Or possibly another way to give a smooth draw distance transition?
|
If you have a skybox/sphere you can apply the fog to that, the only downside is that it will be there if you look straight up as well.
Your best bet is to dive into shaders as Jerry mentioned. Don't worry though they aren't that bad to work with. If you apply the fog to the scene based on distance AND vertical position in space you can create a nice fog effect without taking over your entire skyshape. You can also use a similar method to give yourself some clouds n' the like if you're feeling bold.
Hope this helps!
|
I am interested in Android kernel level programming. Actually I am a Linux kernel programmer. I would like to know how to start with the kernel and how compile, boot and about the Kernel level subsystems (EX: How file systems are implemented etc..) in Android. Any books or articles or a good guide to start are very much appreciated.
|
The Android kernel is a Linux kernel with only a few modifications (the rest of Android has nothing to do with Linux).
There's anice list of modifications on the Embedded Linux Wiki. This page also has several links that should interest you.
The most important feature for everyday Android development isbinders, an Android-specific interprocess communication mechanism, though they're usually used via higher-level interfaces.
The source of the Android kernel is athttps://android.googlesource.com.
|
I have a list of numbers as below:
0, 16, 32, 48 ...
I need to output those numbers in hexadecimal as:
0000,0010,0020,0030,0040 ...
I have tried solution such as:
```
printf("%.4x", a); // Where a is an integer
```
But the result that I got was:
0000, 0001, 0002, 0003, 0004 ...
I think I'm close there. How can I fix it?
I'm not so good atprintfin C.
|
Try:
```
printf("%04x",a);
```
0- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x- Specifier for hexadecimal
integer.
Morehere
|
Is there such a thing as Javadoc-type documentation available for C/C++ libraries?
|
Yes,doxygenfor documenting your code.
If you mean documentation of existing libraries :
For the STL, check out thesgisite.
For a general c/ c++ reference seehere.
For a specific library, check its site.
|
There are many functions (especially in the POSIX library) that return pointers to almost-necessarily freshly allocated data. Their manpages don't say if you should free them, or if there's some obscure mechanism at play (like returning a pointer to a static buffer, or something along these lines).
For instance, theinet_ntoafunction returns achar*most likely out from nowhere, but the manpage doesn't say how it was allocated. I ended up usinginet_ntopinstead because at least I knew where the destination allocation came from.
What's the standard rule for C functions returning pointers? Who's responsible for freeing their memory?
|
You have to read the documentation, there is no other way. My man page forinet_ntoareads:
The string is returned in a statically allocated buffer, which subsequent calls will overwrite.
So in this case you must not attempt to free the returned pointer.
|
If I allocate a C array like this:
```
int array[ 5 ];
```
Then, set only one object:
```
array[ 0 ] = 7;
```
How can I check whether all the other keys (array[1],array[2], …) are storing a value? (In this case, of course, they aren't.)
Is there a function like PHP'sisset()?
```
if ( isset(array[ 1 ]) ) ...
```
|
There isn't things like this in C. A static array's content is always "set". You could, however, fill in some special value to pretend it is uninitialized, e.g.
```
// make sure this value isn't really used.
#define UNINITIALIZED 0xcdcdcdcd
int array[5] = {UNINITIALIZED, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED};
array[0] = 7;
if (array[1] != UNINITIALIZED) {
...
```
|
I am writing a program in C for file compression. The method i am trying to use involves doing math on the file as if it were one long number. Can anyone recommend a bignum library that would not try to do all of that in ram, but rather let me do math with file pointers. any help would be appreciated, thanks in advance.
|
I doubt such a library exists. You could try mmap()ing the files in memory and see if you can do it that way.
|
I'm trying to implement linked-lists with c struct, I use malloc to allocate a new node then allocate space forvalue, so I've been thinking how to free the structure once I'm done with them, my structure looks like this:
```
typedef struct llist {
char *value;
int line;
struct llist *next;
} List;
```
I have a function that walks through the struct and free its members like this:
```
free(s->value);
free(s);
```
My question is, does that also free theint line?
|
Yes.
Theint lineis part of the structure, and so gets freed when you free the structure. The same is true of thechar *value. However, this does not free the memory whichvaluepoints at, which is why you need to callfreeseparately for that.
|
I need to optimize some C code, which does lots of physics computations, using SIMD extensions on the SPE of the Cell Processor. Each vector operator can process 4 floats at the same time. So ideally I would expect a 4x speedup in the most optimistic case.
Do you think the use of vector operators could give bigger speedups?
Thanks
|
The best optimization occurs in rethinking the algorithm. Eliminate unnecessary steps. Find more a direct way of accomplishing the same result. Compute the solution in a domain more relevant to the problem.
For example, if the vector array is a list ofnwhich are all on the same line, then it is sufficient to transform the end points only and interpolate the intermediate points.
|
Let us say i have
File1.c:
```
#include<stdio.h>
#include"File2.c"
void test(void)
{
sum(1,2);
}
int main(void)
{
int sum(int a,int b);
test();
sum(10,20);
return 0;
}
```
File2.c:
```
int sum(int x,int y)
{
printf("\nThe Sum is %d",x+y);
}
```
Now as far as my understanding goes test() calling sum() should give a Compile-Time Error since i have made/declared sum() local to main, which i am not getting, and the program is running fine without any errors.
My main purpose is to define sum in File2.c and make it local to main() so that no other function has visibility to this function sum().
Where am i going wrong?
|
Mark the function asstatic(this makes it local to the current translation unit).For the love of god, donotinclude.cfiles! (read me)
|
I am compiling this program on Windows, with gcc (MinGW) and GTK+:
```
#include <gtk/gtk.h>
void *destroy(GtkWidget *widget, gpointer data)
{
gtk_main_quit();
}
int main(int argc, char *argv[])
{
// Initalize GTK+
gtk_init(&argc, &argv);
// Create GTK+ window
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL);
// Show all widgets
gtk_widget_show_all(window);
// Enter loop
gtk_main();
// Exit program
return 0;
}
```
It compiles and runs, but the problem is that when I launch the program, it launches in a terminal window before opening the GUI window.
How do I prevent this from happening?
|
Edit:
Add the-mwindowsflag when compiling.
|
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.Closed13 years ago.
Can someone tell me in plan and simple terms what some of the more important features and options are for gcc and what they do? I look at the man pages and my head feels like exploding lol.
|
You might want to read the manual ongcc options, that groups the options in meaningful ways, and includes precise descriptions of same.
|
```
#include<stdio.h>
int main(void) {
int arr[3]={1,2,3};
return 0;
}
```
Now what will*(&arr)give me and why? I want a detailed explanation. Don't just tell me how*and&cancel out :P
I want to know how the compiler interprets this expression to give the desired result.
|
&arrcreates a pointer to the array - it's of typeint (*)[3], and points at the arrayarr.
*&arrdereferences that pointer - it's the array itself. Now, what happens now depends on what you do with it. If you use*&arras the subject of either thesizeofor&operators, then it gives the size or address of the array respectively:
```
printf("%zu\n", sizeof *&arr); /* Prints 3 * sizeof(int) */
```
However, if you use it in any other context, then it is evaluated as a pointer to its first element:
```
int *x = *&arr;
printf("%d\n", *x); /* Prints 1 */
```
In other words:*&arrbehaves exactly likearr, as you would expect.
|
Does a quine print the ACTUAL code of the program i.e not obfuscated or does it print the obfuscated program?
|
I don't think obfuscation has anything to do with it. Usually a quine prints the actual source code of the program itself.
|
If a file is opened using the following command:
```
FILE *f1=fopen("test.dat","a+");
```
The man page reads:
a+Open for reading and appending (writing at end of file). The
file is created if it does not exist. The initial file position
for reading is at the beginning of the file, but output is
always appended to the end of the file.
So doesf1have 2 separate offset pointers, one for read & another for write?
|
No.
There is just one pointer which initially is at the start of the file butwhen a write operation is attempted it is moved to the end of the file. You can reposition it usingfseekorrewindanywhere in the file for reading, but writing operations will move it back to the end of file.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
Why use the uglyfor(;;)syntax instead of the slightly better lookingwhile(true)loop?
|
There is no advantage tofor(;;)overwhile(1).
Usewhile(1), because it's easier to comprehend (imho). I've never seen afor(;;)used before, and it may be confusing to others who view your code, and may wonder the same thing you just asked.
EDIT: Here's a link:while (1) Vs. for (;;) Is there a speed difference?
It basically says that they both generate the same code. In assembly, it'sjmp ....
|
I ran the following:
```
#include <stdio.h>
typedef unsigned short boolean;
#define false 0
#define true (!false)
int main()
{
int STATUS = 0;
int i = 0;
boolean ret = true;
for(i = 0; i < 99999; i++)
{
ret = ret && printf("Hello, World.");
}
if(!ret)
{
STATUS = -1;
}
return STATUS;
}
```
It completes in just under a second. Typically 0.9 - 0.92.
Then I changedint i = 0;toint *i = 0;and now I am getting execution times under 0.2 seconds. Why the speed change?
|
Your runtime is dominated by the time required to print to the console. i++ on an int* will increment the pointer by the size of a pointer. That will be either 4 or 8 depending on your computer and compiler settings. Based on the numbers you report, presumably it would be 4. So printf is executed only a quarter as many times.
|
On Linux, I can read available input without blocking the process:
```
fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK )
char buf[n];
int r = fread(buf, 1, n, stdin);
if (r == 0){
printf("nothing\n");
}
else {
printf("read: ");
fwrite(buf, 1, r, stdout);
printf("\n");
}
```
The input origin can be anything, such as a file, a terminal or a pipe.
How can I do it on Windows XP?
Thanks.
|
Why not read the input from a second thread? Depending on your situation, it might be a much easier approach, instead of using non-blocking IO's.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.