question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I have a gtk widget (from gtk_dialog_new()) which was created in a different function and bunch of widgets added to it. Now I want to reparent all the children of this widget to another container.
Something like:
```
get_widget_get_all_childrent(list);
//loop over list and reparent all children
```
|
Actually I found the answer after a bit of googling.
First I need to get a list of children:
```
GList* list = gtk_container_get_children();
//then loop over and reparent
g_object_ref(widget);
gtk_container_remove(GTK_CONTAINER(old_parent), widget);
gtk_container_add(GTK_CONTAINER(new_parent),... |
I have an array and a variable that will hold its size. This array is global (outside of main). The thing is that I don't know the size so I would have to declare it like this (psuedo-code):
```
int a[]; // don't know the size yet (outside main)
int size = [user input] // this is inside main
```
The size variable i... |
In C you cannot have a variable length array with file-scope.
What you can do is to use a file-scope pointer and allocate memory withmalloc.
```
#include <stdlib.h>
int *a; // outside main
int main(void)
{
a = malloc(user_input * sizeof *a); // this is inside main
// ...
}
```
|
When creating a small webserver with libev in C, what is the best strategy to serve files (open, ready, write to socket) without blocking the reactor?
I have across some recommendations to read a few blocks at a time but I am not sure this would be the right approach.
Thanks,
|
I have across some recommendations to read a few blocks at a time but I am not sure this would be the right approach.
Yep, this is a pretty standard approach.
If you are on Linux you may like to usesendfile(). This way you don't have to maintain a buffer into which it reads a file in blocks and then sends it through... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:How do you generate a random double uniformly distributed between 0 and 1 from C++?
I'm trying to figure out how to generate a random number between 0 and pi, but the usual method won't work because mod does integer division:
```
double n... |
Generate a random number between 0 and 1, and then multiply the result by2*M_PI.
If you have a uniform distribution between 0 and 1, you will also have a uniform distribution between 0 and2*M_PI, to the limit of precision available in the numeric type you are using.
For generating a random uniform double between 0 a... |
In the following code:
```
short = ((byte2 << 8) | (byte1 & 0xFF))
```
What is the purpose of& 0xFF? Because sometimes, I see the above code written as:
```
short = ((byte2 << 8) | byte1)
```
And that seems to work fine too.
|
ifbyte1is an 8-bit integer type then it's pointless - if it is more than 8 bits it will essentially give you the last 8 bits of the value:
```
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
& 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
-------------------------------
0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1
```
|
I have two bytes containing a 14-bit left-justifiedtwo's complementvalue, and I need to convert it to a signed short value (ranging from -8192 to +8191, I guess?)
What would be the fastest way to do that?
|
Simply divide by 4.
(Note, right-shift leads to implementation/undefined behaviour.)
|
I would like to write a driver tohttp://www.trulydisplays.com/tft/specs/3.5in%20480x800%20TFT480800-25-E%20Spec.pdfHow do I calculate all the following params:
```
struct fb_videomode {
const char *name; /* optional */
u32 refresh; /* optional */
u32 xres;
u32 yres;
u32 pixclock;
u32 ... |
I hope those fields mentioned are available in theEDIDof the display device.
|
I have some code that looks like this:
```
uint8_t activities[8];
uint8_t numActivities = 0;
...
activities[numActivities++] = someValue;
...
activities[numActivities++] = someOtherValue;
...
switch (numActivities)
{
0 : break;
1 : LogEvent(1, activities[0]); break;
2 : LogEvent(1, activities[0], activities... |
There's no standard way to construct or manipulateva_argsarguments, or even pass them to another function (Standard way to manipulate variadic arguments?,C Programming: Forward variable argument list). You'd be better off seeing if you can access the internal routines ofLogEvent.
|
I'm trying to parse a header for an archive file and I need to skip tabs. I've been trying to usefseek()to do this, but I can't determine if it's even possible.
Here's an example, though I'm sure the syntax is incorrect:
fseek(stream, (long)"\t", SEEK_CUR);
I need to use a method to move the file pointer, because I... |
No -- forfseekyou specify adistanceto move, not something for it to search for.
To skip tabs, you typically read a character, and if it's a tab just ignore it and read another character.
|
I need my scanf to stop when it findes a spac/blank.
For exsample
If I type in "E E", I only need 1 "E", so it has to stop at space/blank.
```
char end[] = "E";
char end1[] = "End";
char info[] = "";
while(run) {
scanf("%s", &info);
...
else if(strcmp(info, end) == 0 || strcmp(info, end1) == 0) {
end_of_tur... |
usebreakto break out of thewhileloop? after callingend_of_turn()
Or use agotostatement if you do not want to break out of the loop.
You can also get all the characters from the input stream and then discard them using the code:while(getchar() != '\n') ;
|
So. I have been experimenting with fwrite().
On my system sizeof( int ) = 4.
I have an array of ints that contains: 1, 2, 3, 4, 5 and 6.
When i write it to a binaryfile and view it with hexdump I get:
```
0000000 0001 0000 0002 0000 0003 0000 0004 0000
0000010 0005 0000 0006 0000
0000018
```
Wh... |
Because 1 (for example) represented as 4-byte hex is00000001. Apparently you're on alittle-endiansystem, hence the apparently back-to-front ordering when you inspect your file.
|
How to printf %d literally
It's probably a simple answer. But I can't seem to find the answer.
Let's say I want to:
```
printf( "printf(\"%d\", x );" );
```
I want the output to literally be:printf( "%d", x );
Is there a way to do it? If I just put in the code that I wrote above, a number gets placed into %d, but... |
Well why don't we exercise some truly safe programming practice around here?
```
printf("%s", "printf(\"%d\", x );" );
```
|
I have known this problem is compiler-dependent. So I want a reliable method to determine.
For example:
```
const wchar_t str[] = L"飞流直下三千尺";
```
How should I know whetherstris little-endian or big-endian?
Is there a compiler's guarantee that the endianness of a wide string literal is the same one as the target ar... |
There's no compiler guarantee thatwchar_tevenhasan endianness (or that it's Unicode, for that matter).
|
```
#define MAX 7
#define BUFFER 16
#define MODULO 8
typedef struct {
int x;
} BLAH;
```
if I have:
```
checkWindow(BLAH *b) {
int mod;
mod = b.MODULO;
}
```
Specifically can I access MODULO from the BLAH structure?
|
I think you misunderstand the meaning of preprocessor definitions.#define-d items only look like variables, but they are not variables in the classical sense of the word: they aretext substitutions. They are interpreted by thepreprocessor, before the compiler gets to see the text of your program. By the time the prepr... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I want to write accode such that th... |
Pipes are not bi-directional.
Try sockets. Or use two pipes.
|
Hi i want to make a function which calculate the size of structure without padding bytes.
Example :
```
struct test{
int x;
char y;
int z;
};
```
If i calculate the size of above structure i must get 9 byte (i.e. without padding bytes)
And consider the case where i might not know the variable pres... |
No, C doesn't have enough introspection to make this possible. At run-time, there is no information left that the program can use to "know" which fields are in a structure, or what their types are.
|
I am trying to add a null termination to my buffer with the following code. But I don't seem to be able to pass my null terminator in.Is this the correct way to do it? When I strlen my buffer the value is 10 but I only keyed in 9 chars.
```
char buffer[256];
int n;
bzero(buffer,256);
fgets(buffer,255,stdin);
buffer[... |
You are assigning a string not a char withbuffer[n-1] = "\0";.Trybuffer[n-1] = '\0';instead.
|
I have extended "libtinyalsa" (a very small version of ALSA) with a method to resample in- & outgoing PCM-audio (with libresample, e.g. from 48 kHz to 44.1 kHz).
Now I would like to extend it with a "downMixing" (is that the right word?) method.
I have 5.1 channel PCM and just need 2 channel stereo audio (left & rig... |
I believe downmixing a 5.1 PCM stream to stereo could be done something like this:
```
L = clamp((FL + RL + C*0.708 + LFE*0.708) / 2)
R = clamp((FR + RR + C*0.708 + LFE*0.708) / 2)
```
You can refer e.g. to thedownmix effect in Androidfor an example of this.
Or just select two of the channels that you will keep (e... |
I run this command in my terminal,
```
gcc -g -I/usr/include -g sample_client.c lsp.o lspmessage.pb-c.o -o sample_client -L/usr/lib -lprotobuf-c
```
in my file directory, I can see a sample_client file. Its property is executable.
However, when I run
```
(gdb) sample_client
```
I got this,
```
Undefined command: ... |
```
$gdb ./sample_client(gdb)run
```
To pass command-line arguments to your program use--args:
```
$gdb --args ./sample_client arg1 arg2 arg3(gdb)run
```
|
How would i find out the length of a string without using loop and String class function like strlen() ?
|
```
int length (const char* p)
{
return *p == 0 ? 0 : 1 + length(p+1);
}
```
Any iterative function can theoretically be implemented recursively and vice versa.
|
Sorry for the poor title. I couldn't find a better title. (Edits are welcome :p )
Lets say that there is a number X=8. I know 2*2=4 so it does not contain the number 8.
EDIT: imagine a 2x2 grid ... 1,2,3,4 ... it does not contain 8
Now, 3*3 = 9 and we have found our winner(n=3)!
My (poor) code for this purpose
``... |
Use thesqrtfunction from<math.h>. It'll be a (fairly) efficient algorithm, and should run much faster than your loop. Then round up, and you have your answer.
```
int find_containing_int(double x)
{
const double sqr = sqrt(x);
return ceil(sqr);
}
```
|
How do i find out what memory addresses are suitable for use ?
More specifically, the example ofHowto use a specific address is here:Pointer to a specific fixed address, but not information onWhythis is a valid address for reading/writing.
I would like a way of finding out that addressesxtoyare useable.
This is so ... |
You can use whatever memory addressmalloc()returns. Moreover, you can specify how much memory you need. And withrealloc()you even can change your mind afterwards.
|
Is it possible to define a macro calledIPHONE_ONLYfor conditional compilation that looks like this:
```
IPHONE_ONLY -(void)myMethod {
//method body
}
```
or
```
IPHONE_ONLY( -(void)myMethod {
//method body
})
```
|
Even though normally you would surround the function with#ifdef, I tested with gcc and indeed the following also works. I don't know if it is standard:
```
#ifdef IPHONE
# define IPHONE_ONLY(...) __VA_ARGS__
#else
# define IPHONE_ONLY(...)
#endif
IPHONE_ONLY(int func(void)
{
return 12;
})
```
I have never seen ... |
I have the following code:
```
typedef struct{
int A;
char* B;
}MYTYPE;
MYTYPE sample;
int nCount;
void doSomething(int A, MYTYPE* B)
{
//doing something inside this function.
}
doSomething(nCount, &sample);
```
Is there a way in my function doSomething() to check if the second argument passsed was exactlysampl... |
Yes, you can simply compare the addresses.
Remember that a pointer to something is actually the address of that something. So you could do like this:
```
void doSomething(int A, MYTYPE* B)
{
if (B == &sample)
{
printf("B is sample\n";
}
}
```
|
I expectReadConsoleW()to return after reading a specific number of bytes.
But it doesn't return.
How can I makeReadConsoleW()return as soon as it finished reading the number of bytes specified?
The code I tried is here:
```
#include <stdio.h>
#include <Windows.h>
int main()
{
//something is being written to s... |
UseSetConsoleModeto turn offENABLE_LINE_INPUTflag. No line editing will be available, but it won't wait until the Enter is pressed.
Note that you can't read threeWCHARs into anint.
|
I'm converting a character string character by character into integers. So 'A' - '0' should be 10. However even though the numbers come out fine, alphabetical characters (i.e. A-F) come out as being off by 7. For instance, here's my line of code for conversion:
```
result = result + (((int) (*new - '0')) * pow(16, ba... |
You are subtracting ASCII values. That is fine for A-Z and for 0-9, but not if you start mixing them. Read about the ASCII table to better understand the issue.
Here is the table:http://www.asciitable.com/index/asciifull.gif
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
you can use ZXing which is avalaible in google codehttp://code.google.com/p/zxing/for c++ and zint for C check the manualftp://ftp.heanet.ie/mirrors/sourceforge/z/project/zi/zint/zint/2.4.2/zint_manual_242.pdfand the source you can download it from sourceforge
|
I've seen many many results for unix systems. I am using cygwin so I am usingunistd.hlibrary. I am trying to run this command but It does not run. What could I be missing here?
execl("C:\\WINDOWS\\SYSTEM32\\CMD.EXE", "/c echo foo>C:\\Users\\Sarp\\Desktop\\foo.txt");
|
Theexeclfunction calldoesnotsplit the arguments for you. This basically means that you need to separate each command line argument as a different string parameter when invoking the function. For example:
```
execl("C::\\WINDOWS\\SYSTEM32\\CMD.EXE", "cmd.exe", "/c",
"echo", "foo", ">C:\\Users\\Sarp\\Desktop\\... |
I'd like to do something likeprintf("?", count, char)to repeat a charactercounttimes.
What is the right format-string to accomplish this?
EDIT: Yes, it is obvious that I could callprintf()in a loop, but that is just what I wanted to avoid.
|
You can use the following technique:
```
printf("%.*s", 5, "=================");
```
This will print"====="It works for me on Visual Studio, no reason it shouldn't work on all C compilers.
|
This question is pure teoretical, and not about the right way of doing it, but do we need to convert char 'x' to network format? I'm intressted in all cases: always / sometimes / never
I personally think I should but i need to be sure, than you.
|
No, char is a single byte value so endianess doesn't matter
|
I have the problem where the linker generates undefined reference errors
from the inline assembly code.
```
int global_var = 0;
void myfunc()
{
asm(".intel_syntax noprefix\n");
asm("lea eax, global_var\n");
}
```
I am compiling with -masm=intel and with no optimizations or anything, using GCC 3.4.2
If anyone... |
Basically, it's an issue ofname mangling- that is to say, the compiler mangles(alters) the names of variables and functions during the compile phase. In this instance, "global_var" is altered to "_global_var"
If you change the 2nd line of your function such that it accesses "_global_var" then it compiles just fine. (... |
I hav tis example code here which i am trying.
```
char test[256], test1[256];
char *combine =("Hello '%s', '%s'",test,test2);
```
how can I parse the value of my test test1 into my char *combine? I get an error of redeclaration of no linkage for my test and test1.
|
Check outsprintf. It will allow you to combine the two strings.
So, something like:
```
char combine[LARGE_ENOUGH_NUMBER_HERE]
sprintf(combine, "Hello %s %s", test1, test2);
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
If all you want to do is make a GUI, why don't you just use HTML?
Alternatively, if you really want it to be a more native app, maybe consider Java.
|
In CMakeLists.txt, I would like to check that bzlib.h exists:
```
include(CheckIncludeFiles)
check_include_file(bzlib.h HAVE_BZLIB_H)
if(NOT HAVE_BZLIB_H)
# How can I exit cmake with an error message if bzlib.h does not exists?
endif()
```
|
It's quite easy:message( FATAL_ERROR "Your message" )
|
When having arrays of structures I often miss the With-block approach I got used to in VB6 (similar to the Using-block in C#). For example, many of my code looks now like:
```
Data.attribute[i].ref->value[i]->member.val1 = 0;
Data.attribute[i].ref->value[i]->member.val2 = 2;
Data.attribute[i].ref->value[i]->member.va... |
```
member_t* m = &(Data.attribute[i].ref->value[i]->member);
m->val1 = 3;
m->val2 = 2;
m->val3 = 3;
```
The above should work fine to shorten the line.
And since you usec99, you can even create those temporaries when you need them only.
|
I was looking for a classification of winapi functions that may (in one or more scenarios) to throw/raise an exception. an obvious example to that will be CloseHandle on an already closed resource.
|
Some Win32 API functions are documented as throwing some exceptions (SEH exceptions of course, not C++ exceptions). You can just go to MSDN and check for each function. But I'm not sure it'sentirelydocumented, given the quality of Win32 API documentation. This ain't .NET :)
|
I would like to ask how I can create a scroll bar (slider) in WinApi32 C so I cansend serial port data depending on the position of the thumb in the scroll bar.
|
You can create a window with a scroll bar by adding theWS_HSCROLLand/orWS_VSCROLLstyles to yourCreateWindow()call.
```
hWnd = CreateWindow("YourWnd","Name",
WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL,
CW_USEDEFAULT, CW_USEDEFAULT, 500, 250,
NULL,NULL,
hInstance,NULL
);
```
You can then check ... |
In C i can use thechar *fgets(char *s, int size, FILE *stream)function to read user input from stdin. But the size of the user input is limited tosize.
How can i read user input of variable size?
|
In C you are responsible for your buffers, and responsible for their size. So you can not have some dynamic buffer ready for you.
So the only solution is to use a loop (either of fgets or fgetc - depends on your processing and on your stop condition)
If you go beyond C to C++, you will find that you can accept std::s... |
So I've used flex to generate a c file from my lex code, and then used gcc to create the corresponding actual parser .exe. However, I can't figure out how to get it to read from anything other than my own typed input. I am trying to get it to parse a huge dictionary file. Can anyone help?
|
You have two ways of solving it. The first is to redirect input from standard input with the command prompt<operation:
```
> parser.exe < some_file.txt
```
The other solution is to let the program open the file, and tell the lexer what the file is. For more information about it seethe Flex manual. The important func... |
I apologize if this is a dumb question, but I have 0 experience with this tool and wanted to know if I'm going about using it properly. I've downloaded flex which, upon compiling my lex file, produces a C file which then needs to be compiled separately. Is this the best way to do it?
|
It's possible to set up a Visual Studio project that usesflexas a custom build step in order to automatically invokeflexand then compile the generated file. I taught a compilers course last summer and we haveinstructions on how to getflexand a sample project fileavailable on the archived course website. You should l... |
Is it possible in C/C++, to "abandon" thread's CPU time?
For example:
```
void wait(int s) //Low cpu usage
{
int tmp = time();
while(tmp + CLOCKS_PER_SEC * s > time())
__AbandonCPUTime();
//Tell cpu to do sth else.
}
```
I've tried Sleep(0), but it doesn't work.
|
Look at C++11's:
```
#include <thread>
std::this_thread::yield();
```
Your CPU may support the_mm_pause()intrinsic (__asm__("pause")for gcc) which may or may not help you.
Otherwise you'll be looking at OS specific functions:sched_yield()for pthreads on Linux, orSwitchToThread()on Windows
|
What language, C or C++, is best suited for writing a native library once and using it in different languages with language bindings (for example, using JNI or Ruby's C extensions), and why?
|
C, because
a program written in C++ can use a C library, the other way around is a whole lot trickier - any construct available in C++ but not in C cannot be exported to a C program, which risks to make your export complicated.A C library will have less dependencies. C++ libraries will quite often depend on libstdc+... |
I'm creating a simple C program that list directory contents. Does anyone know how to list only hidden? The folllowing code pulls every file from the directory and works perfect, but I only need the hidden files. Thanks.
|
On GNU/Linux, a hidden file begin with a dot.
```
#include <string.h>
int is_hidden(const char *name)
{
return name[0] == '.' &&
strcmp(name, ".") != 0 &&
strcmp(name, "..") != 0);
}
```
To check if a file is read-only, it could be a good idea to use thestatfunction.
```
#include <sys/types.h>
... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:square of a number being defined using #define
Can you please explain why the following code outputs "29"?
```
#define Square(x) (x*(x))
void main()
{
int x = 5;
printf("%d", Square(x+3));
}
```
|
Since macros only do textual replacement you end up with:
```
x + 3 * (x + 3)
```
which is 29.
You should absolutely always put macro arguments between parentheses.
```
#define Square(x) ((x)*(x))
```
Better yet, use a function and trust the compiler to inline it.
EDIT
As leemes notes, the fact that the macro... |
Simple setup: There are n prototypes for functions and implementations of the functions. There is one big array of function pointers. Each function is listed in this array. Some still cause -Wunused-function when compiling with gcc.
Code:
```
void foo1(void);
void foo2(void);
void bar1(void);
void bar2(void);
/* an... |
-Wunused-functionWarn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by-Wall.
This warning seems to triggerbothwhen a function is never usedandwhen a function is declared (prototyped) but not defined.
Are you sure you didn't miss implementing... |
I'm writing code for a Cortex M0 (ARM) CPU, and 32-bit reads/writes are atomic. Now I was wondering when I read/write 8bit/16bit variables, are they also guaranteed to be atomic? My instinct says yes, because they are internally aligned to 32-bit sections, so there is no possibility that the CPU needs two separate ins... |
Using packed structures you will never have read/write atomic operations on fields that overlaps a memory unit boundary. This means that only 8bits operations are guaranteed to be atomic, otherwise it depends on the memory alignment of your fields.
|
There is a header filestack.h:
```
typedef char ElemType;
typedef struct{
ElemType data[MaxSize];
int top;
} SqStack;
int Push_Sq(SqStack *s, ElemType e);
int Pop_Sq(SqStack *s, ElemType *e);
int GetTop_Sq(SqStack *s, ElemType *e);
```
And now I have some source file including this header, I want to usei... |
There's not much to do unfortunately. You can refactor the code to make the type a#define, so something like this in the header file:
```
#ifndef ELEMTYPE
# define ELEMTYPE char
#endif
typedef ELEMTYPE ElemType;
```
Then in the source filebeforeyou include the header file you can do
```
#define ELEMTYPE int
```
T... |
I am newbee to buildroot. I can see multiple gccs in buildroot. I assume all are for cross compilation. What are the difference between those ?
```
buildroot-2012.05/output/host/usr/bin/arm-unknown-linux-uclibcgnueabi-gcc
buildroot-2012.05/output/host/usr/libexec/gcc
buildroot-2012.05/output/host/usr/arm-linux/bin/gc... |
The one you should use isbuildroot-2012.05/output/host/usr/bin/arm-unknown-linux-uclibcgnueabi-gcc. The other ones are purely internals binaries.
|
I'm using winsock and I open my sockets in the standard way (I handle errors correctly, but for the sake of this question I've made the code brief);
```
SOCKET sSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
```
If I then connect it like so, it may lose connection occasionally.
```
connect(sSocket, reinterpret... |
After a socket has beenclose()ed, it can not be used anymore.
Or the other way round: As long asclose()has not been called on a socket, it can be (re-)used.
The call tosocket()allocates a socket descriptor to the calling process. The socket descriptor exists and stays assigned to the process untilclose()is called.
|
So I have three files:
```
jarvismarch.c (includes "jarvismarchtools.h")
jarvismarchtools.c
jarvismarchtools.h
```
I would like to use amakefileto compile the aforementioned files. How would I go about this?
|
The typical minimal makefile looks like this:
```
OBJ = jarvismarch.o jarvismarchtools.o
all: $(OBJ)
$(CC) -o jarvismarch $(OBJ)
```
Taking the comment ofasveikauinto account and adding a clean target it becomes:
```
OBJ = jarvismarch.o jarvismarchtools.o
BIN = jarvismarch
CFLAGS = -Wall -pedantic -ansi
... |
In the GObject Reference Manual, it denotes that for a function:
```
g_signal_connect(instance, detailed_signal, c_handler, data)
```
Adetailed_signalstring parameter of form"signal-name::detail"is desired. My initial understanding of that is that there are predefined signal details to pass in. If that is the case, ... |
The::detailpart of the signal name is optional. If a signal takes a detail parameter, then it will say so in the signal's documentation. Otherwise you can ignore it.
The only signal that I'm aware of that actually uses a detail parameter, is thenotifysignal ofGObject. Thenotifysignal without a detail fires wheneveran... |
I have a unix time_t , is there any easy way to convert this to a time_t so it:
Represents midnight of the day of the time_t ?Represents the start of the hour of the time_t ?
|
Something like this:
```
time_t t = time(NULL);
t -= (t % 86400);
```
The constant 86400 = 24 * 60 * 60 - a useful number to remember, I think... ;)
|
If I create a void pointer, and malloc a section of memory to that void pointer, how can I print out the individual bytes that I just allocated?
For example:
```
void * p;
p = malloc(24);
printf("0x%x\n", (int *)p);
```
I would like the above to print the 24 bytes that I just allocated.
|
```
size_t size = 24;
void *p = malloc(size);
for (int i = 0; i < size; i++) {
printf("%02x", ((unsigned char *) p) [i]);
}
```
Of course it invokes undefined behavior (the value of an object allocated bymallochas an indeterminate value).
|
This is a school project I'm working on.
I'm writing a web server. If the requested resource has the extension 'cgi', I need to fork and exec the program. If the cgi is a compiled executable, this works:
```
execl(path, (char*) 0);
```
But if the cgi program is a script that needs to be interpreted, I need to do so... |
Why do you need to invoke"/bin/sh"explicitly if it's a script?
As long as the script has execute permission and the propershebangat the top, you should be able to execute it just as if it were an executable.
|
I have 2 two dimensional arrays. At some point, I need to pick one of the two and loop over it. What kind of pointer do I need to point to a 2 dimensional array in order to loop over it ?
```
const char *a[] = {
"example1",
"example2",
NULL
};
const char *b[] = {
... |
You just need one more*:
```
const char **pointer = a;
```
Your loop condition is wrong too - I think you want:
```
while (pointer[count] != NULL)
```
|
I'm not sure if I'm using the correct terminology. Say, the SkyDrive app from Microsoft creates a virtual "Skydrive" folder on a local computer. What I'm curious to know is how to add such virtual folder with C++/MFC?
|
That is not avirtual folder. It is a system folder made by PathMakeSystemFolder, so the system knows you have some customization going on in desktop.ini. Skydrive merely customized the folder's icon.
Reference:How to Customize Folders with Desktop.ini (Windows)
|
I was wondering how does autility like this oneredirects a folder to a driver letter?
PS. I need this done with C/C++/MFC.
|
It probably usesDefineDosDevice, as an ordinarysubstcommand does.
|
I'm creating a simple C program that list directory contents. Does anyone know how to list only hidden? The folllowing code pulls every file from the directory and works perfect, but I only need the hidden files. Thanks.
|
On GNU/Linux, a hidden file begin with a dot.
```
#include <string.h>
int is_hidden(const char *name)
{
return name[0] == '.' &&
strcmp(name, ".") != 0 &&
strcmp(name, "..") != 0);
}
```
To check if a file is read-only, it could be a good idea to use thestatfunction.
```
#include <sys/types.h>
... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:square of a number being defined using #define
Can you please explain why the following code outputs "29"?
```
#define Square(x) (x*(x))
void main()
{
int x = 5;
printf("%d", Square(x+3));
}
```
|
Since macros only do textual replacement you end up with:
```
x + 3 * (x + 3)
```
which is 29.
You should absolutely always put macro arguments between parentheses.
```
#define Square(x) ((x)*(x))
```
Better yet, use a function and trust the compiler to inline it.
EDIT
As leemes notes, the fact that the macro... |
Simple setup: There are n prototypes for functions and implementations of the functions. There is one big array of function pointers. Each function is listed in this array. Some still cause -Wunused-function when compiling with gcc.
Code:
```
void foo1(void);
void foo2(void);
void bar1(void);
void bar2(void);
/* an... |
-Wunused-functionWarn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by-Wall.
This warning seems to triggerbothwhen a function is never usedandwhen a function is declared (prototyped) but not defined.
Are you sure you didn't miss implementing... |
I'm writing code for a Cortex M0 (ARM) CPU, and 32-bit reads/writes are atomic. Now I was wondering when I read/write 8bit/16bit variables, are they also guaranteed to be atomic? My instinct says yes, because they are internally aligned to 32-bit sections, so there is no possibility that the CPU needs two separate ins... |
Using packed structures you will never have read/write atomic operations on fields that overlaps a memory unit boundary. This means that only 8bits operations are guaranteed to be atomic, otherwise it depends on the memory alignment of your fields.
|
There is a header filestack.h:
```
typedef char ElemType;
typedef struct{
ElemType data[MaxSize];
int top;
} SqStack;
int Push_Sq(SqStack *s, ElemType e);
int Pop_Sq(SqStack *s, ElemType *e);
int GetTop_Sq(SqStack *s, ElemType *e);
```
And now I have some source file including this header, I want to usei... |
There's not much to do unfortunately. You can refactor the code to make the type a#define, so something like this in the header file:
```
#ifndef ELEMTYPE
# define ELEMTYPE char
#endif
typedef ELEMTYPE ElemType;
```
Then in the source filebeforeyou include the header file you can do
```
#define ELEMTYPE int
```
T... |
I am newbee to buildroot. I can see multiple gccs in buildroot. I assume all are for cross compilation. What are the difference between those ?
```
buildroot-2012.05/output/host/usr/bin/arm-unknown-linux-uclibcgnueabi-gcc
buildroot-2012.05/output/host/usr/libexec/gcc
buildroot-2012.05/output/host/usr/arm-linux/bin/gc... |
The one you should use isbuildroot-2012.05/output/host/usr/bin/arm-unknown-linux-uclibcgnueabi-gcc. The other ones are purely internals binaries.
|
I'm using winsock and I open my sockets in the standard way (I handle errors correctly, but for the sake of this question I've made the code brief);
```
SOCKET sSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
```
If I then connect it like so, it may lose connection occasionally.
```
connect(sSocket, reinterpret... |
After a socket has beenclose()ed, it can not be used anymore.
Or the other way round: As long asclose()has not been called on a socket, it can be (re-)used.
The call tosocket()allocates a socket descriptor to the calling process. The socket descriptor exists and stays assigned to the process untilclose()is called.
|
So I have three files:
```
jarvismarch.c (includes "jarvismarchtools.h")
jarvismarchtools.c
jarvismarchtools.h
```
I would like to use amakefileto compile the aforementioned files. How would I go about this?
|
The typical minimal makefile looks like this:
```
OBJ = jarvismarch.o jarvismarchtools.o
all: $(OBJ)
$(CC) -o jarvismarch $(OBJ)
```
Taking the comment ofasveikauinto account and adding a clean target it becomes:
```
OBJ = jarvismarch.o jarvismarchtools.o
BIN = jarvismarch
CFLAGS = -Wall -pedantic -ansi
... |
In the GObject Reference Manual, it denotes that for a function:
```
g_signal_connect(instance, detailed_signal, c_handler, data)
```
Adetailed_signalstring parameter of form"signal-name::detail"is desired. My initial understanding of that is that there are predefined signal details to pass in. If that is the case, ... |
The::detailpart of the signal name is optional. If a signal takes a detail parameter, then it will say so in the signal's documentation. Otherwise you can ignore it.
The only signal that I'm aware of that actually uses a detail parameter, is thenotifysignal ofGObject. Thenotifysignal without a detail fires wheneveran... |
I have a unix time_t , is there any easy way to convert this to a time_t so it:
Represents midnight of the day of the time_t ?Represents the start of the hour of the time_t ?
|
Something like this:
```
time_t t = time(NULL);
t -= (t % 86400);
```
The constant 86400 = 24 * 60 * 60 - a useful number to remember, I think... ;)
|
Consider a functionfoo()that might never exit:
```
int foo(int n) {
if(n != 0) return n;
else for(;;); /* intentional infinite loop */
return 0; /* (*) */
}
```
Is it valid C to omit the final return-statement? Will it evoke undefined behavior if I leave out that final statement?
|
Even if it does return without a return statement there is no UB unless you use the return value.
|
Is it possible to use a function to detect non-printing characters withisctrl()and use printf with %C specifier to print them as '\n' for instance?
Or I should write aniffor every control caracter andprintf("\\n")for instance..?
OK, thanks to All of the kind people below - it is not posible, you HAVE to specify each... |
```
const char *pstr = "this \t has \v control \n characters";
char *str = pstr;
while(*str){
switch(*str){
case '\v': printf("\\v");break;
case '\n': printf("\\n"); break;
case '\t': printf("\\t"); break;
...
default: putchar(*str);break;
}
str++;
}
```
this will print the non-print... |
I think this is a simple question, but I'm struggling with the following. In my example I have the following statement (language is C):
```
int foobar
if (foobar)
{
// do something.
}
```
Now, if I am correct about this, this statement is true whenfoobaris not zero. So it should be much the same asif (foobar!=0).
... |
negative or positive. Anything that's not a 0 is a true value inif
Also, Consider a negative number: -1
-1 in C internally is represented as:0xFFFFFFFF, in which case, it would be a positive number if I cast it to unsigned integer.
But after the advent of C99 standard compilers, I suggest you use<stdbool.h>instead.... |
It's probably a simple correction since the program is super short but please help me understand why am i getting weird output:
```
#include <stdio.h>
int main(void)
{
char x;
printf("please enter a word, and ctrl + d to see the resault\n");
while ((x = getchar()) != EOF)
{
printf("%d", x);... |
The reason you get 10010 is because you are pressing 'd' followed by 'return'.
Change your printf format to "%d\n" to visualize this more easily.
A fix could be:
```
while ((x = getchar()) != '\n' )
{
}
```
|
In this piece of code, why in my testing the result is always1,2, and3?
```
#include <stdio.h>
void test() {
int a;
a++;
printf("%d",a);
}
int main(int argc, char *argv[]) {
test();
test();
test();
}
```
I think the variable intest()is static, isn't it? And Why?
|
The variable is not static. You're accessing an uninitialized variable. The behavior is undefined.
|
I'm try to get the location of file let's say :D\stuff.tifin my program a string like :
```
filename = 'D:\stuff.tif'
```
I need it in ths form so here what I've been trying:
```
char text[50];// = "filename = ";
char filep [50];
printf("get file name ") ;
scanf("%s",&filep);
sprintf(text," filename = \... |
You do realize that what you wrote is C rather than C++? In C++ you would do something like this:
```
#include <iostream>
#include <string>
int main()
{
std::string text, filep;
std::cout << "get file name ";
std::cin >> filep;
text = " filename = '" + filep + "'";
}
```
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:What’s the side effect of the following macro in C ? Embedded C
What will be the output for the following:
```
#include <stdio.h>
#define MAN(x,y) ((x) < (y))?(x):(y)
main()
{
int i=10,j=5,k=0;
k= MAN(i++,++j);
printf("%d %d... |
Remember how macros work.. they replace the text exactly as it is, and do not evaluate their arguements as you would expect functions to do.
```
k= MAN(i++,++j);
```
Is actually
```
k= ((i++) < (++j))?(i++):(++j)
```
This is whyjis incremented twice.
|
I'm trying to open a binary file using system calls, I cannot use functions (fopen etc)
```
if ((fd2 = open("RandomStruct.bin",O_RDWR|O_CREAT)) == -1)
err_sys("Failed to open binary\n");
```
Is this line of code incorrect? thanks!
btw I get ": Error 0" O.o
|
No, it is not correct. If you specify the O_CREAT flag, then open() needs another argument, which is the permission bits for the new file. e.g.
```
open("RandomStruct.bin",O_RDWR|O_CREAT, 0755);
```
|
Is it possible to use a function to detect non-printing characters withisctrl()and use printf with %C specifier to print them as '\n' for instance?
Or I should write aniffor every control caracter andprintf("\\n")for instance..?
OK, thanks to All of the kind people below - it is not posible, you HAVE to specify each... |
```
const char *pstr = "this \t has \v control \n characters";
char *str = pstr;
while(*str){
switch(*str){
case '\v': printf("\\v");break;
case '\n': printf("\\n"); break;
case '\t': printf("\\t"); break;
...
default: putchar(*str);break;
}
str++;
}
```
this will print the non-print... |
I think this is a simple question, but I'm struggling with the following. In my example I have the following statement (language is C):
```
int foobar
if (foobar)
{
// do something.
}
```
Now, if I am correct about this, this statement is true whenfoobaris not zero. So it should be much the same asif (foobar!=0).
... |
negative or positive. Anything that's not a 0 is a true value inif
Also, Consider a negative number: -1
-1 in C internally is represented as:0xFFFFFFFF, in which case, it would be a positive number if I cast it to unsigned integer.
But after the advent of C99 standard compilers, I suggest you use<stdbool.h>instead.... |
It's probably a simple correction since the program is super short but please help me understand why am i getting weird output:
```
#include <stdio.h>
int main(void)
{
char x;
printf("please enter a word, and ctrl + d to see the resault\n");
while ((x = getchar()) != EOF)
{
printf("%d", x);... |
The reason you get 10010 is because you are pressing 'd' followed by 'return'.
Change your printf format to "%d\n" to visualize this more easily.
A fix could be:
```
while ((x = getchar()) != '\n' )
{
}
```
|
In this piece of code, why in my testing the result is always1,2, and3?
```
#include <stdio.h>
void test() {
int a;
a++;
printf("%d",a);
}
int main(int argc, char *argv[]) {
test();
test();
test();
}
```
I think the variable intest()is static, isn't it? And Why?
|
The variable is not static. You're accessing an uninitialized variable. The behavior is undefined.
|
I'm try to get the location of file let's say :D\stuff.tifin my program a string like :
```
filename = 'D:\stuff.tif'
```
I need it in ths form so here what I've been trying:
```
char text[50];// = "filename = ";
char filep [50];
printf("get file name ") ;
scanf("%s",&filep);
sprintf(text," filename = \... |
You do realize that what you wrote is C rather than C++? In C++ you would do something like this:
```
#include <iostream>
#include <string>
int main()
{
std::string text, filep;
std::cout << "get file name ";
std::cin >> filep;
text = " filename = '" + filep + "'";
}
```
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:What’s the side effect of the following macro in C ? Embedded C
What will be the output for the following:
```
#include <stdio.h>
#define MAN(x,y) ((x) < (y))?(x):(y)
main()
{
int i=10,j=5,k=0;
k= MAN(i++,++j);
printf("%d %d... |
Remember how macros work.. they replace the text exactly as it is, and do not evaluate their arguements as you would expect functions to do.
```
k= MAN(i++,++j);
```
Is actually
```
k= ((i++) < (++j))?(i++):(++j)
```
This is whyjis incremented twice.
|
I'm trying to open a binary file using system calls, I cannot use functions (fopen etc)
```
if ((fd2 = open("RandomStruct.bin",O_RDWR|O_CREAT)) == -1)
err_sys("Failed to open binary\n");
```
Is this line of code incorrect? thanks!
btw I get ": Error 0" O.o
|
No, it is not correct. If you specify the O_CREAT flag, then open() needs another argument, which is the permission bits for the new file. e.g.
```
open("RandomStruct.bin",O_RDWR|O_CREAT, 0755);
```
|
how to print the current process state
```
main ()
{
pid_t pid;
printf("parent : %d\n", getpid());
pid = fork();
if (pid == 0)
{
printf("child : %d\n", getpid());
sleep(2);
printf("child exit\n");
exit(1);
}
while (1)
{ /*after the child exit, its a zombie process */
... |
Determining the scheduling state of a process is OS specific. On Linux,topand similar read it from the third field in/proc/$PID/stat.
|
This is what I need to do:
```
int lg(int v)
{
int r = 0;
while (v >>= 1) // unroll for more speed...
{
r++;
}
}
```
I found the above solution at:http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog
This works, butI need to do it without loops, control structures, or constants big... |
Without any control structure, not even the?:operator, you can simulate your own algo
```
int r = 0;
x >>= 1;
r += (x != 0);
x >>= 1;
r += (x != 0);
...
```
provided that, in C,
xis assumed to be positive (otherwise havingint x=-1;for instancex >>= 1n timesis always!= 0a condition likex != 0returns 0 (false) or 1 ... |
It is returning 1 despite what the values of x and y are. I'm not understanding how or why. I copied a program from my textbook so this isn't something I wrote. We are currently studying integer arithmetic.
Can someone please explain what this code is doing? Thank you!
```
#include <stdio.h>
int uadd_ok(unsigned x,... |
The expressionsum >= yis a boolean, and thus it gets converted to either0or1depending on its value. Sincexandyare unsigned, assuming there's no overflow you will always havex + y >= y, so the result is always true, and thus1.
(Presumably the point of the function is to check whether an overflow occurred...)
|
I find myself always appending the name of the enum, to its values, because else I often have conflicts with other enums, for example:
```
typedef enum
{
A_ONE,
A_TWO,
} A;
typedef enum
{
B_ONE,
B_TWO,
} B;
```
Is there a nicer way to do this in C?
|
No, there is not. C++ has namespaces, or enums existing in classes (IIRC), but C is extremely primitive in this regard.
|
Im writing a simple program to count the number of character user is entered, and i wrote an if to check wether there is a newline but still printing it..
the code:
```
#include <stdio.h>
int main()
{
char ch;
int numberOfCharacters = 0;
printf("please enter a word, and ctrl + d to see the resault\n");... |
Think about this line:
```
if (numberOfCharacters != '\n')
```
how can it make sense? You are comparing the number of characters read so far with a newline, it's like comparing apples to oranges and surely won't work. It's another variable that you should check...
|
Thefoofunction below finds the first occurrence of the given number and returns it's index. If the number wasn't found it returns the size of the array(n):
```
int foo(int arr[10], int num, int n)
{
; int *p
for (p=arr;(*p!=num) && (p<arr+n);++p);
;return p-arr
}
```
My question is: is the param... |
My question is: is the parameterint arr[10]the same as writingint *arrorint arr[]for that matter?
Yes, as long as it's part of the declaration of a function argument listandthe array is one-dimensional.
|
When I call:
```
write_byte((uint8_t*)0);
```
It passes a null-pointer. How can I modify it to pass a pointer to the literal value 0?
|
It passes a NULL pointer.
You cannot take the address of a constant (&0). If you want to pass a pointer to the value0, you must assign0to a variable first.
```
uint8_t i = 0;
write_byte(&i);
```
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Modifying a C string: access violation
```
int main()
{
char str_1[7] = "string";
char* str_2 = new char[7];
str_2 = "string";
str_1[2] = 'a'; //ok
str_2[2] = 'a'; //error
return 0;
... |
You can not assign to a string like you do. Instead of copying the strings contents you copy the pointer. Thusstr_2now points to a string literal and can not be modified. To copy string's contents usestrcpy.
Even worse- in your version of the code there is a memory leak for the memory allocated forstr_2in the line wh... |
Is it possible to initialize mutex in this way:
```
pthread_mutex_t mutex = {0};
```
What is the difference between the following 3 initialization of mutex:
```
1) pthread_mutex_init(&mutex, NULL);
2) pthread_mutex_t mutex = {0};
3) pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
```
|
With the first option, you control the time at which the mutex is initialized (also: the argument should be&mutex) by calling the initializer function explicitly.The second option is assuming things about the internal layout of thepthread_mutex_tobject, which is supposed to be opaque. Itshould not be used.The third o... |
Please help,
At first, I created a socket and bound it to address without SO_REUSEADDR.
Then, my program crashed (not properly closing socket)
Next, I run it again and "Address already in use" is returned from bind()
I tried to modify source code to use SO_REUSEADDR but it is no-use.
Now, I couldn't run bind agai... |
You just need to wait until the session times out, then it will be deleted completely.
When a session shuts down in a "dirty" manner, you can't reuse that address again (assuming you're not using SO_REUSEADDR) for twice the maximum segment lifetime - typically this is about four minutes for regular network hardware t... |
Let
```
const char cstring[] = "cstringline";
```
How can the above code be altered, to append CRLF in compile time aka declaration?
|
Unix line ending:
```
const char str[] = "foobarbaz\n";
```
Legacy Mac line ending:
```
const char str[] = "foobarbaz\r";
```
Windows line ending:
```
const char str[] = "foobarbaz\r\n";
```
(But really, google...)
|
I'm working on an open source C project that has two example files to run the library, one called example.c, and one called test.c.
The Makefile consists of the following:
```
test: test.c src/term.c
$(CC) $^ -o $@
example: example.c src/term.c
$(CC) -std=c99 $^ -o $@
.PHONY: t... |
When you just typemakethe first target is being executed, in your case its test. So you will get onlytestexecutable. But if you typemake examplethenexampletarget is executed and you will getexamplebinary. I think you need fresh up with Makefile rules.You can referthisfor basic concepts orthisfor in depth understanding... |
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... |
You can use %o to print a octal number
check this linkhttp://ideone.com/OLXEL7
```
printf("%o\n", x);
```
Hope this helps
|
I need to write a program in C that does the following:
Write a program so that when the user enters a floating point number, it rounds off the number to 3 decimal places. When displaying the result, display 5 decimal places, and this means the 4th and 5th decimal place number will both be 0.
How do I round it to 3 ... |
```
printf("%.5f\n",(int)(number*1000+0.5)/1000.0);
```
|
In C, how would I add the const modifier (or any other modifier) to a global multidimensional array so that both the variable and the values it holds are constant.
For example how would I add a const modifier to this:
```
byte fruitIds[][2] = { { 0x01, 0x02}, {0x02, 0x03} }
```
so that at the end of the assignment ... |
Arrays are already non-modifiable lvalues. That just means you need to make the valuesconst:
```
const byte fruitIds[][2] = { { 0x01, 0x02}, { 0x02, 0x03} };
```
These assignments from your post:
```
fruitIds = vegetableIds;
fruitIds[0] = {0x02, 0x03};
```
Are already illegal. The latter isn't even valid syntax,... |
I have a __int64 variablex = 0x8000000000000000.
I try to shift it right by byte :x >> 4
I`ve thought that the result should be0x0800000000000000, but unfortunately I get0xf800000000000000.
I use VS10. Why is it so? And how can I solve that?
|
try to use__uint64 variable x = 0x8000000000000000
I think you can declare it this way as well:
```
u64 x = 0x8000000000000000;
```
x >> 4you will give you:
```
0x0800000000000000
```
see for more info where theFcamefromin the MSBs.
|
I am trying to store the character at an address in a variable, but I have a compile error ( invalid type argument of unary ‘*’ (have ‘int’)).
```
int address = 4000;
char character = (char) *address
```
Why doesn't this code dereference the pointer to store the character at memory location 4000 and how can I fix it... |
Syntactically, you are looking for
```
char character = *(char*)address;
```
Whether this will do anything useful is another matter...
Some issues to ponder:
intmay or may not be wide enough to represent every valid address (on my system, it isn't).How do you know what's at address 4000 in your process's memory ma... |
Is there a convenient way of doing arithmetic with big-endian data? Here's what I've been doing (in pseudocode):
```
main:
unsigned int big_endian_number = 0x12345678;
int multiplier = 7;
unsigned int little_endian_number = reverse_the_bytes(big_endian_number);
little_endian_number = little_endian_nu... |
Network byte order is big endian, use ntohl (network to host) that will convert to your local endian, then htonl to convert back.
I can post a code example if necessary but I think that's fairly straight forward.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.