question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
In C, you can usestrdupto succinctly allocate a buffer and copy a string into it. As far as I'm aware, however, there is no similar function for general memory. For example, I can't say
```
struct myStruct *foo = malloc(sizeof(struct myStruct));
fill_myStruct(foo);
struct myStruct *bar = memdup(foo, sizeof(struct ... |
You can implement it whith a simple function:
```
void* memdup(const void* mem, size_t size) {
void* out = malloc(size);
if(out != NULL)
memcpy(out, mem, size);
return out;
}
```
|
If I use a whole number in#define, whatdata typeis it considered to be insprintf()inC99?
```
#define NUMBER 100
sprintf(buf, "%i\n", NUMBER); // is it %i, %u, %lu ?
```
|
```
#define NUMBER1 100 /* int: use "%d" or "%i" in printf() */
#define NUMBER2 100U /* unsigned int: use "%u" in printf() */
#define NUMBER3 100L /* long int: use "%ld" or "%li" in printf() */
#define NUMBER4 100UL /* unsigned long int: use "%lu" in printf() */
/* C99 */
#define NUMBER5 100LL /* long long int: use "%... |
How can I know the seconds and microseconds between 1 January 1970 00:00:00 and now using timeval? Thanks.
```
struct timeval {
long tv_sec; /*seconds since 1/1/1970*/
long tv_usec; /*microseconds since tv_sec*/
};
```
|
you callgettimeofday()
```
struct timeval tv;
gettimeofday(&tv, NULL);
tv.tv_sec /* seconds */
tv.tv_usec /* microseconds */
```
Howevergettimeofday()is obsolete, the manual is recommendingclock_gettime(2)instead:
```
struct timespec tp;
clock_gettime(CLOCK_REALTIME, &tp);
tp.tv_sec /* seconds */
tp.tv_usec /* na... |
when running my code in borland c 3.1 it works fine, but when running it on c-free it crashes at this line:while(ptr1->pright)
{
ptr1=ptr1->pright;
}giving SIGSEGV, any logical reasons?
|
You're probably accessing memory outside the bounds of an array or which you didn't allocate. As such, you triggeredundefined behaviour, so pretty much anything can happen, including crashing or evenapparentlyworking fine.
|
Can you give an example of use oftm(I don't know how to initialize thatstruct) where the current date is written in this formaty/m/d?
|
How to usetmstructure
calltime()to get current date/time as number of seconds since 1 Jan 1970.calllocaltime()to getstruct tmpointer. If you want GMT them callgmtime()instead oflocaltime().Usesprintf()orstrftime()to convert the struct tm to a string in any format you want.
Example
```
#include <stdio.h>
#include <t... |
As it is time to study for finals, I have to cover some detailed information regarding loops.I am currently stuck on this question
```
int main(void) {
int x = 0;
int y = 0;
while (y < 10) {
x = 0;
while (x != y) {//
x = x + 3; // how many times will we do this statement?
}
printf(“x... |
This line causes a problem
```
x = 0;
while (x != y) {//
x = x + 3; // how many times will we do this statement?
}
```
wheny=1sincexwill continue to increase until it reaches the maximum integer value (it cant equal y unless some overflow wrapping occurs - this will result in an infinite loop).
|
hi I m trying to convert myjavacode toccode for better speed ,
and I want to generate a random number inc codeusingjni(android)
in java code,
```
public int getRandomNumberFor()
{
Random random ;
random = new Random();
return random.nextInt(0xFF);
}
```
I don't know what code work ... |
Change your code as using C Programming in NDK :
```
#include <stdio.h>
#include <stdlib.h>
JNIEXPORT jint JNICALL Java_com_imrantestndk_androiddemo_NativeLib_Randomnum
(JNIEnv * env, jobject this){
int n;
n = rand()%100 + 1;
return n;
}
```
Or
```
#include <stdio.h>
#include <stdlib.h>
#include <t... |
when running my code in borland c 3.1 it works fine, but when running it on c-free it crashes at this line:while(ptr1->pright)
{
ptr1=ptr1->pright;
}giving SIGSEGV, any logical reasons?
|
You're probably accessing memory outside the bounds of an array or which you didn't allocate. As such, you triggeredundefined behaviour, so pretty much anything can happen, including crashing or evenapparentlyworking fine.
|
Can you give an example of use oftm(I don't know how to initialize thatstruct) where the current date is written in this formaty/m/d?
|
How to usetmstructure
calltime()to get current date/time as number of seconds since 1 Jan 1970.calllocaltime()to getstruct tmpointer. If you want GMT them callgmtime()instead oflocaltime().Usesprintf()orstrftime()to convert the struct tm to a string in any format you want.
Example
```
#include <stdio.h>
#include <t... |
As it is time to study for finals, I have to cover some detailed information regarding loops.I am currently stuck on this question
```
int main(void) {
int x = 0;
int y = 0;
while (y < 10) {
x = 0;
while (x != y) {//
x = x + 3; // how many times will we do this statement?
}
printf(“x... |
This line causes a problem
```
x = 0;
while (x != y) {//
x = x + 3; // how many times will we do this statement?
}
```
wheny=1sincexwill continue to increase until it reaches the maximum integer value (it cant equal y unless some overflow wrapping occurs - this will result in an infinite loop).
|
hi I m trying to convert myjavacode toccode for better speed ,
and I want to generate a random number inc codeusingjni(android)
in java code,
```
public int getRandomNumberFor()
{
Random random ;
random = new Random();
return random.nextInt(0xFF);
}
```
I don't know what code work ... |
Change your code as using C Programming in NDK :
```
#include <stdio.h>
#include <stdlib.h>
JNIEXPORT jint JNICALL Java_com_imrantestndk_androiddemo_NativeLib_Randomnum
(JNIEnv * env, jobject this){
int n;
n = rand()%100 + 1;
return n;
}
```
Or
```
#include <stdio.h>
#include <stdlib.h>
#include <t... |
How would I make a pointer to:
```
char * values [x];
```
I'm trying to pass an array ofchar *to a pointer from outside the block of code, where x can by anything.
|
Pointer to a pointer can do what you want.
```
char ** val ;
```
In the function definition :
```
return_type func(char ** val) {...}
```
In the function call :
```
func(&values)
```
You need to pass the address of the pointer to the function.
|
Is there any difference between theCvCapturestructure and theVideoCapturestructure in OpenCV? If so, when should I useCvCaptureand when to useVideoCapture?
|
VideoCaptureis from the new C++ interface,CvCaptureno longer has a public interface for use.
When using the C++ API,VideoCaptureshould be used. You should avoid mixing the two interfaces.
If you are using the C API, rather than the C++ API, several methods return aCvCapturepointer, such ascvCaptureFromFile.
|
The functioncvCaptureFromAVIallocates and initializes aCvCapturestructure in order to read a video stream from the specified file. The functioncvCaptureFromCAMworks in a similar way, but the source of the video is a webcam. Once theCvCapturestructure has been allocated and initialized properly, the reading of each fra... |
Since you mentioned OpenCV'sCAPI, the magic is done bycvCreateVideoWriter().
Here's a demousing Python.
|
I have been asked to write a function that returns the first non-whitespace character in an inputted string.
It's working when I enter something like "hello" or anything that does not begin with a white space. But when I enter something like " hello", it returns a white space.
Here is my code:
```
int question6... |
```
ch = getchar();
while (ch == 32)
{
ch = getchar();
}
return ch;
```
|
I have some code like this:
```
static int a = 6;
static int b = 3;
static int Hello[a][b] =
{
{ 1,2,3},
{ 1,2,3},
{ 1,2,3},
{ 1,2,3},
{ 1,2,3},
{ 1,2,3}
};
```
But when I compile it, it says error:
variably modified 'Hello' at file scope
How could this happen? And how could I fix it?
|
You can not have a static array whose size is given as a variable.
That's why constants should be#defined:
```
#define a 6
```
This way, the preprocessor will replaceawith6, making it a valid declaration.
|
I have already compilelamefor android as static library.
How can I use lame for convert awavfile tomp3?
What I have to call? There is some tutorial of how use lame as library?
|
You can see thisdeveloper.samsung.comtutorial for porting or how we use LAME on Android with JNI
Porting and using LAME MP3 on Android with JNI
|
can anyone tell me the correct query to delete values from mysql db table,in my case the table name and id are accepted from the user and the row is deleted based on id.This is my query
```
sprintf(Query,"DELETE FROM ('%s') where id = (%d)",tb1,idt1) ;
/*table name is in form of string and id is int */
mysql_quer... |
You should remove parentheses around the table name:
```
sprintf(Query,"DELETE FROM '%s' where id = (%d)",tb1,idt1) ;
```
MySQL considers queries like this syntax errors:
```
delete from (mytable) where id=2;
```
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version f... |
i have the following method contents:
```
FILE *file;
file = fopen("customers.dat", "w");
PList *list;
list = &customers;
fprintf(file, "%s", *(list->person.name));
```
error given on the fprintf line::
```
format '%s' expects argument of type 'char *', but argument 3 has type 'int' [-Wformat]
```
I have the follo... |
Drop the*:
```
fprintf(file, "%s", *(list->person.name));
^
```
|
Would I be correct to say that the underlying object representation (bit pattern) in each of the following definitions is the same?
```
char c = 240;
unsigned char c = 240;
signed char c = 240;
```
So, thesigned-ness matters only whencis used in an expression (or casts)?
|
In general case it is not correct to say that the pattern is the same, if the range ofsigned chardoes not cover240. If240is out of range, the result of this overflowing initialization is implementation-defined (and may result in a signal, see 6.3.1.3/3). The same applies tocharinitialization if it is signed.
The lan... |
I have code similar to the following:
```
void generateInt(int *result)
{
/* chosen by fair dice roll*/
*result = 1;
}
typedef enum colour
{
RED,
GREEN,
BLUE
} COLOUR;
int main(int, char**)
{
COLOUR col, col2;
int i;
generateInt(&i);
col = (COLOUR)i;
generateInt((int*)(&col2));
return 0;
}
... |
That's certainlynotOK. You have no reason to believe that the underlying type of the enum isint, and thus casting the pointers may be wildly inappropriate.
Why not just change the function?
```
void generateInt(COLOUR * c)
{
*c = GREEN;
}
```
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
```
#include<stdio.h>
void call(int,int,int);
int main(){
int a=10;
call(a,a++,++a);
return 0;
}
void call(int x,int y,int z){
printf("x=%d y=%d z=%d\n",x... |
The behaviour of your code isundefinedsince you're changingatwice betweensequence points:
```
call(a,a++,++a);
```
|
Is the compound operator '&=' logical or bitwise AND ?
In other words, isa &= bthe same as:
a = a & ba = a && b
|
a &= bis using the bitwise AND operator. Think of the+=operation:
```
a += 5;
```
is the same as:
```
a = a + 5;
```
It's just a combination of two operations:&and=.
|
Is it at all possible in c/c++ to do something like to following:
```
#define (_asm int 3;) (exit(1))
```
So that everywhere in my code this line will be replaced at compile time.
I know this is bad practice but is it possible.
cheers
|
You could do a global search and replace with your programming editor (or IDE) of choice and change_asm int 3to e.g.FOO, and then define a macroFOOlike this:
```
#if 1 // <<<- change this test to determine how `FOO` is expanded
#define FOO _asm int 3
#else
#define FOO exit(1)
#endif
```
|
I'm working on the so called Hotspot open source project, and looking at the implementation I found a nasty nested union in struct looking like that:
```
typedef struct RC_model_t_st
{
union
{
struct block_model_t_st *block;
struct grid_model_t_st *grid;
};
/* block model or grid model... |
This is ananonymous union.In C++, as per [class.union], paragraph 5:
For the purpose of name lookup, after the anonymous union definition,
the members of the anonymous union are considered to have been defined
in the scope in which the anonymous union is declared
This means you can access its members as if they ... |
Are there any c compilers for ms-dos that support some C99 features?
I have trouble searching for recent compilers that I can run on my system.
Actually, I need this to have a compiler on my Playbook via Dos Box, while I am away from home and wihout internet access.
|
This compiler should work on MSDOS (gcc adapation)
http://personal.ee.surrey.ac.uk/Personal/R.Bowden/C/dos-gcc/index.htm
|
I want to use mmseg in Go as in other languages, for example, in python you can use pymmseg
So, is there is a similar Go package?
Or, how can I call the C functions from Go?
Or, how can I call shared library (*.so) from Go like in python?
|
you can call use C Libs as described in this tutorial:
http://cheesesun.blogspot.de/2009/12/basic-cgo.html
and:
http://siganakis.com/linking-c-libraries-with-go-lang-and-stdc99
or you may have a look at this library:
https://github.com/awsong/MMSEGO
its for chinese, but you may could use it to put your own algor... |
I am trying to break out of a loop when the user inputs the word "exit". If the user inputs anything aside from the word exit, I would like the program to skip a line and write a single "$". It works but is acting a little funny. Here's the code and the output:
```
int main()
{
char input[5];
int x = 5;
w... |
Because you're only reading 4 characters per loop.
|
Inside a function, one can put (for gcc)
```
printf("%s: I am here!", __FUNCTION__);
```
to indicate where a particular message comes from. Now, suppose I have serval functions A1, A2, A3,..., which all might call function B(). I am wondering if there is a neat way to indicate which function calls B() at run-time.
|
You could simply usebacktrace()(which is not completely portable either)
See this link:http://www.kernel.org/doc/man-pages/online/pages/man3/backtrace.3.html
|
I've known thatconstqualifier only affects an object but not it's type:
For example:
```
// Only the elements of an array are constant not the array itself
const int a[5];
```
Suppose if I had:
```
float *const p1; // 1
float const *p2; // 2
```
In the first case above, does it mean that pointertypeis constant an... |
```
float *const p1; // 1
```
Means that the pointerp1is constant and it cannot(rather should not) point to another address.It is not the pointertypethat is constant but the instance of this type which isp1that is contant.
Use theClockwise spiral ruleto understand this better.
How can this be when the types aren't ... |
If i compile the below program with std=c99, i get an error, but the program compiles fine without the c99 flag. Why?
```
#include <signal.h>
void x()
{
sigset_t dd;
}
int main(void)
{
x();
return 0;
}
jim@cola temp]$ gcc -std=c99 blah.c -o blah
blah.c: In function ‘x’:
blah.c:9: error: ‘sigset_t’ unde... |
Becausesigset_tis not part of<signal.h>in standard C and you requested strict standards compatibility with-std=c99. That is, a strictly standard C program can do:
```
#include <signal.h>
int sigset_t;
int main(void) { return 0; }
```
and expect it to work.
|
I've defined the following, of course it's not correct...
```
#define SET_PIN_MODE_INPUT(DREG, PORT, PIN) (DREG &= ~_BV(PIN), PORT &= ~_BV(PIN))
#define LED_CLOCK_PIN (DDRB, PORTB, PB3)
```
and I want to use them like this:
```
SET_PIN_MODE_INPUT(LED_CLOCK_PIN)
```
So I need help withCsyntax.
|
Indirection is required:
```
#define SET_PIN_MODE_INPUT_(DREG, PORT, PIN) (DREG &= ~_BV(PIN), PORT &= ~_BV(PIN))
#define SET_PIN_MODE_INPUT(ARGS) SET_PIN_MODE_INPUT_ ARGS
// Note that this is an object-like macro
#define LED_CLOCK_PIN /**/ (DDRB, PORTB, PB3)
```
With your current macros, you are passing a single ar... |
Win32 has the winmm library, which allows joystick events to be captured in the regular event loop (alongside the general window events, keyboard events, and mouse events).
Is there a similar setup in Xlib? Is my only choice to do raw input?
|
Sounds like the answer is no (until someone smarter than me comes along and corrects me). I need to do raw input. I have to poll at a reasonable interval and convert deltas into my own events.
|
```
static void RadioReleaseSPI(void) {
__disable_interrupt();
spiTxRxByteCount &= ~0x0100;
__enable_interrupt();
}
```
I understand that multiple tasks may attempt to use the SPI resource.spiTxRxByteCountis a global variable used to keep track of whether the SPI is currently in use by another task. When ... |
The &= will do a read-modify-write operation - it's not atomic. You don't want an interrupt changing things in the middle of that, resulting in the write over-writing with an incorrect value.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
These are just parameter names. They both refer to file descriptor.
Read manual for those functions
```
man 2 write
man pwrite
```
|
I am trying to break out of a loop when the user inputs the word "exit". If the user inputs anything aside from the word exit, I would like the program to skip a line and write a single "$". It works but is acting a little funny. Here's the code and the output:
```
int main()
{
char input[5];
int x = 5;
w... |
Because you're only reading 4 characters per loop.
|
Inside a function, one can put (for gcc)
```
printf("%s: I am here!", __FUNCTION__);
```
to indicate where a particular message comes from. Now, suppose I have serval functions A1, A2, A3,..., which all might call function B(). I am wondering if there is a neat way to indicate which function calls B() at run-time.
|
You could simply usebacktrace()(which is not completely portable either)
See this link:http://www.kernel.org/doc/man-pages/online/pages/man3/backtrace.3.html
|
I've known thatconstqualifier only affects an object but not it's type:
For example:
```
// Only the elements of an array are constant not the array itself
const int a[5];
```
Suppose if I had:
```
float *const p1; // 1
float const *p2; // 2
```
In the first case above, does it mean that pointertypeis constant an... |
```
float *const p1; // 1
```
Means that the pointerp1is constant and it cannot(rather should not) point to another address.It is not the pointertypethat is constant but the instance of this type which isp1that is contant.
Use theClockwise spiral ruleto understand this better.
How can this be when the types aren't ... |
If i compile the below program with std=c99, i get an error, but the program compiles fine without the c99 flag. Why?
```
#include <signal.h>
void x()
{
sigset_t dd;
}
int main(void)
{
x();
return 0;
}
jim@cola temp]$ gcc -std=c99 blah.c -o blah
blah.c: In function ‘x’:
blah.c:9: error: ‘sigset_t’ unde... |
Becausesigset_tis not part of<signal.h>in standard C and you requested strict standards compatibility with-std=c99. That is, a strictly standard C program can do:
```
#include <signal.h>
int sigset_t;
int main(void) { return 0; }
```
and expect it to work.
|
I've defined the following, of course it's not correct...
```
#define SET_PIN_MODE_INPUT(DREG, PORT, PIN) (DREG &= ~_BV(PIN), PORT &= ~_BV(PIN))
#define LED_CLOCK_PIN (DDRB, PORTB, PB3)
```
and I want to use them like this:
```
SET_PIN_MODE_INPUT(LED_CLOCK_PIN)
```
So I need help withCsyntax.
|
Indirection is required:
```
#define SET_PIN_MODE_INPUT_(DREG, PORT, PIN) (DREG &= ~_BV(PIN), PORT &= ~_BV(PIN))
#define SET_PIN_MODE_INPUT(ARGS) SET_PIN_MODE_INPUT_ ARGS
// Note that this is an object-like macro
#define LED_CLOCK_PIN /**/ (DDRB, PORTB, PB3)
```
With your current macros, you are passing a single ar... |
Win32 has the winmm library, which allows joystick events to be captured in the regular event loop (alongside the general window events, keyboard events, and mouse events).
Is there a similar setup in Xlib? Is my only choice to do raw input?
|
Sounds like the answer is no (until someone smarter than me comes along and corrects me). I need to do raw input. I have to poll at a reasonable interval and convert deltas into my own events.
|
```
static void RadioReleaseSPI(void) {
__disable_interrupt();
spiTxRxByteCount &= ~0x0100;
__enable_interrupt();
}
```
I understand that multiple tasks may attempt to use the SPI resource.spiTxRxByteCountis a global variable used to keep track of whether the SPI is currently in use by another task. When ... |
The &= will do a read-modify-write operation - it's not atomic. You don't want an interrupt changing things in the middle of that, resulting in the write over-writing with an incorrect value.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
These are just parameter names. They both refer to file descriptor.
Read manual for those functions
```
man 2 write
man pwrite
```
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Why #include <stdio.h> is *not* required to use printf()?
I am facing a problem in the below given code.
```
int main()
{
printf("\nHello Stack Overflow\n\n") ;
return 0 ;
}
```
In the above mentioned code i left including "#include ".
A... |
In C, functions that are not declared are implicitly considered to return anintand to takeintarguments.
This isbad practiceand will bite you. For example if you want to print data not the same size of an int, likedoubleorfloat.
|
I have this little code to demonstrate it:
```
#include "stdio.h"
int main() {
int a = testfunc(); // declared later
printf("%d", a);
return 0;
}
int testfunc() {
return 1;
}
```
It compiles with no error, and a outputs1as expected.
See in action:http://ideone.com/WRF94E
Why there is no error? I... |
The function testfunc() is implicitly declared. The compiler cannot do any signature checks so you might get a runtime error in case you fail to invoke it corectly.
This is part of the C specification. But the recommendation in the C specification is to declare all the functions you plan to implement and use, at the ... |
We need to integrate some C file functions from java android code. Each c function accepts some raw binary data (byte stream) as input parameter, processes and returns pointer to c struct (union struct) that is defined in c file. Is it possible to create some java structure and bind it to c struct? Currently, extracti... |
I'm not sure of the specifics, but I think theJava Native Interfaceis your best bet.
|
I installed GNAT 2012 a while back when I was working with Ada and it came with a version of GCC. I can compile C files from the command prompt using gcc fine, but "make" apparently wasn't included.
How would I go about getting make working? Should I just install the newest version of GCC instead?
|
Make is not part of GCC. On Windows, you can useMSYS. It includes make and other useful tools.
|
```
c99 standard 5.2.1.1 Trigraph sequences
```
2 EXAMPLE The following source line
```
printf("Eh???/n");
```
becomes (after replacement of the trigraph sequence ??/)
```
printf("Eh?\n");
```
It's saying that it will replace the trigraph sequence, but it's not .
It's printing"Eh???/n"
Am I missing something ?... |
Trigraphs are disabled by default in gcc. If you are using gcc then compile with-trigraphsto enable trigraphs:
```
gcc -trigraphs source.c
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
Here are couple of articles you can use:http://courses.engr.illinois.edu/ece390/books/labmanual/c-prog-mixing.html
http://lavernasbrute.blogspot.com/2010/02/calling-assembly-functions-in-c.html
just google 'assembly functions in C'.
|
I am facing an issue with running gcov on shared library from python script.
I have the following scenario where i build my library:
Compile a set of files (file1.c, file2.c) into a statically linked lib(.a). I use ar utility to do this and all the files are compiled using following options:-static -fprofile-arcs -f... |
Found out the issue.
I was not picking up all the .gcda files for generating the report.
Use -object-directory option to search for all gcda files.
GCOV man page
|
This C program I am making reads a set of chars from the command line and stores them using an array (argv[]) like so
```
main (int argc, char *argv[]) {
int temp;
/*prevents no arguments*/
if (argc==1){
printf("Usage;\t[0 < integers < 9] [operators]\n");
exit(0);
}
int i;
for (i = 0 ; i<argc; i++){
... |
argv[i] - is just a pointer to C string; you need first element:
```
temp = argv[i][0] - '0';
```
|
How do I run a C programming language from Xcode on terminal? Please help me with this by answering a step by step procedure in doing this. Thanks.
Version 10.7.5 on a Macbook Air.
|
Write xcode output to file and runtail -fin terminal.
```
int main(int argc, char *argv[])
{
NSAutoreleasePool *nsp = [[NSAutoreleasePool alloc] init];
NSString *logPath =[NSString stringWithFormat:@"%@/xcode.log",NSHomeDirectory()];
freopen([logPath fileSystemRepresentation], "a", stderr);
[nsp relea... |
I am working on an assignment where I am implementing the unix history command in a shell. In my program I have written a signal handler for SIGINT. When a user enters (ctrl)(c) their history is displayed.
When my program terminates I need to store the history in a file. Is there an easy way to detect when my prog... |
atexit()is probably what you're looking for, see the manual page:man 3 atexit
Usage is something like:
```
#include <stdlib.h>
static void save_the_file(void)
{
/* ... */
}
int main()
{
atexit(save_the_file);
return 0;
}
```
Another option is to use thedestructorattribute (GCC/Clang):
```
static __at... |
In C language,
I have an array[3][2];
```
int i = 0, j = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d", array[i][j]);
}
}
```
When I use gcc to compile .c file, the error shows:
```
format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’
```
How to print an... |
The error message seems pretty straight forward. It's telling you thatarray[i][j]is of typeint*, while theprintf()"%d" formatter is expecting an argument of typeint.
I'm not sure what you expect to happen here. You haven't shown us how you declarearray. But, if it's supposed to be a two-dimensional array ofint, then ... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
There was a very nice question on Stack overflow.
For i = 0, why is (i += i++) equal to 0?
But when I tried out the same code in C, it gave different results:... |
The C standard does not specify an order of evaluation. It is left to the compiler implementation.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
i tried this simple C program in GCC
```
#include<stdio.h>
int main(){
int x=5;
printf("%d,%d,%d,%d,%d",++x,x++,x,x++,++x);
return 0;
}
```
and the output was... |
Because your program hasundefined behaviour. There is no sequence point between the evaluations of function arguments, and it is undefined behaviour to mutate the same object more than once without intervening sequence point.
The program is simply ill-formed. It is not a valid C program.
|
According to amanpages the following approaches supports only advisory locking:flock,lockfandfcntl. Is there any way to mandatory lock a some file by a single process, for example with a write lock, so that other process will not able to open this file with the write permissions?
|
No. Operating systems in the Unix family do not generally support mandatory file locking1. This includes Linux, BSD, and OS X.
On some Unixes, you are prevented from opening files for writing if they are executable images that are currently running;open()will fail withETXTBSY. However, you can always just unlink (... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Why #include <stdio.h> is *not* required to use printf()?
I am facing a problem in the below given code.
```
int main()
{
printf("\nHello Stack Overflow\n\n") ;
return 0 ;
}
```
In the above mentioned code i left including "#include ".
A... |
In C, functions that are not declared are implicitly considered to return anintand to takeintarguments.
This isbad practiceand will bite you. For example if you want to print data not the same size of an int, likedoubleorfloat.
|
I have this little code to demonstrate it:
```
#include "stdio.h"
int main() {
int a = testfunc(); // declared later
printf("%d", a);
return 0;
}
int testfunc() {
return 1;
}
```
It compiles with no error, and a outputs1as expected.
See in action:http://ideone.com/WRF94E
Why there is no error? I... |
The function testfunc() is implicitly declared. The compiler cannot do any signature checks so you might get a runtime error in case you fail to invoke it corectly.
This is part of the C specification. But the recommendation in the C specification is to declare all the functions you plan to implement and use, at the ... |
We need to integrate some C file functions from java android code. Each c function accepts some raw binary data (byte stream) as input parameter, processes and returns pointer to c struct (union struct) that is defined in c file. Is it possible to create some java structure and bind it to c struct? Currently, extracti... |
I'm not sure of the specifics, but I think theJava Native Interfaceis your best bet.
|
I installed GNAT 2012 a while back when I was working with Ada and it came with a version of GCC. I can compile C files from the command prompt using gcc fine, but "make" apparently wasn't included.
How would I go about getting make working? Should I just install the newest version of GCC instead?
|
Make is not part of GCC. On Windows, you can useMSYS. It includes make and other useful tools.
|
```
c99 standard 5.2.1.1 Trigraph sequences
```
2 EXAMPLE The following source line
```
printf("Eh???/n");
```
becomes (after replacement of the trigraph sequence ??/)
```
printf("Eh?\n");
```
It's saying that it will replace the trigraph sequence, but it's not .
It's printing"Eh???/n"
Am I missing something ?... |
Trigraphs are disabled by default in gcc. If you are using gcc then compile with-trigraphsto enable trigraphs:
```
gcc -trigraphs source.c
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
Here are couple of articles you can use:http://courses.engr.illinois.edu/ece390/books/labmanual/c-prog-mixing.html
http://lavernasbrute.blogspot.com/2010/02/calling-assembly-functions-in-c.html
just google 'assembly functions in C'.
|
I am facing an issue with running gcov on shared library from python script.
I have the following scenario where i build my library:
Compile a set of files (file1.c, file2.c) into a statically linked lib(.a). I use ar utility to do this and all the files are compiled using following options:-static -fprofile-arcs -f... |
Found out the issue.
I was not picking up all the .gcda files for generating the report.
Use -object-directory option to search for all gcda files.
GCOV man page
|
This C program I am making reads a set of chars from the command line and stores them using an array (argv[]) like so
```
main (int argc, char *argv[]) {
int temp;
/*prevents no arguments*/
if (argc==1){
printf("Usage;\t[0 < integers < 9] [operators]\n");
exit(0);
}
int i;
for (i = 0 ; i<argc; i++){
... |
argv[i] - is just a pointer to C string; you need first element:
```
temp = argv[i][0] - '0';
```
|
How do I run a C programming language from Xcode on terminal? Please help me with this by answering a step by step procedure in doing this. Thanks.
Version 10.7.5 on a Macbook Air.
|
Write xcode output to file and runtail -fin terminal.
```
int main(int argc, char *argv[])
{
NSAutoreleasePool *nsp = [[NSAutoreleasePool alloc] init];
NSString *logPath =[NSString stringWithFormat:@"%@/xcode.log",NSHomeDirectory()];
freopen([logPath fileSystemRepresentation], "a", stderr);
[nsp relea... |
I am working on an assignment where I am implementing the unix history command in a shell. In my program I have written a signal handler for SIGINT. When a user enters (ctrl)(c) their history is displayed.
When my program terminates I need to store the history in a file. Is there an easy way to detect when my prog... |
atexit()is probably what you're looking for, see the manual page:man 3 atexit
Usage is something like:
```
#include <stdlib.h>
static void save_the_file(void)
{
/* ... */
}
int main()
{
atexit(save_the_file);
return 0;
}
```
Another option is to use thedestructorattribute (GCC/Clang):
```
static __at... |
In C language,
I have an array[3][2];
```
int i = 0, j = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d", array[i][j]);
}
}
```
When I use gcc to compile .c file, the error shows:
```
format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’
```
How to print an... |
The error message seems pretty straight forward. It's telling you thatarray[i][j]is of typeint*, while theprintf()"%d" formatter is expecting an argument of typeint.
I'm not sure what you expect to happen here. You haven't shown us how you declarearray. But, if it's supposed to be a two-dimensional array ofint, then ... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
There was a very nice question on Stack overflow.
For i = 0, why is (i += i++) equal to 0?
But when I tried out the same code in C, it gave different results:... |
The C standard does not specify an order of evaluation. It is left to the compiler implementation.
|
```
c99 standard 5.2.1.1 Trigraph sequences
```
2 EXAMPLE The following source line
```
printf("Eh???/n");
```
becomes (after replacement of the trigraph sequence ??/)
```
printf("Eh?\n");
```
It's saying that it will replace the trigraph sequence, but it's not .
It's printing"Eh???/n"
Am I missing something ?... |
Trigraphs are disabled by default in gcc. If you are using gcc then compile with-trigraphsto enable trigraphs:
```
gcc -trigraphs source.c
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
Here are couple of articles you can use:http://courses.engr.illinois.edu/ece390/books/labmanual/c-prog-mixing.html
http://lavernasbrute.blogspot.com/2010/02/calling-assembly-functions-in-c.html
just google 'assembly functions in C'.
|
I am facing an issue with running gcov on shared library from python script.
I have the following scenario where i build my library:
Compile a set of files (file1.c, file2.c) into a statically linked lib(.a). I use ar utility to do this and all the files are compiled using following options:-static -fprofile-arcs -f... |
Found out the issue.
I was not picking up all the .gcda files for generating the report.
Use -object-directory option to search for all gcda files.
GCOV man page
|
This C program I am making reads a set of chars from the command line and stores them using an array (argv[]) like so
```
main (int argc, char *argv[]) {
int temp;
/*prevents no arguments*/
if (argc==1){
printf("Usage;\t[0 < integers < 9] [operators]\n");
exit(0);
}
int i;
for (i = 0 ; i<argc; i++){
... |
argv[i] - is just a pointer to C string; you need first element:
```
temp = argv[i][0] - '0';
```
|
How do I run a C programming language from Xcode on terminal? Please help me with this by answering a step by step procedure in doing this. Thanks.
Version 10.7.5 on a Macbook Air.
|
Write xcode output to file and runtail -fin terminal.
```
int main(int argc, char *argv[])
{
NSAutoreleasePool *nsp = [[NSAutoreleasePool alloc] init];
NSString *logPath =[NSString stringWithFormat:@"%@/xcode.log",NSHomeDirectory()];
freopen([logPath fileSystemRepresentation], "a", stderr);
[nsp relea... |
I am working on an assignment where I am implementing the unix history command in a shell. In my program I have written a signal handler for SIGINT. When a user enters (ctrl)(c) their history is displayed.
When my program terminates I need to store the history in a file. Is there an easy way to detect when my prog... |
atexit()is probably what you're looking for, see the manual page:man 3 atexit
Usage is something like:
```
#include <stdlib.h>
static void save_the_file(void)
{
/* ... */
}
int main()
{
atexit(save_the_file);
return 0;
}
```
Another option is to use thedestructorattribute (GCC/Clang):
```
static __at... |
In C language,
I have an array[3][2];
```
int i = 0, j = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d", array[i][j]);
}
}
```
When I use gcc to compile .c file, the error shows:
```
format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’
```
How to print an... |
The error message seems pretty straight forward. It's telling you thatarray[i][j]is of typeint*, while theprintf()"%d" formatter is expecting an argument of typeint.
I'm not sure what you expect to happen here. You haven't shown us how you declarearray. But, if it's supposed to be a two-dimensional array ofint, then ... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
There was a very nice question on Stack overflow.
For i = 0, why is (i += i++) equal to 0?
But when I tried out the same code in C, it gave different results:... |
The C standard does not specify an order of evaluation. It is left to the compiler implementation.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
i tried this simple C program in GCC
```
#include<stdio.h>
int main(){
int x=5;
printf("%d,%d,%d,%d,%d",++x,x++,x,x++,++x);
return 0;
}
```
and the output was... |
Because your program hasundefined behaviour. There is no sequence point between the evaluations of function arguments, and it is undefined behaviour to mutate the same object more than once without intervening sequence point.
The program is simply ill-formed. It is not a valid C program.
|
Is there any framework written in C/C++/C++11 for writing code completion tools?
Or maybe are there some libraries that allow code completion for Java or C++ (also written in C++?).
I'm writing my custom IDE in C++ for Java (and not only Java) development and I want to add code completion support to it the best possib... |
clang_complete is a plugin for vim for accurately completing C, C++, Objective-C and Objective-C++ code:https://github.com/Rip-Rip/clang_complete/It uses clang - an open source C++ compiler written in C++ for doing the job. I guess you may find it useful.
|
```
for (count = index, packet_no = 0;
count < TOTAL_OBJ, packet_no < TOTAL_PKT;
count++, packet_no++)
```
=>left-hand operand of comma expression has no effect.
I find the above code is correct and could not understand why this error comes.
|
This is how the comma operator works, what you want to do is to useORorAND(probably AND in your case):
```
// the condition for resuming the loop is that one of the conditions is true
count < TOTAL_OBJ || packet_no < TOTAL_PKT
// the condition for resuming the loop is that both conditions are true
count < TOTAL_OBJ &... |
I have an existing C libraries which uses Win32 API but it is not supported in windows 8 metro store apps.
I tried calling WinRT API but failed so is there any way ican use WinRT apis in C.
|
Since the question although very general seems to bespecificallyaboutSHGetSpecialFolderPath()onWinRTI'll address this:
As you found out WinRT (Metro) apps run in a sandboxed environment which only supports a limited subset of the win32 api.
SHGetSpecialFolderPath is officiallydeprecatedon MSDN and its functionality ... |
```
void OneDToTwoD(char* rel){
/* all the declarations here */
while(rel[i] != '\0'){
i++;
}
...
```
In the code above, I am getting all "sometimes" a segmentation fault. and valgrind check throws "Invalid read of size 1" at me at the linewhile(rel[i] != '\0'){
In that line, I'm trying to figure out t... |
Ifiis initialized as zero, andrelis pointed to valid memory block, this will work well.
relis pointed to invalid memory block or NULL.rel is not terminated with\0iis not started with 0.
And one more answer, you can't know the size of memory block from pointer. pointer is not memory block. pointer can specify invalid... |
How safe would it be to do the following cast considering that the size of the pointer varies? (32/64 bits) Could it lead to incorrect program behavior?
```
#define APL 1
#define GRP 2
void *fruits[][2] = {
{"Apples", (void *) APL},
{"Grapes", (void *) GRP},
};
```
|
considering that the size of the pointer varies?
That plays no role, the standard allows casting integers to pointers.
But the result of the cast is (apart from a constant expression evaluating to 0) implementation-defined, and probably not a pointer to memory you are allowed to manipulate or even read.
Could it le... |
I want to compare two dates "2010-08-12" and "2010-8-12" but using strcmp it is failing so please suggest any inbuilt C function or any C function to compare these dates.
Regards
|
You can write a simple and straightforward function to convert a date to a number that is good enough for ordering purposes by usingstrtol:
```
int seq_day(char *date) {
int y = strtol(date, &date, 10);
int m = strtol(++date, &date, 10);
int d = strtol(++date, &date, 10);
return (y*12+m)*31+d;
}
```
... |
I have a program that is running under MinTTY (cygwin's shell) and calls toGetConsoleMode/SetConsoleModefail._getchechos to the console as well. This is a native win32 app without bindings to the cygwin environment, so any cygwin functions are out. How do I turn off the echo so that I can input a password?
|
I essentially emulated the following viapopen:
```
save_state=$(stty -g)
/bin/echo -n "Account: "
read acct
/bin/echo -n "Password: "
stty -echo
read password # this won't echo
stty "$save_state"
echo ""
echo account = $acct and password = $password
Read more at http://www.askdavetaylor.com/how_to_read_password_wit... |
In the following code:
```
char *p = "Linux";
```
Is the memory for "Linux" on the stack or the read only segment of the program?
Refer to question 9 in the article12 Interesting C Interview Questions and Answers.
Thanks.
|
The implementation is free to store it wherever it wants. It's a constant, so it can be in read-only memory, but it is not required to be.
My instructor for C programming always says its on the stack, hence the doubt.
He probably means the pointer. Consider:
```
char *p = "Linux";
p = "Rules";
```
In the second li... |
I use this malloc style all the time
```
int *rc = 0;
rc = malloc(sizeof(*rc));
```
However, it doesn't seg fault even though when I callsizeof(*rc)I assume thatrc==0, and I am dereferencing aNULLpointer.
|
You are not really dereferencing anything. The argument ofsizeofis not evaluated, unless it is a VLA. It is explicitly allowed by the language to put whatever "garbage" you want as the argument ofsizeof. The language guarantees that it will not evaluate anything, just perform compile-time analysis of the type of the e... |
I am programing for a while but for this i couldn't find an answer yet .
lets say i want to run on a loop when i change the names of the variables.
lets say i have :
```
int ran1;
int ran2;
int ran3;
```
now i want to run a for loop that put numbers to them :
```
for(int k=0;k<3;k++)
ran%k=k; // this is wrong ,b... |
Make it an array! Using different names differentiated by a number is a bad practice:
```
int ran[3];
for (int k = 0; k < 3; k++)
{
ran[k % 3] = k;
}
```
Now, instead of usingran1, orran2, you would useran[1]orran[2].
Arrays in C are quite confusing, and they are distinct from pointers.
|
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.
In C, I have a simple server/client... |
The kernel will put packets into socket'sreceive bufferexpecting the application to read them. When that buffer fills up the kernel starts dropping new datagrams.
|
How to generate the same effect for random number generation in GNU SGL like the following:
```
int ind = rand() % 2
```
i.e. generating either 0 or 1 exactly.
|
YOu can try this example:-
```
#include <stdio.h>
#include <gsl/gsl_rng.h>
int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;
int i, n = 10;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
for (i = 0; i < n; i++)
{
double u = gsl_rng_uniform (r);
... |
```
#include<stdio.h>
#include<string.h>
int main()
{
char buffer[32];
char c;
int i;
printf("input: ");
fgets(buffer, 32, stdin);
printf("items filled: %d\n", sscanf("%c%d\n", &c, &i));
printf("%c%d\n", c, i);
return 0;
}
```
When typing a character followed by a number "f7", im expecting "f... |
Actualsscanf()signature is this :
```
int sscanf(const char *str, const char *format, ...);
```
check your signature ofsscanf()you have used wrong signature
It should be
```
sscanf(buffer,"%c%d\n", &c, &i);
```
|
The following C code will draw a rectangle. I know how to draw the ellipse, but how can i draw an ellipse into this rectangle?
```
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
rectangle(100,100,200,200);
getch();
closegraph();
return 0;... |
Asuming you're using theellipsefunctionfromgraphics.h, you could do the following:
```
int left = 100;
int right = 200;
int top = 100;
int bottom = 200;
rectangle(left, top, right, bottom);
int x = (left + right) / 2;
int y = (top + bottom) / 2;
int start = 0;
int end = 360;
int xrad = (right - left) /... |
please let me know how a pointer ( in C / C++ programming language ) can reference to a segment in hard disk, a storage of say upto 1 GB.
In more details i am going to write the signature of a function which will take a pointer as argument and that should point to a segment in hard disk, which can hold upto 1 GB spac... |
You can look intommap. This allows to map files into your main memory.
|
i have this line of code:
```
base_num = (arr[j]/base)%256;
```
This line runs in a loop and the operations "/" and "%" take a lot of resources and time to perform. I would like to change this line and apply bit operations in order to maximize the program performance. How can i do that?
Thanks.
|
If base is the nth power of two, you can replace division by it with a bitshift of n to the right. Then, since taking the mod 256 of an integer is equivalent to taking its last 8 bits, you can AND it with 0xFF. Alternately, you can reverse the operations if you AND it with 256*base and then bitshift n to the right.
... |
I am trying to implement the htoi(s) [Dennis Ritchie chapter2 exercise 2-3 Q] which converts a string of hexadecimal digits, into its equivalent integer, can anyone help me out in the logic of this program, i dont need the code, i just need the logic for implementing it. I am not able to get the correct logic
|
Let's take a step back:
How would you implement a function that accepts a single hex digit and returns it's decimal equivalent?
In other words, how would you write this function:
```
unsigned int hextodec(char c)
{
... your code here
}
```
Hint: for decimal digits what happens when you calculatec -'0'?
Once y... |
```
#include <stdio.h>
int main(int argc, char * argv[])
{
int *ip;
printf("%d\n", *ip);
ip=NULL;
if (1)
{
int i=300;
printf("Inside If Block \n");
ip=&i;
printf("*ip=%d----------\n", *ip);
}
//printf("i=%d\n", i); /* Now this wil... |
The local variableiis out of scope, so cannot be accessed, but by chance its memory location on the stack, stored inip, has not been overwritten. You absolutely cannot rely on this behaviour, but in practice you'll find it holds true on many platforms.
|
Well, I've a weird problem withprintf(). It's outputting garbage on the screen. It's kind of connected with memory, I guess. Have a look:
```
char string1[] = "SAMPLE STRING";
char string2[20]; // Some garbage in it
/* Let's clear this madness*/
int i = 0;
for (i; i < 20; i++) string2[i] = ' '; // Space, why not?
... |
Because C strings need to be NUL terminated. This means the last char of your string must be'\0'. This is howprintf(and all other C string functions) know when a string is finished.
|
I am coding an application in C. One of the screens has a cursor. The cursor needs to keep blinking. I have a infinite while loop that keeps refreshing the screen. To get the effect of blinking, at every fifth iteration of thiswhileloop, the cursor needs to alternate between appear and disappear.
I need to somehow ke... |
Simply have astaticvariable inside the function.
```
void drawCursor()
{
static int counter;
if ((counter++ % 5) == 0)
{
// toggle the cursor state
}
}
```
|
How safe would it be to do the following cast considering that the size of the pointer varies? (32/64 bits) Could it lead to incorrect program behavior?
```
#define APL 1
#define GRP 2
void *fruits[][2] = {
{"Apples", (void *) APL},
{"Grapes", (void *) GRP},
};
```
|
considering that the size of the pointer varies?
That plays no role, the standard allows casting integers to pointers.
But the result of the cast is (apart from a constant expression evaluating to 0) implementation-defined, and probably not a pointer to memory you are allowed to manipulate or even read.
Could it le... |
I want to compare two dates "2010-08-12" and "2010-8-12" but using strcmp it is failing so please suggest any inbuilt C function or any C function to compare these dates.
Regards
|
You can write a simple and straightforward function to convert a date to a number that is good enough for ordering purposes by usingstrtol:
```
int seq_day(char *date) {
int y = strtol(date, &date, 10);
int m = strtol(++date, &date, 10);
int d = strtol(++date, &date, 10);
return (y*12+m)*31+d;
}
```
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.