question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I have confusions about what implementation of errno() should I use in my programs.
As far as I know, the standard errno() is defined in errno.h. However, Visual Studio also has errno() in stdlib.h. Maybe that's incorrect, but for me stdlib.h's errno() is faster than errno.h's one. But errno() is also defined in stdd... |
In C, useerrno.hand in C++ usecerrnoheader.
errnocan be defined in other headers for convenience but for maximum portability you should use the ones above.
|
Two projects:
The loader, a standalone executable (only loads modules)any module, a shared library (librainbowdash.so) (there can be many modules)
Now, the module is linked with-lpthreads, but I get some weird errors which make me think pthreads is bound as a shared object only, and when the loader loads a module pt... |
-lspecifies library names. It is up to the linker to resolve the library names into static libraries or shared objects to be linked against as appropriate. And it is the loader's job to load any shared libraries used.
|
My application hogs memory, but does not leak it. During analysis I discovered that most of the allocated memory comes fromgetcandfprintfcalls who domalloc(16kb). I did not know that those functions allocate memory on the heap? Especiallyfprintf? How can I free it?
|
I forgot to call fflush on the streams before closing them... (turns out my setup does not allow fflushing the streams because they are still blocked by cancelled threads...). Thanks for your help!
|
If I have a socket and someone sent data to it that I didn't yet handle viaread(), and now I make anev_iowatcher for it and run it, will the callback fire?
|
I don't know the answer to your question as I've never usedlibev. But I can suggest in the absence of this knowledge you might try to simulate the scenario and see what happens. :-)
|
I'm learning C and want to write programs with GUI. Personally I'm OK with terminal in Linux or the black window in Windows. However, I want to write something that could be used by other non-professional users. So I wrote this post to ask how to write a GUI program in C (C++ is OK). What kind of books should I read? ... |
For pure C, you could useGTK+, but if you're familiar with C++ too, i 'd recommendQtFramework from Nokia. There are over 100 of youtube videos for mastering Qt. Follow this link:Qt training
|
I'm using asynchronous pipes for inter-process communication (I removed error checks for simplification)
```
int pipe_fd[2];
pipe(pipe_fd);
int fdflags = fcntl(pipe_fd[1], F_GETFL, 0);
fdflags |= O_NONBLOCK;
fcntl(pipe_fd[1], F_SETFL, fdflags);
```
I'm looking for a way to increase pipe internal buffer size.
I know ... |
On the kernel of CentoS 5, a pipe is fixed at 64 KB
|
In C, is there a way to start a timer using setitimer, then pause it, then resume the timer with the time remaining when it was paused? My initial thought was to save the time left by using getitimer, stop the timer, then set the timer back to the saved value in getitimer, but this doesn't seem to be working.
|
You cannot pause a timer. Saving the time remaining, stopping the timer and then starting a new timer istheway to do this. That method does work so I guess you have a bug in your code.
|
I am learning C currently and wanted to know whether the following two pieces of code perform differently, or if it's just a style thing.
Looking at some sources they the have the following code:
```
...
FILE * pFile;
pFile = fopen ("myfile.txt","r");
if (pFile == NULL)
{ some code }
...
```
While my professor has ... |
There is no difference.More experienced programmers sometimes go with the second form, just to save a line, but they areessentially identical. The second tends to be a little more "UNIX-y", where most function calls are checked for error (as opposed to success) before continuing.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
Why not use memcpy?
```
unsigned char uChars[count];
signed char sChars[count];
memcpy(uChars, sChars, count);
```
|
Is the a amount of padding in Cstructwell defined in standards or compiler and/or target architecture dependent. I could not find an answer in the standards.
|
It is implementation-defined. From section 6.7.2.1 of the C99 standard:
...Each non-bit-field member of a structure or union object is aligned in an implementation-defined
manner appropriate to its type......There may be unnamed
padding within a structure object, but not at its beginning...
The compiler will ty... |
I came across to a question from one of my friend.
What is the difference between these?
```
* char ptr
char * ptr
```
|
This is an error:
```
* char ptr;
```
This declaresptras a variable of type pointer-to-char:
```
char * ptr;
```
|
```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glBegin(GL_TRIANGLES);
// glVertex3f(-0.5,-0.5,0.0);
// glVertex3f(0.5,0.0,0.0);
// glVertex3f(0.0,0.5,0.0);
//glEnd();
glutSolidSphere(200,10,10);
glutSwapBuffers();
```
the triangle shows up but not the sphere
why?
I just get a black window
|
Your radius is probably too big and you are culling back faces.
```
glutSolidSphere(1,10,10);
```
Glut is close-sourced and unmaintained. Consider something else, like SDL.
|
I have a C console app, using VS2010, to which I would like to add a simple Window interface. (All the program does is a simple loop: get some input from the user, run the program, produce a single number as a result, continue). The input from the user basically involves just modifying the values of a C structure:
... |
GTKis probably theeasiestway (but, not easy at all).Qtwill be much better if you can move to C++.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:C pointer to array/array of pointers disambiguation
How ischar (*p)[4];different fromchar *p[4];?
|
http://cdecl.org/
char (*p)[4];-- declare p as pointer to array 4 of char.char *p[4];-- declare p as array 4 of pointer to char.
|
I'm trying to use a circular buffer like the one mentioned in this post:https://stackoverflow.com/a/827749
When I need to push and pop things to the buffer I find myself doing something like this all the time:
```
int data;
int *data_ptr = &data;
cb_pop(spi_buffer, data_ptr);
```
Is this the best (probably not) way... |
Why won't you just do:
```
int data;
cb_pop(spi_buffer, &data);
```
the creation of another pointer variable is redundant.
|
I'm trying to pass my sqlite database through to a function and then through to another one again. Here is my code.
```
//database Name
// Create a handle for database connection, create a pointer to sqlite3
sqlite3 *dataDB;
//I send it through to the function here
// Execute the query for creating table
retval = sq... |
From withinreadInFiles,dataDBis of typesqlite3**already, so you need to call:
```
addCourse(dataDB,deg,k);
```
|
I'm doing some computer hardware architectural explorations and I was eager to test different tasks on my prototype. so I need some code to simulate the task of video encoding and/or decoding (H264 would be perfect but other codecs are also ok).
Is there anything that I can use? It doesn't have to be exactly encoding... |
Have a look atlibavcodec. It ispure C.
|
I have ;
```
default :
gcc -o function function.c
```
When I type make in terminal, following message is emitted
```
user@user-laptop:~/Desktop$ make
gcc -o function function.c
user@user-laptop:~/Desktop$
```
But I want
```
user@user-laptop:~/Desktop$ make
user@user-laptop:~... |
Use an@to quiet the output:
```
default:
@gcc -o ...
```
You can find the documentation here:Recipe echoing. (Or you can invokemakewithmake -sto suppress all echoing.)
|
I want to develop my own C compiler to get deeper into flex and bison for my compiler lessons at University, but I can't find flex and bison, which I've seen described in some other posts. Do I need to install extra packages for Xcode or is there any other way?
I'm running Mac OS X Lion and have Xcode 4.3.2.
|
Flexandbisonare also included with the optional Command-Line Tools download for Xcode 4.3. See instructions athttps://developer.apple.com/library/ios/#documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_4_3.htmlon how to install this. They end up installed in /usr/bin.
You may prefer getting them via... |
I'm looking to save an HBITMAP to a PNG image. Is this possible using only the GDI API? (I'm using C, so no GDI+.) I have only found examples likethis, to save to a BMP file. Or should I uselibpngand useGetDIBits?
Related question(about reading).
|
Unfortunately, GDI does not support PNGs.
|
This is mymain.c
```
......
int main(int argc, char **argv)
{
init_arg(&argc, &argv);
......
}
```
This is myinit_arg.c
```
......
void init_arg(int *argc, char ***argv)
{
printf("%s\n", *argv[1]);
......
}
```
I compiler it with no error and warning.
I run it:
./a.out include
It getSegmentation... |
You need to add a pair of parentheses around (*argv) to change the order of evaluation. The way you currently have it, the [1] is evaluated first, yielding an invalid pointer, which then gets dereferenced, causing undefined behavior.
```
printf("%s\n", (*argv)[1]);
```
|
I have heard that C doesn't have closure, and today I saw the use of closure in Objective-C. Is closure supported in Objective-C and not in C?
Update: thanks for all the answers.I found this guide on the web on blocks as well:http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1
|
Apple added the^operator to add closure support. It is not tied to Objective-C however, and can be used in C and C++ as well, as long as you compile the project with Apple's brach of GCC or LLVM. This new feature is calledblocks.
|
I've always wondered if there are any naming convetions as when to use ALLCAPS for a type and when to append_t(and when to not use anything?). I know back in the days K&R published all kinds of documents about how to use C, but I couldn't find anything about this.
Among the C standard library types,_tseem prettys dom... |
Actually according to the POSIX standard, all type names ending in _t are reserved, as definedhere:
Names that end with ‘_t’ are reserved for additional type names.
|
This question already has answers here:C function syntax, parameter types declared after parameter list(7 answers)Closed2 years ago.
A few times now, I've encountered code like this:
```
int
main(argc, argv)
int argc; char **argv;
{
...
}
```
Why areargcandargvdeclared in this way?
|
This was the syntax that was used for K&R*styleparameter lists.
* K&R - Brian Kernighan and Dennis Ritchie, authors of the book, "The C Programming Language."Dennis Ritchiewas also the creator of the C programming language and with Ken Thompson, the UNIX operating system.
|
Is there a portable equivalent of__attribute__ ((__packed__))
(by portability I mean working on PC, Android and iPhones, regardless architecture)
|
By definition,__attribute__s are non-portable. If you want your data a specific way, the Plan9 solution is usually to useunsigned chararrays in your structure:
```
struct foo {
uchar data1[4];
uchar other[2];
}
```
Usually won't have any alignment, since it's fundamentally using unsigned characters. Of cours... |
I have the below code to choose sin or cos to be integrated,
```
while( x !=1 || y !=(1||0) ){
printf("Sin (1) or Cos (0)?\n");
x = scanf("%d",&y);
_flushall();
if(y==1){
printf("Sin set\n");
}
else if(y==0){
printf("Cos set\n");
}
}
```
However the
``... |
You need(y != 1 && y != 0)(or similar, it depends on what you really mean to express there). The||operator is being applied to the operands1and0. Put another way,y != (1 || 0)means "Do(1 || 0)then doy != result".
|
Hello I'm getting an error when i try to pass a char through to a function.
here is my code.
variable
```
char *temp;
```
Prototype
```
int checkIfUniqueCourseNo(char,int);
```
Call
```
checkIfUniqueCourseNo(temp,k);
```
and my error
```
warning: improper pointer/integer combination: arg #1
```
Im new to C so... |
Your function accepts achar; you are trying to pass in achar*.
To fix this you need todereferenceyour pointer to obtain the character that it points to, so that your function receives the type of argument it expects:
```
checkIfUniqueCourseNo(*temp,k);
```
|
I'm trying to implement the ringbuffer from this posthttps://stackoverflow.com/a/827749and the only code I've added is a main that looks like this.
```
int main(int argc, char** argv) {
circular_buffer *my_buff;
cb_init(my_buff, 16, sizeof(char));
return (EXIT_SUCCESS);
}
```
I get a SIGSEV (Segmentatio... |
You need to allocate memory formy_buff
At the moment you're passing an uninitialised pointer intocb_initwhich is then dereferenced.
But I'm sure you must have realised this because I'm sure you will have tried running the code in a debugger...
|
have been searching for a mod operator in ios, just like the%in c, but no luck in finding it. Tried the answer in thislinkbut it gives the same error.
I have a float variable 'rotationAngle' whose angle keeps incrementing or decrementing based on the users finger movement.
Some thing like this:
```
if (startPoint.x... |
You can usefmod(fordouble) andfmodf(forfloat) of math.h:
```
#import <math.h>
rotationAngle = fmodf(rotationAngle, 360.0f);
```
|
I am using binary search to search a number from a sorted array of numbers in O(log(n)) time. My C function for search is as follows:
```
search(int array[],int size,int search)
{
int first=0;
int last=size-1;
int middle = (first+last)/2;
while( first <= last )
{
if ( array[middle] < search )
... |
Yes, use a hash table. It should be faster in the average case.
|
In C how can I separate a char array by a delimiter? Or is it better to manipulate a string? What are some good C char manipulation functions?
|
```
#include<string.h>
#include<stdio.h>
int main()
{
char input[16] = "abc,d";
char *p;
p = strtok(input, ",");
if(p)
{
printf("%s\n", p);
}
p = strtok(NULL, ",");
if(p)
printf("%s\n", p);
return 0;
}
```
you can look this program .First you should use the strtok... |
I have a program in x86 assembly which I want to decompile to a higher level language. I checked outboomerangfor that purpose, but it seems that it only takes binary files as input. What are my options here?
|
There is a product which works from assembler calledRelogix, but I expect their pricing is geared towards enterprise customers with big code base and not single-file private users. From the free solutions,Boomerang(somewhat dead) andREC Studio(seems to be active) need some kind of compiled binary.Hex-Raysneeds binary ... |
I am using non-local jumps (setjmp,longjmp). I would like to know if it can be a problem for the performances. Doessetjmpsave all the stack, or just some pointers ?
Thanks.
|
setjmphas to save sufficient information for the program to continue execution whenlongjmpis called. This will typically consist of the current stack pointer, along with the current values of any other CPU registers that could affect the computation.
I can't comment on whether this causes a "performance problem", be... |
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.Closed11 years ago.
How can I use ffmpeg functions to d... |
You can use ffmpeg to extract images from videos and in reverse generate video back from sequence of images.
Either you can use ffmpeg wrapper e.ghttp://www.mediasoftpro.com/post/18/extracting-frames-from-video-and-re-encoding-image.aspxor can use c# "Process() class to execute ffmpeg commands in background with c# a... |
I am making a module to do some basic stuff in my pen drive following the examplehere. its stating that the usb storage(in my case pen drive) device uses usb-storage driver . I saw in hardware info that its usb_storage(which is same as usb-storage as when i do rmmod usb -storage it states that ERROR: Module usb_storag... |
Assuming that your kernel actually has usb-storage support this means the module is built in to the kernel and cannot be removed.
Try rebuilding your kernel after changing the usb-storage support to be built as a module, rather than directly into the kernel.
|
what will be the output of following codeint x,a=3;x=+ +a+ + +a+ + +5;printf("%d %d",x,a);
ouput is: 11 3. I want to know how? and what does + sign after a means?
|
I think DrYap has it right.
```
x = + + a + + + a + + + 5;
```
is the same as:
```
x = + (+ a) + (+ (+ a)) + (+ (+ 5));
```
The key points here are:
1) c, c++ don't have + as a postfix operator, so we know we have to interpret it as a prefix
2) monadic + binds more tightly (is higher precedence) than dyadic +
F... |
I am looking on a way to convert decimals to degrees in C. For instance, the asin() function in C returns a decimal number but I need that number to be in degrees ° minutes ' seconds ".
e.g. 1.5 would be 1°30'0"
|
Theasinfunction returns radians. There are 2 π radians in a circle.
There are 360 degrees in a circle, 60 minutes in a degree, and 60 seconds in a minute. So there are 360*60*60 seconds in a circle.
```
double radians = asin(opposite / hypotenuse);
int totalSeconds = (int)round(radians * 360 * 60 * 60 / (2 * M_PI)... |
In the following code:
```
int foo();
int bar();
int i;
i = foo() + bar();
```
Is it guaranteed by the C standard thatfoois called beforebaris called?
|
No, there's no sequence point with+. There's actually a quote on the Wikipedia page about it that answers your question:
Consider two functions f() and g(). In C and C++, the + operator is not associated with a sequence point, and therefore in the expression f()+g() it is possible that either f() or g() will be execu... |
I have heard that C doesn't have closure, and today I saw the use of closure in Objective-C. Is closure supported in Objective-C and not in C?
Update: thanks for all the answers.I found this guide on the web on blocks as well:http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1
|
Apple added the^operator to add closure support. It is not tied to Objective-C however, and can be used in C and C++ as well, as long as you compile the project with Apple's brach of GCC or LLVM. This new feature is calledblocks.
|
I've always wondered if there are any naming convetions as when to use ALLCAPS for a type and when to append_t(and when to not use anything?). I know back in the days K&R published all kinds of documents about how to use C, but I couldn't find anything about this.
Among the C standard library types,_tseem prettys dom... |
Actually according to the POSIX standard, all type names ending in _t are reserved, as definedhere:
Names that end with ‘_t’ are reserved for additional type names.
|
This question already has answers here:C function syntax, parameter types declared after parameter list(7 answers)Closed2 years ago.
A few times now, I've encountered code like this:
```
int
main(argc, argv)
int argc; char **argv;
{
...
}
```
Why areargcandargvdeclared in this way?
|
This was the syntax that was used for K&R*styleparameter lists.
* K&R - Brian Kernighan and Dennis Ritchie, authors of the book, "The C Programming Language."Dennis Ritchiewas also the creator of the C programming language and with Ken Thompson, the UNIX operating system.
|
I want to change one value of a file, but the follow code doesn't work at all. It works properly when i remove the if statement.Code follows:
```
#include <stdio.h>
int main()
{
int b;
FILE *fp;
fp=fopen("new", "r+");
fseek(fp, 0x30, 0);
b = fgetc(fp);
if(b == 0x63)
fputc(0x64, fp);... |
You've written onepastbif it is0x63, becausefgetcadvances the file stream:
```
b = fgetc(fp);
if(b == 0x63) {
fseek(fp, -1, SEEK_CUR);
fputc(0x64, fp);
}
```
|
This question already has answers here:How to compare ends of strings in C?(25 answers)Closed7 years ago.
How can I check whether a string ends with.csvin C?
I've tried usingstrlenwithout any success.
|
How about:
```
char *dot = strrchr(str, '.');
if (dot && !strcmp(dot, ".csv"))
/* ... */
```
|
I was looking for some code about macros, and I found a code like this, for the macro « va_start » :
```
#define __va_argsiz(t) \
(((sizeof(t) + sizeof(int) - 1) / sizeof(int)) * sizeof(int))
#define va_start(ap, pN) \
((ap) = ((va_list) (&pN) + __va_argsiz(pN)))
```
I would like to know what is the goa... |
Both alignment, and the default type promotion rules in C.
|
Let's say I have a criteria and I want to add a delta if that criteria is true, and do the opposite (subtract) if it is false.
```
bool bBoolean;
int iDelta;
int iQuantity;
```
Is there a more concise and elegant way to write that piece of code ? I mean without repeating the keywords iQuantity and iDelta.
```
if(bB... |
The shortest thing I can think of is:
```
iQuantity += (bBoolean) ? -iDelta : iDelta;
```
Edit: This is commonly called a ternary statement, though it's proper name (what it's called in the standard) is "conditional expression" or "conditional operator".
(Thanks to Rune for the official name.)
|
I am accepting an input from user as a float value.
This value can go up to "10 raised to power 18".
The next step involves finding all the divisors of this number. for which i am doing the following:
```
for(i=2; i<=n/2 ; i++)
{
if(n%i==0)
v.push_back(i);
}
```
Here, n is the numbe... |
You can use anunsigned long longwhich is 264or roughly 1019
This assumes that your compiler supports 64-bit integers.
|
Sorry for such a simple question, but does anyone have a C example of initializing the MSP430 for SPI mode and performing poll read and write operations? Very new stuff to me and am not sure where to start.
Thanks.
|
You might have a look atMSP430Warewhich is "a collection of code examples, datasheets and other design resources for ALL MSP430 devices..."
|
In quite some articles they suggest using thefistpinstruction for converting float->integer in a fast way. This is dependent on the current rounding mode of the CPU, so you'll have to set it.
But can this rounding mode get changed during the runtime of the program by other programs? By the OS?
Even worse, is this a ... |
No sane general-purpose OS would share the rounding mode across processes and threads. It should only change when a thread requests it and the change should be local to that thread only. You may, however, encounter that some libraries (especially, 3rd party) change it and sometimes (or always) fail to restore it and f... |
I'm trying to remove some confusion with pointer to structures which are used as members in class. I wrote following code, but even though the program compiles it crashes. Could you please say what I'm doing wrong in the following code?
```
#include<stdio.h>
#include<string.h>
struct a{
int s;
int b;
cha... |
```
void test::dh()
{
a d; <--
d.s=1;
d.b=2;
d.h="ffdf";
f=&d; <--
}
```
You're creating a local object,d, and then settingfto the address of this object. Once the function ends, the object goes out of scope and you're left with a dangling pointer.
|
I have a program that is listening to a certain event file handle. Is there a file I can read to get details about the specific event's device that I am listening to?
|
Assuming that (a) you're on Linux and (b) you havesysfsmounted (typically on/sys), you can look at/sys/class/input/eventX. This will be a symlink into the device tree; this should provide you some device details. For example:
```
$ readlink /sys/class/input/event4
../../devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1... |
I was solving some simple pointer exercises when i came across the following example:
```
void deallocate2D(int** array, int nrows) {
/* deallocate each row */
int i;
for(i = 0; i < nrows; i++) {
free(array[i]);
}
/* deallocate array of pointers */
free(array);
}
```
The array is defined i... |
Yes, that's correct.int***is only necessary if you intend to change the value of the pointer, which you don't need to.
There do exist tools which can check your memory allocations/frees - Valgrind should be able to do it.
|
Is there any API(or special file) on Linux that provides an event on the change in link status of an ethernet card without polling ? i.e. when you plug in/out the cable ?
|
You can get link up/down events via netlink. You would create aPF_NETLINKsocket, bind to theRTMGRP_LINKgroup, and wait forRTM_NEWLINK/RTM_DELLINKmessages. Link up events haveIFF_RUNNINGandIFF_LOWER_UPset inifinfomsg.flags, while link down events have both flags cleared (funnily enough, I'm gettingRTM_NEWLINKmessages f... |
I have an example code like this:
```
int var;
var = MACRO_A;
```
I expect theMACRO_Ahas been defined like this:
```
#define MACRO_A 1234
```
However, I cannotfind theMACRO_Adefined anywhere in the source code, but I can build the code successfully, so what is the value ofvarat the end ?
The compiler is gcc.
|
However, I can not find the MACRO_A defined anywhere in the source
code, but I can build the code successfully, so what is the value of
var at the end
It's there somewhere or it wouldn't compile. Perhaps it's defined directly on the command line ? (-DMACRO_A)
|
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
I am not sure what is going on. No error message displayed, though Windows error reporting is enabled. I ev... |
You can useProcess Dumperto get a memory dump on any process exit. Postmortem debugging of the result might help identify the cause.
|
i have dialog window with GtkEntry. I want to select all text in entry right after dialog window becomes visible to user. I tried this, but its not working, i see no selection:
```
static void OnEntryShow(GtkWidget *entry, gpointer user_data)
{
gtk_editable_select_region(GTK_EDITABLE(entry), 0, -1);
}
...
gtk_en... |
Perhaps you want the GtkEntry to grab focus?
Try this:
```
gtk_widget_grab_focus (entry);
```
whereentryis in this case the pointer to your GtkEntry widget.
The documentation of the function can be foundhere.
|
I am trying to write a C program to get the character in the file which is ofset by some bytes, lets say three as below
```
fseek(fp,3,SEEK_CUR);
```
I wish to print the character which that particular byte represents. For example if my file contains something like below,I need to print every third character.
```
/... |
fgetcmoves the file offset by one. Try the following:
```
fseek(fp,3,SEEK_CUR);
while(fp!=EOF)
{
ch = fgetc (fp); // moves offset by 1
fseek(fp,2,SEEK_CUR); // moves offset by another 2
printf("%c",ch);
}
```
|
Is there a library like Python's httplib for C?
I am asking because I want to write a C program that creates an HTTPSConnection.
Thanks.
|
libcurl is indead the most famous, but there are also a lot of alternativeshere.
|
How do i initialize a variable of structure B or C?
```
typedef struct _A
{
union
{
struct
{
int b;
} B;
struct
{
int c;
} C;
} u;
} A;
```
Something likeA.u.B *bVar;doesn't work
|
Thetypedefonly coversA, not the union or structures defined therein.
typedefcan't be nested like that - each user-defined "type" must have a single label, so a declaration of a variable of typeA.u.Bis illegal.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
I am sorting floats.
In this case,tempmust be of typefloat:
```
float temp=pd[i];
```
Otherwise, you're truncatingpd[i]tointeach time you do a swap.
Also, if yourfloatarray might containNaNs, they'll require extra care in comparisons.
|
We use#warningto show compile message, like this:
```
#warning Are you sure it is correct?
```
Is is possible redefine the#warningand can choice if enable or disable it, like this:
```
#ifdef ACTIVE_MY_WARNING
#define #my_warning #warning
#else
#define #my_warning
#endif
```
We can do it in C or not?
|
No, it's not possible to redefine preprocessor keywords (#if,#define,#ifdef, etc).
Your best shot is to have a parser that can replace your code with:
```
#ifdef ACTIVE_MY_WARNING
#warning Are you sure it is correct?
#endif
```
|
As we know the integer storage length is 4 bytes and character storage is 1 byte.Here comes my problem,I have a huge data and I need to write them into a file.
For eg. my data is like
```
Integers - 123456789 (of length 9) (Total 9! factorial records)
Character - abcdefghi (of length 9) (Total 9! factorial reco... |
It's insignificant compared to the file's access time.
|
I have a const char* variable "str" which can be like the following one:
```
const char* str ="/v1/AUTH_abb52a71-fc76-489b-b56b-732b66bf50b1/images/bhs";
```
I have to split thisstrvariable and store them in an array which is likechar a[256]. But I want to split by detecting every slash(/). I mean I want to storev1,... |
strcpy(), then strtok().
Or do it the really basic way by iterating through the array.
Is this homework?
|
I have below code.
I am getting error as'list' undeclared (first use in this function).
Please help me
```
#include <stdio.h>
#include <stdlib.h>
struct list{
int data;
struct list *next;
};
typedef struct list *head;
int main()
{
struct list *start;
int i;
start = (list *) malloc(sizeof(struct list));
... |
You're using the typelistinstead of variable namestart. Proper code:
```
while (start->next != NULL)
{
start = start->next;
// etc.
}
```
|
I have a program that uses_mm_crc32_u64. I include the header filesmmintrin.hfor that purpose and also use the flag-msse4.1when compiling it withgcc. However, when I compile it I getundefined reference to _mm_crc32_u64error. What is the problem here?
|
I did it like this and it worked! So basically I had to use msse4.2 instead of msse4.1.
```
gcc44 crc.c -msse4.2
```
|
This is the structure of my code
```
if(someFunction())
{
// Some code
}
```
wheresomeFunction()evaluates to0most of the time
When GDB is at line 1 above, if I donextthen// Some codewill not be executed.
Is there a way to tell GDB to execute the code inside theifstatement?
|
I can just propose you a workaround. Have a temporary variableint i=0and then do the if as
```
if(i==1){
//some code
}
```
When you reach the desired position with gdb. Setito 1 using
```
set i = 1
```
and then your loop will be executed. Of course after the loop you will have to reset you i if you don't want it... |
I included some sample ASM code in a small program to do a test.
My program is:
```
#include <stdio.h>
static inline
unsigned char inb (int port) {
unsigned char data;
asm volatile("inb %w1,%0" : "=a" (data) : "d" (port));
return data;
}
int main()
{
printf("hello world %d\n", inb(22));
return ... |
You need to useiopermbefore you're allowed to use port I/O. Also, note the kernel already providesinbandoutbfunctions.
Use ioperm(2) or alternatively iopl(2) to tell the kernel to allow the
user space application to access the I/O ports in question. Failure
to do this will cause the application to receive a segm... |
I am running the following C code:
```
#define cube(x) (x*x*x)
void main()
{
int x=2,y;
y=cube(++x);
printf("%d %d",++x,y);
}
```
I am expecting result as
```
6,60
```
But it is giving different result. I think I have misconception on pre-processor. I think the code will be simila... |
You defined a macro, which works as a simple string substitution, so that the presented translation is correct.
However, the order of execution of subexpressions is undefined and they can be, for example, interleaved and this makes theundefined behaviour.
|
I want to write a small program inC: When I plug my headphones in my notebook, it should turn the volume lower. Then, when I remove headphone from my notebook, it should turn the volume back up.
I am using thealsadriver, and I know how to control the volume.
The question is: How to get notified, when the headphone g... |
Maybe you don't need to write any program. Alsamixer should let you specify the volume of the speaker and the volume of the headphones. You just set the headphones' volume a little lower, and that's all.
|
How do you explain the Rounding happening here?I thought assigning float values to Int's always cause loss of value after decimal?
```
int z=39.99999999999999999999999;
printf("%d",z); // gives 40
```
Thanks
|
You can't have a double precise enough to hold all those 9s.
```
>>> '%.15f' % 39.9999999999999
'39.999999999999901'
>>> '%.15f' % 39.99999999999999
'39.999999999999993'
>>> '%.15f' % 39.999999999999999
'40.000000000000000'
```
|
Once my embedded device is connected to USB port of my PC, it should trigger an exe as an event. How can I achieve this??
Should I create a service to keep monitoring the USB connector bus or is there any default API's available in Windows to achieve this??
thanks.
|
A simple exe which is started on connect is not possible. But you can write a service or user mode application which listens for device arrival events.WM_DEVICECHANGEis sent to all (registered) applications with a device interface guid which represents which device is plugged in. You can then use this id with the setu... |
If I have 3 source like "a b c", how do I separate a from b from c?
```
struct target *t = target_start;
char *source_start = p_colon+1;
while (*source_start == ' ' || *source_start == '\t')
{ source_start++; }
char *source_end = source_start;
while (*source_end == ' ' || *source_end == '\t')
... |
Lookup the strtok() function to break a string into a series of tokens.
|
```
void run_hot(void) {
// I am called very often!
serve();
// <more code here>
}
void run_cold(void) {
// I am called only occasionally!
serve();
// <more code here>
}
???inline??? void serve(void) {
// I only want to be called inline from hot functions!
// <more code here>
}
```
I... |
You are completely at the mercy of the compiler with inlining.Leave aside partially, whether or not toinlinea function is solely a decision that is best made by the compiler and you should rely on it to make the best decision.
|
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed7 years ago.
I am wondering why am I getting segmentation fault in the below code.
```
int main(void)
{
char str[100]="My name is Vutukuri";
char *str_old,... |
You haven't initialized*str_newso it is just copyingstr_oldto some random address.
You need to do either this:
```
char str_new[100];
```
or
```
char * str = (char *) malloc(100);
```
You will have to#include <stdlib.h>if you haven't already when using the malloc function.
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question
Is there a way/tutorial to take a PCB (Printed Circuit Board) and make an LED Blink? Im basically asking:
Is there a DIY ... |
O'Reilly published a book calledProgramming Embedded Systems in C and C ++. The book dedicates an entire chapter to precisely this exercise (the chapter is called, not surprisingly, "Das Blinkenlights").
|
I have a scenario where multiple clients connect to a TCP server. When any of the clients sends a packet to the server, the server is supposed to have a retransmission timer and keep sending that packet to another server until it receives a reply. How do I go about setting up this retransmission mechanism? I'm doing t... |
If you use a TCP socket, retransmit will happen automatically. Admittedly, if you want more control, you'll need to use UDP and handle the retransmit yourself.
|
How do you explain the Rounding happening here?I thought assigning float values to Int's always cause loss of value after decimal?
```
int z=39.99999999999999999999999;
printf("%d",z); // gives 40
```
Thanks
|
You can't have a double precise enough to hold all those 9s.
```
>>> '%.15f' % 39.9999999999999
'39.999999999999901'
>>> '%.15f' % 39.99999999999999
'39.999999999999993'
>>> '%.15f' % 39.999999999999999
'40.000000000000000'
```
|
Once my embedded device is connected to USB port of my PC, it should trigger an exe as an event. How can I achieve this??
Should I create a service to keep monitoring the USB connector bus or is there any default API's available in Windows to achieve this??
thanks.
|
A simple exe which is started on connect is not possible. But you can write a service or user mode application which listens for device arrival events.WM_DEVICECHANGEis sent to all (registered) applications with a device interface guid which represents which device is plugged in. You can then use this id with the setu... |
If I have 3 source like "a b c", how do I separate a from b from c?
```
struct target *t = target_start;
char *source_start = p_colon+1;
while (*source_start == ' ' || *source_start == '\t')
{ source_start++; }
char *source_end = source_start;
while (*source_end == ' ' || *source_end == '\t')
... |
Lookup the strtok() function to break a string into a series of tokens.
|
```
void run_hot(void) {
// I am called very often!
serve();
// <more code here>
}
void run_cold(void) {
// I am called only occasionally!
serve();
// <more code here>
}
???inline??? void serve(void) {
// I only want to be called inline from hot functions!
// <more code here>
}
```
I... |
You are completely at the mercy of the compiler with inlining.Leave aside partially, whether or not toinlinea function is solely a decision that is best made by the compiler and you should rely on it to make the best decision.
|
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed7 years ago.
I am wondering why am I getting segmentation fault in the below code.
```
int main(void)
{
char str[100]="My name is Vutukuri";
char *str_old,... |
You haven't initialized*str_newso it is just copyingstr_oldto some random address.
You need to do either this:
```
char str_new[100];
```
or
```
char * str = (char *) malloc(100);
```
You will have to#include <stdlib.h>if you haven't already when using the malloc function.
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question
Is there a way/tutorial to take a PCB (Printed Circuit Board) and make an LED Blink? Im basically asking:
Is there a DIY ... |
O'Reilly published a book calledProgramming Embedded Systems in C and C ++. The book dedicates an entire chapter to precisely this exercise (the chapter is called, not surprisingly, "Das Blinkenlights").
|
I have a scenario where multiple clients connect to a TCP server. When any of the clients sends a packet to the server, the server is supposed to have a retransmission timer and keep sending that packet to another server until it receives a reply. How do I go about setting up this retransmission mechanism? I'm doing t... |
If you use a TCP socket, retransmit will happen automatically. Admittedly, if you want more control, you'll need to use UDP and handle the retransmit yourself.
|
I have downloaded and looked over the code forlibs3, a library written for C/C++ that interacts with Amazon S3. This library uses a couple of concepts I am not completely comfortable with, so I am curious as to whether or not people know of any tutorials or sample programs that utilize this library.
|
Givehttp://ceph.com/docs/master/radosgw/s3/cpp/, a read; there are several examples there. Additionally, the source code has some good examples such ashttps://github.com/ceph/libs3/blob/master/src/s3.c#L1396which is an example of putObject.
|
I am working on an assignment that deals with using various data structures to store and sort data. The data structures portion is fairly straight forward to me, however, I am getting hung up on the first step, reading/parsing a wtmp file. I've parsed several files previously, but never have I parsed a binary file. Wh... |
Try usingutmp.h.
|
I am new to C and I would like to know the difference between the below two snippet codes.When I try executing first one it works fine,but when I run the second one it gives me segmentation fault.Whats the reason for this behavior?
```
printf("%c\n",*strptr++);
printf("%c\n",*(strptr+i));
```
Here is the be... |
Entirely different.
The first snippet prints the character atstrptrand then incrementsstrptrby one.
The second snippet prints the character atstrptr + i.
|
I have my vim setup to use omnicomplete with ctags and its all working well. I have set my .ctags to tag struct members and they are in the tag file but omnicomplete just shows
```
Omni completion (^O^N^P) Pattern not found
```
when I do something like mystruct. or mystruct->
Everything else offers good completion.... |
Do you mean "omnicppcomplete" instead of "omnicomplete"? If no, then you might want to useomnicppcomplete.
Also, take a look atclang_completefor perfect completion of C/C++/Objective-C code.
|
In my application, at one point I need to perform calculations on a large contiguous block of memory data (100s of MBs). What I was thinking was to keep prefetching the part of the block my program will touch in future, so that when I perform calculations on that portion, the data is already in the cache.
Can someone... |
gccuses builtin functions as an interface for lowlevel instructions. In particular for your case__builtin_prefetch. But you only should see a measurable difference when using this in cases where the access pattern is not easy to predict automatically.
|
```
struct hostent *hostName;
struct in_addr ipv4addr;
inet_pton(AF_INET, inet_ntoa(client.sin_addr), &ipv4addr);
hostName = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);
printf("Host name: %s\n", hostName->h_name);
```
It segfaults on the last line. I looked up proper use of hostent, and the msdn docs sho... |
Thegethostbyaddr()function returnsNULLin the case of an error, and I don't see you checking for that in your code. Attempting to dereference aNULLpointer would cause a segfault.
You need something like:
```
if (hostName == NULL) {
printf("There was an error!\n");
exit(1);
}
```
You may be able to use theherror... |
What I'm trying to do is find all explicit casts from type double or float to any other type in some source files I have. Is there a built-in gcc way to do this?
Language is C.
Thanks!
|
If your C code can also be compiled in C++ mode, you can use g++'s-Wold-style-castwarning flag to trigger a warning on all such casts.
You can determine whether Clang has any warnings which will trigger for a particular coding pattern by using its-Weverythingswitch (but note that this is not useful for almost any oth... |
I would like to know if there is a difference between:
```
char s[32] = "";
```
and:
```
char s[32] = {0};
```
Thanks.
|
No there is no difference between both declarations:
```
char bla[32] = {0};
and
char bla[32] = "";
```
See the relevant paragraph of the C Standard (emphasis mine):
(C99, 6.7.8p21) "If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate,or fewer characters in ... |
I have PC's with a lot of applications running at once, i was thinking is it possible to SUSPEND all applications, i want to do that to run periodically one other application that is using a lot the CPU so want it to have all the processor time.
The thing is i want to suspend all applications run my thing that uses th... |
It's possible but not recommended at all.
Set the process and thread priority so your application will be given a larger slice of the CPU.
This also means it won't kill the desktop, any network connections, antivirus, start menu, the window manager, etc as your method will.
|
I have created one file that contains (degree celcius character) and other character that required more then one byte. In Notepad++ it shows encode ANSI and as it is ANSI then why Notepad shows that multibyte character ?
Any idea ?
Thanks,
Neel
|
If you don't save it in UNICODE! Notepad will save it in ANSI as long as the codepage supports the characters involved.
To save in UNICODE you must select that from the drop-down list when saving a file.
|
I am usingCODE::BLOCKS in windows XP. Tried to write a device driver. But right after creating a project, I got below error. I did below settings, but still getting the error as
"ntddk.h no such file or directory". I have tried with all compilers (Project built option), but it is still there.
Please help.
Created th... |
If, like most people using Code::Blocks on Windows, you use MingW-TDM (commonly detected as "GNU GCC Compiler" by Code::Blocks, and bundled with the "easy install" package), the filentddk.his located in theddksubfolder of the system include folder.
Thus, you either have to add theddkfolder to the include search path,... |
I'm renewing an old code in C with C API OpenCV and I need to load at least 300 images in memory to make some algorithms with them.
So, I've been thinking that I can load that images in memory to make operations more faster instead to load from disk and make a single operation each one.
What is the best way to do th... |
If you're working with C code, then your images will automatically stay in memory until you explicitly release them. Simply callcvLoadImageon each image you wish to load from disk. I would recommend you store theIplImage*pointers in a big array so you don't lose track of them. When you're done, simply callcvReleaseIma... |
c89
gcc (GCC) 4.6.3
Hello,
I am getting a stack dump on *search = '\0'; I thought it was possible to nul terminate a string.
```
char *ptr_name = "hello@home";
char *search = ptr_name;
search = strchr(ptr_name, '@');
search++;
*search = '\0';
```
Many thanks for any suggestions,
|
ptr_name points to a string in read-only area.
Instead try :
```
char ptr_name[] = "hello@home"
```
|
I want to send a UDP packet to a camera from the PC when the PC resumes from sleep. Since it takes some time (unknown) to the network interface to become alive after the PC resumes, I keep sending packets to the camera in a loop. When the camera receives the packet, it sends an acknowledge signal to the PC.
My problem... |
UseMSG_DONTWAITflag passed torecvfromfunction. It enables non-blocking mode. If the operation would block this call returnsEAGAINorEWOULDBLOCKerror code.
|
I am not at a computer so cannot test this at the moment but have some code to review. I'm still somewhat in a C++ mindframe unfortunatley.
So, when a typedef is declared within a C source file what is its scope? I am aware that to make functions and variables only available within the same translation unit you need ... |
Typedefs are declarations. If you have a typedef in a C file, no other C file will be aware of that since they are compiled indepedendly of each other.
For a typedef in a header, it will of course be visible from all C files that include it.
|
How can I find that an IP address is a LAN IP address or WAN IP address? I am writing a C API in Windows.Thanks
|
Most likely, what you want to determine is whether the address is a global address, or aprivate address. The wikipedia article lists the address blocks that are reserved for private use.
|
I'm renewing an old code in C with C API OpenCV and I need to load at least 300 images in memory to make some algorithms with them.
So, I've been thinking that I can load that images in memory to make operations more faster instead to load from disk and make a single operation each one.
What is the best way to do th... |
If you're working with C code, then your images will automatically stay in memory until you explicitly release them. Simply callcvLoadImageon each image you wish to load from disk. I would recommend you store theIplImage*pointers in a big array so you don't lose track of them. When you're done, simply callcvReleaseIma... |
c89
gcc (GCC) 4.6.3
Hello,
I am getting a stack dump on *search = '\0'; I thought it was possible to nul terminate a string.
```
char *ptr_name = "hello@home";
char *search = ptr_name;
search = strchr(ptr_name, '@');
search++;
*search = '\0';
```
Many thanks for any suggestions,
|
ptr_name points to a string in read-only area.
Instead try :
```
char ptr_name[] = "hello@home"
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.