question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I understand how to create astructon the heap usingmalloc. Was looking for some documentation regarding creating astructin C on the stack but all docs. seem to talk about struct creation on heap only.
|
The same way you declare any variable on the stack:
```
struct my_struct {...};
int main(int argc, char **argv)
{
struct my_struct my_variable; // Declare struct on stack
.
.
.
}
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How to pass a multidimensional array to a function in C and C++
so I have charbuffer[4][50]
I need to pass it to a methodvoid SetBuffer(char **buffer)or at least that's how i think it's suppose to be formatted.
so I doSetBuffer(buffer);?... |
The C++ way would be to use a proper container (e.g.std::vector<unsigned char>orstd::string) as appropriate.
OTOH, if there's a particular reason to fall back on arrays, using pointers (as you already do) and passing in the dimensions explicitly are one way to do it..
|
I want to create a game project, and I need a server and a client for this.
I'm using Xcode 4.3, how can I create a projetGamewhich will contain two "sub-projects" :
ClientServer
I'd like to be able to build both independently. Is this kind of trick possible with xcode or shall I create two different projects ?
Th... |
Yes, this is possible, it's called a workspace. Drag one of your projects onto the other and you will be asked to make a workspace.
Create a Server Project.Create a client Project.Drag the client project into the server project and drop it below. (or vice-versa)
|
Suppose I have the following structs:
```
struct A{
int a;
} a;
struct B{
A a;
int b;
} b;
```
how to check ifbis of typeBor ifbis of the typeA?
|
Do you mean at runtime, given avoid *that points to one or the other? Unfortunately, this is not possible; C doesn't have any kind of runtime type information mechanism.
|
How can I get the current total allocated memory so far (in a Linux process inC/C++ (gcc))?
|
Try parsing/proc/self/mapsor/proc/$PID/maps. Look for a line marked[heap].
|
I recently upgraded to Lion and to XCode 4.3 and now anything that I do with perl that requires the C compiler is failing to build:
```
root# perl Makefile.PL
Couldn't find your C compiler
Compilation failed in require at Makefile.PL line 5.
BEGIN failed--compilation aborted at Makefile.PL line 5.
```
my c compiler... |
The new version of Xcode doesn't install the binaries (such as the C compiler) where they can be found in your$PATH. You'll need to go to the "Downloads" section of your XCode preferences and elect to install the command line tools.
More informationfrom Apple(look for "Command line tools are optional").
|
I want to get as an input from the user a maximum length of 30 chars string and check whether it contains an end of line.
This is what I tried to write so far:
```
int main(void) {
int i;
char* command = (char*)calloc(31, sizeof(char));
while (0 < 1) {
scanf("%s", command);
for (i = 0; i <= strlen(command); ... |
This is becausescanf()doesn't include the linefeed, it considers it whitespace and uses whitespace to separate the values it converts. Just usestrlen()'s return value.
|
For my project i have two servos and i need to set them to the right angle every time the program loops. In order do this i use a serial usb connection and send a number to set one of the servos. But for the second servo i need to pass two numbers in one message. I was thinking about a string "X,Y" that i could send a... |
According to the documentation, a call such asSerial.write("90,90");should work and will result in the given string being sent. There's no mention of the comma having some separate meaning.
You should probably check the return value.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Confused about C macro expansion and integer arithmeticA riddle (in C)
The output of the following C program is to print the elements in the array. But when actually run, it doesn't do so.
```
#include<stdio.h>
#define TOTAL_ELEMENTS (... |
sizeof()returnsunsigned intand so in the <= comparison,dgets converted tounsigned int. -1 when converted tounsigned intis0xffffff. Since0xffffff > (7-2), for-loop body won't be executed even once.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why doesn't getchar() recognise return as EOF in windows console?
I'm new in C and trying to figure out how EOF and getChar() works.
```
#include <stdio.h>
main()
{
int number = 0;
while(getchar() != EOF)
number++;
printf("%d", nu... |
Because you aren't sending anEOFcharacter. "EOF" stands for "end-of-file"; console input (known as "standard input") is a special case of a file. But in order to denote that this special file has ended, you need to send a special signal. You can get this effect on Windows by pressing Ctrl+Z (followed by Enter, for ... |
I would like to know how can I
```
1. power on a remote computer
2. automatically log in (that client does have username and password to log in) with a given pair of username and password
```
I finish the first and wonder if the second is possible ? Any help is appreciated. Thank you a lot.
|
You can use the registry to auto login a computer. The key you need is:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
ChangeAutoAdminLogonto1.
SetDefaultUserNameandDefaultPasswordto the accounts username and password.
If the values don't exist just create them. UsuallyAutoAdminLogonandDefaultUserNamea... |
What would following typedef mean, and why would it be required
```
typedef unsigned long int ULONG;
```
how different is it from
```
typedef unsigned long ULONG;
```
For gcc sizeof int = 4, sizeof long = 8, and sizeof ULONG = 8.
|
They are the same. Becauselongis a modifier for anintby default,intcan be omitted. The same goes forshortandshort int,unsignedandunsigned int, etc.
The essential thing to understand here is thatlong,shortandunsignedaretype modifiers, not types themselves, unlikeint,char,double, etc.
|
Is there a way via Arduino Processing (The program running on the computer) to open a network socket? I would like to open a client or server socket on the processing program so i can talk to it via WiFi and control my Arduino over serial connection. The serial connection stuff is working, all i want now is some way t... |
As I understand your question your looking to do networking in Processing. There is alibraryto do exactly that. It allows you to create simple clients or servers.
The Network library makes it easy to read and write data across machines on the Internet. It allows the creation clients and servers. A server connects ... |
```
#include <stdio.h>
int main()
{
long double n = (long double)1208925819614629174706175; // (1<<80)-1 (generated in python)
printf("%LG\n",n);
}
```
On compiling this with gcc, I get a warning
```
test.c:5:31: warning: integer constant is too large for its type [enabled by default]
```
On running it pri... |
Long double will handle 10**300 and above, that's not what the compiler is complaining about. It says the integer that you are trying to cast into a long is too big for an integer. ( hint - add a decimal point ) – starbolin
|
When I sendWM_SETREDRAWto disable redraw for a window, how do I "restore" the previous state when I'm done?
What's the proper way to send this message?
|
You can'trestore the previous state, as there is no way to access the current state. There is noWM_GETREDRAW. Once you are done you sendWM_SETREDRAWagain withTRUEas an argument this time, and if anyone else had set redraw toFALSEon an outer scope then well.. that's bad for them..
|
If I haveint someArray[100]that contains items in various elements, how can I reset them all back to 0?
Basic question, I know, but I usually use Objective-C arrays however for this purpose I'm just storing some numbers and want to deal with it "old school."
|
You need to set each element to the value you want:
```
for (int i = 0; i < 100; ++i)
SomeArray[i] = 0;
```
For the specific case of integers and the value 0, you can also make use of the fact that their bitwise representation is known (all bits are 0), and so you can usememset:
```
memset(SomeArray, 0, sizeof(... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Is main() really start of a C++ program?
Is possible to call my function before program's startup? How can i do this work inC++orC?
|
You can have a global variable or astaticclass member.
1)staticclass member
```
//BeforeMain.h
class BeforeMain
{
static bool foo;
};
//BeforeMain.cpp
#include "BeforeMain.h"
bool BeforeMain::foo = foo();
```
2) global variable
```
bool b = foo();
int main()
{
}
```
Note this link -Mirror of http://www.paras... |
How to get the return value of an exe which is called by shellexecute function.
```
ShellExecute(NULL, NULL, TEXT ( ".\\dpinstx86.exe" ), NULL, NULL, SW_SHOWNORMAL);
```
In the above example I want the return value of "dpinstx86.exe".
|
UseShellExecuteExinstead to get the process handle, andGetExitCodeProcessto get the exit code.
```
SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = "c:\\MyProgram.exe"; ... |
I am creating a shared object library which will be LD_PRELOADed with my program. In that shared library, I also want to use some variables from my program. What is the way of declaring such variables. Note that shared object library is compiled separately from my program.
|
Yes. You must link your program with--export-dynamicto make the symbol table of the program accessible to the libraries opened. If you wish to control exactly which symbols are available and usinglibtoolfor linking, you can use parameters like-export-symbols-regexto specify which are available. If the symbols required... |
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.
I know various ways to check if ani... |
You can revert a number with some code like:
```
int revert(int num) {
int reverted = 0;
while (num) {
reverted = reverted*10 + num%10;
num /= 10;
}
return reverted;
}
```
And now you only check if
num == revert(num)
That is all. Sorry for giving the exact solution instead of just a tip, but I don'... |
I have the following simple program. And I am running "program file.txt" from the command line and getting "Bus error" with no output. I don't know what I'm doing wrong here.
```
#include<stdio.h>
int main(char *arg[])
{
FILE *file = fopen(arg[0], "r");
if (file == NULL) {
printf("Cannot open file.... |
The prototype for the c entry function is
```
int main(int argc, char *arg[]);
```
So with your prototype you are actually trying to dereference an int to passing to fopenTry this instead
```
#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
... |
I have a number like this:int num = 36729;and I want to get the number of digits that compose the number (in this case 5 digits).
How can I do this?
|
Use this formula:
```
if(num)
return floor(log10(abs((double) num)) + 1);
return 1;
```
|
I have a pointerchar *str;
for a particular case,if (!str)is not NULL butstr[0] == '\0', how and when is this possible?
Edit:0Thanks for all the responses. Basically I need to pass this string as a source param instrlcpy()which is sag faulting because this is an empty string. It seems I need a check something like t... |
\0is the null-byte or null-terminator. Therefore, it is seen as null. C-strings are null-terminated. That is, the first time a null-byte is seen, the string is considered complete. If nothing other than\0exists, it isNULL.
If you have information beyond this byte (this is bad practice for strings) you could try to ch... |
Indouble (*foo)[2]what does the[2]represent? And how would I convert an array as such to an array of float* in C?
|
```
double (*foo)[2]
```
foois a pointer to an array of twodoubleelements.
For example:
```
double bla[2];
double (*foo)[2] = &bla;
```
|
In assembly, should you backup registers before calling a C Standard Library function?Does the Standard Library guarantee that all of its functions backup the caller's registers and recover them in the end?Where can I find official information about this matter?
|
I think just calling conventions apply here.http://en.wikipedia.org/wiki/X86_calling_conventions
The C standard library does not guarantee that it's functions backup registers for the caller. It depends on the calling conventions and how it's handled by a complier.
Assume that a C function knows nothing about regist... |
```
int do_memory()
{
int * empty_ptr = (int *) malloc(sizeof(int));
*empty_ptr = 5;
return *empty_ptr;
}
...
int b = do_memory();
free(&b); //obviously not valid
```
Whenbgoes out of scope, I would be right in assuming the memory in empty_ptr still exists? But is impossible to free and therefore this is bad co... |
The "int *empty_ptr" (the pointer to the allocated memory block) is never released, you just get the return value from do_memory.
If you want no leaks, use this
```
int* do_memory()
{
int * empty_ptr = (int *) malloc(sizeof(int));
*empty_ptr = 5;
return empty_ptr;
}
...
int* b = do_memory();
int b_local = *b;... |
I have an array of int and i have to initialize this array with the value -1. For now i use this loop:
```
int i;
int myArray[10];
for(i = 0; i < 10; i++)
myArray[i] = -1;
```
There are faster ways?
|
The quickest way I know for the value-1(or0) ismemset:
```
int v[10];
memset(v, -1, 10 * sizeof(int));
```
Anyway you can optimize the loop in this way:
```
int i;
for(i = 10; i--;)
v[i] = -1;
```
|
Thedocstalk about a file calledinput.hthat doesn't seem to appear in any of the packages, at least according to:
```
apt-file search /usr/include/xcb/xinput.h
```
I need that because I was trying to use the functionxcb_input_open_device.
What am I doing wrong?
|
It seems that XInput Extension is disabled by default because it's not yet stable enough; hence not packaged in Debian.
In theconfigurescript:
```
--enable-xinput Build XCB XInput Extension (default: "no")
```
|
I have to write a C program to convert XML file to WBXML format, without using external conversion library. Is it possible?
I have created the XML file in C and now want to convert it into WBXML file.
|
You want to know if it is possible? - Yes.
You want to know how? - check the implementation of one of theexternal libraries. I'm sure you can get an idea if you browse the source code.
|
How can I retrieve a process description and company name using a handle to it.
I'm using Windows API function.
|
Version (and copyright) informations are stored in the file version info. You can obtain them using theGetFileVersionInfofunction.
Version can be retrieved with asimplecall toGetFileVersionInfoto fill theVS_FIXEDFILEINFOstructure but copyright information (in your caseProductNameandCompanyName) is stored in localized... |
My current assignment is regarding implementing thepipe()inLinuxusingshared memory.
Since this is my first time working with semaphores & shared memory (mutexalso) I have zero experience with it .
Can somebody shed some light on it with explanation regarding its implementation ? thanks
|
Start with the man pages below:
Shared memory
```
ftok
shmget
shmat
shmctl
shmdt
```
Semaphores
```
sem_init
sem_wait
sem_post
```
The idea is, two different applications that will use your pipe to be able to exchange data. This can be done with shared memory. Also some synchronization should be done (here comes ... |
I often see something likeattributein error messages. What is this? Are there any similar things like thisattribute? Can anyone give me a detailed explanation?
|
It is aGCC extensionwhich allows a developer to attach characteristics to function declarations to allow the compiler to perform more error checking.
Detailed Explanation also foundhereandhere. A set of GCC extensions for C can be foundhere.
|
In linux, argc and argv count arguments in terminal. But in Windows, I can't find anywhere to put the second arguments. Actually every time when I run the program, it creates that ugly black window and I even have no chance to give any argument. So are these two variables useless in Windows platform? Or there's anothe... |
If you start from the command prompt, you can give the arguments there.
Start menu -> run -> "cmd" -> "MyProgram.exe arg1 arg2"
|
I have seen this complex declaration of sizeof operator somewhere in book which is teasing me:
```
#define SIZEOF(int) (int)&((int *)0)[1]
```
Can any one explain this declaration, whats going on here...?
|
Here it is with the[1]part 'expanded':
```
(int)(&(*(((int*)0) + 1)))
```
Now do you see how it works?
The 0 will increase by thesizeofintdue to the properties of pointer arithmetic and the finalintcast is getting you the value of the resulting address which is the 'size'.
It's totally undefined behavior though (t... |
I need to delete an element from linked list where address of that element is given.Something like this
1->2->3->4->5
a1 a2 a3 a4 a5 where a1,a2..a5 are addresses of elements 1,2 ..5 respectively.
sum1 just says delete(a3) N since I have no access to header of given list.
I cant traverse the whole linked list and co... |
Classic interview question.
You don't delete that element, but copy the next element into it:
So you do:
a3 = a4delete a4
|
My questionis : how can I store the content of a .txt file in achar*named m_str, in C++?
Kindly note that my file has a very defined format that I want to keep. I don't want to merge the lines together. I want what is one line 1 to stay on line 1, and what is one line 2 to stay in line 2. Because eventually I am goi... |
You can use vector as:
```
std::ifstream file("file.txt");
std::istreambuf_iterator<char> begin(file), end;
std::vector<char> v(begin, end); //it reads the entire file into v
char *contentOfTheFile= &v[0];
```
The content of the file is stored incontentOfTheFile. You can use it, andmodifyit as well.
|
How do I get the key codes so I can process arrow, pageUp, pageDown, etc, keys using simple C or C++?
I can get the regular keys, I do not know how to get these special keys.
|
Ncurses should be able to handle that. There is lots of tutorials out there
|
when I end my program, I found 'glibc detected' message like this.
However, I do not know this is error or warning or else.. could someone explain what this message meaning and how I have to do?
|
It means you have heap corruption in your program. You likely allocate some memory usingmalloc, but write outside the actual bounds, corrupting the heap. When you callfree, glibc detects the corruption and reports it (specifically, the size of the next free chunk is overwritten).
You should definitely fix this prob... |
In Native Client, how do I create a proper instance ofPPB_Graphics3Din C (not C++)??
I've looked at the 'Tumbler' native client demo, but it's in C++ and seems to be calling a static method for the creation of the object... but how do I create thePPB_Graphics3Din C?
The Google dochereshows it's using an instance ofP... |
```
int32_t PPP_InitializeModule(
PP_Module module,
PPB_GetInterface get_browser_interface) {
PPB_Graphics3D *g3d =
get_browser_interface(PBB_GRAPHICS_3D_INTERFACE);
}
```
|
I want to disassemble only one particular line of code in gdb; to do this, I need the memory address of said line. How can I get the address of a particular line of code in gdb? Or better yet, is there a command in gdb to disassemble by line number?
|
Put a break on the line you want to disassemble and then, you could try to get the current instruction with.
```
disp/i $pc
```
This always works for me, when I debug binaries with no debug info. Also one could simply get the currentpceither byprint $pcorinfo registersor simply use thexinstruction.
e.g.:
```
x/10i ... |
So,offsetof(struct, field)returns the relative offset of field inside a plain structure. But is there a way to get the relative offset of a field inside of a nested structure.
e.g.
```
struct my_struct {
int a;
struct {
int b;
int c;
} anonymous_struct;
}
```
Is there any way to get the offset ... |
Yes, you can still useoffsetof.
E.g.
```
size_t boff = offsetof(struct my_struct, anonymous_struct.b);
```
The requirements ofoffsetofare that thetypeandmember-designatormust be such that givenstatictypet;,&(t.member-designator)evaluates to an address constant. Themember-designatordoesn't have to be a simple identi... |
If I want to target all iOS devices version 4.3 or later, I can use:
```
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_3
```
Also, if I want to target iOS devices in general, I can use:
```
#if TARGET_OS_IPHONE
```
Is there something similar for Mac OS X?
|
NSAppKitVersionNumberis your friend on OS X. To target eg. 10.5 and upwards, you can do this:
```
#if NSAppKitVersionNumber >= NSAppKitVersionNumber10_5
// ...
#endif
```
Edit:Just seen that there are also__MAC_OS_X_VERSION_MAX_ALLOWEDand__MAC_OS_X_VERSION_MIN_REQUIREDon OS X, which might work better and which are... |
How do I find out the minimum OS requirements for usingarc4random_uniform()? Is it defined in BSD? If so, from what version? Does it run on any Mac OS X version? How about iOS versions? Is there any official place I can find these things out?
|
If you look atstdlib.hwhere it is defined, it says:
```
u_int32_t arc4random_uniform(u_int32_t /*upper_bound*/) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
```
So it is available from Lion on for desktops and iOS 4.3 on the iPhone.
|
I have a C++ application that isn't callingpthread_joinand has O(time running) threads. My question is - how would this affect the health of the server task? Is there a fixed number of threads a C++ task can hold before it crashes or fails to start new threads? Will this manifest as an error code inpthread_create? ... |
The POSIX manual sayspthread_createcan returnEAGAIN:
The system lacked the necessary resources to create another thread, orthe system-imposed limit on the total number of threads in a process
{PTHREAD_THREADS_MAX} would be exceeded.
A simple fix would be to mark the threads detached usingpthread_detachor using an ... |
I want to process an Array of strings, so it is an array of an array of chars
I've defined the strings like that
```
char que1[4][LEN_STRING]={{'\0'}};
```
and I want to pass them to the function
```
void print_results(char *pqueries[],document p_docs[]);
```
using a simple
```
print_results(que1,indoc);
```
re... |
An array of arrays is not the same as an array of pointers. See the C FAQ more details:http://c-faq.com/aryptr/pass2dary.html.
One solution is to modify your function to take fixed-width strings:
```
void print_results(char (*pqueries)[LEN_STRING],document p_docs[]);
```
|
When I attach gdb to a process that uses many source files, such as PHP, sometimes I want to set a breakpoint on line x of file y. How do I specify the file for gdb?
|
It's as simple as:
```
b filename.c:XYZ
```
Seethe documentationfor more info.
|
I want to add a field to a structure in C. So for example I have the following structure.
```
struct A
{
some_type x;
some_type y;
}
```
I declare a new structure, like this.
```
struct B
{
A a;
some_type z;
}
```
Now say I have a function like this.
```
int some_function( A * a )
```
Is it possible to pass ... |
Yes, it is valid. Word of the Standard, C99 6.7.2.1/13:
... A pointer to a
structure object, suitably converted, points to its initial member (or if that member is a
bit-field, then to the unit in which it resides), and vice versa. There may be unnamed
padding within a structure object, but not at its beginning... |
I have seen this complex declaration of sizeof operator somewhere in book which is teasing me:
```
#define SIZEOF(int) (int)&((int *)0)[1]
```
Can any one explain this declaration, whats going on here...?
|
Here it is with the[1]part 'expanded':
```
(int)(&(*(((int*)0) + 1)))
```
Now do you see how it works?
The 0 will increase by thesizeofintdue to the properties of pointer arithmetic and the finalintcast is getting you the value of the resulting address which is the 'size'.
It's totally undefined behavior though (t... |
I need to delete an element from linked list where address of that element is given.Something like this
1->2->3->4->5
a1 a2 a3 a4 a5 where a1,a2..a5 are addresses of elements 1,2 ..5 respectively.
sum1 just says delete(a3) N since I have no access to header of given list.
I cant traverse the whole linked list and co... |
Classic interview question.
You don't delete that element, but copy the next element into it:
So you do:
a3 = a4delete a4
|
My questionis : how can I store the content of a .txt file in achar*named m_str, in C++?
Kindly note that my file has a very defined format that I want to keep. I don't want to merge the lines together. I want what is one line 1 to stay on line 1, and what is one line 2 to stay in line 2. Because eventually I am goi... |
You can use vector as:
```
std::ifstream file("file.txt");
std::istreambuf_iterator<char> begin(file), end;
std::vector<char> v(begin, end); //it reads the entire file into v
char *contentOfTheFile= &v[0];
```
The content of the file is stored incontentOfTheFile. You can use it, andmodifyit as well.
|
How do I get the key codes so I can process arrow, pageUp, pageDown, etc, keys using simple C or C++?
I can get the regular keys, I do not know how to get these special keys.
|
Ncurses should be able to handle that. There is lots of tutorials out there
|
when I end my program, I found 'glibc detected' message like this.
However, I do not know this is error or warning or else.. could someone explain what this message meaning and how I have to do?
|
It means you have heap corruption in your program. You likely allocate some memory usingmalloc, but write outside the actual bounds, corrupting the heap. When you callfree, glibc detects the corruption and reports it (specifically, the size of the next free chunk is overwritten).
You should definitely fix this prob... |
In Native Client, how do I create a proper instance ofPPB_Graphics3Din C (not C++)??
I've looked at the 'Tumbler' native client demo, but it's in C++ and seems to be calling a static method for the creation of the object... but how do I create thePPB_Graphics3Din C?
The Google dochereshows it's using an instance ofP... |
```
int32_t PPP_InitializeModule(
PP_Module module,
PPB_GetInterface get_browser_interface) {
PPB_Graphics3D *g3d =
get_browser_interface(PBB_GRAPHICS_3D_INTERFACE);
}
```
|
To handle platform specific code between Mac and Windows,WIN32andAPPLEare the terms to use, right?
So, thw code would look like this:
```
#ifdef _WIN32
// Windows code
#endif
#ifdef __APPLE__
// Mac code
#endif
```
What about Linux ?
How can i do that for all three? right
|
It's similar:
```
#ifdef __linux__
// Linux code
#endif
```
Since you are going to have either one of these three defined at a time, this should be ok for all three.
List of defines.
|
If I import the std.c libaries instead of including the libraries in C, would C code compile with a D compiler, or are there other backwords compatibility issues?
|
There are several subtleties in D that can make C code not behave exactly as you may want it to. For instance, integer promotion rules are not quite the same (but almost), and initialization rules are different (floating point values -- including arrays of such -- are initialized to NaN, for example). Further, C funct... |
I have a C program which uses a small part of theGandalf C Machine Vision Library. There are thousands of source files. Some are includes (both .h and .c) and some are dependent in the linker stage.
I don't want to have a monolithic library. I would like to include in my source tree only the include and source fil... |
Klocworkhas an On-the-Fly source code analysis product which can figure out redundant and unused header file. Have a look to see if it fulfills your requirements.
|
I am trying to use MPI_REDUCE in C (or c++) to find the minimum (and the index) in an array. I have this working for regular array, but now I want to switch to one in which the value is dynamically computed. i.e the value of arr[n] is calculated by calling fun(n). Due to memory problems I cannot compute all values an ... |
You'll need to useMPI_Op_create()to create a custom MPI operation: in your case, this operation would compare the values obtained by calling fun() on each element of the array, and select the minimum. You can then use this custom operation in the Op argument of MPI_Reduce().
|
Probably have wrong title,but I don't know how to describe it.
```
int x=0x4a;
h=!(0x80000000000&(0x39+(~x+1)));
```
the result is h=0.
The question is x has 32 bits, while 0x80000000000 has more than 32 bit. If I set variable i to 0x80000000000 and print it as hex format,it will show 0. So in that case, why not the... |
0x8000000000 is along long intconstant. Therefore the C compiler promotes the types in an arithmetic expression to the highest precision that occurs within an expression.
If instead you wrote:
```
int x=0x4a;
int h1=(0x80000000000&(0x39+(~x+1)));
int h = !h1;
```
Thenhwould become 1. And perhaps a warning on mi... |
I want to compile an OpenGL program but I don't have the necessary headers. Maybe you know how to get these?
```
#include <GL/glx.h> /* this includes the necessary X headers */
#include <GL/gl.h>
#include <X11/X.h> /* X11 constant (e.g. TrueColor) */
#include <X11/keysym.h>
```
It's the OpenGL example from th... |
The OpenGL headers are part of Mesa, and the X11 headers are in Xorg's protocol development package.
|
someone please tell me which one of the following is more fast and why ??
```
int add(int a, int b){
return a+b;
}
```
OR
```
void add(int a, int *b){
*b = a+(*b);
}
```
|
Chances are functions areinlinedand both result in the same generated code.
|
I met a problem with including a header file which hassys/type.h. When I compile usingg++orgcc filename.cppit always show me the error:sys/type.h, no such a file or directory. very confused. Can someone help me?
```
#include<stdio.h>
#include<sys/type.h>
#include<unistd.h>
int main()
{
pid_t child_pid;
... |
It should be<sys/types.h>with an 's'
|
How can I print the dollar sign $ in the following code or any string for that matter?
```
system("powershell -executionpolicy unrestricted -file \"$env:userprofile\\Desktop\\Test.ps1\"");
```
|
$env is PowerShell variable.use getenv in coruse %%USERPROFILE%% (BATCH(shell:cmd.exe) variable)
E.g
```
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *userprofile;
char command[1024];
userprofile = getenv("USERPROFILE");
sprintf(command, "powershell -executionpolicy unrestricted -file... |
I am writing some customized application and allowed to change interrupt handler code in the linux kernel.
I am having a user thread which is waiting for an interrupt to happen. If that interrupt happens then the first thing I want to do is to execute that user thread.
Is there any way to make it work.
Thanks
|
Create a character device (that's what the kernel does, handles devices). Have the user thread read from that device. It will hang as there are no characters to read.
When the interrupt happens, output a character (or some meaningful message) to that device from your module. The thread will wake up, read the message ... |
So quite simply, the question is how to get the system boot up time in windows with c/c++.
Searching for this hasn't got me any answer, I have only found a really hacky approach which is reading a file timestamp ( needless to say, I abandoned reading that halfway ).
Another approach that I found was actually reading... |
GetTickCount64"retrieves the number of milliseconds that have elapsed since the system was started."
Once you know how long the system has been running, it is simply a matter of subtracting this duration from the current time to determine when it was booted. For example, using the C++11 chrono library (supported by ... |
I've seen lots of methods been used to resolved the dependencies in Makefile, such as usinggcc -MMandsedcommond, or using theincludedirective (plus a little Perl magic), orqmake, orautomake, orinfo make, etc.
Facing such many options, I am confused of which should I choose. So, I wanna know what's the common way to r... |
Generally if all you care about is systems that support GNU make and gcc (such as all linux variants and most unix like systems these days), you just use gcc's various-Mflags to generate the dependencies and then-includethem in your Makefile. There's some good infoin this question-- generally there's no need to use s... |
I want to write a function to round a double to an int using Banker's Rounding method (round half to even:http://en.wikipedia.org/wiki/Rounding#Round_half_to_even), like:
```
int RoundToInt(double x);
```
How can I do that?
Update:
The best I can get is this:
```
int RoundToInt(double x)
{
int s = (int)x;
dou... |
Use the standardlrintfunction; in the default rounding mode, it gives exactly the result you want.
|
I wonder how to write a C program with options that can be invoked by a terminal.Example : Person.c
```
#include <stdio.h>
void main ()
{
char option;
if(option == 'f') printf("First Name");
else if(option == 'l') printf("Last Name");
else printf("Full Name");
}
```
Compile it with
cc Person.c ... |
void main ()is wrong, if you copied this from a book, throw the book away
It should beint main(int argc, char **argv), argc will then be set to the number of arguments and argv[1] .... argv[argc-1] are the argument strings (argv[0] is the name of the program)
|
What kind of API or algorithm is normally used to generate session ids? For something like an online game?
Thanks
|
You can useUUID-v4. Implementations are available in pretty much any language. Here is one for C++:
http://sourceforge.net/projects/ooid/
|
I try to read a number from a string with strtol() and it returns the LONG_MAX number which is supposed to return when the number is out of range, but my number is not that big
```
main(){
char linea[30]={"110111010111111000000000"};
long num=strtol(linea,NULL,0);
printf("%s\n%X",linea,num);
}
```
Actual... |
According to the man page for strtol, the '0' argument you've given means 'use you best judgement', which in this case isdecimal. If you want it to convert abinarynumber, as the 'Needed result' you've specified suggests, don't use '0', use '2'.
|
This question already has answers here:The ## operator in C(7 answers)Closed5 years ago.
something like #NAME or ##NAME. what do they mean in C? I saw them in GCC documents about macro.
|
operator ## concatenates two arguments leaving no blank spaces between them..
```
#define printe(a,b) a ## b
printe(c,out) << "testing";
```
output is : testing
and single # is used for parameter replacement withe the string parameter
like
```
#define st(x) #x
cout<<st(tesing); // equivalent to cout<<"test... |
I realized that my program has to be able to handle special characters such as Japanese or Chinese. But I know the built-in typecharis far from enough. So how can I use these special characters in C program?
|
like this in windows VS :)
```
#include <tchar.h>
typedef struct _我的结构{
int 数据;
TCHAR 字符串指针[100];
}我的结构;
int main(int argc,char** argv){
我的结构 我的变量 = {1, _T("字符串123abc")};
_tprintf(_T("%s, %d"),我的变量.字符串指针,我的变量.字符串指针);
return 0;
}
```
|
I saw the following code in CCTL (~line 330)https://github.com/jobytaffey/cctl/blob/master/cctl/main.c
```
switch(page)
{
// ...
ack:
cons_putc(0);
}
```
What is theack:section for? It looks like same asdefault:to me. I can't find it in the SDCC docs either.
Is this something in C spec?
Thank you
|
It's not a C keyword; it's just a label. Note the correspondinggotostatements.
|
Very new to C so please bear with me! I'm trying to read 3 arguments separated by spaces from "instruction" into the 3 strings using sscanf. I've got the following code so far:
```
char * buffer;
buffer = (char*) malloc (5000);
sscanf(instruction, "%s %s %s", &opcode, &arg1, &arg2, buffer);
```
However whilst it com... |
Remove the ampersands. The three%sescapes will then fill them (assuming you have them pointing to valid memory and the buffers are large enough). Note the buffer will be never filled as your format strings refers only to three args
|
I'm pretty new to C, but I have come across a problem with fread...
My end goal is to read (and then printf to console) the binary from a .bin file, but for now i'm taking it one step at a time and trying to just read the first bit...
My code:
```
...
FILE *file = fopen("test1.bin", rb);
int i = 0;
fread(&i, 1, 1, ... |
Change thefread()call to:
```
fread(&i, sizeof(int), 1, file);
```
The second argument is the size of an element to read, the third argument is the number of elements to read. The posted code is reading a single byte into anint.
You should also check the return values fromfopen()andfread()calls to ensure they were ... |
Can someone tell me why the gets in thecase 1is being completely ignored?
```
// #define M 50 is at the top
char product[M] = {0};
int choice = -1;
printf("Command: ");
scanf("%d", &choice);
switch(choice){
case 0:
break;
case 1:
printf("Product: ");
... |
The gets might be skipped by an ending char from a previous input. Try adding a getchar() before the gets to see if that is the problem.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why do these two pointer subtractions give different results?
```
char arr[] = "stackoverflow";
char *p1 = arr;
char *p2 = arr + 3;
printf("%d", (int*)p2 - (int*)p1);
```
it's answer is 0..Can you explain why is it so ?
|
Becausep2 - p1is< sizeof (int). So(int *) p2 - (int *) p1 == 0, the number ofintelements between the two pointers.
|
Do I need to include a library?
Can anyone please elaborate in it?
I know is used to get the process id of the current task where is being called from
But I want to printk something with current->pid
printk("My current process id/pid is %d\n", current->pid);
...and is giving me an error
error: dereferencing poin... |
You're looking for#include <linux/sched.h>. That's wheretask_structis declared.
|
I'm writing code that depends on whether or not a header file is included. If the file is included, I want certain added functionality. Is there any way to do this, perhaps with an #if? Using C btw
|
Just#definea symbol in that header and use#ifdeflater on.
```
header.h
#define HAVE_IPV6
some_file.c
#ifdef HAVE_IPV6
/* code */
#endif
```
|
Is this possible?
I know it's possible in the command prompt using COLOR ##
but is it possible in C using bloodshed?
Thanks,
|
What operating system? What terminal do you have available? Note that this has nothing to do with C, let alone bloodshed. You output a string which the terminal may or may not choose to interpret as a color. You have to see how to do that with your terminal. The solution of course is not portable. One such example for... |
I saw the following code in CCTL (~line 330)https://github.com/jobytaffey/cctl/blob/master/cctl/main.c
```
switch(page)
{
// ...
ack:
cons_putc(0);
}
```
What is theack:section for? It looks like same asdefault:to me. I can't find it in the SDCC docs either.
Is this something in C spec?
Thank you
|
It's not a C keyword; it's just a label. Note the correspondinggotostatements.
|
Very new to C so please bear with me! I'm trying to read 3 arguments separated by spaces from "instruction" into the 3 strings using sscanf. I've got the following code so far:
```
char * buffer;
buffer = (char*) malloc (5000);
sscanf(instruction, "%s %s %s", &opcode, &arg1, &arg2, buffer);
```
However whilst it com... |
Remove the ampersands. The three%sescapes will then fill them (assuming you have them pointing to valid memory and the buffers are large enough). Note the buffer will be never filled as your format strings refers only to three args
|
I'm pretty new to C, but I have come across a problem with fread...
My end goal is to read (and then printf to console) the binary from a .bin file, but for now i'm taking it one step at a time and trying to just read the first bit...
My code:
```
...
FILE *file = fopen("test1.bin", rb);
int i = 0;
fread(&i, 1, 1, ... |
Change thefread()call to:
```
fread(&i, sizeof(int), 1, file);
```
The second argument is the size of an element to read, the third argument is the number of elements to read. The posted code is reading a single byte into anint.
You should also check the return values fromfopen()andfread()calls to ensure they were ... |
Can someone tell me why the gets in thecase 1is being completely ignored?
```
// #define M 50 is at the top
char product[M] = {0};
int choice = -1;
printf("Command: ");
scanf("%d", &choice);
switch(choice){
case 0:
break;
case 1:
printf("Product: ");
... |
The gets might be skipped by an ending char from a previous input. Try adding a getchar() before the gets to see if that is the problem.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why do these two pointer subtractions give different results?
```
char arr[] = "stackoverflow";
char *p1 = arr;
char *p2 = arr + 3;
printf("%d", (int*)p2 - (int*)p1);
```
it's answer is 0..Can you explain why is it so ?
|
Becausep2 - p1is< sizeof (int). So(int *) p2 - (int *) p1 == 0, the number ofintelements between the two pointers.
|
Do I need to include a library?
Can anyone please elaborate in it?
I know is used to get the process id of the current task where is being called from
But I want to printk something with current->pid
printk("My current process id/pid is %d\n", current->pid);
...and is giving me an error
error: dereferencing poin... |
You're looking for#include <linux/sched.h>. That's wheretask_structis declared.
|
I'm writing code that depends on whether or not a header file is included. If the file is included, I want certain added functionality. Is there any way to do this, perhaps with an #if? Using C btw
|
Just#definea symbol in that header and use#ifdeflater on.
```
header.h
#define HAVE_IPV6
some_file.c
#ifdef HAVE_IPV6
/* code */
#endif
```
|
Is this possible?
I know it's possible in the command prompt using COLOR ##
but is it possible in C using bloodshed?
Thanks,
|
What operating system? What terminal do you have available? Note that this has nothing to do with C, let alone bloodshed. You output a string which the terminal may or may not choose to interpret as a color. You have to see how to do that with your terminal. The solution of course is not portable. One such example for... |
I have this cpp file where I include bunch of C files.
main.cpp
```
extern "C" {
#include "types.h"
#include "file1.h"
}
...
```
types.h
```
#IFNDEF TYPES_H
#DEFINE TYPES_H
typedef unsigned short int char16;
...
#ENDIF // TYPES_H
```
file1.h
```
#include "file2.h"
...
```
file2.h
```
...
char16* testCode();
..... |
You should include the types.h in file2.h. You don't seem to be doing that.
Btw, the code posted compiles on my machine without any errors, whereas if I comment the"#include "types.h"in main.cpp, it gives me an error.
|
Is there anyway to print into a textarea or something using printf( or something similar)?
I need to print chars with different colours including spaces.
A table can be a solution if is possible to "paint" the cells.
Using labels would be awesome but is in a random IxJ (columnsxrows) and is impossible to select each o... |
Since you mentionprintf, I assume you want to output to the console. You can useSetConsoleTextAttributeto set the foreground and background colour to be used.
|
Question:
if I loopmount a file, like this
```
mount /volumes/jfs.dsk /mnt/jfs -t jfs -o loop
```
then what happens behind the scenes is
```
losetup /dev/loop1 /volumes/jfs.dsk
mount /dev/loop1 /mnt/jfs -t jfs -o loop
```
My question now:If I have /dev/loop1, how can I find which file this device belongs to ?e.g.... |
I think calling:
```
strace losetup /dev/loop1
```
and then googling will give you answer.
From what I've seen on my PC, to get status of loopback device ioctl 0x4c05 is called.
|
I have a call likeclock_gettime(CLOCK_REALTIME), does it handle leap seconds? If not, what changes are required? Working on Solaris.
|
If your Unix system is synchronized with NTP, chances are that it handles leap seconds.
See this article for more information:NTP Leap Second.
|
I have very simple xml
```
<root>
<node>some value</node>
</root>
```
How can I get the serialized HTML fragment, using libxml and C. I mean same as you can get usingouterHTMLin JS (document.getElementsByTagName("node")[0].outerHTML).
|
You have to usexmlNodeDump. Or if you want to print node out to file/stdout, then usexmlElemDump
|
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.
I have created a thread in windows ... |
Using theTerminateThreadfunction.
The function you posted does:
```
PostThreadMessage(hookThreadId, WM_QUIT, (WPARAM) NULL, (LPARAM) NULL);
WaitForSingleObject(hookThreadHandle, 5000);
```
So it sends a quit message to that thread, and then waits for it to close.
|
As the title said, I have a task that I need to read data from excel files. I'm wondering how to implement it in pure C, not C++ or C#. Btw, I need to write and test the program in Linux but others may use the code in Windows, which means my code has to be OS independent. Thank you.
|
Check outhttp://xlslib.sourceforge.net/
|
If I use macros in my C code, such as
```
#define var 10
```
then where exactly are the stored in the space allocated to the process by the kernel?
In heap or BSS or global data? Or is it just a text replacement for var in one of the compiler passes?
|
Yes.the last one
just a text replacement
It is performed by a preprocessing pass.
Some good details can be foundhere
|
I'm programming in C in unix OS and I'm stuck in a problem.
I need to operate in some files selected by the user and check if sometoken stringis in there, but it only makes sense if it checks the file when it is changed. So I thought to use aSIGALARMthat every second checks the modification date of the file but it see... |
On Linux, there is an API called inotify which will do what you want. For a more portable solution, look into the gio sublibrary of glib, specificallyhere. It might be able to do what you want but I am not completely certain.
|
I'm flummoxed by how to convert from a binary value to a char in c.
For example, let's say I have 01010110 and want to print the corresponding letter 'V' from that. How do I do this?
Thanks for any help!
|
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *data = "01010110";
char c = strtol(data, 0, 2);
printf("%s = %c = %d = 0x%.2X\n", data, c, c, c);
return(0);
}
```
Output:
```
01010110 = V = 86 = 0x56
```
References:
strtol()Correct usage ofstrtol()
|
Some system libraries like malloc strlen want or return size_t as parameter.
What is the right choice in LLVM IR to interact with these functions?Is the selection the task for the compiler?Does LLVM IR have a size_t type?
|
At the LLVM level, size_t doesn't exist. It is a construct for the benefit of the developer that is typedef'd to a native type. The native types have a fixed size for the target architecture and that is how the compiler represents them in LLVM bit code. So on x86, size_t might by viewed by the front end as unsigned... |
```
#include <stdio.h>
int main()
{
int X = 200;
float Y = 1500;
printf("Enter your initial Balance and the Amount to be Withdrawn. Note the Values should lie between 0 and 2000");
scanf("%d", "%e", &X, &Y);
if ((0 < X < 2000) && (0 < Y < 2000)) {
if ((X < Y) && (X % 5 == 0)) {
... |
```
scanf("%d,%e", &X, &Y);
```
|
I have a fairly complex algorithm I'm building using both visual c 2008 and visual c 2010. The algorithm is producing bad output when I compile with optimization enabled in VC 2010 (specifically, /Og).
Building the same exact code in VC 2008 (with or without optimization) or in VC2010 without optimization produces an... |
It could be a compiler bug, but you should try /Wall to enable all the warnings and fix all of them. There are also runtime checks like /RTCu (Uninitialized local usage checks) which you can use to isolate the problem. Also inspect all the type castings in your code to make sure they are legit.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.