question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I'm trying to create a hash from an array and the documentation forhttp://ruby-doc.org/ruby-1.9/classes/Array.src/M000744.htmlshows an internal ruby method called ary_make_hash. The source uses this to diff arrays. The relevant line in the source is: ary_make_hash(to_ary(ary2), 0);
Is there a way to access the ary_make_hash function and other internal Ruby functions from inside Ruby? I ask since I'm trying to convert a huge array to a hash and I'd love to use the built in C methods since they're so much faster. (FYI I can see the speed difference by subtracting two arrays, which internally invokes the converter method). Thanks for any thoughts.
Robert
|
in general if it's not in ruby.h, then it's not a "public" api
looking for a method called rb_xxx might also help.
GL.
|
Currently I have a client process and a server process. The client process needs to contact the server process every so often to exchange data, but needs to know the server's pid to do so. How should the client know how to do this? I want to avoid repeated hard disk access. This application runs only under linux. Currently the server sets up a lock file with its pid which lives or a RAM disk. The client checks the file. How else can I accomplish this transaction efficiently such that the server can send a signal to the client? (note: client is PHP, server is c)
|
Some ideas:
do nothing; if you repeatedly read it, reading a disc file (on a proper, permanent disc) will not cause any IO, because the file will already be in cache.Refactor your system so you don't need to know the pid fileAre you sure that you really care? Premature optimisation and all that. How many times per second are you doing this, 1000 or more?
|
I have a question on the relative position of C header files. I noticed that my code will work if the C header files were placed in a particular position, otherwise it will fail without errors.
Any reason why? Sorry to ask, newbie here.
|
The problem is that importing headers in C and C++ are basically code insertion, similar to a macro, into that point in the file that is being compiled.
If two different header files define the same symbol (for example, there are dozens of different possible failure scenarios with header files) you'll get a compiler error. You don't provide enough information to track down your specific problem, but in general, header file ordershould notmatter -- unless the header file is poorly written.
I suggest you perform a very thorough review of your header files.
|
I'm getting errors while compiling with-ansi -pedanticon lines that have// Comment here. Why does this happen?
expected expression before '/' tokenstray '\347' in program
Example codeint someVariable = 0; // Some comment
I have many many errors of these, what is it?
|
C89 does not support C++-style comments.
|
Both has bindings for C, both can play various formats.
Which one is more superior? in terms of simplicity, performance, overhead and memory footprint.
Also which one is better at handling multiple streams?
|
I have not programmed with either of those, but I believe that OpenAL has beendesignedto render and output multiple-channel audio for games, with real-time performance as a requirement.
libSoX is more for input and output from audio files, as well as for format conversions. There are lots of plugins but AFAIK it has not been designed for real-time audio output. It seems significantly simpler to use, though.
You might also want to have a look atlibsndfile.
What exactly is it that you want to do?
|
Why is the imho missing indentation of the "case" - keywords in a switch statement considered good style?
No indentation of the "case" keyword seems to be the default formatting option in about every IDE:
```
switch (i){
case 0:
break;
case 1:
break;
}
```
while I find this format more intuitive:
```
switch (i){
case 0:
break;
case 1:
break;
}
```
Is there some logic behind this, that eludes me?
|
The cases are logically labels. Many people put labels at the same indentation level as the block they are in. In my opinion, that way it's easier to read through the text.
I compare it with a timeline you can scroll through. You have markers on the time line itself, not indented into the content. You can then quickly point out where labels/markers are, without moving your eye away from the base-line.
|
Kind of trivial thing but ...
I want to print japanese characters using plain C from Hexadecimals
Fromthis table, I know that, the first char in the table, あ's Entity is &# 12353 and its Hex Entity is x3041, etc.
But how do I use this two numbers in order to get printed all characters in the command line?
|
If your terminal is set to UTF-8 and locale is set correctly, you may write:
```
char s[]="あ";
```
you can also try
```
char s[]={0xe3,0x81,0x82,0x0}
```
(the last is the Unicode UTF-8 encoding for "あ"), and then justprintf("%s",s);
|
What would be the best way to copy unsigned char array to another?
For example:
```
unsigned char q[1000];
unsigned char p[1000];
strcpy (q,&p);
```
The above code does not work, it gives me error saying "cannot convert parameter 1 from unsigned char [1000] to char *".
|
As indicated by its name,strcpyworks on C string (which a unsigned char array is not).
You should considermemcpy.
|
Ie, how to get keystrokes send directly to my program without waiting for the user to press enter. Basicly I'm trying get something like curses'scbreak()call. (But I can't use curses due a couple of bugs/misfeatures that I haven't been able to work around.) This seems like something that should just be a trival escape sequence, but I haven't been able find anything.
|
Lookuptermiosand thetcsetattrfunction.
|
I have made the following #defines
```
#define GOLD 1;
#define SILVER 2;
```
later in my program I set up some variables
```
int source, target;
```
They are then set to the values:
```
source = GOLD;
target = SILVER;
```
I now want to compare in an if statement:
```
if(source == GOLD) {...}
```
But the compiler complains Expected ')' before ';' token. If I change the line to
```
if(source == 1) {...}
```
There is no problem with the compiler or the behavior. How do I reference the #define in the if statement to make myself clear to the compiler?
|
Because you have an errant;after the#define GOLD 1and#define SILVER 2. Remove them, your problem will go away.
|
I have a pointer that's holding 100 bytes of data.
i would like to add 5 to every 2nd byte.
example:
```
1 2 3 4 5 6
```
will become:
```
1 7 3 9 5 11
```
Now i know i can do a for loop, is there a quicker way? something like memset that will increase the value of every 2nd byte ?
thanks
|
A loop would be the best way. memset() is efficient for setting a contiguous block of memory. Wouldn't be much help for you here.
|
```
struct node
{
void *data;
struct node *link;
};
```
Given such a structure we call it as generic linked list.what is the use of such a list in terms of its real time application use.
|
It's genericness allows you to create some (tested and reliable) library code around it, which can then be reused.
Of course it's not typesafe this way, that's why C++ introduced (among other things) generic template classes.
As for the use of a linked list per se: you use it where you want to store and retrieve a variable number of similar objects. Typically you don't know the number of the objects in advance and you are fine with getting them in the order you stored them. It's also quite efficient to delete an object from a linked list (once you have a pointer to its list entry).
|
e.g. quake engines have
```
typedef enum {qfalse, qtrue} qboolean;
```
When one does
```
static qboolean variable;
```
Is the variable's start-up value 0?
|
static and global variables are cleared by default, if there is no value assigned at initialization.
In your examplevariablewill have the enum's equivalent of0, i.e.qfalse.
|
can any one please elaborate how to find largest of four numbers without using conditional operator.for 3 numbers i have done but for four numbers how to write different comparisons.
|
There is a standard way to computeminormaxin 2's complement arithmetics without using conditionals:
```
int max(int a, int b){
unsigned diff = b - a; // negative if a > b
int sign = -(diff >> (sizeof(int) * CHAR_BIT - 1)); // -1 if a > b, 0 otherwise
return (a & sign) | (b & ~sign);
}
```
it can be easily scaled.
|
This question already has answers here:What are the best (portable) cross-platform arbitrary-precision math libraries? [closed](5 answers)Closed9 years ago.
I need the fastest library that is available for C++. My platform will be x86 and x86-64 which supports floating points.
|
GMPLIB
GMP is a free library for arbitrary precision arithmetic, operating on signed ... C++ class based interface to all of the above.
|
What is assumed to be the preferred way to fix "comparison between signed and unsigned integer" warnings safely? In my case I have to compare some uint_32 variables with #define constants.
Really simplified:
```
#define MAX(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; })
#define c (10)
unsigned int d = 11;
if(MAX(c,d)>10){
//...
}
```
But I havereallya lot of such cases - what would you suggest to solve this?
|
In this case, you can just change your constant to be unsigned as well:
```
#define c 10U
```
or alternatively, use a cast so that thetypeofin your macro creates anunsignedvariable:
```
if (MAX((unsigned)c, d) > 10) {
```
|
Which should I use to link for mysqlclient library? What is the difference between them? I can't seem to find the answer. Thanks.
|
Newer versions of the MySQL client distributions do not include the "_r" version. Some may have a symbolic link from libmyqslclient_r.a to libmyqslclient.a
|
How does the const qualification on variables differ in C and C++?
from:Does "const" just mean read-only or something more?
"What prompted this question was this answer:https://stackoverflow.com/questions/4024318#4024417where he states const "just" means read-only in C. I thought that's all const meant, regardless of whether it was C or C++. What does he mean?"
|
constin C cannot be used to build constant expressions.
For example :
```
#include <stdio.h>
int main()
{
int i = 2;
const int C = 2;
switch(i)
{
case C : printf("Hello") ;
break;
default : printf("World");
}
}
```
doesn't work in C because case label does not reduce to an integer constant.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question
does someone know good literature for C/C++?
language: german/english
thanks
|
This is the classic treatsie ...
Smashing The Stack For Fun And Profitl
|
I'm porting a header with this declaration:
```
struct tMaterialInfo {
char strName[255]; // the texture name
char strFile [255]; // the texture
BYTE color [3]; // the color of the object
};
```
The header has the following includes:
```
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include <vector>
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include<gl\glu.h>// Header File For The GLu32 Library
#include <gl\glaux.h>
```
Where does that BYTE come from?
|
I'm guessing it's fromWindows.
A byte (8 bits).This type is declared in WinDef.h as follows:typedef unsigned char BYTE;
|
I've seen this operator pop up quite a few times in example code in "Learn Objective C on the Mac."
I believe it's an operator in the C language which Objective C inherits.
I tried Googling and searching Stack Overflow and oddly nothing came up.
Does it have an English name?
|
It has to do with structures.
When we have a struct available locally on the stack, we access its members with the.operator. For example:
```
CGPoint p = CGPointMake(42,42);
NSLog(@"%f", p.x);
```
However, if we instead have apointerto a structure, we have to use the->operator:
```
CGPoint *p = malloc(1*sizeof(CGPoint));
p->x = 42.0f;
NSLog(@"%f", p->x);
free(p);
```
|
In my Fedora 12, when I run this for just a test, it shows a window but then it shows nothing like its frozen. And, it keeps my terminal image instead of video source.
```
$ gst-launch-0.10 v4l2src ! xvimagesink
```
or
```
$ gst-launch-0.10 autovideosrc ! autovideosink
```
How to do a test loopback, not having my screen shot inside the popup window?
|
This works:
```
$ gst-launch videotestsrc ! ffmpegcolorspace ! ximagesink
```
Which means, I have colorspace problem while using autovideosink. Any experts tips, would be appreciated.
Thanks
|
Which one is the fastest/least memory consuming option of these two:
```
struct {
int index;
char string[10];
} a[10];
```
or
```
struct {
int index[10];
char string[10][10];
} a;
```
The first one is clearly easier to use and implement. I also have to mention I will dynamically allocate them. But which one will run faster or be least time consuming?
Thank you!
|
```
struct {
int index;
char string[10];
} a[10];
```
will introduce padding for eacha[]item.
The second solution will introduce padding only once.
If you are going to allocate a large number of items ina[]then you will pay the price of having a larger domain to cover (not to mention the additional dereferencing).
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question
Please let me know what this C inCprogramming and C++ programming is used for? I'm serious as this question was put in front of me in an interview.
|
Nothing at all. It was just the successor of B, which was a stripped-down version of BCPL.
|
I would like to write a custom GlusterFS Translator for file encryption with AES. Besides this rather rare description:http://europe.gluster.org/community/documentation/index.php/GlusterFS_Contributors_FAQ, is there any other documentation on writing a custom Translator?
|
Maybe HekaFS is what you need, it already has a encryption translator.
|
Have a question abouttypedefin C.
I have defined struct:
```
typedef struct Node {
int data;
struct Node *nextptr;
} nodes;
```
How would I createtypedefpointers tostructNode ??
Thanks !
|
You can typedef them at the same time:
```
typedef struct Node {
int data;
struct Node *nextptr;
} node, *node_ptr;
```
This is arguably hard to understand, but it has a lot to do with why C's declaration syntax works the way it does (i.e. whyint* foo, bar;declaresbarto be an int rather than anint*
Or you can build on your existing typedef:
```
typedef struct Node {
int data;
struct Node *nextptr;
} node;
typedef node* node_ptr;
```
Or you can do it from scratch, the same way that you'd typedef anything else:
```
typedef struct Node* node_ptr;
```
|
```
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
```
In the above code, which character will break the loop?I am new to C, please help me.Also, what is it meant by this error:codec5.c:8:2: warning: no newline at end of file
|
The warning just means that you need to have a new line at the end of your source code. Put your cursor at the last}in your file at the end ofmain()and press enter.
You need to check for a specific character to end the program if you are not loading from a file. If you pipe (|) (<in Windows) a file into your program, then the program should end. If your program is namedtest.exeand your input file isfoo.txt, try runningtest.exe < foo.txt(make sure they are in the same directory).
|
I think it's the very first strtok call that's failing. It's been a while since I've written C and I'm at a loss. Thanks very much.
```
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char *str = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
```
|
String literals should be assigned to a const char*, as modifying them is undefined behaviour. I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.
|
memmove doesn't really move memory isn't that right? It just copies memory from one region to other and allows those two regions to overlap. I'm asking this question because I just want to know why is this fnc called in very misleading manner.For I understand that when something is moved from one place to the other, the "thingy" is after this operation in the other place and not in the first. And with memmove it doesn't work that way. Am I right?
|
You are right, it copies it. However, there is a difference betweenmemmoveandmemcpy, becausememmovecan treat correctly the case when the buffers overlap, so it is recomended in these cases.
However, because of additional checks thatmemmoveperforms, when the buffers are small and surely does not overlap,memcpyis better.
|
So I have G++ installed, I can eselycapture from main camera with OpenCV (at least 4 fps). But I also want to capture Live sound from mic. What are my options?
|
Take a look atQT for Maemo. It should handle the capturing part. Not sure about openCV though.
|
I'm having a hard time understanding what the WINAPI tag is with respect to c.
For example:
BOOL WINAPI CreateProcessA( ...);
What exactly is this WINAPI tag, does it have more formal name, and is it part of c or implementation specific?
Sorry if my question is a bit confusing.
Many Thanks!
|
It is thecalling convention, normally defined as__stdcallfor Windows.
|
I am looking for a real (source and generated code) example of software pipelining (http://en.wikipedia.org/wiki/Software_pipelining) produced by GCC. I tried to use-fmodulo-schedoption when compiling for IA64 and PowerPC architectures by GCC versions 4.4-4.6 with no success.
Are you aware about such example? The actual CPU architecture has no difference.
Thank you
|
There are some tests from gcc testsuite for "-fmodulo-sched" option. You can check them:
http://www.google.com/codesearch/p?hl=en#OV-zwmL9vlY/gcc/gcc/testsuite/gcc.dg/sms-1.c&q=sms-6.c&d=4
files sms-1.c --- sms-7.c
Also here,http://gcc.gnu.org/viewcvs/trunk/gcc/testsuite/gcc.dg/but gnu's viewcvs is very slow. The sms-8.c is added.
|
So, to start off, here's the code, with actual names switched for generic ones to limit confusion.
```
/* Get the list of Hotkey commands */
#define A_COMMANDS_MACRO(a, b, c, d) a = b ,
enum {
#include "commandsFile.def"
} ;
#undef A_COMMANDS_MACRO
```
This is a snippet from some source code I have been looking over and considering forking as a way to familiarize myself with the intricacies of theCprogramming language. So, to my untrained eye, this appears to do nothing. To my brain, defining something and then immediately undefining it would seem to cancel each other out.
Obviously, I realize that I'm wrong. But why am I wrong?
|
The "commandsFile.def" file probably uses the "A_COMMANDS_MACRO" macro somewhere internally.
Remember that "#include" essentially pastes the included file into the including one, so the #define is still in effect when "commandsFile.def" is processed.
|
What are the differences between,
```
malloc ( sizeof ( char ) * N )
```
and
```
size_t datalen = N
malloc ( datalen )
```
Where should we usesize_tinstead ofsizeof ( char )and vice versa?
Are there any performance difference betweensize_tandsizeof ( char )?
|
size_tis an unsigned integer type guaranteed to support the longest object for the platform you use. It is also the result of thesizeofoperator.sizeofreturns the size of the type in bytes.So in your context of question in both cases you pass asize_ttomalloc
|
I have a server which receives and sends data.
When i make server down, I wish to stop receiving the data abruptly but wish to keep the send active so that the data in buffer is sent.
IS there any params to be set during setsockopt and any other option as closing the socket will close both send and receive.
Thanks,
|
You can use theshutdown()function to do this. Fromman 2 shutdown:
SYNOPSIS#include <sys/socket.h>
int shutdown(int s, int how);DESCRIPTIONThe shutdown() call causes all or part of a full-duplex connection on the
socket associated with s to be shut down. If how is SHUT_RD, further
receives will be disallowed. If how is SHUT_WR, further sends will be
disallowed. If how is SHUT_RDWR, further sends and receives will be dis-
allowed.
|
Is it possible to implement OS independent threading model of User Level Threads (ULT) in C/C++? In other words, can we break down a process logically into ULTs and dynamically make switches in between them?
|
Boost.Thread offers a fair amount of abstraction for cross-platform threading.
|
I have a string.
```
char foo[] = "abcdefgh";
```
I would like to write aforloop, and one by one print out all of the characters:
```
a
b
c
```
etc.
This is in C.
|
Ok, well, this is a question so I'm going to answer it, but my answer is going to be slightly unusual:
```
#include <stdio.h>
int main(int argc, char** argv)
{
char string[] = "abcdefghi";
char* s;
for ( s=&string[0]; *s != '\0'; s++ )
{
printf("%c\n", *s);
}
return 0;
}
```
Thisis notthe simplest way to achieve the desired outcome; however, it does demonstrate the fundamentals of what a string is in C. I shall leave you to read up on what I've done and why.
|
What is assumed to be the preferred way to fix "comparison between signed and unsigned integer" warnings safely? In my case I have to compare some uint_32 variables with #define constants.
Really simplified:
```
#define MAX(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; })
#define c (10)
unsigned int d = 11;
if(MAX(c,d)>10){
//...
}
```
But I havereallya lot of such cases - what would you suggest to solve this?
|
In this case, you can just change your constant to be unsigned as well:
```
#define c 10U
```
or alternatively, use a cast so that thetypeofin your macro creates anunsignedvariable:
```
if (MAX((unsigned)c, d) > 10) {
```
|
Which should I use to link for mysqlclient library? What is the difference between them? I can't seem to find the answer. Thanks.
|
Newer versions of the MySQL client distributions do not include the "_r" version. Some may have a symbolic link from libmyqslclient_r.a to libmyqslclient.a
|
How does the const qualification on variables differ in C and C++?
from:Does "const" just mean read-only or something more?
"What prompted this question was this answer:https://stackoverflow.com/questions/4024318#4024417where he states const "just" means read-only in C. I thought that's all const meant, regardless of whether it was C or C++. What does he mean?"
|
constin C cannot be used to build constant expressions.
For example :
```
#include <stdio.h>
int main()
{
int i = 2;
const int C = 2;
switch(i)
{
case C : printf("Hello") ;
break;
default : printf("World");
}
}
```
doesn't work in C because case label does not reduce to an integer constant.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question
does someone know good literature for C/C++?
language: german/english
thanks
|
This is the classic treatsie ...
Smashing The Stack For Fun And Profitl
|
I'm porting a header with this declaration:
```
struct tMaterialInfo {
char strName[255]; // the texture name
char strFile [255]; // the texture
BYTE color [3]; // the color of the object
};
```
The header has the following includes:
```
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include <vector>
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include<gl\glu.h>// Header File For The GLu32 Library
#include <gl\glaux.h>
```
Where does that BYTE come from?
|
I'm guessing it's fromWindows.
A byte (8 bits).This type is declared in WinDef.h as follows:typedef unsigned char BYTE;
|
I've seen this operator pop up quite a few times in example code in "Learn Objective C on the Mac."
I believe it's an operator in the C language which Objective C inherits.
I tried Googling and searching Stack Overflow and oddly nothing came up.
Does it have an English name?
|
It has to do with structures.
When we have a struct available locally on the stack, we access its members with the.operator. For example:
```
CGPoint p = CGPointMake(42,42);
NSLog(@"%f", p.x);
```
However, if we instead have apointerto a structure, we have to use the->operator:
```
CGPoint *p = malloc(1*sizeof(CGPoint));
p->x = 42.0f;
NSLog(@"%f", p->x);
free(p);
```
|
In my Fedora 12, when I run this for just a test, it shows a window but then it shows nothing like its frozen. And, it keeps my terminal image instead of video source.
```
$ gst-launch-0.10 v4l2src ! xvimagesink
```
or
```
$ gst-launch-0.10 autovideosrc ! autovideosink
```
How to do a test loopback, not having my screen shot inside the popup window?
|
This works:
```
$ gst-launch videotestsrc ! ffmpegcolorspace ! ximagesink
```
Which means, I have colorspace problem while using autovideosink. Any experts tips, would be appreciated.
Thanks
|
Which one is the fastest/least memory consuming option of these two:
```
struct {
int index;
char string[10];
} a[10];
```
or
```
struct {
int index[10];
char string[10][10];
} a;
```
The first one is clearly easier to use and implement. I also have to mention I will dynamically allocate them. But which one will run faster or be least time consuming?
Thank you!
|
```
struct {
int index;
char string[10];
} a[10];
```
will introduce padding for eacha[]item.
The second solution will introduce padding only once.
If you are going to allocate a large number of items ina[]then you will pay the price of having a larger domain to cover (not to mention the additional dereferencing).
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question
Please let me know what this C inCprogramming and C++ programming is used for? I'm serious as this question was put in front of me in an interview.
|
Nothing at all. It was just the successor of B, which was a stripped-down version of BCPL.
|
I would like to write a custom GlusterFS Translator for file encryption with AES. Besides this rather rare description:http://europe.gluster.org/community/documentation/index.php/GlusterFS_Contributors_FAQ, is there any other documentation on writing a custom Translator?
|
Maybe HekaFS is what you need, it already has a encryption translator.
|
Have a question abouttypedefin C.
I have defined struct:
```
typedef struct Node {
int data;
struct Node *nextptr;
} nodes;
```
How would I createtypedefpointers tostructNode ??
Thanks !
|
You can typedef them at the same time:
```
typedef struct Node {
int data;
struct Node *nextptr;
} node, *node_ptr;
```
This is arguably hard to understand, but it has a lot to do with why C's declaration syntax works the way it does (i.e. whyint* foo, bar;declaresbarto be an int rather than anint*
Or you can build on your existing typedef:
```
typedef struct Node {
int data;
struct Node *nextptr;
} node;
typedef node* node_ptr;
```
Or you can do it from scratch, the same way that you'd typedef anything else:
```
typedef struct Node* node_ptr;
```
|
```
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
```
In the above code, which character will break the loop?I am new to C, please help me.Also, what is it meant by this error:codec5.c:8:2: warning: no newline at end of file
|
The warning just means that you need to have a new line at the end of your source code. Put your cursor at the last}in your file at the end ofmain()and press enter.
You need to check for a specific character to end the program if you are not loading from a file. If you pipe (|) (<in Windows) a file into your program, then the program should end. If your program is namedtest.exeand your input file isfoo.txt, try runningtest.exe < foo.txt(make sure they are in the same directory).
|
I think it's the very first strtok call that's failing. It's been a while since I've written C and I'm at a loss. Thanks very much.
```
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char *str = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
```
|
String literals should be assigned to a const char*, as modifying them is undefined behaviour. I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.
|
memmove doesn't really move memory isn't that right? It just copies memory from one region to other and allows those two regions to overlap. I'm asking this question because I just want to know why is this fnc called in very misleading manner.For I understand that when something is moved from one place to the other, the "thingy" is after this operation in the other place and not in the first. And with memmove it doesn't work that way. Am I right?
|
You are right, it copies it. However, there is a difference betweenmemmoveandmemcpy, becausememmovecan treat correctly the case when the buffers overlap, so it is recomended in these cases.
However, because of additional checks thatmemmoveperforms, when the buffers are small and surely does not overlap,memcpyis better.
|
I need to find the path of where my program is running.
Using argv[0] doesn't seem to work because the program has to be run on the windows console, for example,C:\ >player parameter1 parameter2and I only get player on argv[0].
How can I accomplish this?
|
You can use Windows'GetModuleFileNamefunction to obtain the path of the executable by setting thehModuleparameter toNULL.
|
Is it possible?
```
typedef struct {
listLink *next;
listLink *prev;
void *data;
} listLink;
```
|
Yes, with this syntaxis
```
struct list {
int value;
struct list *next;
};
```
or
```
typedef struct list
{
int value;
struct list *next;
} list;
```
|
Is there any way to get all opened sockets usingc++? I know thelsofcommand and this is what I'm looking for, but how to use it in ac++application?
The idea is to get the FD of an opened socket by itsportnumber and thepid.
|
Just open the files in /proc/net, like /proc/net/tcp, /proc/net/udp, etc. No need to slog through the lsof sources. :)
|
This was my Interview question in HP. I answered a++ takes less instruction compared to a = a +1;
I want to know which is useful in efficient programming, and how both are different from each other..?
Hoping for quick and positive response..
|
In C, there would be no difference, if the compiler is smart.
In C++, it depends on what typeais, and whether the++operator is overloaded. To complicate matters even more, the=operator can be overloaded too, anda = a + 1might not be the same asa++. For evenmorecomplication, the+operator can also be overloaded, so an innocent looking piece of code such asa = a + 1might have drastic implications.
So, without some context, you simply cannot know.
|
```
typedef struct Matrix
{
double * matrix;
int sizex;
int sizey;
}Matrix;
int nn = 257;
Matrix * g = (Matrix *)malloc(sizeof(Matrix *));
g->matrix = malloc(sizeof(double) * nn * nn);
g->sizex = nn;
g->sizey = nn;
```
This code give an error when it gets tog->matrix = malloc(sizeof(double) * nn * nn);anyone see a problem with it ?
edit: found problem to be accessing unallocated memory in a place before the allocation shown, it was causing a SIGSEGV:Segmentation fault.
|
You need to passmallocthe sizeof theMatrixnot sizeofpointerto theMatrix.
Change
```
Matrix * g = (Matrix *)malloc(sizeof(Matrix *));
^^
```
to
```
Matrix * g = (Matrix *)malloc(sizeof(Matrix));
```
Also youmustalways check the return value ofmallocand make sure allocation succeed before you go and use the allocated memory.
|
I was just curious to know if it is possible to have a pointer referring to #define constant. If yes, how can I do it?
|
The#definedirective is a directive to thepreprocessor, meaning that it is invoked by the preprocessor before anything is even compiled.
Therefore, if you type:
#define NUMBER 100
And then later you type:
int x = NUMBER;
What your compiler actuallyseesis simply:
int x = 100;
It's basically as if you had opened up your source code in a word processor and did a find/replace to replace each occurrence of "NUMBER" with "100". So your compiler has no idea about the existence ofNUMBER. Only the pre-compilation preprocessor knows whatNUMBERmeans.
So, if you try to take the address ofNUMBER, the compiler will think you are trying to take the address of an integer literal constant, which is not valid.
|
Given the following recursive function:
```
// Pre-condition: y is non-negative.
int mysterious(int x, int y) {
if (y == 0) return x;
return 2*mysterious(x, y-1);
}
```
What is the return value of mysterious(3, 2)?
Here is my call stack:
```
return 2*mysterious(3, 2-1) => 2*3 => 6, 2*1 => mysterious(6,2)
return 2*mysterious(6, 2-1) => 6*2 => 12, 2*2 => mysterious(12, 2)
```
But it seems like y will never reach 0. What am I doing wrong?
|
```
mysterious(3, 2)
= 2 * mysterious(3, 1)
= 2 * 2 * mysterious(3, 0)
= 2 * 2 * 3
= 12
```
|
I have to call a COM component from C done in Visual Studio. I am able to call it fromVisual C++using the '#import' directive by specifying the .tlb file. But I don't see #import directive in the C language. Is there an alternative I can use instead of that?
I cannot write in C++ as I have to create the module in pure C only.
|
Ok, you should (in brief):
If you would like to call COM created from .NET then you should prepare those classes in the right way (GUID, ComVisible etc.)Generate appropriate headers for C (OleView.exe can do that)In C use those stub files to call ctor's, properties, methods etc.
Here it is the complete, step by step solution for your question:http://www.codeproject.com/Articles/632616/How-to-use-NET-Csharp-COM-objects-in-plain-C
|
I have a number of function in my "C" code. When I compile .so, I see all names in result .so file. How can I specify (in code or in make file) that only some functions should be exported, where as others are private just for internal use.
|
Since you mention.sofiles, it seems like a reasonable assumption that you're usinggccor a gcc-alike compiler.
By default allexternfunctions are visible in the linked object. You can hide functions (and global variables) on a case-by-case basis using thehiddenattribute (while keeping themextern, which allows them to be used from other source files in the same library):
```
int __attribute__((visibility("hidden"))) foo(void)
{
return 10;
}
```
Alternatively you can change the default tohiddenby passing the-fvisibility=hiddenoption togccat compile time. You can then mark particular functions for export using:
```
__attribute__((visibility("default")))
```
|
This question already has answers here:Serialize double and float with C(9 answers)Closed5 years ago.
How should a program read and write float numbers from and into binary files in C or Vala language?
The common APIs to do writing and reading are generally designed to write in byte format. I mean you have to write arrays of one-byte data into file and read in the same format.
I'm looking for a way to write and read in float format. without typecasting and without having to change the number into string. Is it possible?
|
fwrite() and fread() or write() and read() will work just fine.
```
float da, db ;
...
fwrite( &da, 1, sizeof(da), fpout ) ;
...
fread( &db, 1, sizeof(db), fpin ) ;
```
|
For example the option array is:
```
static struct option const long_options[] =
{
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
```
Is it for padding?
|
Look at the man page forgetopt_long():
int
getopt_long(int argc, char * const *argv, const char *optstring,
const struct option *longopts, int *longindex);
Theargcandargvpair show one way to say how many entries there are in an array (by explicit count, though sinceargv[argc] == 0, there is also a sentinel there). Theoptstringindicates short arguments; thelongindexis an output parameter. That leaves only the pointerlongoptswhich means that the function must be able to tell how many entries are in the array without any supporting count (there is nolongoptcountargument), so the end of the array is marked by all values zero - a sentinel value.
|
I am wondering how you can get a child process to wait to execute a statement after it's parent does a particular thing.
My needs are fairly simple, I just need to spawn the child process with fork, have the parent write something to a file, then have the child write something to the file, then they both finish executing their separate commands.
I've only learned about using wait() and waitpid() to have child processes execute first, then have the parent execute, but that obviously won't work here.
Any ideas?
Help is greatly appreciated, thanks.
|
You can use apipe()between the parent and child. The parent writes to the child via the pipe after the parent has finished writing to the file.
|
i converted the output XImage of my code to Bitmap, but the output file is massive, so i thought about compressing it using lzrw
i use this code to write the bitmap to file
```
fwrite(&bmpFileHeader, sizeof(bmpFileHeader), 1, fp);
fwrite(&bmpInfoHeader, sizeof(bmpInfoHeader), 1, fp);
fwrite(pImage->data, 4*pImage->width*pImage->height, 1, fp);
```
is there anyway i could write it to a (char *) insted of (FILE *) so i can use lzrw compression on it?
or even better, some way to convert the XImage to PNG directly...
thanks;
|
Usememcpyinstead offwrite
```
char* tmp = buf;
memcpy(tmp, &bmpFileHeader, sizeof(bmpFileHeader));
tmp += sizeof(bmpFileHeader);
memcpy(tmp, &bmpInfoHeader, sizeof(bmpInfoHeader));
tmp += sizeof(bmpInfoHeader);
memcpy(tmp, pImage->data, 4*pImage->width*pImage->height);
```
EDIT: I update code, thaks @bdk for pointing out
|
i have to write an high efficiency sock reverse proxy in C/C++, so i was wondering, is there any library/framework to easily handle sockets, proxying, etc just to focus on the main part of the project (not the proxy itself :)) ?
Something like the ACE framework but possibly i little bit smaller and/or proxy oriented ...
Thanks
|
libeventis pretty good. ACE is horrible :)
|
I am looking for an inter-processes barrier implementation. Processes are in shared memory (ie. on the same ndoe).
Processes are MPI ones. I do not want to use the MPI_Barrier function, because the general policy for all the MPI implementation is active waiting. I want my processes sleeping as long as they wait.
The restrictions:
should be in C, maybe in C++no spinlock, so it could use semaphorelinux OS
I am confident it exists thousands of barrier implementation, but I do not find any?!
Thanks
|
pthread_barrieris the POSIX API for barriers. They may live in process shared memory if youinitializethem accordingly.
|
When C says start-up values of global[/static] variables are zero, does it mean also struct members? And what is the initial value of a [global/static] pointer? NULL?
|
Yes, this is specified by C99 6.7.8p10:
If an object that has automatic
storage duration is not initialized
explicitly, its value is
indeterminate. If an object that has
static storage duration is not
initialized explicitly, then:if it has pointer type, it is initialized to a null pointer;if it has arithmetic type, it is initialized to (positive or unsigned)
zero;if it is an aggregate, every member is initialized (recursively) according
to these rules;if it is a union, the first named member is initialized (recursively)
according to these rules.
|
I have an address or pointer to an object.
How do I convert the address to unsigned char array? I am using it as a reference to transport using sockets. Thanks.
|
```
Object * pObject = ...;
unsigned char * pSz = reinterpret_cast<unsigned char *>(pObject);
// thru pSz you can see your object blindly as a pointer of unsigned char
// (the first char is pointed)
//and only if you know the size of your object (sizeObject) you can do this:
unsigned char pArray[sizeObject] = pSz;
```
Be really carefullif you ever use polymorphism, inherited objects may have totally differents sizes than there mother class Object;
|
```
typedef struct {
char a[100];
char const *secondHalfOfA;
}
//Can i set { secondHalfOfA = a[49]; } somehow?
```
|
Sure you can.
```
typedef struct {
char a[100];
char const *const secondHalfOfA;
} toto;
#define TOTO_INITIALIZER(NAME) { .secondHalfOfA = &((NAME).a[49]) }
static toto A = TOTO_INITIALIZER(A);
```
Using initializers like that consistently has the extra plus that it initializes your array with all0, too.
This is for C99 with designated initializers. If you only have historical C you could do something like
```
#define TOTO_INITIALIZER(NAME) { { 0 }, &((NAME).a[49]) }
```
Edit:Seeing your comment on another answer, I suppose that you had theconstin your type on the wrong side. But real C initialization works very well for that case, too.
|
In c( ansi ) , we say input taken by (s/v/f)scanf and stored in stdin , same as we say
stdout . I wonder, in linux ( unix ) where are they reside, under which folder .
Or they ( stdin / stdout ) are arbitrary ( that is, no such things exist )
|
They are streams created for your process by the operating system. There is no named file object associated with them, and so they do not have a representation within the file system, although as unwind points out, they may be accessed via a pseudo file system if your UNIX variant supports such a thing.
|
Since I had read realloc will act as malloc if the size pointed is 0, I was using it without malloc(), provided the pointer was static, global, or explicitly set to NULL if automatic.
However, I notice a lot of programmers try to set it or set it to malloc(1). Is it needed?
|
FromOpen Groups' specifications:
If ptr is a null pointer, realloc()
shall be equivalent to malloc() for
the specified size.If ptr does not match a pointer
returned earlier by calloc(),
malloc(), or realloc() or if the space
has previously been deallocated by a
call to free() or realloc(), the
behavior is undefined.
|
why is the output fffffffa rather than 0000000a for this code
```
char c=0Xaa;
int b=(int)c;
b=b>>4;
printf("%x",b);
```
what i thought was char c=OXaa will be aa and when it is typecasted to int it changes to 000000aa.
can anyone tell me what is happening when the char is being typecasted to integer..
|
intis signed so the upcast is sign-extending. Consider the binary representations.
0xAA = 10101010
charis often signed, so when you cast to the (signed by default)int, the first1means that it's interpreted as a negative twos-complement number:
```
((int) ((signed char)0xAA) ) = 11111111111111111111111110101010
```
To avoid this, use anunsigned charor anunsigned int.
|
This is my code:
```
int main()
{
const int LEN = 5;
int x[LEN];
}
```
VS10 says:
error C2057: expected constant
expressionerror C2466: cannot allocate an array
of constant size 0error C2133: 'x' : unknown size
I even tried the the code in this page and it gives the same problem (I commented the code which gives the error, and uncommented the correct one):http://msdn.microsoft.com/en-us/library/eff825eh%28VS.71%29.aspx
If I was trying a crappy compiler, I would think it's a bug in the compiler, but it's VS2010!
|
You might have compiled your code using .c extension. MS Visual C doesn't support C99. In C89 the size of an array must be a constant expression.constqualified variables are notconstantsin C. They cannot be used at places where a realconstantis required.
Also readthis excellent postby AndreyT.
Try saving the file with .cpp extension.
|
I’m reading some C code that can be found athttps://home.hccnet.nl/h.g.muller/umax4_8.c.
There, inmain(), it has the following:
```
N=-1;W(++N<121)
printf("%c",N&8&&(N+=7)?10:".?+nkbrq?*?NKBRQ"[b[N]&15]);
```
I don’t understand what thisprintf()call is doing, but somehow it outputs a chess board to the terminal.
Any idea?
|
Basically, this:
```
for (n = 0; n < 121; ++n) {
if (n & 8) {
n += 7;
putchar('\n');
} else {
putchar(".?+nkbrq?*?NKBRQ"[b[n] & 15]);
}
}
```
What that does is, after every 8 board items, print a newline; otherwise, print out the board item indicated byb[n].
|
I'm looking for a simple non-validating XML parser in either C or C++.
Several years back I found one that was just a single file solution but I can't find
it anymore.
I'm after some links and suggested ones that are very small and lightweight
ideally suited for an embedded platform.
|
Expat
You can work with or without validation and in "streaming mode". It is very lightweight.
|
```
typedef struct {
char a[100];
char const *secondHalfOfA;
}
//Can i set { secondHalfOfA = a[49]; } somehow?
```
|
Sure you can.
```
typedef struct {
char a[100];
char const *const secondHalfOfA;
} toto;
#define TOTO_INITIALIZER(NAME) { .secondHalfOfA = &((NAME).a[49]) }
static toto A = TOTO_INITIALIZER(A);
```
Using initializers like that consistently has the extra plus that it initializes your array with all0, too.
This is for C99 with designated initializers. If you only have historical C you could do something like
```
#define TOTO_INITIALIZER(NAME) { { 0 }, &((NAME).a[49]) }
```
Edit:Seeing your comment on another answer, I suppose that you had theconstin your type on the wrong side. But real C initialization works very well for that case, too.
|
In c( ansi ) , we say input taken by (s/v/f)scanf and stored in stdin , same as we say
stdout . I wonder, in linux ( unix ) where are they reside, under which folder .
Or they ( stdin / stdout ) are arbitrary ( that is, no such things exist )
|
They are streams created for your process by the operating system. There is no named file object associated with them, and so they do not have a representation within the file system, although as unwind points out, they may be accessed via a pseudo file system if your UNIX variant supports such a thing.
|
Since I had read realloc will act as malloc if the size pointed is 0, I was using it without malloc(), provided the pointer was static, global, or explicitly set to NULL if automatic.
However, I notice a lot of programmers try to set it or set it to malloc(1). Is it needed?
|
FromOpen Groups' specifications:
If ptr is a null pointer, realloc()
shall be equivalent to malloc() for
the specified size.If ptr does not match a pointer
returned earlier by calloc(),
malloc(), or realloc() or if the space
has previously been deallocated by a
call to free() or realloc(), the
behavior is undefined.
|
why is the output fffffffa rather than 0000000a for this code
```
char c=0Xaa;
int b=(int)c;
b=b>>4;
printf("%x",b);
```
what i thought was char c=OXaa will be aa and when it is typecasted to int it changes to 000000aa.
can anyone tell me what is happening when the char is being typecasted to integer..
|
intis signed so the upcast is sign-extending. Consider the binary representations.
0xAA = 10101010
charis often signed, so when you cast to the (signed by default)int, the first1means that it's interpreted as a negative twos-complement number:
```
((int) ((signed char)0xAA) ) = 11111111111111111111111110101010
```
To avoid this, use anunsigned charor anunsigned int.
|
This is my code:
```
int main()
{
const int LEN = 5;
int x[LEN];
}
```
VS10 says:
error C2057: expected constant
expressionerror C2466: cannot allocate an array
of constant size 0error C2133: 'x' : unknown size
I even tried the the code in this page and it gives the same problem (I commented the code which gives the error, and uncommented the correct one):http://msdn.microsoft.com/en-us/library/eff825eh%28VS.71%29.aspx
If I was trying a crappy compiler, I would think it's a bug in the compiler, but it's VS2010!
|
You might have compiled your code using .c extension. MS Visual C doesn't support C99. In C89 the size of an array must be a constant expression.constqualified variables are notconstantsin C. They cannot be used at places where a realconstantis required.
Also readthis excellent postby AndreyT.
Try saving the file with .cpp extension.
|
I’m reading some C code that can be found athttps://home.hccnet.nl/h.g.muller/umax4_8.c.
There, inmain(), it has the following:
```
N=-1;W(++N<121)
printf("%c",N&8&&(N+=7)?10:".?+nkbrq?*?NKBRQ"[b[N]&15]);
```
I don’t understand what thisprintf()call is doing, but somehow it outputs a chess board to the terminal.
Any idea?
|
Basically, this:
```
for (n = 0; n < 121; ++n) {
if (n & 8) {
n += 7;
putchar('\n');
} else {
putchar(".?+nkbrq?*?NKBRQ"[b[n] & 15]);
}
}
```
What that does is, after every 8 board items, print a newline; otherwise, print out the board item indicated byb[n].
|
I'm looking for a simple non-validating XML parser in either C or C++.
Several years back I found one that was just a single file solution but I can't find
it anymore.
I'm after some links and suggested ones that are very small and lightweight
ideally suited for an embedded platform.
|
Expat
You can work with or without validation and in "streaming mode". It is very lightweight.
|
I tried to compile this simple pthreads program with this command
$ gcc -pthread -o pthreads pthreads.c
```
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void *myThread(void *arg);
int main()
{
pthread_t mythread;
int ret;
ret = pthread_create( &mythread, NULL, myThread, NULL );
if (ret != 0){
printf( "Can't create pthread: %s", strerror(errno));
exit(-1);
}
return 0;
}
void *myThread(void *arg){
// Thread code goes here..
printf("OK! NOW ON THE THREAD\n");
pthread_exit(NULL);
}
```
but when trying ./pthreads there is no output presented!!
|
You need to wait for the thread to finish. Otherwise you risk exiting before the thread starts executing.
```
...
pthread_create( &mythread, NULL, myThread, NULL );
...
// Wait for the thread to finish.
pthread_join( mythread, NULL);
```
|
I have structure(A) and it takes another structure(B) as member.
Now i want structure C as member of A instead of B.
Both B and C are of same type
```
typedef struct
{
int a;
B b;
}A
typedef struct
{
int a;
}B
typedef struct
{
int a;
}C
```
How can i assign struct C as member instead of B. How to do typecasting
Please help
|
C and C++ are statically typed languages. You can't do it. If you declare something as apple, it will stay as apple until the end of the times.
|
I know both arrays and structs count as variables, but do their fields/elements?
I'm trying to write some documentation about a program that deals with deeply nested structs and arrays, but don't know if I can refer to these fields/elements as variables.
|
In ordinary documentation, words like "variable" take their meaning from context. Other options would be "value" or "datum"/"data". As long as your explanation of your interface is clear and consistent, it probably doesn't matter which of those you use.
(Language in Standards, and discussion of Standards, is something else. In that case, more precision and lots of definitions are required.)
|
I need to sample a (cli) application with shark and pass parameters to it like so:
```
shortest-path <input-ref-littleendian|diff -u - output-ref
```
How can I do this withshark? Shark assumes that the parameters i need to pass to the launched cli app are for shark itself, not the process.
|
That's not "parameters to a program", that's a shell pipeline. You might need to use parenthesis to make it clear in which order things should happen, e.g. perhaps something like
```
$ shark ( shortest-path < input-ref-littleendian | diff -u - output-ref )
```
I don't have access to shark so I cannot verify this.
|
if i have a variable from fgets
for example fgets(question,200,stdin);
how do i determine the size of the variable question without all the trailing blank elemets?
|
Usestrlen(3). Was there a question aboutmalloc(3)too?
|
I found the following declaration in my c Book, can anyone explain it:
```
char *dic[][40]={
"atlas", "A volume of maps",
"car", "a vehicle",
"telephone", "a communication device",
"", ""
}
```
Here what does the 40 means i.e. which dimension this is?
|
This is actually kind of a weird way to initialize the dictionary.
It is a 2D array ofchar*(zero terminated (\0) strings).
The dimensions are [rows][columns].
So you have 1 row (determined by the initializer) and 40 columns of strings,
where 8 of them are initialized.
NOTE: Are you sure it isnt chardic[][40](i.e., a list of strings of max-length 40) ?
|
I noticed many mentions ofptyandttyin some open source projects, could someone tell me what do they mean and what is the difference between them?
|
ttyoriginally meant"teletype"and"pty"means"pseudo-teletype".
In UNIX,/dev/tty*is any device that acts like a"teletype", i.e: a terminal. (Called teletype because that's what we had for terminals in those benighted days.)
Aptyis apseudotty, a device entry that acts like a terminal to the process reading and writing there, but is managed by something else. They first appeared (as I recall) for X Window and screen and the like, where you needed something that acted like a terminal but could be used from another program.
|
I have integers which I put in a matrix in order to use them in a specific function in openCV. The matrix that I created is only cvMat and I want to use this matrix in the function. I'm getting an error:
error: cannot convert ‘CvMat’ to ‘const CvMat*’
So how can I convert these ints to const in order to create that matrix as const CvMat i.e how to change CvMat to const CvMat?
|
" error: cannot convert ‘CvMat’ to ‘const CvMat*’ "
The important thing there is the asterix at the end. That means the function you are calling wants a pointer. you can just take the address of your matrix and pass that, insteadsomefunction(myMatrix)it needssomefunction(&myMatrix). Don't worry about the const. A pointer can always be converted to a const pointer implicitly.
|
Suppose there are two threads, the main thread and say thread B(created by main). If B acquired a mutex(say pthread_mutex) and it has called pthread_exit without unlocking the lock. So what happens to the mutex? Does it become free?
|
nope. The mutex remaines locked. What actually happens to such a lock depends on its type, You can read about thathereorhere
|
I'm using libsndfile to load the music file and i use jack to play it.
how do I resolve issues when the sample rate of the song is lower or higher then the sample rate of my sound card? is there something i can configure in jack or do i need to use libsamplerate to convert the sample rate ?
Thanks
|
jack does not resample.
there is a library called libsamplerate that converts from one sample rate to another. I can use it to convert a song to the sound card's sample rate.
|
I'm trying to compilepythonsource code foo.py to C usingcython.
Infoo.py:
```
print "Hello World"
```
The command I'm running iscython foo.py.
The problem is that when compiling foo.c usinggcc, I get the error:
undefined reference to 'main'.
|
when converting the code from python to c (using Cython) it converts it to c code which can be compiled into a shared object.
in order to make it executable, you should add "--embed" to cython conversion command. this flag adds the 'main' function you need, so you could compile the c code into executable file.
please notice you'll need the python.soruntime libraries in order to run the exec.
|
How to count the no of arguments passed to the function in following program:
```
#include<stdio.h>
#include<stdarg.h>
void varfun(int i, ...);
int main(){
varfun(1, 2, 3, 4, 5, 6);
return 0;
}
void varfun(int n_args, ...){
va_list ap;
int i, t;
va_start(ap, n_args);
for(i=0;t = va_arg(ap, int);i++){
printf("%d", t);
}
va_end(ap);
}
```
This program's output over my gcc compiler under ubuntu 10.04:
```
234561345138032514932134513792
```
so how to find how many no. of arguments actually passed to the function?
|
You can't. You have to manage for the caller to indicate the number of arguments somehow. You can:
Pass the number of arguments as the first variableRequire the last variable argument to be null, zero or whateverHave the first argument describe what is expected (eg. the printf format string dictates what arguments should follow)
|
```
#define BS 1000
XDR *xdrs;
char buf1[BS];
xdrmem_create(xdrs,buf1,BS,XDR_ENCODE);
```
I followed what the text book said but whenever I ran my program, it has segmentation fault.
I think there is problem with xdrmem_create. Has anybody here been successful when using this function?
(I'm using Ubuntu 10.10)
|
You didn't initialize the pointer. Fix:
```
XDR stream;
xdrmem_create(&stream, buf1, BS, XDR_ENCODE);
```
|
So I'm trying to write a C program that uses inotify. I've used pyinotify before so I understand how it works. However, I'm following some guide and it tells me to include<linux/inotify.h>. The problem is that this header only has macro definitions, not the funciton prototypes. It looks like the functions are prototyped in<sys/inotify.h>.
My question is what's the difference betweenlinux/inotify.handsys/inotify.h? Why are there both?
|
sys/inotify.his part of theGNU C library. It exposes the structures and functions that your program will use in order to receive filesystem change notifications. It can be considered as the public API of the notification system.
linux/inotify.his part of the Linux kernel. It defines the kernel structures and constants used to implement the notification system itself. You shouldn't include that file unless you're writing something like a kernel module, because it's Linux-specific and thus not portable.
|
When I try to write the file using C;fwritewhich acceptsvoidtype as data, it is not interpreted by text editor.
```
struct index
{
index(int _x, int _y):x(_x), y(_y){}
int x, y;
}
index i(4, 7);
FILE *stream;
fopen_s(&stream, "C:\\File.txt", "wb");
fwrite(&i, sizeof(index), 1, stream);
```
but when I try with C++; ofstreamwritein binary mode, it is readable. why doesn't it come up same as written usingfwrite?
|
This is the way to write binary data using a stream in C++:
```
struct C {
int a, b;
} c;
#include <fstream>
int main() {
std::ofstream f("foo.txt",std::ios::binary);
f.write((const char*)&c, sizeof c);
}
```
This shall save the object in the same way asfwritewould. If it doesn't for you, please post your code with streams - we'll see what's wrong.
|
Given a pointer to structure, can I write a#definethat would access a member of the structure?
```
struct s_block {
size_t size;
struct s_block *ptr;
};
#define SIZER(ptr) // will access size member ????
```
|
```
#define SIZER(ptr) (ptr)->size
```
Do note though that you must pass in a pointer to ans_blockfor this to work.
Finally, this should be in any reference manual covering the C programming language. I suggest you pick one up.K&Ris very good, even today.
|
I can't get why the following bit of C code doesn't work:
```
int obtainStringLength(char* str, char c1, char c2) {
char* firstOcurrence = strchr(str, c1);
char* endOcurrence = strchr(str, c2);
return 2+(endOcurrence - firstOcurrence) / sizeof(char*);
}
```
The idea is to find how many characters are betweenc1andc2:
```
printf("%d\n", obtainStringLength("abc def ghi", 'a', 'i')); //should yield 11
```
Unfortunately, this is always printing 1. What is the problem? Shouldn'tstrchrwork like C#'sstring.IndexOf()?
|
Division bysizeof(char*)? That's incorrect - the result of subtracting two pointers is a numerical value (ptrdiff_t) corresponding to the number of values, not a pointer or difference of addresses.
There's also the off-by-one error in calculating the length. So that last line should look like:
```
return 1 + (endOcurrence - firstOcurrence);
```
|
I was reading C Traps and Pitfalls and read that the following code may work on some implementations and won't on others due to an undefined order of = and ++. Is this still true of C?
```
int i = 0;
while (i < n)
y[i] = x[i++];
```
If so, that's really incredible.
|
Nothing incredible. Pretty defined undefined behavior. Read more aboutsequence points.
Just writing as:
```
int i = 0;
while (i < n)
{
y[i] = x[i];
i++;
}
```
is safer and more readable.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.