question
stringlengths 25
894
| answer
stringlengths 4
863
|
|---|---|
Is there any C grammar available which generates the AST, which includes all the parser rules using "^" and "!" notations?
I went through the book written by Terence Parr, to write such a grammar, but it seems that writing one such grammar for C lang is a time consuming process, so was wondering if its available already which can me save a lot of time!
(A grammar for a smaller subset of C language is also fine..)
Thanks :)
|
Seethis. It's straight from the ANTLR 4 source repo: a C11 grammar. Itlookspretty compliant.
Of course, it doesn't come with a preprocessor, but handing cpp or mcpp the file first is easy enough.
It also doesn't come with AST rules, but it doesn't looktoohard to do (albeit time consuming).
|
For example,system("sh /mydir/some-script.sh &")
|
```
system("sh /mydir/some-script.sh &")
```
executes
```
/bin/sh -c 'sh /mydir/some-script.sh &'
```
systemwill return as soon as outer shell returns, which will be immediately after it launches the inner shell. Neither shell will wait forsome-script.shto finish.
```
$ cat some-script.sh
sleep 1
echo foo
$ /bin/sh -c 'sh some-script.sh &' ; echo bar ; sleep 2
bar
foo
```
|
I have the following code:
```
int **ptr = (int **)malloc(sizeof(int*)*N);
for(int i=0;i<N;i++)
ptr[i]=(int*)malloc(sizeof(int)*N));
```
How can I freeptrusingfree? Should I loop overptrand freeptr[i]or should I just do
```
free(ptr)
```
andptrwill be freed?
|
Just the opposite of allocation:
```
for(int i = 0; i < N; i++)
free(ptr[i]);
free(ptr);
```
|
This question already has answers here:What's the purpose of each of the different UIDs a process can have?(5 answers)Closed9 years ago.
In Unix, whenexec
IfReal user IDis not same with file owner, andSet user IDbit is on, then,effective user idis changed to file owner's, andsaved set user IDtoo.BecauseEffective user IDis copied toSaved set user IDwhen exec.
At this moment, Why saved set userID is needed?
Because of security problem? if it is right, especially what case?
|
Having a saved user id allows you to drop your privileges (by switching the effective uid to the real one) and then regain them (by switching the effective uid to the saved one) only when needed.
|
I'm looking for the reference/documentation of thedos.hAPI.
(especially for an openwatcom specific version).
Where to get the documentation?
|
One reasonable starting point would probably be thelibrary documentationat OpenWatcom.
|
I have two dates and I'm wondering how to check if their difference is at least 2 months or greater.
Currently I'm converting both dates to seconds since Jan 1900 and then checking the difference in seconds and comparing it to the # of seconds in a month. Does C have a better built in function that gives timespans?
My date format: MM/DD/YYYY
|
C hasdifftimewhich basically does what you are doing. There are many more powerfully date libraries you can use.
|
I get a warning
warning: comparison between pointer and integer
on the line containingiffrom the next piece of code:
```
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != (char*)NULL)
printf("%s\n",cwd);
else
error_print("error in pwd");
```
how and what do I need to fix?
|
Do you include unistd.h? If not, the error appears because your C compiler is assuming getcwd returns int.
The fix? Include unistd.h
|
Suppose i have a directory in /tmp/myDir where files are constantly created, modified and destroyed by a daemon.
I need to periodically (every 45 seconds) monitor last created files. To do that i must determine which files were created after the last check.
What would be the best way to do that from a c daemon?
If possible, the method should avoid opening every file in the directory during each check.
|
inotifyis pretty nifty... If you can't use that, I would suggest obtaining thest_mtimefor each file in the directory, and comparing it to(time(0) - 45). If it's greater, then it's within your 45 second window. Put your executable on thecrontabif you're rather not create a continually running daemon.
|
InlemonI was able to use the third parameter of the parsing function to pass back the result to the caller when the starting symbol was reduced.
How would I do the same in bison? Is it enough to assign that value to $$ within the starting symbol's action code, and from the caller to take it as the "yy minor" value, after the final call toyypush_parse()?
The parser is push and pure. Thread-safety is a must.
|
You'll pretty much have to do-it-yourself with bison/yacc if you want an AST, by creating your own nodes and assigning them to $$.
The example athttp://epaperpress.com/lexandyacc/(look at the .y file in Calculator->Yacc input) orhttp://www.progtools.org/compilers/tutorials/cxx_and_bison/cxx_and_bison.htmlmight give you ideas on how to do that.
|
Is there any CSS parser for C/C++ with CSS3 support? I found a few but they all don't support CSS3 yet.
|
If you need CSS3 support before any libraries support it, you could try a non-validating solution such ashtmlcxx.
|
I have written a following code (see code comments for the question),
```
#include<stdio.h>
int main()
{
int size;
scanf("%d",&size);
int arr[size]; /*is it a valid statement?*/
for(int i=1;i<=size;i++)
{
scanf("%d",&arr[i]);
printf("%d",arr[i]);
}
return 0;
}
```
|
The use of a non constant array size is valid C99 but not C90. There is an older gcc extension allowing it.
Note that taking advantage of this make it harder to check that memory allocation succeed. Using it with values provided by the user is probably not wise.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Weird behavior of right shift operator
Hello
Why both numbers from this function are printed the same? It is not a cyclic shift.
```
unsigned int i=0x89878685;
int main()
{
printf("0x%x\n", i);
printf("0x%x\n", i>>32);
}
$ ./a.out
0x89878685
0x89878685
```
Do all compilers work in this way?
|
Shifting a 32-bit integer by 32 bits isundefined behavior. The result is not predictable.
In C and C++ if the integer hasNbits, you are only allowed to shift by less thenNbits. If you shiftNor more the behavior is undefined.
In practice, when shifting a 32-bit integer, some platforms will simply interpret the shift count as a 5-bit value (discard any bits above the lower 5), meaning that32will be interpreted the same way as0. This is apparently what happens on your platform. The value is not shifted at all.
|
How does one modify a threads data from outside a thread?
If a thread is running a function that loops for the runtime of the application, how can its data be set, changed?
How does one call functions which modify a specific threads functions?
Where do these functions belong?
|
The advantage and disadvantage of threads is that they share the memory space with every other thread in the process. You can use any form of data transfer you would use in single threaded applications to pass data betweens segments of you application. However, in a multi-threaded application you must use some type of synchronization to assure data integrity and prevent deadlocks.
|
```
#include<stdio.h>
int main(void)
{
int a=-3,b=5,c;
c=a|b;
printf("%d ",c);
c=a&b;
printf("%d ",c);
}
```
The output is-3 5, please explain how?
|
To understand the output, you need to become familiar with theTwo's Complementwhich is used to represent negative binary numbers. The conversion from +x to -x is actually quite easy: Complement all bits and add one.
Now just assume your ints are of length 8 bits (which is sufficient to examine 5 and -3):
```
5: 0000 0101
3: 0000 0011 => -3: 1111 1101
```
Now lets take a look at the bitwise or:
```
1111 1101 | 0000 0101 = 1111 1101
```
Exactly the represantation of -3
And now the bitwise AND:
```
1111 1101 & 0000 0101 = 0000 0101
```
Exactly the binary representation of 5
|
Is there any difference about p.a and p->a where p is pointer? or they are just same thing.
|
The.operator is actually the operator for structure member access.
```
struct Foo
{
int bar;
int baz;
} aFoo;
aFoo.bar = 3;
```
If you have a pointer to a struct, (very common) you can access its members using pointer dereferencing and the.operator.
```
struct Foo *p;
p = &aFoo;
(*p).baz = 4;
```
The parentheses are needed because.has higher precendence than*. The above dereferencing a member of a structure pointed to by something is extremely common, so->was introduced as a shorthand.
```
p->baz = 4; // identical to (*p).baz = 4
```
If p is a pointer, you never seep.anythingin plain C, at least not in anything that compiles. However, it is used to denote property access in Objective-C which was a mistake IMO.
|
I am trying to find the syntax that will let me redirect standard input output toward a named pipe after using the mkfifo() function and creating a child process using fork.
Which man page should I be looking at for the syntax?
Thanks,
Aaron
|
Do you referredthis
gives you idea about the syntax.
|
when I read from stdin like this:
```
size_t bufSize = 1024;
unsigned char inputBuffer[bufSize];
size_t readNum = 0;
readNum = fread(inputBuffer, sizeof(unsigned char) * bufSize, 1, stdin);
```
in the readNum are stored number of object, this mean when I read from stdin 1024 bytes, the readNum has value 1. But when I read from stdin < 1024 bytes, than readNum has value 0. Question is, how can I recognize how many bytes was read from stdin when the number is less then 1024?
|
UsereadNum = fread(inputBuffer, sizeof(unsigned char), bufSize, stdin);
You're trying to readbufSizeelements, each with a sizesizeof(char)- not one element with a size ofbufSize * sizeof(char)- so yourfreadcall should reflect that.
|
The following code runs fine, except my output file does not contain the integer 10, but instead the characters ^@^@^@ when I open it up in VIM. If I open it in textedit (on the mac) the file appears to be empty.
Does anybody know where I am going wrong here?
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 256
#define MAX_NAME 30
int main() {
FILE *fp;
char fname[MAX_NAME] = "test1.dat";
int x =10;
int num= 0;
if( (fp =fopen(fname, "w")) == NULL) {
printf("\n fopen failed - could not open file : %s\n", fname);
exit(EXIT_SUCCESS);
}
num= fwrite(&x, sizeof(int), 1, fp);
printf("\n Total number of bytes written to the file = %d\n", num);
fclose(fp);
return(EXIT_SUCCESS);
}
```
|
You're writing binary data and expecting to see ASCII.
You could write the number in ASCII usingfprintf:fprintf(fp, "%d", x)
|
I just came across some code which used the kill system call to send a SIGSEGV signal to an app. The rationale behind this was that this would force the app to core dump and quit. This seems so wrong to me, is this normal practice?
|
SIGQUIT is the correct signal to send to a program if you wish to produce a core dump.killis the correct command line program to send signals (it is of course poorly named, since not all signals will kill the program).
Note, you should not send random signals to the program, not all of them will produce a core dump. Many of them will be handled by the program itself, either consumed, ignored, or induce other processing. Thus sending a SIGSEGV is wrong.
GCC Says:http://www.gnu.org/s/libc/manual/html_node/Termination-Signals.html
POSIX/Unix Says:http://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html
|
So we want to use SQL lite directly from source (mainly because we create a crossplatform opensource app and there areno crossplatfrom lib distributions of SQL LITE) So we download sqlite-amalgamation and create a simple static lib from it. We include sqlite3.h and sqlite3ext.h to our project file and than what - how to create a simple DB file and fill any fields in it?
|
I found thistutorialas well as thisvideovery helpful to get started. The video should help you set up the project so that you can create and connect to a simple db. The code from the first tutorial is almost identical to the example on the sqlite homepage. Despite lack of in-depth explanation the tutorial was extremely helpful to me since it comes with source code and MSVS projects. You can use those to have a play with. I would also recommend getting the SQLite Administrator tool to have a GUI for your db.
|
```
printf ("%#p [ buf ] (%.2d) : %s \n", buf, strlen (buf), buf);
```
I never see%#p (%.2d)before,how does it work?
|
Fromhttp://www.cplusplus.com/reference/clibrary/cstdio/printf/:
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero.Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written.Used with g or G the result is the same as with e or E but trailing zeros are not removed.
So it seems to do nothing in your case, sincepis used to print a pointer address. I guess some compilers might interpret this differently, but I can't find any mention of it.
|
I'm wondering if it's possible to activate multiple Mono domains and execute them in parallel fromnative code:
I use the following code to activate a domain:
```
///Create a new domain.
m_domain = mono_domain_create();
///Activate the domain.
mono_domain_set(m_domain, 0);
///Invoke some function ...
mono_runtime_invoke (m_method, m_objectInstance, NULL, &exception);
```
|
Yes this can be done. Given that the Mono virtual executable runs alongside your C application when it's embedded (and shares the same address space), The best approach would be to launch each domain in a separate process. The easiest way to do this would be to have your code fork multiple processes and each process would manage a separate Mono domain instance. You'd have to write some code to coordinate interprocess communications, particularly application clean-up and shutdown.
|
I am not very clear with this API from it's definition in man page: timer_getoverrun( ).
Can someone help me to explain, with the context of a timer?
Thanks in advance
|
If you create e.g. a 1ms timer, but due to various delays it takes e.g 4.5ms from the signal is generated until it is actually accepted by the application, therecould have been3 more signals issued in the meantime (but isn't, since only one signal is pending at a time).timer_getoverrun()retrieves the value 3 - the number of signalsnotgenerated.
|
When i make some opensource project, there is one error: make: flex: Command not found
I want to know what is the flex ?
|
Flexis the Fast Lexical analyzer generator.
|
I have a macro which works well only on static local variables (since it uses inline assembly notation to extract data about the variable). I need a way to enforce that the input to the macro is indeed a static local variable:
correct:
```
func f()
{
static int x;
my_macro(x);
}
```
not correct:
```
func f()
{
int x;
my_macro(x);
}
```
I work with GCC for C (no C++).
|
You can use following trick:
```
#define ASSERT_LOCAL_STATIC(v) static void *p_ ## v = &v
void fn()
{
int nonstatic_var = 0;
static int static_var = 0;
ASSERT_LOCAL_STATIC(static_var);
ASSERT_LOCAL_STATIC(nonstatic_var);
}
```
GCC issues an error "initializer element is not constant" for non-static variables.
|
Hello I have started writing common data structure library in C similar to STL.
Here is the link .http://code.google.com/p/cstl/
I struggled a lot of whether to go ahead with havingvoid*as basic element for data structure. and End up with structure which has two elements
```
typedef struct __c_lib__object {
void* raw_data;
size_t size;
} clib_object, *clib_object_ptr;
```
This approach allow me to store each element, but it requires lot of memory allocation , during saving and returning back the element from the container.
Can anybody please review this , and let me know if there is any other approach.
Thanks
Avinash
|
Names starting with double-underscore are reserved to 'the implementation' and should be avoided in user code.
Personally, I dislike typedefs for pointers; I'd rather useclib_object *x;thanclib_object_ptr x;.
Why do you need to record the size of the object?
|
is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program.
Thanks
|
You can use theclockfunction in<time.h>along with the macroCLOCKS_PER_SEC:
```
clock_t start = clock() ;
do_some_work() ;
clock_t end = clock() ;
double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;
```
Nowelapsed_timeholds the time it took to calldo_some_work, in fractional seconds.
|
I have got some data in a buffer and want to put those data in an array.
```
typedef struct chunk
{
char data[300]; /* the bufferr. */
} CHUNK;
char *buffer, CHUNK c [100];
```
Assuming I have got data into the buffer, how can I put 300 char per chunk? I'm new to C so please explain me with simple example.
Thanks,
Kevin
|
The declaration is invalid, but I think you mean:
```
typedef struct chunk
{
char data[300]; /* the bufferr. */
} CHUNK;
char *buffer;
CHUNK c [100];
```
If I understand your question correctly (which I'm far from certain that I do), the code would be something like:
```
int j = 0;
char *bp = buffer;
while (*bp)
{
strncpy (c [j] .data, bp, 300); // copy data into next item
bp += strlen (bp);
++ j;
}
```
|
I am taking in an argument using fopen. What are some checks I can do to make sure that fopen actually takes in the string to a valid filename?
|
The number one method is to try opening the file. Iffopen()returns NULL, there was an error. Check theerrnovariable or function to find out the problem.
Trying to preprocess a file specification is an exercise in futility. The operating system will do every relevant check for you, including those which are hard for you to do, like checking file protection ACLs, etc.
|
```
printf ("%#p [ buf ] (%.2d) : %s \n", buf, strlen (buf), buf);
```
I never see%#p (%.2d)before,how does it work?
|
Fromhttp://www.cplusplus.com/reference/clibrary/cstdio/printf/:
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero.Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written.Used with g or G the result is the same as with e or E but trailing zeros are not removed.
So it seems to do nothing in your case, sincepis used to print a pointer address. I guess some compilers might interpret this differently, but I can't find any mention of it.
|
I'm wondering if it's possible to activate multiple Mono domains and execute them in parallel fromnative code:
I use the following code to activate a domain:
```
///Create a new domain.
m_domain = mono_domain_create();
///Activate the domain.
mono_domain_set(m_domain, 0);
///Invoke some function ...
mono_runtime_invoke (m_method, m_objectInstance, NULL, &exception);
```
|
Yes this can be done. Given that the Mono virtual executable runs alongside your C application when it's embedded (and shares the same address space), The best approach would be to launch each domain in a separate process. The easiest way to do this would be to have your code fork multiple processes and each process would manage a separate Mono domain instance. You'd have to write some code to coordinate interprocess communications, particularly application clean-up and shutdown.
|
I am not very clear with this API from it's definition in man page: timer_getoverrun( ).
Can someone help me to explain, with the context of a timer?
Thanks in advance
|
If you create e.g. a 1ms timer, but due to various delays it takes e.g 4.5ms from the signal is generated until it is actually accepted by the application, therecould have been3 more signals issued in the meantime (but isn't, since only one signal is pending at a time).timer_getoverrun()retrieves the value 3 - the number of signalsnotgenerated.
|
When i make some opensource project, there is one error: make: flex: Command not found
I want to know what is the flex ?
|
Flexis the Fast Lexical analyzer generator.
|
I have a macro which works well only on static local variables (since it uses inline assembly notation to extract data about the variable). I need a way to enforce that the input to the macro is indeed a static local variable:
correct:
```
func f()
{
static int x;
my_macro(x);
}
```
not correct:
```
func f()
{
int x;
my_macro(x);
}
```
I work with GCC for C (no C++).
|
You can use following trick:
```
#define ASSERT_LOCAL_STATIC(v) static void *p_ ## v = &v
void fn()
{
int nonstatic_var = 0;
static int static_var = 0;
ASSERT_LOCAL_STATIC(static_var);
ASSERT_LOCAL_STATIC(nonstatic_var);
}
```
GCC issues an error "initializer element is not constant" for non-static variables.
|
Hello I have started writing common data structure library in C similar to STL.
Here is the link .http://code.google.com/p/cstl/
I struggled a lot of whether to go ahead with havingvoid*as basic element for data structure. and End up with structure which has two elements
```
typedef struct __c_lib__object {
void* raw_data;
size_t size;
} clib_object, *clib_object_ptr;
```
This approach allow me to store each element, but it requires lot of memory allocation , during saving and returning back the element from the container.
Can anybody please review this , and let me know if there is any other approach.
Thanks
Avinash
|
Names starting with double-underscore are reserved to 'the implementation' and should be avoided in user code.
Personally, I dislike typedefs for pointers; I'd rather useclib_object *x;thanclib_object_ptr x;.
Why do you need to record the size of the object?
|
is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program.
Thanks
|
You can use theclockfunction in<time.h>along with the macroCLOCKS_PER_SEC:
```
clock_t start = clock() ;
do_some_work() ;
clock_t end = clock() ;
double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;
```
Nowelapsed_timeholds the time it took to calldo_some_work, in fractional seconds.
|
I have got some data in a buffer and want to put those data in an array.
```
typedef struct chunk
{
char data[300]; /* the bufferr. */
} CHUNK;
char *buffer, CHUNK c [100];
```
Assuming I have got data into the buffer, how can I put 300 char per chunk? I'm new to C so please explain me with simple example.
Thanks,
Kevin
|
The declaration is invalid, but I think you mean:
```
typedef struct chunk
{
char data[300]; /* the bufferr. */
} CHUNK;
char *buffer;
CHUNK c [100];
```
If I understand your question correctly (which I'm far from certain that I do), the code would be something like:
```
int j = 0;
char *bp = buffer;
while (*bp)
{
strncpy (c [j] .data, bp, 300); // copy data into next item
bp += strlen (bp);
++ j;
}
```
|
I am taking in an argument using fopen. What are some checks I can do to make sure that fopen actually takes in the string to a valid filename?
|
The number one method is to try opening the file. Iffopen()returns NULL, there was an error. Check theerrnovariable or function to find out the problem.
Trying to preprocess a file specification is an exercise in futility. The operating system will do every relevant check for you, including those which are hard for you to do, like checking file protection ACLs, etc.
|
I have an string array in the form of char**
I am struggling to find the length of that array:
```
typedef struct _stringArray
{
int (*Length)(char**);
char** (*Push)(char**, char*);
char** (*Pop)(char**, char*);
}StringArray;
StringArray* StringArray_Constructor(void)
{
StringArray* stringArray = (StringArray *)malloc(sizeof(StringArray));
stringArray->Push = StringArray_Push;
stringArray->Pop = StringArray_Pop;
}
char** StringArray_Push(char** array, char* string)
{
int size = 0; //how to find how many elements in the array object???
array = realoc(array, (sizeof(char *) * (size + 1));
array[size] = string;
return array;
}
```
Any help would be greatly appreciated!
Thanks.
|
With C, you will have to keep track of this yourself.
|
Why do I receive a warning for this code ?
```
switch(iInput)
{
...
case 1I64<<31: return 31; break;
...
}
```
1>C:\path-to-file.cpp(44) : warning C4309: 'case' : truncation of constant value
1I64<<31 is 0x0000000080000000 (__int64) so no truncation here,
it's there a maximum value for case ?
|
The type of the expression controlling theswitchcontrols they type of the expression thecaselabels will use.
You'll need an__int64(or equivalent) type in the controlling expression to get rid of the warning.
|
When I test my program using a web browser I can write to the socket/FD just fine so i decided to loop it and cut the connection mid-connection and I noticed a problem. send() is capable of closing down the entire program when the socket is unavailable. I thought the problem was that the program caught itself in a catch-22 and closed itself. So I set the socket to not block. No change. Any ideas of why this is happening?
```
else if ( b->temp_socket_list[read].revents & POLLOUT ) {
printf ( "#Write#\n" );
char *done = "Done!";
int sent = send ( sock, done, 5, 0 );
printf ( "end\n", sent );
}
```
|
This is likely due to the default action of theSIGPIPEsignal. To ignore this signal, use something like:
```
signal(SIGPIPE, SIG_IGN);
```
Socket errors will then be reported as return values from socket functions, rather than a signal.
|
I'm using libltdl in my C code to dynamically load libtool made shared object files. Apparently a reference count is internally kept for each module handle returned by libtool's version of dlopen. Is there any way to access this reference count?
|
```
const lt_dlinfo *info;
info = lt_dlgetinfo(myhandle);
printf("refcount is %d\n", info->ref_count);
```
|
I know how to make YACC generate an AST, but how do you actaully get it? I mean, how do you actaully get the value of the root node from YACC?
|
Yacc only gives you back one node at a time, and it'salwayssomething that you just gave yacc at some earlier time, i.e., whatever you wanted to return from a reduced production or whatever you wanted to return from a terminal symbol. (Sorry, you said you knew that, but some people reading this might not.)
So, take whatever you woud have returned from the root or top rule, and save it (in your attached C reduction code) any way you like.
|
The following code gives me a zero value for 'count' all the time...
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 128
int main ()
{
char mychar , string [SIZE];
int i;
int count =0 ;
printf ("Please enter your string: \n\n");
fgets (string, SIZE, stdin);
printf ("Please enter char to find: ");
mychar = getchar();
for (i=0 ; (string[i] == '\0') ; i++ )
if ( string[i] == mychar )
count++;
printf ("The char %c appears %d times" ,mychar ,count);
return 0;
}
```
Thanks !
|
This
```
int const count =0 ;
```
and this
```
count++;
```
conflicts , value of const variable can't be changed (that is why it is called constant)
|
I have some doubts in basic C programming.
I have a char array and I have to copy it to a char pointer. So I did the following:
```
char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);
```
My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?
|
Firstly, C strings (the%sinprintf) are expected to be NUL-terminated. You're missing the terminators. Trychar a[] = {0x3f, 0x4d, 0}(same goes forstr).
Secondly,pstrandstrpoint to the same memory, so yourmemcpyis a no-op. This is a minor point compared to the first one.
|
I wrote the following code:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 128
int main ()
{
char mychar , string [SIZE];
int i;
int const count =0 ;
printf ("Please enter your string: \n\n");
fgets (string, SIZE, stdin);
printf ("Please enter char to find: ");
mychar = getchar();
for (i=0 ; (string[i] == '\0') ; i++ )
if ( string[i] == mychar )
count++;
printf ("The char %c appears %d times" ,mychar ,count);
return 0;
}
```
The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".
What seems to be wrong ?
Thank !
|
Try usingfgetsinstead as:
```
fgets (string, SIZE, stdin);
```
Whygetsis unsafe, has been answered several times on SO. You can seethis.
|
```
gcc 4.4.4
c89
```
I am wondering what is the real difference between the following 2 implementations of defining structures?
```
channel.h file
struct channel_tag;
struct channel_tag* init_channel(size_t channel_id);
void dispose_channels(struct channel_tag *channel);
channel.c file
typedef struct channel_tag {
size_t channel_id;
} channel_t;
```
=================== Second implemenation ===============
```
channel.h file
typedef struct channel_tag channel;
channel* init_channel(size_t channel_id);
void dispose_channels(channel *channel);
channel.c file
struct channel_tag {
size_t channel_id;
};
```
Many thanks for any suggestions,
|
In the first case you have one data type, and the second you have two (where the 2nd is typedef'ed to the first). There is no difference in the generated code. Its for many people just more convenient to read/write code that omits the extrastructkeyword.
|
at times if we don't list libs in certain order inside a makefile, it fails.
The reason being - definition should come before its use.
How to determine the correct order?
|
Actually, when linking libraries, the use should come before the definition. Any unresolved symbols need to be known before a library file providing their definitions is processed.
What comes to the order, I'm afraid you have to do this manually. If libA depends on libB (i.e. libA uses symbols from libB), then you have to link in this order:-lA -lB.
This is mostly a matter of documentation. A well-documented library clearly states what other libraries it depends on, so you can figure out the correct linking order.
If you don't want to read documentation or there is no documentation available, trial and error is always an option :)
|
how can i write my own module in C ?
is it possible ?
|
Yes, it is possible. Here's an old article that I used when I wrote my first extension:
http://web.archive.org/web/20110222035803/http://devzone.zend.com/article/1021
Things may have changed since then, so you may want to search for similar tutorials for additional references.
Oh, and this should be useful:
http://www.php.net/manual/en/internals2.php
|
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.
Solution : Sort the array and take the second element butSorting not allowed
Modification : By definition second largest element will be the one which is numerically smaller. Like if we have
Arr = {5,5,4,3,1}
Then second largest is 4
AdditionLets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.
|
Go through the array, keeping 2 memory slots to record the 2 largest elements seen so far. Return the smaller of the two.
.... is there anything tricky about this question that I can't see?
|
if i have created an array like
int marks[4][2];
then the name of the array must give me the address of the first element,as is in case of one dimensional array,but it is not so?
& alsoprintf("%d",marks[0]);
&
printf("%d",marks);yield the same result?????????
|
```
printf("%d",marks);
```
Giving a wrong format-specifier leads toundefined-behavior.marksleads to a pointer to 1D array( i.e., pointer pointing to the first element of first row ).
So, to print a pointer's content%pshould be used instead.
```
printf("%p",marks);
```
And it seems you are trying to print the value at a location0*0. So -
```
printf("%d",marks[0][0]); // [m][n] is the way of accessing 2D array elements.
```
|
(source:blogcu.com)
Assume there is a rabbit and at position (1,1). Moreover, its home is at position (7,7). How can it reach that position ?
Home positon is not fix place.
Real question, I am trying to solve a problem on a book for exersizing c.What algorithm should I apply to find solution?Should I use linked list to store data?
Data is (1,1), (1,2),..., (3,3) ..., (7,7)
Place marked with black shows wall.
|
Use A*. It is the classic go-to algorithm forpath-finding(that article lists many other algorithms you can consider too).
By using A* you learn an algorithm that you might actually need in your normal programming career later ;)
An example evaluation of a maze similar to that in the question using A*:
|
I am trying to run a script inside my C program usingsystem()command. Insidemain(), I run the script and it returns the results. How can I put the result of the script in some string and check for conditions? I know I can do it with files but was wondering if its possible to put the result into a string.
Sample would be like:
```
main()
{
system("my_script_sh"); // How can I get the result of the my_script_sh
}
```
|
You can't use the system command for that. The best thing to do is usepopen:
```
FILE *stream;
char buffer[150];
stream = popen("ls", "r");
while ( fgets(buffer, 150, stream) != NULL ){
// Copy the buffer to your output string etc.
}
pclose(stream);
```
|
I would like to, in C code, create more than one terminal processes. As in, I want to runfooin a terminal process, and then in a separate terminal process, I want to runbar. Is this possible? Could I do it withsystem(char *)?
|
This sounds like a job forposix_spawn(). Here is anexample. Definitely donotcallsystem()to launch new processes.
|
For example, I want to run:
```
ssh root@127.0.0.1 -p 2222
```
in C (viasystem) command. But right after I run that, it asks for input:
```
root@127.0.0.1's password:
```
Then I'm expected to type in the password. How can I do this in C code? Could I please get some code on how I could simulate key presses? Or is there a better way to do this?
|
There are better ways to do this, such askey-based SSH authentication.
|
This is what I came up with, but I always get a Run-Time Check Failure #2 - Stack around the variable 'h' was corrupted.
```
int mostCommonLetter(char s[]) {
int i=0, h[26],k=0, max=0, number=0;
while ( k < 26){
h[k] = '0';
k++;
}
while(s[i] != '\0'){
h[whichLetter(s[i])] = h[whichLetter(s[i])]+1;
i++;
}
h[26] = '\0';
for(i=0;h[i]!='\0';i++){
if(h[i] > max)
number=i;
}
return number;
}
```
|
You cannot doh[26] = '\0';- h has 26 elements indexed 0..25. As you know the length of h you don't need to 0-terminate it, simply dofor (i=0; i < 26; ++i)
Also, are you certainwhichLetteralways returns a value in the 0..25 range? What does it do if it e.g. encounters a space?
|
```
void CalculateFrameRate()
{
static float framesPerSecond = 0.0f; // This will store our fps
static float lastTime = 0.0f; // This will hold the time from the last frame
float currentTime = GetTickCount() * 0.001f;
++framesPerSecond;
if( currentTime - lastTime > 1.0f )
{
lastTime = currentTime;
if(SHOW_FPS == 1) fprintf(stderr, "\nCurrent Frames Per Second: %d\n\n", (int)framesPerSecond);
framesPerSecond = 0;
}
}
```
Should I call this function invoid play(void)orvoid display(void)?
Or it does not make any difference?
|
You should put it in the display loop.Here'san article that explains some intricacies of game loops that you should read.
|
(source:blogcu.com)
Assume there is a rabbit and at position (1,1). Moreover, its home is at position (7,7). How can it reach that position ?
Home positon is not fix place.
Real question, I am trying to solve a problem on a book for exersizing c.What algorithm should I apply to find solution?Should I use linked list to store data?
Data is (1,1), (1,2),..., (3,3) ..., (7,7)
Place marked with black shows wall.
|
Use A*. It is the classic go-to algorithm forpath-finding(that article lists many other algorithms you can consider too).
By using A* you learn an algorithm that you might actually need in your normal programming career later ;)
An example evaluation of a maze similar to that in the question using A*:
|
I am trying to run a script inside my C program usingsystem()command. Insidemain(), I run the script and it returns the results. How can I put the result of the script in some string and check for conditions? I know I can do it with files but was wondering if its possible to put the result into a string.
Sample would be like:
```
main()
{
system("my_script_sh"); // How can I get the result of the my_script_sh
}
```
|
You can't use the system command for that. The best thing to do is usepopen:
```
FILE *stream;
char buffer[150];
stream = popen("ls", "r");
while ( fgets(buffer, 150, stream) != NULL ){
// Copy the buffer to your output string etc.
}
pclose(stream);
```
|
I would like to, in C code, create more than one terminal processes. As in, I want to runfooin a terminal process, and then in a separate terminal process, I want to runbar. Is this possible? Could I do it withsystem(char *)?
|
This sounds like a job forposix_spawn(). Here is anexample. Definitely donotcallsystem()to launch new processes.
|
For example, I want to run:
```
ssh root@127.0.0.1 -p 2222
```
in C (viasystem) command. But right after I run that, it asks for input:
```
root@127.0.0.1's password:
```
Then I'm expected to type in the password. How can I do this in C code? Could I please get some code on how I could simulate key presses? Or is there a better way to do this?
|
There are better ways to do this, such askey-based SSH authentication.
|
This is what I came up with, but I always get a Run-Time Check Failure #2 - Stack around the variable 'h' was corrupted.
```
int mostCommonLetter(char s[]) {
int i=0, h[26],k=0, max=0, number=0;
while ( k < 26){
h[k] = '0';
k++;
}
while(s[i] != '\0'){
h[whichLetter(s[i])] = h[whichLetter(s[i])]+1;
i++;
}
h[26] = '\0';
for(i=0;h[i]!='\0';i++){
if(h[i] > max)
number=i;
}
return number;
}
```
|
You cannot doh[26] = '\0';- h has 26 elements indexed 0..25. As you know the length of h you don't need to 0-terminate it, simply dofor (i=0; i < 26; ++i)
Also, are you certainwhichLetteralways returns a value in the 0..25 range? What does it do if it e.g. encounters a space?
|
```
void CalculateFrameRate()
{
static float framesPerSecond = 0.0f; // This will store our fps
static float lastTime = 0.0f; // This will hold the time from the last frame
float currentTime = GetTickCount() * 0.001f;
++framesPerSecond;
if( currentTime - lastTime > 1.0f )
{
lastTime = currentTime;
if(SHOW_FPS == 1) fprintf(stderr, "\nCurrent Frames Per Second: %d\n\n", (int)framesPerSecond);
framesPerSecond = 0;
}
}
```
Should I call this function invoid play(void)orvoid display(void)?
Or it does not make any difference?
|
You should put it in the display loop.Here'san article that explains some intricacies of game loops that you should read.
|
What does length mean exactly in this sentence: "Each array is passed to the function along with the “length” of that array."
Does it mean the size of the array?
|
Not necessarily. Thesizeof the array is thenumber of byteslocated for it (or at least that whatsizeof(array)will return if it knows how many elements are there in the array) thelengthof the array is thenumber of elementsin the array.
For example:short arr[10];its length is 10, but its size is 20 (each short is two bytes)
|
I'm looking for a good introduction to the Berkeley db api that is installed on OS X. I have looked at this Oracle document:http://download.oracle.com/docs/cd/E17076_02/html/gsg/C/BerkeleyDB-Core-C-GSG.pdf
Which seems to be a newer version. I am not able to compile this and get the following error:
```
test.c:23: error: ‘DB_CREATE’ undeclared (first use in this function)
test.c:23: error: (Each undeclared identifier is reported only once
test.c:23: error: for each function it appears in.)
test.c:26: error: ‘DB’ has no member named ‘open’
test.c:42: error: too many arguments to function ‘dbp->close’
```
AFAIK, the version installed on OS X is the old BSD licensed 1.85.
|
DB 1.85 is only there to support some system configuration files such as/etc/pwd.db, so it shouldn't really be used.
That being said, itismuch simpler than the newer Berkeley DB releases.dbopen(3)is a good start.
|
This is totally outside my area of expertise, so forgive me if this seems rather elementary. I've never really worked with C, so this is a bit new to me. I've been tasked with cross-compilingthe ISC's DHCP implementationinto MIPS. I have the compiler (mipsel-linux-gcc) and other assorted tools and it compiles fine but it fails when linking on every file:
Bad value: failed to merge target
specific data of file ... linking PIC
files with non-PIC files
-fPIC and -fno-PIC changed nothing. Is there a simple solution to this, or will I need to start rewriting chunks of this software? Any input would be appreciated, I'm at a bit of a loss.
My configure line is as follows:
```
./configure CC=mipsel-linux-gcc CPP=mipsel-linux-cpp --host=mips --build=i686-pc-linux-gnu
```
|
Something's wrong with libraries you're linking in. Make sure you have the standard library compiled for PIC, and that you link to it, not your system's.
|
I know to create a patch for an existing file is easy:
diff -aru oldFile newFile 2>&1 | tee myPatch.patch
But what to do, if i want to create a patch for a totally new file? Assume my file is residing in a folder calledTestDir. EarlierTestDirdid not have a file calledentirelyNewfile.c, but now it is having the same.
How to create a patch forentirelyNewfile.c? The idea is, the patch should get properly applied to the specs and generate the RPM build. With BUILD dir having this new file.
Just to add: if i try to take diff between the two directories, one having the new file and the other missing the same, to create the patch, it generates an error saying that file is only present in one folder
|
Add-Nto thediffarguments.
|
Hey, im using WinAVR and programing an ATMEGA32 in C.Basically, I want to link my C program to asm via the:
asm(" ") command.
Im trying to define memory locations in C to exact memory locations so that I can then access them within the asm command line.
I have 5 variables:
unsigned char var1, var2, var3, var4,
var5;
I know I could use pointers to a memory location, but im unsure how to do this.Any help would be appreciated.Thanks,Oliver.
|
This method is completely compiler-independent, simple, and straightforward:
```
#define var1 (*(volatile unsigned char *)0xDEADBEEF)
#define var2 (*(volatile unsigned char *)0xDECAFBAD)
#define var3 (*(volatile unsigned char *)0xBADC0DE)
```
etc.
|
I have a fd descriptor, which I can use to read from by callingread(fd, buffer,...). Now, I want to check if there is anything to read before actually making the call, because the call is blocking. How do I do this?
|
```
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
```
The code snippet above will configure such a descriptor for non-blocking access. If data is not available when you call read, then the system call will fail with a return value of -1 and errno is set to EAGAIN. See thefcntlman pages for more information.
Alternatively, you can useselectwith a configurable timeout to check and/or wait a specified time interval for more data. This method is probably what you want and can be much more efficient.
|
I want to make an array of 20 strings (char*) where each of them is allocated automatically length ofMAXLENGTH
will by saying:
```
char *string_arr[MAXLENGTH][20];
```
I'll be able to address each string asstring_arr[i]where0=<i<20and more importantly, will I be able to put things intostring_arr[i]without dynamically allocating memory, e.g:
```
strcpy(string_arr[2],"some string");
```
?
|
Instead of
```
char *string_arr[MAXLENGTH][20];
```
Say:
```
char string_arr[20][MAXLENGTH];
```
You also probably want to sayMAXLENGTH+1for null termination.
|
I am trying to allocate ~ 1GB , but when I check the pointer address it's a negative number. Could this be a configuration limit I am hitting somewhere.
goal to allocate ~1GBlimit of ~0.7GB ([struct]48 * 16890)1.5GB free memoryno large amounts of memory were allocated before this.using fedora linux.no compiler errors
|
Don't test for a pointer's "sign", it's irrelevant. The only invalid pointer thatmallocwill return is the null pointer. If it returned something else, you can use it.
|
I am dealing with an existing project (in C) that is currently running on a single thread, and we would like to run on multiple platforms AND have multiple threads. Hopefully, there is a library for this, because, IMHO, the Win32 API is like poking yourself in the eye repeatedly. I know about Boost.Thread for C++, but, this must be C (and compilable on MinGW and gcc). Cygwin is not an option, sorry.
|
TryOpenMPAPI, it's multi-platform and you can compile it with GCC.
Brief description from thewikipedia:
OpenMP (Open Multi-Processing) is an application programming interface
(API) that supports multi-platform shared memory multiprocessing
programming in C, C++, and Fortran,[3] on most platforms, processor
architectures and operating systems, including Solaris, AIX, HP-UX,
Linux, macOS, and Windows. It consists of a set of compiler
directives, library routines, and environment variables that influence
run-time behavior.
|
I've been doing hours of research which brought me to mach override:http://guiheneuf.org/mach%20inject%20for%20intel.html
I'm trying to rewrite the opcode 8b5508 at the given address in my target with nops (909090). I think mach override seems to be the solution, but I have no idea how to use it... has anybody got any advice? Thank you in advance!
|
Without any other context, this seems like a textbook problem. If you're using C, you could do it this way:
```
char *myptr = my_given_addr;
myptr[0] = 0x90;
myptr[1] = 0x90;
myptr[2] = 0x90;
```
There's probably a more elegant solution but this gets the general gist. I'm new to SO... is there a homework tag?
|
I'm having a hard time understanding the ways C handles returned values. Say for example we have:
```
int one = 0;
one = foo(); // Why isn't one being assigned 10?
// Clearly there is a difference between these two
printf("%d", one); // one is still 0
printf("%d", foo());
int foo()
{
return 10;
}
```
I can't seem to elucidate why there is a difference, and why one won't work over the other.
Thank you!
|
The following program's output is1010. I compiled it withgcc -Wall -std=c99 main.c -o main.exeSo, I think it's either your compiler problem, or you were wrong when claimed thatprintf("%d", one);prints zero.
```
#include <stdio.h>
int foo(void);
int main()
{
int one = 0;
one = foo();
printf("%d", one);
printf("%d", foo());
return 0;
}
int foo()
{
return 10;
}
```
|
I am wondering, how to check if I am opening file which exists with fopen? I want to diplay some message, when user selects file with bad name. Is must be some simple checking, but I am not able to solve it.
Thanks
|
in your param list:
```
FILE pFile ;
```
then:
```
pFile = fopen ("myfile.txt","r");
if (pFile == NULL)
printf("No Such File !! ");
```
|
If I allocated memory in my C program usingmallocand now I want to exit, do I have to free the allocated memory, or can I assume that since my entire program terminates, it will be freed by the OS?
I run in Linux environment.
|
Any modern operating system will clean up everything after a process terminates, but it's generally not a good practice to rely on this.
It depends on the program you are writing. If it's just a command line tool that runs and terminates quickly, you may not bother cleaning up. But be aware that it is this mindset that causes memory leaks in daemons and long-running programs.
|
I have some tools I'm working on in portable C that works in Windows Visual Studio 2008 and gcc in Ubuntu Linux based on#ifdef _WIN32but adding support for Solaris seems to be trickier, especially if I want to supportccas well asgcc.
For one example I have some code whichsprintfs into an allocated memory buffer which usesvasprintfon Linux/gcc and_vscprintf/vsprintfon Windows/MSVC. Neither are available on Solaris where I could usevsnprintfbut I have no idea what to add to my#ifdefs or whether I should move to something else.
Hopefully I don't have to move to configure with cygwin, mingw.
|
Theautoconf(1)manual has asection on portable C programming.
|
in my program I will use two parameters. It could look like this:
```
./myApp -status 7 -file abc.txt
```
My question is how to make conditions like "if(parameter_status==7)" and how to get to abc.txt from -file in my main?
Thanks
|
Use the GNU C Library getopt() call. An example of how to use it is atwww.gnu.org.
|
im trying to add arc4random into my C console-based project.Basically im including the .c file in my project and then a method call as:
```
#include <stdio.h>
#include <stdlib.h>
#include "arc4random.c"
//Define globals
int r;
int main(int argc, char *argv[]) {
r = (arc4random() % 100);
system("PAUSE");
return 0;
}
```
Its pretty straight forward, except compiler gives me an error, what am I doing wrong?Thanks,Oliver.
|
Including C files is not a good practice in C programming, except in some cases with automatically-generated code.
Instead, all the source files should be passed to the compiler and you should only include header files which contain function prototypes and type definitions.
|
I'm getting this error when I try and compile my program on my school's external server.
```
Undefined first referenced
symbol in file
pow /var/tmp//ccWbipvM.o
sqrt /var/tmp//ccWbipvM.o
ld: fatal: Symbol referencing errors. No output written to assign1
collect2: ld returned 1 exit status
```
The problem is I don't get it when I compile it locally - it runs fine. Can anyone give me some advice as to what the problem is here?? Thanks!
PS: math.h has been included.
|
Trylinkingyour program with the math library by using the-lmflag:
```
gcc -o prg -lm prg.c
```
|
I have built a small code for static analysis of C code. The purpose of building it is to warn users about the use of methods such as strcpy() which could essentially cause buffer overflows.
Now, to formalise the same, I need to write a formal Grammar which shows the excluded libraries as NOT a part of the allowed set of accepted library methods used.
For example,
AllowedSentence->ANSI C Permitted Code, NOT UnSafeLibraryMethods
UnSafeLibraryMethods->strcpy|other potentially unsafe methods
Any ideas on how this grammar can be formalised?
|
I think, this should not be done at the grammar level. It should be a rule that is applied to the parse tree after parsing is done.
|
I find little things like this throughout the C programming language; something that is very easy to provide, has very little chance of breaking old code, and has an obvious way to standardize it. Is minimalism the reason?
|
Because they're trivial to compute if you have the "standard" trig functions?
|
When I use Xcode (3.1.4 Leopard) to code in plain C (using the "Standard Tool" template that creates a "main.c"), the compiler behaves like aC++compiler. It allows single-line comments (like "// comment here"), it allows declaring a variable in the for-loop initializer (like "for(inti = 0; ...)"), it even allows inline functions (but then the linker reports that the symbol couldn't be found, great).
How can I set it to be more strict? I'm worried about accidentally writing C++ and having to correct a lot of code once I compile it on a different system.
Also, is it normal that Xcode won't auto-close brackets when you're not writing Objective C?
Thanks for any advice! :)
|
All of those so-called "C++ features" are in fact part of C. All three were added in C99.
If you are compiling using GCC, you can use the-std=c89to force the compiler into C89/C90 mode.
|
I am wondering how to compile the source code of libdvdcss using Xcode on Mac OS X? The filebsdi_ioctl.chas include statements for/sys/dev/scsi/scsi.hand/sys/dev/scsi/scsi_ioctl.h.
What I did is run./bootstrapand./configureto generate theconfig.hfirst, but I still got the problem.
Can anyone shed some light on it?
|
It is unusual that your Makefile will be trying to include those files as the autoconf file has an instruction to look for them before including them in your Makefile. But whatever the reason, you have a couple options for compiling:
Edit src/Makefile. Search for$(bsdi_sources)and delete all occurrences then re-make (do not reconfigure)orEdit configure.ac. Search forAM_CONDITIONAL(SYS_BSDIand replace withSYS_BSDI='0'. Then re-run ./bootstrap & ./configureorRunSYS_BSDI="0" ./configure(single command) to re-make without.
|
Sohereis shown a simple example - 2 floats as data + 1 float as output:
```
Layer 1: 2 neurons (2 inputs)
Layer 2: 3 neurons (hidden layer)
Layer 3: 3 neurons (hidden layer)
Layer 4: 1 neurons (1 output)
```
And we create ANs with something like
```
cvSet1D(&neuralLayers1, 0, cvScalar(2));
cvSet1D(&neuralLayers1, 1, cvScalar(3));
cvSet1D(&neuralLayers1, 2, cvScalar(3));
cvSet1D(&neuralLayers1, 3, cvScalar(1));
```
And than we just tall openCV to train our network.
I wonder if we had Nx2 floats of data + 1 float as for output and we would want to give first neuron as input first line (N floats) and to second neuron second line (N float data elements) what would we need to add to our code?
|
I would definitely use the KNN mentioned.
|
What are typical uses ofnull statement
```
;
```
in C ?
I know that it is basically used to skip expression where it is expected by the compiler, but here I'm interested only in real-world examples of such use cases.
|
It's typically the side-effect of a code block that was stripped by the preprocessor, like
```
#if DEBUG
#define ASSERT(_x) Assert(_x)
#else
#define ASSERT(_x)
#endif
ASSERT(test); // Results in null statement in non-debug builds
```
That, or in loops where your condition already contains whatever needs to be done in each iteration.
|
I'm looking for an algorithm to find the date of a day in the future, which is in N days from today.
My main problem is how to deal with leap years in the middle.
|
If I take your question correctly, your best option is to do the following:
Convert a date into a number, where the number signifies the number of days since a specific dateAdd N to that numberConvert the results back into a date
You can do this using the julian day number for a date.
See theWikipedia article on Julian Day Number (JDN)for more information.
Having said that, if you're actually using a modern programming language, most have facilities to deal with dates already, such as Java, C#/.NET, Python, etc.
|
I am working on some core audio code and have a problem that could be solved by a variable array in a struct--a la Flexible Array Members. In doing a bit of looking around, I see that there is a lot of dialogue about the portability and viability of Flexible Member Arrays.
From what I understand, Objective-C is C99 compliant. For this reason, I think Flexible Array Members should be a fine solution. I also see that Flexible Array Members are not a good idea in C++.
What to do in Objective-C++? Technically, I won't use it in Objective-C++. I am writing callbacks that are C and C++ based... That seems like a point against.
Anyway, can I (should I) do it? If not, is there another technique with the same results?
|
You can always just declare a trailing array of size 1. In the worst case here, you waste a pretty small amount of memory, and it is very slightly more complicated to compute the right size for malloc.
|
I am learning C language and I use code::blocks IDE to write and build C programs. It uses GNU C compiler. I learnt that there are many ways to optimize the code by tweaking the compiler settings and using compilers command. I can see many options to change compiler's setting from the menu. But I don't know how and where to apply the compilers commands? Any help is appreciated..
|
Under the Settings menu, select Compiler and Debugger. Select GNU GCC Compiler at the top. Go to the Compiler Settings tab, and within that select the Compiler Flags tab. Scroll about halfway down, and you'll find all of the "-O" related options.
|
Inkernel.hmin is defined as:
```
#define min(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
```
I don't understand what the line(void) (&_min1 == &_min2);does. Is it some kind of type checking or something?
|
The statement
```
(void) (&_min1 == &_min2);
```
is a guaranteed "no-op". So the only reason it's there is for its side effects.
But the statement has no side effects!
However:it forces the compiler to issue a diagnostic when the types ofxandyare not compatible.Note that testing with_min1 == _min2would implicitly convert one of the values to the other type.
So, that is what it does.It validates, at compile time, that the types ofxandyare compatible.
|
Is it possible to implement thecontainer_ofmacro in pure C90? I'm not sure how to do it as the Kernel implementation depends onGCC Hackssuch as thetypeofoperator.
I'm asking because I would like to implement a generic container in C90 similar to the Kernel'slinked list. The actual container I'm thinking of is a sequenced set similar to what you might get fromBoost MultiIndex.
|
The use oftypeofin the kernel definition ofcontainer_of()is just for compile-time type-checking - it ensures that the passedptris really a pointer to the same type asmember. It can be modified to be entirely ANSI C at the cost of this type-checking:
```
#define container_of(ptr, type, member) ((type *)((char *)ptr - offsetof(type, member)))
```
(offsetof()is in<stddef.h>)
|
I find little things like this throughout the C programming language; something that is very easy to provide, has very little chance of breaking old code, and has an obvious way to standardize it. Is minimalism the reason?
|
Because they're trivial to compute if you have the "standard" trig functions?
|
When I use Xcode (3.1.4 Leopard) to code in plain C (using the "Standard Tool" template that creates a "main.c"), the compiler behaves like aC++compiler. It allows single-line comments (like "// comment here"), it allows declaring a variable in the for-loop initializer (like "for(inti = 0; ...)"), it even allows inline functions (but then the linker reports that the symbol couldn't be found, great).
How can I set it to be more strict? I'm worried about accidentally writing C++ and having to correct a lot of code once I compile it on a different system.
Also, is it normal that Xcode won't auto-close brackets when you're not writing Objective C?
Thanks for any advice! :)
|
All of those so-called "C++ features" are in fact part of C. All three were added in C99.
If you are compiling using GCC, you can use the-std=c89to force the compiler into C89/C90 mode.
|
I am wondering how to compile the source code of libdvdcss using Xcode on Mac OS X? The filebsdi_ioctl.chas include statements for/sys/dev/scsi/scsi.hand/sys/dev/scsi/scsi_ioctl.h.
What I did is run./bootstrapand./configureto generate theconfig.hfirst, but I still got the problem.
Can anyone shed some light on it?
|
It is unusual that your Makefile will be trying to include those files as the autoconf file has an instruction to look for them before including them in your Makefile. But whatever the reason, you have a couple options for compiling:
Edit src/Makefile. Search for$(bsdi_sources)and delete all occurrences then re-make (do not reconfigure)orEdit configure.ac. Search forAM_CONDITIONAL(SYS_BSDIand replace withSYS_BSDI='0'. Then re-run ./bootstrap & ./configureorRunSYS_BSDI="0" ./configure(single command) to re-make without.
|
Sohereis shown a simple example - 2 floats as data + 1 float as output:
```
Layer 1: 2 neurons (2 inputs)
Layer 2: 3 neurons (hidden layer)
Layer 3: 3 neurons (hidden layer)
Layer 4: 1 neurons (1 output)
```
And we create ANs with something like
```
cvSet1D(&neuralLayers1, 0, cvScalar(2));
cvSet1D(&neuralLayers1, 1, cvScalar(3));
cvSet1D(&neuralLayers1, 2, cvScalar(3));
cvSet1D(&neuralLayers1, 3, cvScalar(1));
```
And than we just tall openCV to train our network.
I wonder if we had Nx2 floats of data + 1 float as for output and we would want to give first neuron as input first line (N floats) and to second neuron second line (N float data elements) what would we need to add to our code?
|
I would definitely use the KNN mentioned.
|
What are typical uses ofnull statement
```
;
```
in C ?
I know that it is basically used to skip expression where it is expected by the compiler, but here I'm interested only in real-world examples of such use cases.
|
It's typically the side-effect of a code block that was stripped by the preprocessor, like
```
#if DEBUG
#define ASSERT(_x) Assert(_x)
#else
#define ASSERT(_x)
#endif
ASSERT(test); // Results in null statement in non-debug builds
```
That, or in loops where your condition already contains whatever needs to be done in each iteration.
|
I'm looking for an algorithm to find the date of a day in the future, which is in N days from today.
My main problem is how to deal with leap years in the middle.
|
If I take your question correctly, your best option is to do the following:
Convert a date into a number, where the number signifies the number of days since a specific dateAdd N to that numberConvert the results back into a date
You can do this using the julian day number for a date.
See theWikipedia article on Julian Day Number (JDN)for more information.
Having said that, if you're actually using a modern programming language, most have facilities to deal with dates already, such as Java, C#/.NET, Python, etc.
|
I am working on some core audio code and have a problem that could be solved by a variable array in a struct--a la Flexible Array Members. In doing a bit of looking around, I see that there is a lot of dialogue about the portability and viability of Flexible Member Arrays.
From what I understand, Objective-C is C99 compliant. For this reason, I think Flexible Array Members should be a fine solution. I also see that Flexible Array Members are not a good idea in C++.
What to do in Objective-C++? Technically, I won't use it in Objective-C++. I am writing callbacks that are C and C++ based... That seems like a point against.
Anyway, can I (should I) do it? If not, is there another technique with the same results?
|
You can always just declare a trailing array of size 1. In the worst case here, you waste a pretty small amount of memory, and it is very slightly more complicated to compute the right size for malloc.
|
I am learning C language and I use code::blocks IDE to write and build C programs. It uses GNU C compiler. I learnt that there are many ways to optimize the code by tweaking the compiler settings and using compilers command. I can see many options to change compiler's setting from the menu. But I don't know how and where to apply the compilers commands? Any help is appreciated..
|
Under the Settings menu, select Compiler and Debugger. Select GNU GCC Compiler at the top. Go to the Compiler Settings tab, and within that select the Compiler Flags tab. Scroll about halfway down, and you'll find all of the "-O" related options.
|
Inkernel.hmin is defined as:
```
#define min(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
```
I don't understand what the line(void) (&_min1 == &_min2);does. Is it some kind of type checking or something?
|
The statement
```
(void) (&_min1 == &_min2);
```
is a guaranteed "no-op". So the only reason it's there is for its side effects.
But the statement has no side effects!
However:it forces the compiler to issue a diagnostic when the types ofxandyare not compatible.Note that testing with_min1 == _min2would implicitly convert one of the values to the other type.
So, that is what it does.It validates, at compile time, that the types ofxandyare compatible.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.