question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am trying to understand what the following typedefs mean. Are they function pointers?
```
typedef int Myfunc(char *);
static Myfunc myfunc;
int myfunc(char *string)
{
printf("%s\n", string);
return 0;
}
```
I knowtypedef int Myfunc(char *)means funcMyfuncreturn an integer,that's all,all right? And I thou... |
The second line is a declaration of a function, not a function pointer. The function is of typeMyFunc, is calledmyfunc, and has staticlinkage: meaning that the function is not available to other source files compiled into the same object.
|
I am confused by thefor(;;)construct. I think it is a form of shorthand for an unlimited for loop but I can't be sure.
Here is the code:
```
for(;;)
{
//whatever statements
}
```
|
Your guess is correct; it's an infinite loop.*This is a common C idiom, although many people (including me) believe the following to be less cryptic:
```
while (1) { whatever statements; }
```
* It's infinite assuming there are nobreak/return/etc. statements inside the loop body.
|
I'm used to//to mark a single line comment from Java and Visual Studio and was surprised that this does not exist for Ansi-C. Using/* my comment */is quite annoying. Is there any other way to mark a single line comment when using Ansi-C?
|
ANSI-C, no, but the current standard revision allows them, and has done so ever since C99.
|
There are some files we want ignored, not tracked, by git, and we are having trouble figuring out how to do that.
We have some third-partyClibrary which is unpacked and we have it in Git. But when youconfigure && makeit, it produces many new files. How to write.gitignoreto track source files and not the new stuff. (i... |
Use!to include all the types of files you need. Something like in the following example"
```
*
!*.c
!*.h
```
|
I am trying to pass a float32_t * const value to a function argument and I am getting exception errors. I have tried a lot of things but still receiving errors. My function is:
```
float32_t Distance(float32_t *const argDistance);
```
wherefloat32_tis:typedef float float32_t;
I am trying to access this function lik... |
You are sending in a pointer containing a0memory address, which is an invalid address to access. If you want to send in a pointer to the value0.0use:
```
float32_t value = 0.0;
float32_t* const tempTipDistance = &value;
```
|
```
#include <stdio.h>
int arr[] = {1, 2,3,4,5};
#define TOT (sizeof(arr)/sizeof(arr[0]))
int main()
{
int d = -1, x = 0;
if(d<= TOT){
x = arr[4];
printf("%d", TOT);
}
printf("%d", TOT);
}
```
TOT has the value 5 but the if condition is failing..why is that?
|
Because there are "the usual arithmetic conversions" at work for theif.
Thesizeofoperator returns an unsigned type ... anddis converted to unsigned making it greater than the number of elements inarr.
Try
```
#define TOT (int)(sizeof(arr)/sizeof(arr[0]))
```
or
```
if(d<= (int)TOT){
```
|
I'm trying to convert this C code to C#, is there a C# equivalent to the C union typedef?
```
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
typedef struct in_addr {
union {
struct {
u_char s_b1,s_b2,s_b3,s_b4;
} S_un_b;
... |
You may check out thefollowing page. This being said, in .NET you have classes that allows you to work directly with sockets and TCP/IP such as Socket, TcpListener, TcpClient and you don't need to translate C code blindly.
|
Recently I foundthis articlethat claims that the idea to preferfor(;;)overwhile(1)for infinite loop came because the C compiler originally available on PDP-11 generated an extra machine instruction forwhile(1).
Btw now even Visual C++ warningstend to favor the former.
How realistic is such attribution offor(;;)idiom... |
The "for(;;)" idiom is explicitly mentioned in the original K&R. That's attribution enough for me :)
|
All I'm trying to do is initialize my array to all 0s in C, but my compiler keeps giving me errors (and the errors aren't helpful). The array has 24 entries and the values are floating point values.
```
main()
{
/* Array of users arrival & departure time */
float user_queue[24];
/* Initialize queue to 0 */
int i;
f... |
You may not be allowed to declare variables after you have already used expressions. Try moving the declaration oftimeto the top:
```
main()
{
/* Array of users arrival & departure time */
float time, user_queue[24];
/* Initialize queue to 0 */
int i;
for(i = 0; i < 24; i++)
{
user_queue[i] = 0.0;
}
/* Simulat... |
just wondering, how do you use global arrays of a structure's?
For example:
```
int y = 0;
object objectArray [100];
typedef struct object{
time_t objectTime;
int objectNumber;
} object;
int main(void)
{
while(1)
{
time_t time_now;
time_now = time(NULL);
object x = {time_no... |
Move the definition of the struct to before your declaration of the array:
```
typedef struct object{
time_t objectTime;
int objectNumber;
} object;
object objectArray [100];
```
You're getting that error because the compiler doesn't know the size ofobjectwhen it gets to the array declaration.
|
I feel this might be a weird/stupid question, but here goes...
In the questionIs NULL in C required/defined to be zero?, it has been established that theNULLpointer points to an unaddressable memory location, and also thatNULLis0.
Now, supposedly a 32-bit processor can address2^32memory locations.
2^32is only the n... |
If a 32-bit processor can address 2^32 memory locations, that simply means that a C pointer on that architecture can refer to 2^32 - 1 locations plusNULL.
|
If I never use the address of a static const variable, is memory allocated for it when using a reasonably modern compiler?
|
It depends on thetypeof the variable, and on whether "constant" also means "constant expression". Example:
```
static const Foo = get_foo(std::cin);
static const int q = argc * 3;
static const std::string s(gets());
```
These variables are const, but blatantly need an actual allocation.
On the other hand, the fol... |
I am trying to learn C for my class. One thing I need to know is given an array, I have to take information from two characters and store it in one bytes. For eg. if string is "A1B3C5" then I have to store A = 001 in higher 3bits and then store 1 in lower 5bits. I have to function that can get two chars from array at ... |
Assuming an ASCII character set, subtract '@' from the letter and shift left five bits, then subtract '0' from the character representing the digit and add it to the first part.
|
I'm trying to compile the NIF Test from Erlang (http://www.erlang.org/doc/man/erl_nif.html) on Mac OS X Lion. I can't get it to compile. Am I missing a compiler flag? Here's the error I get:
```
Computer:~ me $ gcc -fPIC -shared -o niftest.so niftest.c -I /usr/local/Cellar/erlang/R14B02/lib/erlang/usr/include/
Undefi... |
for 64-bit Erlang, the following works for me:
```
gcc -undefined dynamic_lookup -dynamiclib niftest.c -o niftest.so \
-I /usr/local/Cellar/erlang/R14B02/lib/erlang/usr/include
```
|
I am new to threads and processes.
I have code that works fine right now with forking the code into multiple processes. However each process needs to add to a global variable, but from what I read, each time the process forks, it takes a copy of the global, and adds them independently. Is there a way to join them, ... |
Different processes can communicate and exchange data via shared memory.
On linux, you can look:
man shm_overview
for attaching a memory segment on several processes
and
man sem_overview
for the semaphore library for controlling parallel access.
|
I am implementing a netcat clone and currently need a way to run command-line programs over the network.
My solution so far is to execute a process and use pipes for STDIN and STDOUT, then forward the data back and forth over TCP.
The problem is, I feel like this is a round-about way of doing things. When I run bash... |
Correct terminal behavior can't be obtained using pipes -- you will need to use aPTY (pseudoterminal)to get the right results.
Note that what you're trying to write here is essentiallytelnetd...
|
What is a "verbose build" in C? I can's seem to find a good answer. There's a check box in Pelles C for Verbose Build and I can't figure out what this does. Does it include libraries in with the exe or something?
|
No, it simply spits out more messages for you during the building process.
|
Can I useboost::bind(mycallback, this, _1, _2)across C code?
Update
The short answer isno, boost bind does not return a function pointer, which can be called in C code, but afunctor(C++ object with overloaded()operator) see answer below.
|
The best way to do what you want to do is to create a C callback that then calls the boost::function, which is stored in some sort of user memory with new.
Example:
```
void callFunction(void* data)
{
boost::function<void(void)> *func = (boost::function<void(void)>* ) (data);
(*func)();
delete(func);
}
```... |
How to know whether an array is initialized in C ? Functions like strlen() are not helping me as I dont want to know whether the array is empty or not.
|
There's no way to test that at runtime -- an uninitialized array looks just like one that has been initialized with garbage.
Depending on what you're doing, you needeitherto make sure the array is actually initializedorexplicitly pass around a flag that tells you whether the values in the array are meaningful yet.
A... |
I prefernotdoing a resolve. A quick hardcoded macro to0x0100007Fwould work beautifully for IPv4, is there one for IPv6 too?
This is for thebind()BSD sockets structuresockaddr_in6andsockaddr_in
|
man ipv6 is your friend :)
There is ain6addr_loopbackvariable and for initializations a macroIN6ADDR_LOOPBACK_INIT.
Be careful about the macro you want to do for IPv4, don't forget that this is stored in network order, so the endianess of the system is an issue, here.
|
I was wondering why C's and C++'s FILE type is spelled with capital letters. Other types are spelled with lower case letters.
Editsee § 27.9.2 of C++11, table 134
|
Invery olddialects of C, before there was any of standardization, when the FILE type was invented, and before typedef existed, that name was a macro:
```
#define FILE struct _iobuf
```
The convention was to have macros named in all uppercase.
http://minnie.tuhs.org/cgi-bin/utree.pl?file=V7/usr/include/stdio.h
(the... |
I have a soft real-time application project that needs extensive monitoring.
JMX would seem well suited for that task, except that this application project is c++-based.
Are there any lightweight alternatives to JMX (with a c/c++ supporting library) that are minimally invasive for the monitored application?
(SNMP ... |
Even if SNMP would seem overkill for your application it still may be your best bet. Net SNMP is not hard to use and it has a well known standard for monitoring applications.
Some other alternatives would be:
rsyslogThe problem you may experience with this one though is that it may be harder to integrate it into the... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:How can I create directory tree in C++/Linux?Why mkdir fails to work with tilde (~)?
i'm trying to create a directory in a C program and i use the mkdir function.
My program is as follows:
```
#include <stdio.h>
#include <string.h>
#de... |
mkdir()function doesn't expand~shortcut, you'll have to pull the value from theHOMEenvironment variable. (seeman getenv).
|
This simple issue is causing my entire program to crash during the first input. If I remove the input, the program works fine but once I add scanf into the code and enter the input the program crashes.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXEMPS 3
// stub program code
int main (v... |
You must pass the address of the variable to scanf:
```
scanf("%c", &answer);
```
|
I have the following makefile:
```
CC = gcc
SRC = source1.c
EXE = source1
FLAGS = -fopenmp
all: $(src)
$(CC) -o $(EXE) $(SRC) $(FLAGS)
clean:
rm $(EXE)
```
How can I modify it so I can use multiple sources, some of them compiled with the flag -fopenmp, some of them compiled without. Thanks a lot.
|
This should get you started: Note how-fopenmpgets added just for source2.c
```
CC=gcc
SRC=source1.c source2.c
OBJ=$(patsubst %.c,%.o,$(SRC))
EXE=source1
FLAGS= -g -O2
source2.o: FLAGS+=-fopenmp
all: $(EXE)
$(EXE): $(OBJ)
$(CC) -o $@ $^ $(FLAGS)
%.o: %.c
$(CC) -c -o $@ $^ $(FLAGS)
clean:
rm $(EXE)$
``... |
I am a beginner in C programming language but I have knowledge of programming in QBasic. I make lots of small programs in Qbasic to solve my basic tasks and I am recently rewriting those programs into C .
While rewriting one of the programs I stumbled upon a problem where the computer would be able to get input but w... |
On windows the easiest way iskbhit
|
How to know whether an array is initialized in C ? Functions like strlen() are not helping me as I dont want to know whether the array is empty or not.
|
There's no way to test that at runtime -- an uninitialized array looks just like one that has been initialized with garbage.
Depending on what you're doing, you needeitherto make sure the array is actually initializedorexplicitly pass around a flag that tells you whether the values in the array are meaningful yet.
A... |
I prefernotdoing a resolve. A quick hardcoded macro to0x0100007Fwould work beautifully for IPv4, is there one for IPv6 too?
This is for thebind()BSD sockets structuresockaddr_in6andsockaddr_in
|
man ipv6 is your friend :)
There is ain6addr_loopbackvariable and for initializations a macroIN6ADDR_LOOPBACK_INIT.
Be careful about the macro you want to do for IPv4, don't forget that this is stored in network order, so the endianess of the system is an issue, here.
|
I was wondering why C's and C++'s FILE type is spelled with capital letters. Other types are spelled with lower case letters.
Editsee § 27.9.2 of C++11, table 134
|
Invery olddialects of C, before there was any of standardization, when the FILE type was invented, and before typedef existed, that name was a macro:
```
#define FILE struct _iobuf
```
The convention was to have macros named in all uppercase.
http://minnie.tuhs.org/cgi-bin/utree.pl?file=V7/usr/include/stdio.h
(the... |
I have a soft real-time application project that needs extensive monitoring.
JMX would seem well suited for that task, except that this application project is c++-based.
Are there any lightweight alternatives to JMX (with a c/c++ supporting library) that are minimally invasive for the monitored application?
(SNMP ... |
Even if SNMP would seem overkill for your application it still may be your best bet. Net SNMP is not hard to use and it has a well known standard for monitoring applications.
Some other alternatives would be:
rsyslogThe problem you may experience with this one though is that it may be harder to integrate it into the... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:How can I create directory tree in C++/Linux?Why mkdir fails to work with tilde (~)?
i'm trying to create a directory in a C program and i use the mkdir function.
My program is as follows:
```
#include <stdio.h>
#include <string.h>
#de... |
mkdir()function doesn't expand~shortcut, you'll have to pull the value from theHOMEenvironment variable. (seeman getenv).
|
This simple issue is causing my entire program to crash during the first input. If I remove the input, the program works fine but once I add scanf into the code and enter the input the program crashes.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXEMPS 3
// stub program code
int main (v... |
You must pass the address of the variable to scanf:
```
scanf("%c", &answer);
```
|
I have the following makefile:
```
CC = gcc
SRC = source1.c
EXE = source1
FLAGS = -fopenmp
all: $(src)
$(CC) -o $(EXE) $(SRC) $(FLAGS)
clean:
rm $(EXE)
```
How can I modify it so I can use multiple sources, some of them compiled with the flag -fopenmp, some of them compiled without. Thanks a lot.
|
This should get you started: Note how-fopenmpgets added just for source2.c
```
CC=gcc
SRC=source1.c source2.c
OBJ=$(patsubst %.c,%.o,$(SRC))
EXE=source1
FLAGS= -g -O2
source2.o: FLAGS+=-fopenmp
all: $(EXE)
$(EXE): $(OBJ)
$(CC) -o $@ $^ $(FLAGS)
%.o: %.c
$(CC) -c -o $@ $^ $(FLAGS)
clean:
rm $(EXE)$
``... |
I am a beginner in C programming language but I have knowledge of programming in QBasic. I make lots of small programs in Qbasic to solve my basic tasks and I am recently rewriting those programs into C .
While rewriting one of the programs I stumbled upon a problem where the computer would be able to get input but w... |
On windows the easiest way iskbhit
|
I just readthisSO C++ FAQ about undefined behavior and sequence points and experimented a bit. In the following codegcc-4.5.2gives me a warning only in the line mentioned in the code comment, although the one line before shows undefined behaviour too, doesn't it? You can't say which operand of addition is executed fir... |
The behaviour of i = i + foo(); is unspecified but not undefined. Undefined means any possible behaviour is permitted, even aborting the program. Unspecified means either i is evaluated first, or foo(). Yes, foo writes to that same i, but since it happens in a separate statement, there is a sequence point before and a... |
I declared an array of struct and initialized it at compile time.
Now, for unit testing purposes, I would like to initialize it from a function which I can call from main() and from my unit tests.
For some reason, probably involving a 16 hour coding marathons & exhaustion, I can't figure it out.
|
So assuming you have
```
struct foo {
int a;
int b;
};
struct foo foo_array[5] = {
{ 0, 0 }, { 1, 1 }, { 2, 2 }
};
int main() {
memcpy(foo_array, some_stuff, sizeof(foo_array)); // should work
...
```
OR you could:
```
int main() {
int i;
for ( i = 0; i < sizeof(foo_array)/sizeof(struct ... |
This question already has answers here:preventing an exe file from closing [duplicate](5 answers)Closed6 years ago.
see i have compile one c program and prepare one a.exe
Now when ever iclick on a.exe
cmd windows opens
a.exe run
and automatically close that windows.
What should i do in program or anywhere so thi... |
Create a batch file with the following content:
```
a.exe
pause
```
Then start the batch file
As an alternative you could add a line to your C program that prompts the user for input before exiting.
|
I am compiling this program with gcc from cygwin package on my windows machine
```
#include<stdio.h>
#include<pthread.h>
void* thread_function(void)
{
printf("hello");
}
int main(int argc,char *argv[])
{
pthread_t thread_id[argc-1];
int i;
int status;
printf("argc is %d ",argc-1);
for(i=0;i<a... |
They are not "Linux threads", they arePOSIXthreads. Cygwin provides a POSIX compatibility layer, includingpthread.h.
|
Is there a way to loop through all the included/defined header files and then#undefthem all?
If looping is the issue, is there another way to#undefall of them with ease?
|
GNU cpp provides a -dM directive to do exactly that, you can list all the defines:
gcc -E -dM -c foo.c
You can then use a sed script to undef them on command line :)
gcc -E -c foo.c | sed 's/#define/#undef/'
or do whatever...
have fun :)
|
```
#include <stdio.h>
int main()
{
struct value
{
int bit1:1;
int bit2:4;
int bit3:4;
} bit;
printf ("%d\n", sizeof(bit));
return 0;
}
```
Output on Tc/Tc++:
2
Output under Linux:
4
I know I am missing some concept of bit fields.
|
Thesizeoffor the struct is not the same as the sum of the sizes of all the elements - this is especially the case with bitfields.
Typically, the struct needs to be padded to a certain size and alignment. (Which apparently is 2 on Tc/Tc++ and 4 in Linux.)
So although there's only 9 bits in use, it's being padded out ... |
I am trying to access keystrokes in C. I can access alphanumeric keys. How can I accessControl,ShiftandAltkey?Plus I read somewhere that sometimes while entering text in console, OS masks backspace key. I would like to know where user pressed backspace key. It's not same as knowing when '\n' was pressed.
GNU C. Ubuntu... |
Dietrich Epp answered in a comment: usencurseslibrary.
See alsothis question
And you might make anX11client graphical application; in that case use a graphical toolkit library likeGTKorQt
If you want to make a console application, usencursesor perhapsreadline
And your question, when taken literally, has no sense: ... |
I need some clever logging library for a daemon-likeC(notC++) program on Linux. It needs to be open-source. It should support logging to files, maybe sockets etc.
Or at least some good tips or tricks or best practices.
|
Usesyslog() . This decouples your in program logging from how the logs are handled.rsyslogis used on most Linux distributions nowadays, and allows great flexibility on how the logs are processed.
|
I would like to tryC memcpyfunction. I have this code:
```
char destination[40];
memcpy(destination, "My favorite destination is...", 11);
printf(destination);
```
I woul like to copy first 11 letters to destination array. When I use printf, the result is "My favorite2". Why?
|
You are missing the NULL terminator at the end of the 11 characters -> Printf is just printing whatever is in that part of memory until it finds a NULL terminator.
Simply add in destination[11] = 0;
That should work :)
|
I am writing a C library. I want to return the contents of a file from this function to the caller.
How can I convert the file contents to char[]?
fopen is crashing since I am using perl.h in my C code.
Is there any other way to convert file into a char array apart from opening & reading the file?
Here is my code:
... |
Get the file size (seeHow can I get a file's size in C?)Allocate memory to store contents of the file (seemalloc).Read contents of the file into allocated memory (seeread).Return a pointer and a length of data in bytes to the user.
Don't forget to check for errors in between those steps.
|
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.
Please, advise me SDK for emulating... |
There are multiple possibilities of applications for windows . I'm usingboxedapp.
|
I want to assign an array using inline assembly using the AT&T syntax. I want to achieve something like the following. Note thatrsphere is the%rspregister.
```
long saved_sp[N];
long new_sp[N];
void some_function( unsigned int tid, ... )
{
// These two lines should be in assembly
saved_sp[tid] = rsp;
rsp = new_s... |
I'm sure I don't need to warn you...
```
__asm__ __volatile__ (
"movq %%rsp, (%0, %2, 8)\n\t"
"movq (%1, %2, 8), %%rsp\n\t"
: : "r" (saved_sp), "r" (new_sp), "r" ((long) tid));
```
Perhaps "memory" should be added as a clobber, but it seems kind of redundant. Wherever you go after this, remember that t... |
I have a giant C project with numerous C files. I have to find all inner-loops. I am sure there is no any O(n³) block in the project, so only O(n²)-compexity blocks must be found (a loop in a loop).
Is it possible to find all inner loops using grep? If yes, what regexp may I use to find all occurrences of inner loops... |
Regex are for regular languages, what you are describing seems like a Context-Free, and i'm pretty sure it can't be done using Regular Expressions. See the answer to a similar questionhere. You should look for other type of automata like a scripting language(python or so).
|
I just need to clear all the actors added to the table_layout. So that i can add new actors . Is there any way i can do that.
|
you can useclutter_container_foreach(), e.g.:
```
clutter_container_foreach (the_actor_using_the_layout_manager,
CLUTTER_CALLBACK (clutter_actor_destroy),
NULL);
```
or you can simply get the list of children using clutter_container_get_children(), and iterat... |
This question already has answers here:Header file included only once in entire program?(4 answers)Closed5 years ago.
Whenfile1.cincludesinc.h(containing the include guard#ifndef INC_H) for the first time, the#define INC_His performed. But now, when anotherfile2.cincludes the sameinc.h, is the macroINC_Halready defin... |
The macro definition is not preserved between separate compilations.
|
I am implementing the(ls)command on Unix while learning from a book. During the coding part of my implementation of the(ls)command with the(-l) flag, I see that I have to prompt the user and group names of the file. So far I have the user and group IDs from the following lines:
```
struct stat statBuf;
statBuf.st_ui... |
You usegetpwuidto look up the password file entry for a particular UID (which includes the user name, but now not the password itself) andgetgrgidto look up the group file entry for a particular GID.
|
Due to some reason, I switch the stack for calling some functions in my application. I usemakecontext/getcontext/swapcontextfor that purpose. However, I find it to be too slow.
I tried to use custom made code for that purpose, which saves the stack pointer and other registers and then assign the stack pointer the valu... |
The excellentGNU Pthlibrary makes heavy use of these techniques. It's very well documented, and determines the most efficient context switching mechanism at compile time.edit:at configure time actually.
The author's paper:rse-pmt.psgives a technical account of user-space context switching and related issues - alterna... |
Lets say I have an array = {2, 3, ABCD}
First, I need to make the third element equal to a new Array. And I know char newArr [] = array [2] wont work, so how do I go about this?
Second, I need to print out the characters of the newArr one by one. So my output should be
A
B
C
D
They should be separated from each o... |
Something like:
```
char *array[] = {"2", "3", "ABCD"}; // your existing array.
char n = strlen(array[2]); // size of 2nd element.
char *newArr = malloc(n); // create new array.
int i;
// populate the new array.
for(i=0;i<n;i++) {
newArr[i] = array[2][i];
}
// print.
for(i=0;i<n;... |
I would like to make the output of a number to always have 6 digits
e.g.:
if number is 1 the output should be 100000if number is 23 the output should be 230000if number is 236 the output should be 236000
How can I do this withprintf/sprintf?
|
printf and its variants can pad zeroes to the left, not to the right. sprintf the number, then add the necessary zeros yourself, or make sure the number is 6 digits long:
```
while(num < 100000)
num *= 10;
```
(This code assumes the number isn't negative, or you're going to get in trouble)
|
I'm trying to find programmatically the inet address of an Infiniband interface whose name is not knowa priori.
I'm on Linux, and I would like to avoid the parsing ofifconfig (8)output.
I've read the second comment onthisanswer, that suggests to usegetifaddrs()to retrieve the interfaces, but then I cannot select the... |
getifaddrs()returns one entry of typeAF_PACKETfor each interface, which has hardware address details, as described inthis answer. In particular, theiface->ifa_addrholds astruct sockaddr_ll, and thesll_hatypemember of that structure holds the hardware address type. So to figure out which interfaces are IPoIB you can ... |
I am writing a big code and I don't want it all to be in my main.c so I wrote a .inc file that has IF-ELSE statement with function and I was wondering can it be written like this:
```
#if var==1
process(int a)
{
printf("Result is: %d",2*a);
}
#else
process(int a)
{
printf("Result is: %d",10*a);
}
#endif
```
... |
The preprocessor doesn't "know" the value of any variable, because it does its work even before compilation, not at runtime.
In the condition of a preprocessor#ifyou can only evaluate#define'd symbols and constant expressions.
The particular example you are showing can be simply converted to:
```
printf("Result is:... |
First I declare a class:
```
class Op(var x : Int) {
def +++(op: Op) = {
println(this.x + " +++ " + op.x)
this.x += op.x
this
}
def ***(op: Op) = {
println(this.x + " *** " + op.x)
this.x *= op.x
this
}
}
```
Now I execute the expression in REPL:
```
op1 +++ op2 +++ op3 *** op4
```
... |
```
op1 +++ op2 +++ op3 *** op4
```
is equivalent to
```
((op1 +++ op2) +++ (op3 *** op4))
```
since method calls are left-associative. Thus first(op1 +++ op2)is evaluated, since it's the first operand to the second+++. Then the second operand,(op3 *** op4)is evaluated. And finally, the outermost operator is evalua... |
I have ubuntu 11 installed in my system. I have a c program that uses the pthread library.
I get the errorUndefined reference to sem_wait()even if I have compiled with the flag-lpthread.
for example:
```
gcc -lpthread prog.c
```
The program works fine on other ubuntu installations.
|
Try:
```
gcc -pthread
```
instead of-lpthread. The difference is significant, I believe. The latter is linking againstlibpthread, the former is linking against libpthread and a bunch of other things, too!
sem_waitis part of librt, so you could just as well usegcc -lrt, but-pthreaddoes this for you (and everything... |
I'm trying to a binary file consisting of floats with Octave (on OS X), but I'm getting the following error:
```
octave-3.2.3:2> load Input.dat R -binary
error: load: failed to read matrix from file `Input.dat'
```
The file was written like so:
```
std::ofstream fout("Input.dat", std::ios::trunc | std::ios::binary)... |
load Input.dat R -binaryexpects the file Input.dat to be in Octave's binary file format.
You need to figure out what Octave's binary format is if you want to do it like that. However, if instead you want to output the file from C++ as you have, then you can read it in using Octave'sfopenandfreadfunctions.
|
I am reading/writingchars to a binary file. The program doing the reading/writing may run on either a 32 or 64 bit machine. Furthermore, the file could be written in a 32-bit environment then read in 64 and vice-versa.
Therefore I need some way of storingchars that guarantees a certain width (the smaller the better).... |
On any "normal" modern architecturechars are always of 8 bits, regardless of 64/32 bit issues. Those arise when you dump directly on a file the binary representation ofintor other types (which can vary in size and byte ordering depending on architecture), but plainchars should be safe.
... obviously if you are writin... |
I've been trying to get the "names" of all GtkWidgets in a GtkBuilder object.
I've managed to get all objects from the builder object viagtk_builder_get_objects()and store them in a GSList.
However, when I usegtk_widget_get_name()on the gobjects (which i cast to GtkWidgets), I get generic names such as "GtkWindow" a... |
I am doing the exact same thing. I was able to get theid=strings from the.gladefile usinggtk_buildable_get_name()as specifiedhere.
Note: Prior to 2.20, GtkBuilder was setting the "name" property of constructed widgets to the "id" attribute. In GTK+ 2.20 or newer, you have to usegtk_buildable_get_name()instead ofgtk_w... |
I am doing a port scanner program as part of a school project where am using raw sockets. My understanding is this:
When using multithreading with raw sockets, each pthread does NOT get a copy of the packets seen by the NIC. Hence to handle all the different thread, I would need a receiving thread that passes message... |
I think if you want to receive the packets in all threads, you just need to create a separate raw socket (with the same arguments) in each thread. I haven't found a good resource describing this on Linux, but that's how it'sdocumentedon Windows:
if several SOCK_RAW sockets are open on a computer at the same time,
... |
When I am compiling this program I am getting some random number as output.. In Cygwin the output is 47 but in RHEL5, it is giving some negative random numbers as output.
Can anyone tell me the reason?Code:
```
main()
{
printf("%d");
}
```
|
This program provokesundefined behaviorsince it does not follow the rules of C. You should giveprintfone argument per format specifier after the format string.
On common C implementations, it prints whatever happens to be on the stack after the pointer to"%d", interpreted as an integer. On others, it may senddemons f... |
I'm programming an offline packets decoding program in C under Windows 7 x86.
I wonder how it is possible to know packet protocol, either if it isUDPorTCP?
|
You can know by checking the IP packet header, there is aProtocolfield in the packet header that is used to indicate the type of the packet according to its value :
1is ICMP6is TCP17is UDP
and so on. More information on this is available onWikipedia
Edit:Here'sthe listof all the possible values for that field.
P.S... |
I'm currently writing a Linux kernel module, and I need to handleva_listin one of my functions, which looks like:
```
void blah(int flag, va_list va) {
...
if (flag & BLAH_1) {
...
printk(... va here ...); // where I need the printk() with va_list support
...
}
...
}
```
So I ... |
You can always usevsnprintf()to format ava_listinto a buffer, and pass that buffer toprintk().
However, avprintk()function seems to exist in the kernel.
|
I am doing some projects with Arduino at the moment, and I was wondering if it is possible to make HTTP requests without the Internetshield.
The idea was to make a program which does HTTP requests and sends the response to the Arduino over the serial port.
I did some search online, but I could not find a way how to ... |
Yep, I've done this. I had a remote temperature logger built with an Arduino. Then I used the USB cable to connect the Arduino to a laptop. The laptop had a WiFi connection to my network and could get out to the Internet if it wanted to, but I actually just connected to my desktop.
I didn't do anything special on the... |
How do you convert anint(integer) to a string?
I'm trying to make a function that converts the data of astructinto a string to save it in a file.
|
You can usesprintfto do it, or maybesnprintfif you have it:
```
char str[ENOUGH];
sprintf(str, "%d", 42);
```
Where the number of characters (plus terminating char) in thestrcan be calculated using:
```
(int)((ceil(log10(num))+1)*sizeof(char))
```
|
I have some code in a project which should never be used in the release build, but is useful when testing. I'd like to do something like this:
```
#ifdef DEBUG
// Run my debugging only code
#endif
```
Where do I add the DEBUG setting in Xcode 4? I tried putting it in the "Edit Scheme" under Run MyApp->Arguments ... |
In recent Xcode project templates there’s already aDEBUG=1macro defined for the Debug build configuration (in thePreprocessor Macrossection). You can test it using the#ifpreprocessor directive.
|
Current way:
```
while(read(pipe, input, sizeof(input))>0);
```
Is there a better one with seeking?
|
Pipes on computers are like pipes in the "real" world... Data flows from one end to the other, and once it's gone from the pipe there is no getting it back. And like a real pipe there is no knowing when the flow will stop, so there is no meaning to try and find the end of the flow before it actually ends.
|
I need to make a counter in c and Im having kind of a noobish question. Here is my code :
```
time_t start = time((time_t *) NULL);
time_t finish = start;
while((finish-start) < 5){
finish=time((time_t *)NULL);
printf("TIME : %d\n", (finish-start));
}
printf("TIMER HAS STOPED !");
```
What... |
Perhaps you want
```
printf("TIME : %d\r", (finish-start));
fflush (stdout);
```
But for more complex command & terminal oriented I/O, consider usingncurses
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
How can I start a new process in C?... |
Check theexampleon Wikipedia; basically, after you fork you have to check the pid to understand if you are in the parent or child process.
```
if (pid == 0) { // child process
call_child_function();
} else { //parent process
call_parent_function();
}
```
|
Is it possible to create (or open existing) C program files in Netbeans without creating an entire project? Can these be later run and compiled?
|
You can use Netbeans as fancy oversized editor for C files, but if you want to build program from Netbeans, you will need a project.
|
```
void main()
{
char s[]="\12345s\n";
printf("%d",sizeof(s));
}
```
When i compile it it giving 6. I am not geting why it is giving 6 insted of 8.
Like{'\1','2','3','4','5','s','\n'}
Please can anybody tell the reason for this, I want some deep and clear explanation. I will be thankful to them.
|
Because\123is considered one character, it's an escape sequence (octal). Sosizeofcalculates 5 characters'\123','4','5','s','\n', and the ending'\0'.
|
From K&R C
A.6.5 Arithmetic ConversionsMany operators cause conversions and yield result types in a similar way. The effect is to bring
operands into a common type, which is also the type of the result. This pattern is called the
usual arithmetic conversions.
In the code below EOF is defined to be -1 which is a sign... |
getcreturns anint(as it must be able to hold all character values as well asEOF).
In your code, you truncate this value tounsigned charwhen you assign it toch. Then you extend it toint, which will never result inEOF, as -1 truncated becomes 255, which will become theint255.
|
Any sample on makingEntryElementalign to the right?
I can't figure out how to inherit/override theEntryElement.
Thanks,
Mojo
|
This looks near identicalMonoTouch.Dialog: Setting Entry Alignment for EntryElement
See my ownanswerabout overridingCreateTextField.
|
I know that in C, arrays are not supposed to be dynamically sized.
With that in mind, would the following code be allowed? (Trying to declare an array of chars the same length as a double.)
```
char bytes[sizeof(double)];
```
My guess is thatsizeofoperates on its argument during program execution and so this wouldn... |
The sizeof expression is evaluated at compile time (by the compiler not the preprocessor) so the expression is legal.
There's an exception to this rule in C99 where dynamic arrays are allowed. In that case sizeof is, depending on context, evaluated at runtime (http://en.wikipedia.org/wiki/Sizeof). It doesn't change t... |
Following is my code saved as .cpp file and .c file
in .c it compiled fine, but threw the following error in .cpp
```
test.cpp:6: error: initializer-string for array of chars is too long
test.cpp:6: error: initializer-string for array of chars is too long
```
```
#include< stdio.h>
int main()
{
char str[2][2]= ... |
The character string "12" hold 3 places in C++ (In C too, BTW). You need one more char for the terminating'\0'.
```
char str[2][3]= { "12", "12"};
```
|
I have a requirement, part of which needs conversion from decimal to hex.
I prefer the following way to do that thing as below:
```
sprintf(mcc,"%x",n);
```
nhere will be an integer.
But my peer says it is not a good way to do that.
Instead he says to manually convert the decimal using a function,
but I did not ge... |
As long as you make sure that the buffer pointed to bymccis big enough for the resulting string, I see no problem.
|
I have 4 different application running.so every application can send data to server. now i want to send data to paticular socket (server and client are done through socket programming)
from server side.
|
When you create a socket, first you establish a connection between a server and a client (usingconnectsystem call on the client side, andbind,listen, andacceptsystem calls on the server side). You can have many such connections, from a server to different clients. The server can send data on any of these established c... |
I have successfuly intercepted calls toread(),write(),open(),unlink(),rename(),creat()but somehow with exactly the same semantics interceptingstat()is not taking place. I have changed the execution environmnet using LD_PRELOAD.
Am I missing something?
The code is quite huge, which part of it will be most helpful to ... |
Compile a function that callsstat(); see what reference(s) are generated (nm -g stat.o). Then you'll have a better idea of which function(s) to interpose. Hint: it probably isn't calledstat().
|
```
uint8_t a = 0x1234;
```
Willa == 34? Is this because0x34is the first byte?
If so, how do I perform checks to ensure that the value I assign toadoes not exceed the size ofuint8_t?
|
jslagle@AR-E642-45QS3R1:~ $ cat test.c
```
#include <stdio.h>
#include <inttypes.h>
int main (int argc, char **argv) {
uint8_t a = 0x1234;
printf("%d %x\n",a,a);
return 0;
}
```
```
jslagle@AR-E642-45QS3R1:~ $ gcc -o test test.c
test.c: In function ‘main’:
test.c:5:3: warning: large integer implicitly trun... |
Is there any way to emulate the list data structure in C? (What I really need is a doubly-linked list.)
More simply put, is there a good way to solve the Least Recently Used memory management technique?
My train of thought at the current time has me needing access to both the head and tail of the list (for obtaining... |
An oft-cited list implementation in C comes from the Linux kernel:list.h
It does a lot of things right, in the context of the C language.
|
I'm attempting to run an event loop from within a pthread but I've run into a problem I can't seem to google-fix. Basically, it looks like this:
```
event_thread = pthread_create(&event_thread, NULL,
(void *) g_main_loop_run, (void *) event_loop);
printf("GOT HERE\n");
```
The message below pthread_create never ... |
Well, figured that one out as soon as I posted this, here's what I ended up doing:
```
pthread_attr_t attr;
...
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
event_thread = pthread_create(&event_thread, &thread_attr,
(void *) g_main_loop_run, (void *) event_... |
I came across this line:
```
void (*(*x)(void (*[10])(int *)))(int *)
```
Can anybody tell me what it is?
|
To break this down yourself, start from the inner most parentheses and work your way out.
(*[10])<---- Array of 10 pointers(*[10])(int *)<------ Array of 10 pointers to functions which has a pointer tointas its argument(void (*[10])(int *))<------ Array of 10 pointers to functions which has a pointer tointas its argu... |
Does it make sense to both write and read on a socket (SOCK_STREAM) in parallel with multiple threads? On Linux. Do those syscalls block each other?
|
Yes, it makes sense. Since they are in separate threads they do not block each other.
|
I want to simulate a FAM event. The API doesn't seem to support this.
Why? Because I have a thread waiting on a FAMNextEvent() and I want to wake it up from another thread.
I guess I could touch one of the files being monitored but that seems very crude.
|
Instead of usingFAMNextEventdirectly, how about usingselectorpollon
FAMCONNECTION_GETFD(FAMConnection)When it triggers, checkFAMPendingbefore callingFAMNextEvent.aself-pipe
The thread will wait for either a FAM eventora byte written to the self-pipe.
|
How big is (approximately) an I/O syscall overhead on Linux fromCprogram, I mean how bad is running e.g. many smallread / writeoperations compared withread / writeon large buffers (on regular files or network sockets)? App is strongly multithreaded.
|
Syscalls take at least 1-2 microseconds on most modern machinesjust for the syscall overhead, and much more time if they're doing anything complex that could block or sleep. Expect at least 20 microseconds and up to the order of milliseconds for IO. Compare this with a tiny function call or macro that reads a byte fro... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
I'm reading a file from C code. It looks the whitespace character is two bytes long. Is it so?
The content... |
My understanding is that a space character can be 2 bytes if its Unicode(0x0020).
However, most text in still in ASCII or something that is backwards compatible with ASCII, which would make whitespace a single character on Linux machines. On Windows, you could get a\r\ncombination as Jim Clay mentioned.
|
I'm making a program in C and this is my code:
```
int main(int argc, char **argv) {
int n;
char aux[10];
sscanf(argv[1], "%[^-]", aux);
n = atoi(aux);
}
```
So, if I run the program from command line: my_program -23, I want to get the number "23" to isolate it in a var like an integer, but this don'... |
Yoursscanfcall is trying to read anything up to (but not including) the first-in the string. Since the-is (presumably) the first character, itauxends up empty.
You could do something like:sscanf(argv[1], "%*[-]%d", &n);. This will skip across any leading-characters, so arguments of23,-23and--23will all be treated ide... |
I'm having trouble understanding what this line of code does:
```
sprintf(obj, "%s.o", root);
```
obj and root are both character buffers, from what I read root is basically copied to obj?
I'm not sure what "%s.o" is doing. %s is to specify a String but the .o?
thanks for any help
|
The%swill be replaced with the contents ofroot, and followed by the.opart of the string, which is just an "additional" text. For example, ifroothas "file",objwill be set to "file.o".
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
How can I start a new process in C?... |
Check theexampleon Wikipedia; basically, after you fork you have to check the pid to understand if you are in the parent or child process.
```
if (pid == 0) { // child process
call_child_function();
} else { //parent process
call_parent_function();
}
```
|
Is it possible to create (or open existing) C program files in Netbeans without creating an entire project? Can these be later run and compiled?
|
You can use Netbeans as fancy oversized editor for C files, but if you want to build program from Netbeans, you will need a project.
|
```
void main()
{
char s[]="\12345s\n";
printf("%d",sizeof(s));
}
```
When i compile it it giving 6. I am not geting why it is giving 6 insted of 8.
Like{'\1','2','3','4','5','s','\n'}
Please can anybody tell the reason for this, I want some deep and clear explanation. I will be thankful to them.
|
Because\123is considered one character, it's an escape sequence (octal). Sosizeofcalculates 5 characters'\123','4','5','s','\n', and the ending'\0'.
|
From K&R C
A.6.5 Arithmetic ConversionsMany operators cause conversions and yield result types in a similar way. The effect is to bring
operands into a common type, which is also the type of the result. This pattern is called the
usual arithmetic conversions.
In the code below EOF is defined to be -1 which is a sign... |
getcreturns anint(as it must be able to hold all character values as well asEOF).
In your code, you truncate this value tounsigned charwhen you assign it toch. Then you extend it toint, which will never result inEOF, as -1 truncated becomes 255, which will become theint255.
|
I need some help at RPC Programming. I really want understand how works the RPCGEN and the MAKEFILE structure. I would like a recommendation of a good introductory book at RPC. I found some examples but I dont know how to compile/integrate the files. More specifically i have a Client source code (one file), a Server s... |
Here are a few resources you might find helpful.
Tutorial of RPC programmingHow RPC works -pdf link
|
The code below compiles well
```
int a=5,b=4,c;
a>b?30:40;
```
Also does,
```
int a=5,b=4,c;
a>b?c=30:40;
```
But why this does not work?
```
int a=5,b=4,c;
a>b?c=30:c=40;
```
|
You are being bitten by precedence.?:has very low precedence, but not as low as=or,(see theoperator precedence table).
Your code is parsed as:
```
(a>b ? c=30 : c) = 40;
```
Rather than:
```
a>b ? c=30 : (c=40);
```
You don't need parenthesis aroundc=30because?and:act like parentheses to the expression within.
... |
How can I, in C, output a value from a syscall to the Linux console so that it will be visible after admesg? What method do I use for printing?
|
You're looking for theprintk()function; some documentation on the types that it supports is found inDocumentation/printk-formats.txt. It is defined inkernel/printk.c.
|
```
class app {
public int x = 3;
static void Main(string[] args)
{
}
}
```
it's possible get the memory address allocated byxvariable?
the example can be inC,C++,C#orD.
I hope it is clear
Thanks in advance
|
The ampersand (&) is the "address-of" operator in most C-like languages:
```
int x;
printf("Address of x is %p\n", &x);
```
The return value of&is effectively apointerto its operand.
|
I can pass struct into pthread_create as thread argument.
But is it possible to modify this struct within the thread so that when the thread terminates, the main program can access this struct to obtain modified data?
If so, do I need to cast the struct back to void in the thread?
|
Yes - assuming the thread function is passed the structure by pointer, you can modify the structure it points at.
No - there is no need to cast the struct back to void in the thread; indeed, I'm not quite sure what you're thinking of, but there's no need for it. The thread function gets avoid *argument. It will cas... |
I'm using Netbeans to write a C program. Where do I need to paste my input.txt file for the program to read it if I don't want to specify a directory in the program?
|
In the currentworking directorywhere the program executes. You'll have to see where exactly Netbeans causes the binary to be output, but most likely, you will want your input.txt file to be in that same directory. Possibly abinsubdirectory of wherever your source is.
|
```
const char* returnStr()
{
char time[40] = {"France"};
char* time1;
time1 = time;
return time1;
}
int main(int argc, char* argv[]) {
printf ("return String is %s\n",returnStr());
}
```
This code returns some junk characters. Won't theconst char*not enough to return the local char pointer?... |
Do I have to use the static too in the function?
Yes. Theconstis just a qualifier on the return value, signaling to callers ofreturnStrthat they shouldn't modify the result of the function. It doesn't changetime's temporary character.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.