question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Can anybody explain the difference between
```
#define int* char
```
and
```
typedef int* char;
```
|
There's no difference because both are illegal.
int*isn't a valid identifier for a macro, and even if you put a space in, neither isint, because it's a keyword and reserved. Even if you switched it to your likely intended#define char int*, it fails for the same reason.
And you cannot redefine the typechar, so thetypedefis a bust.
The difference, had you given examples that were legal, is that#defineis a preprocessing directive. It only does textual replacement, before the compiling stage. Contrarilytypedefdefines a new type, and that new type identifier respects "the rules" just like any other type.
|
Fairly abstract question here, as I don't know quite where to start my own investigations.
I have a C package constructed with CMake that produces librpdb.so; I have a Ruby Gem set up for the same library, which produces rpdb.bundle.
When used in Ruby, I get this:
```
dyld: lazy symbol binding failed: Symbol not found: _RPDB_RuntimeStorageController_sharedInstance
Referenced from: /usr/local/lib/ruby/gems/1.9.1/gems/rpdb-0.1.0/lib/rpdb/rpdb.bundle
Expected in: flat namespace
```
When I look into the library, nm reports:
```
000000000000ea40 T _RPDB_RuntimeStorageController_sharedInstance
```
So it appears that the symbol is indeed in the library. Why, then, would binding fail?
|
Simply put, linking wasn't occurring at the level of the first library, although it wasn't reporting as much because the headers were found appropriately.
More details regarding why this was occurring for my circumstances, here
and also, here
|
I notice that drawing dashed lines with GL will not make them even apart unless each vertex is equidistant from the last. Is there a way to simply make the whole path dashed evenly regardless of the distance between each point?
Thanks
|
I'm guessing you're drawingGL_LINESrather thanGL_LINE_STRIPsorGL_LINE_LOOPs. With the latter, the individual segments are connected and the stipple pattern is continuous from one to the next.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
What are the key differences between Ruby and C?
|
They are almost totally different.
Ruby
Strong, dynamic typingPurely object orientedAutomatic garbage collection and no pointersInterpreted (or JIT compilation with JRuby/IronRuby)ReflectiveSupports functional programming (closures, coroutines, etc.)No preprocessor or macros
C
Weak, static typingProcedural (not object oriented)Not garbage collected and has pointersCompiledNo reflectionDoes not support functional programmingHas a preprocessor and supports macros
To Ruby From C and C++
|
This question already has answers here:When is assembly faster than C? [closed](40 answers)Closed2 years ago.
This is purely a theory question, so, given an "infinite" time to make a trivial program, and an advanced knowledge of C and Assembly, is it really better to do something in Assembly? is "performance" lost when compiling C into Assembly (to machine code)?
By performance I mean, do modern C compilers do a bad job at certain tasks that programming directly in Assembly speeds up?
|
Modern C can do a better job than assembly in many cases, because keeping track of which operations can overlap and which will block others is so complex it can only be reasonably be tracked by a computer.
|
How do I bring another app's window to front on Mac in C/C++?
I have the app's pid.
I found solutions for AppleScript, but I'm not familiar with AppleScript. (and also not with Objective C)
Thanks!
edit: I cannot use Carbon in this program, because it must be a 64 bit binary.
edit2: I'm also interested in Carbon and Cocoa solutions. I could put this into an exernal 32 bit app to use Carbon.
|
You can do it like this:
```
#include <stdlib.h>
system("osascript -e \"tell application \\\"Address Book\\\" to activate\"");
```
This will also launch the app (Address Book in this example) if it's not already running.
|
I am just starting to learn C and (of course) struggling with pointers :)
Given this snippet:
```
int *storage, *storage_p;
storage = malloc(sizeof(int[GROW_BY]));
storage_p = storage;
// do something with storage, using storage_p
free(storage);
storage = NULL;
```
Is it really necessary to have two variables declared to work with themalloc()'ed data? Is it good practice to create astorageandstorage_pthe way I did? If not, what would would be 'the way'?
|
You will need a pointer that will hold the value returned by malloc(), so that you can free it later.
If what you plan on using storage_p for is going to change it value, then you are going to need two pointers.
However, I generally keep the pure initial pointer, and create new ones, ad hoc, as I need one.
```
int *storage = (int*) malloc(sizeof(int[GROW_BY]));
// :
int* ptr = storage;
while (*ptr)
{
// :
++ptr;
}
```
|
I'd seen some ancient code that simplifed Unix paths for comparison by doing something like the following pseudocode:
strip off the last path component to get a directory only part: /foo/bar -> /foogetcwd and remember original pathchdir /foogetcwd and remember to return to callerchdir old original path
Is there a standard Unix system function that does all this without the thread unsafe current directory manipulation?
A mutex could make that code sequence less thread unsafe, but isn't really ideal (you'd have to know that all other code using getcwd or other functions dependent on the process cwd including system and vendor code protects with this same mutex).
|
What aboutrealpath(3)?
Since it returns its result in a buffer you supply, thread-safety should not be an issue.
|
I have successfully gotten Dreamweaver to accept my DLL and call it's methods. The DLL is written in C++ with C interpeted functions (so function names aren't mangled.)
I would like to become comfortable with C++ pointers and datatype, but I have a much stronger proficiency with C# so for our timeline I think it's worthwhile to investigate alternatives to a straight C solution.
Would I theoretically be able to build a DLL in C# that would be seen from the "outside" the same as a C DLL?
and as an alternative
Would I be able to "wrap" a C# DLL with the working C DLL?
The main part of my concern is the datatypes of the functions, as when dreamweaver calls them it is expecting void and char pointers as the format for passing data back and forth.
Thank you.
|
Contrary to popular belief, thisispossible.Seehere.
|
When declaring an array like this:
```
int array[][] = {
{1,2,3},
{4,5,6}};
```
I get an error saying: "Array type has incomplete element type"
What is going on??
|
With an N-dimensional array (N>0), you need to define the sizes of N-1 dimensions; only one dimension can be left for the compiler to determine, and it must be the first dimension.
You can write:
```
int d1[] = { ... };
int d2[][2] = { ... };
int d3[][2][3] = { ... };
```
Etc.
|
i need a tool that can convert c/c++ code to delphi(object pascal) code, have triedopenc2pasbut it is pretty much useless and a pain to use is their a usable alternative?(free or commercial)
|
Unless you need this for academic purposes, stop looking, because:
Delphi doesn't support everything that's supported in C++. Examples: Delphi doesn't support operator overloading. Delphi can't instantiate class instances on stack (all Delphi objects are dynamically allocated, using the equivalent of the C++ "new" operator)The language itself is not all. You'll need equivalent libraries for every C++ library you used!
|
I am developing a GTK based application which has to support clipboard. For that I am exporting selection data usinggtk_clipboard_set_with_datawith the target formats:UTF8_STRING,STRING,TEXT,COMPOUND_TEXT,text/plain,text/plain;charset=utf-8,text/rtf,text/htmlandtext/url. Using this I am able to copy-paste text from my aplication to other text editors like gedit. However, I am not able to paste text to XTerm. Should I be exporting to any other target? Where can I get a list of formats accepted by XTerm?
|
xterm only uses thePRIMARYselection buffer, so you should probably add that to your list.
Seehttp://www.davidsimmons.com/soft/xtermhacks/#copynpasteandhttp://www.freedesktop.org/wiki/Specifications/ClipboardsWikifor more information.
|
I've been assigned to upgrade an embedded application written in C. The application is configured via a web interface.
When the user modifies the web application a file is written to/var/www/settings.jsonand the file/var/www/UPDATE_SETTINGSis touched.
In the main application loop it checks to see ifUPDATE_SETTINGSexists. If it does it parses thesettings.jsonwith json-c and then deletesUPDATE_SETTINGS.
This works well enough, however, we would prefer to move to an event-driven architecture (perhaps libev) in whichsettings.jsonis fed directly into the program by the webapp script to a plain-old UDP port and then issue a callback to perform the update.
What are some other elegant ways to solve this problem? Should we just stick with the current approach?
|
Just useinotify. It was created for cases like yours.
|
```
int i,n=20;
for(i=0;i<n;i--)
printf("-");
```
I have been rattling my brain but have not been able to solve this.
Deleteany single character or operatorfrom above code and the program should print "-" 20 times
Please help!
|
I don't think you can do it bydeletinga character, but I have three solutions thatreplace(well, one of them adds a character, but only because you have no whitespace in your program. If you had whitespace, it would replace a space).
Solution 1
```
int i,n=20;
for(i=0;-i<n;i--) // -i < n
printf("-");
```
Solution 2
```
int i,n=20;
for(i=0;i<n;n--) // n--
printf("-");
```
Solution 3
```
int i,n=20;
for(i=0;i+n;i--) // while i + n is not zero
printf("-");
```
|
If my application runs out of memory, I would like to re-run it with changed parameters. I havemalloc/newin various parts of the application, the sizes of which are not known in advance. I see two options:
Track all memory allocations and write a restarting procedure which deallocates all before re-running with changed parameters. (Of course, I free memory at the appropriate places if no errors occur)Restarting the application (e.g., withWinExec()on Windows) and exiting
I am not thrilled by either solution. Did I miss an alternative maybe.
Thanks
|
You could embedd all the application functionality in a class. Then let it throw an expection when it runs out of memory. This exception would be catched by your application and then you could simply destroy the class, construct a new one and try again. All in one application in one run, no need for restarts. Of course this might not be so easy, depending on what your application does...
|
When I compile C code with my cross toolchain, the linker prints pages of warnings saying that my executable uses hard floats but my libc uses soft floats. What's the difference?
|
Hard floats use an on-chip floating point unit. Soft floats emulate one in software. The difference is speed. It's strange to see both used on the same target architecture, since the chip either has an FPU or doesn't. You can enable soft floating point in GCC with -msoft-float. You may want to recompile your libc to use hardware floating point if you use it.
|
Is there any way to make this code shorter?
```
long call_f(int argc, long *argv) {
switch (argc) {
case 0:
return f();
break;
case 1:
return f(argv[0]);
break;
case 2:
return f(argv[0], argv[1]);
break;
case 3:
return f(argv[0], argv[1], argv[2]);
break;
case 4:
return f(argv[0], argv[1], argv[2], argv[3]);
break;
// ...
}
return -1;
}
```
|
No, there isn't any good way to do this. See here:http://c-faq.com/varargs/handoff.html
You can write a macro with token pasting to hide this behavior but that macro will be no simpler than this code, thus it's only worth writing if you have multiple functions like f() where you would otherwise have to duplicate this case statement.
|
I know we can use
```
perror()
```
in C to print errors. I was just wondering if there is a C++ alternative to this, or whether I have to include this (and therefore stdio.h) in my program. I am trying to avoid as many C functions as possible.
|
You could do something like:
```
std::cerr << strerror(errno) << std::endl;
```
That still ends up callingstrerror, so you're really just substituting one C function for another. OTOH, it does let you write via streams, instead of mixing C and C++ output, which is generally a good thing. At least AFAIK, C++ doesn't add anything to the library to act as a substitute forstrerror(other than generating anstd::string, I'm not sure what it would change fromstrerroranyway).
|
I wrote up a quick memory reader class that emulates the same functions asfreadandfscanf.
Basically, I usedmemcpyand increased an internal pointer to read the data likefread, but I have afscanf_scall. I usedsscanf_s, except that doesn't tell me how many bytes it read out of the data.
Is there a way to tell how many bytessscanf_sread in the last operation in order to increase the internal pointer of the string reader? Thanks!
EDIT:
And example format I am reading is:|172|44|40|128|32|28|
fscanf reads that fine, so does sscanf. The only reason is that, if it were to be:
|0|0|0|0|0|0|
The length would be different. What I'm wondering is how fscanf knows where to put the file pointer, but sscanf doesn't.
|
Withscanfand family, use%nin the format string. It won't read anything in, but it will cause the number of characters read so far (by this call) to be stored in the corresponding parameter (expects anint*).
|
I am looking to learn open GL, I have a strong foundation of the maths behind graphics. What is the best route to take in learning the Open GL technology i'm open to using both Windows and Mac.
Thanks in advance
|
http://www.opengl.org/OpenGL programming guide aka "Red Book"Francis s Hill, "Computer Graphics using OpenGL".OpenGL shading language (aka "Orange Book")NVidia OpenGL resources.And you might want to take a look atOpenGL reference manucal ("Blue Book")
|
I'm trying to parse socket info from/proc/net/tcpand while I can identify some fields, such as memory addresses or send queue use, I can't find how each entry is bound to its socket descriptor. e.g., with this data:
```
1: 5922140A:E459 D5C43B45:0050 01 00000000:00000000 00:00000000 00000000 1000 0 507218 1 f6ab1300 57 3 12 4 -1
```
I want to know which is the correspondant socket descriptor.
|
Take the inode number (in this case, 507218). Each open file descriptor to that socket (there may be multiple file descriptors for the same socket) will appear as a link of the form:
```
/proc/<PID>/fd/<N> -> socket[507218]
```
(where<PID>is the process ID and<N>is the file descriptor).
|
What is C# analog of C fread()?
InC code here we use
```
fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
```
What could be its exact analog?
|
The closest would beStream.Read
```
byte[] buffer = new byte[8192];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
```
|
How to write a macro which calls goto END_ label?
For ex:
```
#define MY_MACRO() \
//How to define goto END_##function_name label??
my_function()
{
MY_MACRO();
END_my_function:
return;
}
```
The MY_MACRO should simply replace with the line
```
goto END_my_function;
```
|
I don't think it can be done. Even though some compilers define__FUNCTION__or__func__, these are not expanded in macros.
However, note that you don't need a separate label for each function: you can useENDfor all functions and simply writegoto END.
|
I was going through this linkWill it optimizeand wondered how can we know what optimizations are done by a particular compiler.
Like does VC8.0 convert if-else statements to switch-case?
Is such information available on msdn?
|
As everyone seems to be bent on telling the OP that he shouldn't worry about it, there is some useful although not as specific as the OP requested) information about compiler optimization (options).
You'll have to figure out what flags you're using, especially for MSVC and Intel (GCC release build should default to -O2), but here are the links:
GCCMSVCIntel
This is about as close as you'll get before disassembling your binary after compilation.
|
My program (a text-mode web browser) is dynamically allocating memory.
I do free unneeded blocks during runtime, of course. And I do free everything before normal termination - so that memory leak checkers won't give me false positives (and to be flexible should major refactorings ever become needed).
Now, what I donotdo is freeing memory before abnormal termination. (Currently, my program terminates on signals and after failed mallocs/reallocs.)
My question is: Do you consider this bad style? Should I free on abnormal termination?
|
No. I think it's perfectly acceptable to simply throw up your hands and let the OS reclaim the memory after the program terminates. I think if this is truly an abnormal situation and the intention is to have the program terminate, then a well-behaved program should simply clean up any disk resources/locks, and exit as quickly as possible.
|
```
pthread_rwlock t1;
pthread_rwlock_wrlock(&t1);
pthread_rwlock t2 = t1;
```
what happend?
is t2 locked or not?
|
Nothing special happens.pthread_rwlock_t(notpthread_rwlock, AFAIK) is an opaque C struct. Copying the variable simply copies the struct, byte for byte.
At the Pthreads level, copying apthread_rwlock_tresults in undefined behaviour. Don't do it.
|
Can anybody explain the difference between
```
#define int* char
```
and
```
typedef int* char;
```
|
There's no difference because both are illegal.
int*isn't a valid identifier for a macro, and even if you put a space in, neither isint, because it's a keyword and reserved. Even if you switched it to your likely intended#define char int*, it fails for the same reason.
And you cannot redefine the typechar, so thetypedefis a bust.
The difference, had you given examples that were legal, is that#defineis a preprocessing directive. It only does textual replacement, before the compiling stage. Contrarilytypedefdefines a new type, and that new type identifier respects "the rules" just like any other type.
|
Fairly abstract question here, as I don't know quite where to start my own investigations.
I have a C package constructed with CMake that produces librpdb.so; I have a Ruby Gem set up for the same library, which produces rpdb.bundle.
When used in Ruby, I get this:
```
dyld: lazy symbol binding failed: Symbol not found: _RPDB_RuntimeStorageController_sharedInstance
Referenced from: /usr/local/lib/ruby/gems/1.9.1/gems/rpdb-0.1.0/lib/rpdb/rpdb.bundle
Expected in: flat namespace
```
When I look into the library, nm reports:
```
000000000000ea40 T _RPDB_RuntimeStorageController_sharedInstance
```
So it appears that the symbol is indeed in the library. Why, then, would binding fail?
|
Simply put, linking wasn't occurring at the level of the first library, although it wasn't reporting as much because the headers were found appropriately.
More details regarding why this was occurring for my circumstances, here
and also, here
|
I notice that drawing dashed lines with GL will not make them even apart unless each vertex is equidistant from the last. Is there a way to simply make the whole path dashed evenly regardless of the distance between each point?
Thanks
|
I'm guessing you're drawingGL_LINESrather thanGL_LINE_STRIPsorGL_LINE_LOOPs. With the latter, the individual segments are connected and the stipple pattern is continuous from one to the next.
|
I'm writing a java binding for a C code and I'm not really familiar with C.
I have a uint64_t and need to cast it to a int. Does anyone know how to do that?
(My binding returns then a jint...)
|
The short answer:
```
uint64_t foo;
int bar;
bar = foo;
```
Technically this has undefined behavior if the value offoodoes not fit in anint. In practice, it will always simply truncate the upper bits. If you want to be more correct, then:
```
if (foo-INT_MIN <= (uint64_t)INT_MAX-INT_MIN)
bar = foo;
else
/* error case here */
```
|
I experience quite annoying side-effect of class/structure padding withPurify. E.g.
```
struct something {
int field1;
char field2;
};
/* ... */
struct something smth, smth2;
smth.field1 = 1;
smth.field2 = 'A';
smth2 = smth;
```
The last line would highly likely trigger UMR warning saying that 3 bytes of initialized memory are accessed. This is obviously a false positive: there are no user data in the last three bytes of the struct, it's just a padding.
Often the warnings very very quickly fill up log files making it very hard to see the other, real problems.
Does anybody know any way to suppress the false positives?
|
I have no experience with purify, but perhaps explicitly initialising the first struct removes this warning:
```
struct something smth = {0};
struct something smth2;
```
I assume your structs have block scope (not file). If they have file scope the zero initialising is implicit.
|
for example there is code
```
#include <algorithm>
#include <stdio.h>
#include <iostream>
int intcomp(int *x,int *y) { return *x-*y;};
int a[10000];
int main(void){
int i; int n=0;
while (scanf("%d",&a[n])!=EOF)
n++;
qsort(a,n,sizeof(int),intcomp);
for (int i=0;i<n;i++)
printf("%d\n",a[i]);
return 0;
}
```
how tell computer that EOF is reached?
|
You mean when entering input interactively?
In a windows shell, ctrl+z on a line on its own. In a *nix shell, ctrl+d. Or just put your input in a file and pipe it, then not only will eof be detected at the appropriate time but also you can automate your testing.
|
I found the member variable name of m_rgNames in some source code. According to the naming convention, such as m_iNumber typed as int, rg could represent a type name. If this is case, what type did rg represent? Or else what's the meaning of rg in this variable name?
|
It stands forarray or range. The author uses theHungarian notation.
|
Given log(a) and log(b), return log(a+b)
```
double log_sum(double log_a, double log_b){
double v;
if(log_a < log_b){
v=log_b+log(1+exp(log_a-log_b));
}
else{
v=log_a+log(1+exp(log_b-log_a));
}
return v;
}
```
I want to know what are the benefits of the above function?
|
The primary (brute force) alternative looks like:
```
v = log(exp(log_a) + exp(log_b));
```
That has three transcendental function evaluations.
The computation shown uses just two transcendental functions - and should be quicker.
It may also be more stable numerically.
|
I'm using Objective-C language. But I don't know how to use c with Objective-C.
Ex) This is Function method.
```
- ( ?? ) function{
unsigned int first = ..
unsigned int second = ..
unsigned int third = ..
int infoData = {first,second,third};
return infoData;
}
```
How to fill in parenthesis.
I don't use NSArray.
Please help me.
|
the answer is the same as it is in C. Objective-C is a strict superset of C.
|
I need to run a linux command such as "df" from my linux daemon to know free space,used space, total size of the parition and other info. I have options like calling system,exec,popen etc..
But as this each command spawn a new process , is this not possible to run the commands in the same process from which it is invoked?And at the same time as I need to run this command from a linux daemon, as my daemon should not hold any terminal. Will it effect my daemon behavior?
Or is their any C or C++ standard API for getting the mounted paritions information
|
There is nostandardAPI, as this is an OS-specific concept.
However,
You can parse/proc/mounts(or/etc/mtab) with (non-portable)getmntent/getmntent_rhelper functions.Using information about mounted filesystems, you can get its statistics withstatfs.
|
If I'm writing a library in C that includes a Python interface, is it OK to just write unit tests for the functions, etc in the Python interface? Assuming the Python interface is complete, it should imply the C code works.
Mostly I'm being lazy in that the Python unit test thing takes almost zero effort to use.
thanks,
-nick
|
Tests through the Python interface will be valuableacceptance testsfor your library. They will not however be unit tests.
Unit testsarewritten by the same coders, in the same language, on the same platform as the unit which they test. These should be written too!
You're right, though, unit testing in Python is far easier than C++ (or even C, which is what you said!).
|
I'm trying to write a tool that will take as input some C code containing structs. It will compile the code, then find and output the size and offset of any padding the compiler decides to add to structs within it. This is pretty straightforward to do by hand for a known struct using offsetof, sizeof, and some addition, but I can't figure out an easy way to do it automatically for any input struct.
If I knew how to iterate through all elements in a struct, I think I could get the tool written with no problems, but as far as I know there's no way to do that. I'm hoping some StackOverflow people will know a way. However, I'm not stuck in my approach, and I'm certainly open to any alternate approaches to finding padding in a struct.
|
Isn't this whatpaholedoes?
|
Usingdeflate()I was unable to open the zipped file using WinZip. Are the gz() the only ones compatible with WinZip? or is there some sort of mode I must calldeflate()with?
|
fromhttp://www.zlib.net/zlib_faq.html
Can zlib handle .zip archives?Not by
itself, no. See the directory
contrib/minizip in the zlib
distribution.
|
I'm writing a drawing program. I'm trying to take an ordered list mouse positions, and approximate a smooth Quadratic BSpline Curve. Does anyone know how to accomplish this?
Thanks!
|
"B-spline curve fitting based on adaptive curve refinement using dominant points" by Park & Leeand"Fair interpolation and approximation of B-splines by energy minimization and points insertion" by Vassilevseem to be solving this problem. Also there look like a few references on the first link that should help you.
Converting data points to control points in areas of high curvature and removing data points in areas of little curvature is a general approach.
|
I am trying to find a program in C code that will allow me to compute a eigenvalue (spectral) decomposition for a square matrix. I am specifically trying to find code where the highest eigenvalue (and therefore its associated eigenvalue) are located int the first column.
The reason I need the output to be in this order is because I am trying to compute eigenvector centrality and therefore I only really need to calculate the eigenvector associated with the highest eigenvalue. Thanks in advance!
|
In any case I would recommend to use a dedicated linear algebra package likeLapack(Fortran but can be called from C) orCLapack. Both are free and offer routines for almost any eigenvalue problem. If the matrix is large it might be preferable to exploit its sparseness e.g. by usingArpack. All of these libraries tend to sort the eigenvectors according to the eigenvalues if they can (real or purely imaginary eigenvalues).
|
I'm writing a java binding for a C code and I'm not really familiar with C.
I have a uint64_t and need to cast it to a int. Does anyone know how to do that?
(My binding returns then a jint...)
|
The short answer:
```
uint64_t foo;
int bar;
bar = foo;
```
Technically this has undefined behavior if the value offoodoes not fit in anint. In practice, it will always simply truncate the upper bits. If you want to be more correct, then:
```
if (foo-INT_MIN <= (uint64_t)INT_MAX-INT_MIN)
bar = foo;
else
/* error case here */
```
|
I experience quite annoying side-effect of class/structure padding withPurify. E.g.
```
struct something {
int field1;
char field2;
};
/* ... */
struct something smth, smth2;
smth.field1 = 1;
smth.field2 = 'A';
smth2 = smth;
```
The last line would highly likely trigger UMR warning saying that 3 bytes of initialized memory are accessed. This is obviously a false positive: there are no user data in the last three bytes of the struct, it's just a padding.
Often the warnings very very quickly fill up log files making it very hard to see the other, real problems.
Does anybody know any way to suppress the false positives?
|
I have no experience with purify, but perhaps explicitly initialising the first struct removes this warning:
```
struct something smth = {0};
struct something smth2;
```
I assume your structs have block scope (not file). If they have file scope the zero initialising is implicit.
|
for example there is code
```
#include <algorithm>
#include <stdio.h>
#include <iostream>
int intcomp(int *x,int *y) { return *x-*y;};
int a[10000];
int main(void){
int i; int n=0;
while (scanf("%d",&a[n])!=EOF)
n++;
qsort(a,n,sizeof(int),intcomp);
for (int i=0;i<n;i++)
printf("%d\n",a[i]);
return 0;
}
```
how tell computer that EOF is reached?
|
You mean when entering input interactively?
In a windows shell, ctrl+z on a line on its own. In a *nix shell, ctrl+d. Or just put your input in a file and pipe it, then not only will eof be detected at the appropriate time but also you can automate your testing.
|
I found the member variable name of m_rgNames in some source code. According to the naming convention, such as m_iNumber typed as int, rg could represent a type name. If this is case, what type did rg represent? Or else what's the meaning of rg in this variable name?
|
It stands forarray or range. The author uses theHungarian notation.
|
Given log(a) and log(b), return log(a+b)
```
double log_sum(double log_a, double log_b){
double v;
if(log_a < log_b){
v=log_b+log(1+exp(log_a-log_b));
}
else{
v=log_a+log(1+exp(log_b-log_a));
}
return v;
}
```
I want to know what are the benefits of the above function?
|
The primary (brute force) alternative looks like:
```
v = log(exp(log_a) + exp(log_b));
```
That has three transcendental function evaluations.
The computation shown uses just two transcendental functions - and should be quicker.
It may also be more stable numerically.
|
I'm using Objective-C language. But I don't know how to use c with Objective-C.
Ex) This is Function method.
```
- ( ?? ) function{
unsigned int first = ..
unsigned int second = ..
unsigned int third = ..
int infoData = {first,second,third};
return infoData;
}
```
How to fill in parenthesis.
I don't use NSArray.
Please help me.
|
the answer is the same as it is in C. Objective-C is a strict superset of C.
|
I need to run a linux command such as "df" from my linux daemon to know free space,used space, total size of the parition and other info. I have options like calling system,exec,popen etc..
But as this each command spawn a new process , is this not possible to run the commands in the same process from which it is invoked?And at the same time as I need to run this command from a linux daemon, as my daemon should not hold any terminal. Will it effect my daemon behavior?
Or is their any C or C++ standard API for getting the mounted paritions information
|
There is nostandardAPI, as this is an OS-specific concept.
However,
You can parse/proc/mounts(or/etc/mtab) with (non-portable)getmntent/getmntent_rhelper functions.Using information about mounted filesystems, you can get its statistics withstatfs.
|
If I'm writing a library in C that includes a Python interface, is it OK to just write unit tests for the functions, etc in the Python interface? Assuming the Python interface is complete, it should imply the C code works.
Mostly I'm being lazy in that the Python unit test thing takes almost zero effort to use.
thanks,
-nick
|
Tests through the Python interface will be valuableacceptance testsfor your library. They will not however be unit tests.
Unit testsarewritten by the same coders, in the same language, on the same platform as the unit which they test. These should be written too!
You're right, though, unit testing in Python is far easier than C++ (or even C, which is what you said!).
|
I'm trying to write a tool that will take as input some C code containing structs. It will compile the code, then find and output the size and offset of any padding the compiler decides to add to structs within it. This is pretty straightforward to do by hand for a known struct using offsetof, sizeof, and some addition, but I can't figure out an easy way to do it automatically for any input struct.
If I knew how to iterate through all elements in a struct, I think I could get the tool written with no problems, but as far as I know there's no way to do that. I'm hoping some StackOverflow people will know a way. However, I'm not stuck in my approach, and I'm certainly open to any alternate approaches to finding padding in a struct.
|
Isn't this whatpaholedoes?
|
Usingdeflate()I was unable to open the zipped file using WinZip. Are the gz() the only ones compatible with WinZip? or is there some sort of mode I must calldeflate()with?
|
fromhttp://www.zlib.net/zlib_faq.html
Can zlib handle .zip archives?Not by
itself, no. See the directory
contrib/minizip in the zlib
distribution.
|
I'm writing a drawing program. I'm trying to take an ordered list mouse positions, and approximate a smooth Quadratic BSpline Curve. Does anyone know how to accomplish this?
Thanks!
|
"B-spline curve fitting based on adaptive curve refinement using dominant points" by Park & Leeand"Fair interpolation and approximation of B-splines by energy minimization and points insertion" by Vassilevseem to be solving this problem. Also there look like a few references on the first link that should help you.
Converting data points to control points in areas of high curvature and removing data points in areas of little curvature is a general approach.
|
I am trying to find a program in C code that will allow me to compute a eigenvalue (spectral) decomposition for a square matrix. I am specifically trying to find code where the highest eigenvalue (and therefore its associated eigenvalue) are located int the first column.
The reason I need the output to be in this order is because I am trying to compute eigenvector centrality and therefore I only really need to calculate the eigenvector associated with the highest eigenvalue. Thanks in advance!
|
In any case I would recommend to use a dedicated linear algebra package likeLapack(Fortran but can be called from C) orCLapack. Both are free and offer routines for almost any eigenvalue problem. If the matrix is large it might be preferable to exploit its sparseness e.g. by usingArpack. All of these libraries tend to sort the eigenvectors according to the eigenvalues if they can (real or purely imaginary eigenvalues).
|
Suppose there is a C program, which stores its version in a globalchar*in main.c. Can the buildsystem (gnu make) somehow extract the value of this variable on build time, so that the executable built could have the exact version name as it appears in the program?
What I'd like to achieve is that given the source:
```
char g_version[] = "Superprogram 1.32 build 1142";
```
the buildsystem would generate an executable namedSuperprogram 1.32 build 1142.exe
|
Theshellfunctionallows you to call external applications such assedthat can be used to parse the source for the details required.
|
Given the full path, the API should give me the base file name. E.g., "/foo/bar.txt" --> "bar.txt".
|
There'sbasename().
Feed it with a path (in the form of achar*) and it will return you the base name (that is the name of the file/directory you want) in the form of anotherchar*.
EDIT:
I forgot to tell you that the POSIX version ofbasename()modifies its argument. If you want to avoid this you can use the GNU version ofbasename()prepending this in your source:
```
#define _GNU_SOURCE
#include <string.h>
```
In exchange this version ofbasename()will return an empty string if you feed it with, e.g./usr/bin/because of the trailing slash.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Are there any open source C libraries with common data structures?
What is the best source of algorithm and data structure implementations for C programmers? Links to an open source library or a book will do. (Please don't point to Sedgewick, as I already have his book).
|
Though I have not usedGDSL( Generic Data Structures Library ) I think it's worth considering as it implements many frequently used data structures.
|
Consider the following file:
```
-rw-r--r-- 1 user user 470886479 2009-12-15 08:26 the_known_universe.png
```
How would you scale the image down to a reasonable resolution, using no more than 4GB of RAM?
For example:
```
$ convert -scale 7666x3833 the_known_universe.png
```
What C library would handle it?
Thank you!
|
I believe libpng has a stream interface. I think this can be used to read parts of the image at a time; depending on the image file you might be able to get the lines in order. You could then shrink each line (e.g. for 50% shrinking, shrink the line horizontally and discard every second line) and write to an output file.
Using libpng in C can take a fair amount of code, but the documentation guides you through it pretty well.
http://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-3.8
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago.
How can I compile C code for use in .NET?
There is a game that written in C; how can I convert it to .Net code or use some parts of it?
|
You can't use C code directly within .NET.
You have a couple of options:
Compile the C code into a dynamic link library, and use P/Invoke in order to call it from your .NET program.Port the C code to .NET.Wrap the C code using C++/CLI (making a mixed mode assembly), and use these from within your other .NET language of choice.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Why is ++i considered an l-value, but i++ is not?
In C++ (and also in C), if I write:
```
++x--
++(x--)
```
i get the error: lvalue required as increment operand
However(++x)--compiles. I am confused.
|
Post- and pre-increment operators only work on lvalues.
When you call++ithe value ofiis incremented and theniis returned. In C++ the return value is the variable and is an lvalue.
When you calli++(ori--) the return value is the value ofibefore it was incremented. This is acopyof the old value and doesn't correspond to the variableiso it cannot be used as an lvalue.
Anyway don't do this, even if it compiles.
|
I want to get the source IP of UDP packet kindly guide me so that I can make it possible. I am working in c under windows platform.
|
Use therecvfromfunction. It has afromparameter that points to a sockaddr structure that will receive the source address.
|
Consider the following file:
```
-rw-r--r-- 1 user user 470886479 2009-12-15 08:26 the_known_universe.png
```
How would you scale the image down to a reasonable resolution, using no more than 4GB of RAM?
For example:
```
$ convert -scale 7666x3833 the_known_universe.png
```
What C library would handle it?
Thank you!
|
I believe libpng has a stream interface. I think this can be used to read parts of the image at a time; depending on the image file you might be able to get the lines in order. You could then shrink each line (e.g. for 50% shrinking, shrink the line horizontally and discard every second line) and write to an output file.
Using libpng in C can take a fair amount of code, but the documentation guides you through it pretty well.
http://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-3.8
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago.
How can I compile C code for use in .NET?
There is a game that written in C; how can I convert it to .Net code or use some parts of it?
|
You can't use C code directly within .NET.
You have a couple of options:
Compile the C code into a dynamic link library, and use P/Invoke in order to call it from your .NET program.Port the C code to .NET.Wrap the C code using C++/CLI (making a mixed mode assembly), and use these from within your other .NET language of choice.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Why is ++i considered an l-value, but i++ is not?
In C++ (and also in C), if I write:
```
++x--
++(x--)
```
i get the error: lvalue required as increment operand
However(++x)--compiles. I am confused.
|
Post- and pre-increment operators only work on lvalues.
When you call++ithe value ofiis incremented and theniis returned. In C++ the return value is the variable and is an lvalue.
When you calli++(ori--) the return value is the value ofibefore it was incremented. This is acopyof the old value and doesn't correspond to the variableiso it cannot be used as an lvalue.
Anyway don't do this, even if it compiles.
|
I want to get the source IP of UDP packet kindly guide me so that I can make it possible. I am working in c under windows platform.
|
Use therecvfromfunction. It has afromparameter that points to a sockaddr structure that will receive the source address.
|
I am defining some values in the preprocessor. e.g.
```
#define a 1000
#define b 0.5*a
```
When I try to use b in a place where integer is needed I get an error. I don't want to castbalways in my code and do it once in the#defineline, is that possible?
|
Try this:
```
#define a 1000
#define b (a/2)
```
|
I want to call one command(user defined) from C program(Windows).
Can you tell me the function available?
|
system()is the simplest way to call external programs.
It's a matter of doing something like:
```
system ("runme.exe");
```
The Win32 API has a lot of process control calls as well, which give you better control and monitoring. Look forCreateProcessand its brethren.
|
Is there a way to get the destination MAC address, if the destination IP is known, using ANSI C? I would preferably do it with a system call so the kernel deals with it all and I can take advantage of the ARP cache. I know I can build and send my own ARP request, but then I would not have the caching functionality etc unless I implement it myself so it feels like letting the kernel handling it is the way to go.
|
Not an exact answer, because it's not ANSI C, but you can read the arp table from/proc/net/arp(in Linux, that is). That's wherearplooks. For any other OS, the easiest way is to usestraceor an equivalent on the equivalent arp-cache-showing utility.
|
I want to extract x509 cert and private key from pkcs12 file using a C lib. I found lot of .net utils to do this, but did not find any C libraries. My code will run in WinPE environment, so .net will not work.
|
You can use OpenSSL to do this. The functiond2i_PKCS12_fp()can be used to load a PKCS#12 file into aPKCS12object, and the functionPKCS12_parse()can be used to parse the resulting object to extract the certificate and private key:
```
PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12);
int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca);
```
See thePKCS12_parse()man pagefor more details.
|
How can access the lower half of a 64bit integer using C or C++? I can do it easily in Assembly but I have no clue on how to do it in C/C++
EDIT: What about accessing the upper half?
|
```
long long BigOne = 0x1234567890ABCDEFLL;
long long LowerHalf = BigOne & 0xFFFFFFFFLL;
long long UpperHalf = (BigOne >> 32) & 0xFFFFFFFFLL;
```
Sorry if the hexadecimal literals require some prefix/suffix, I'm not very familiar with C. Please fix the answer if you know.
|
I am a beginner in C#
I wonder how to write in C# C's
```
static void example(const char *filename)
{
FILE *f;
outbuf_size = 10000;
outbuf = malloc(outbuf_size);
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename);
exit(1);
}
fwrite(outbuf, 1, outbuf_size, f);
fclose(f);
}
```
Plase help.
BTW: Well I am trying to port FFMPEG api-example presentedhereusing Tao.FFMpeg (Tao is .Net wrapper around C#.. old and with sintax exact as in FFMPEG itself) so could you please read that one and tell what I missed in my code sample...
My problem is - I understand how to port FFMpeg part and I just do not det how to port File IO part\function in the way good for .Net
|
Rather than writing all of the code for you, I'm going to direct you toSystem.IO.File.
|
```
#include<stdlib.h>
#include<stdio.h>
int main(){
int row;
int col;
int i=1;
double ** doubleNode;
// *(*(doubleNode+row)+coln)
doubleNode=malloc(sizeof(double)*4);
*doubleNode=malloc(sizeof(double *)*4);
for(row=0; row <4; row++){
for(col =0; col<4;col++){
*(*(doubleNode+row)+col)=i;
i++;
}
}
free(doubleNode);
free(*doubleNode);
return 0;
}
```
this is a test code for a double pointer. it compiles fine with gcc, but when i run it. it gives me segmetation fault. do u know where i did wrong?
thanks
|
Memory fordoubleNodemust be allocated as a pointers to double and then you should allocate memory for each pointer in array:
```
doubleNode=malloc(sizeof(double*)*4);
for (int i = 0; i < 4;++i)
doubleNode[i]=malloc(sizeof(double)*4);
```
The same applies to freeing the memory:
```
for (int i = 0; i < 4;++i)
free(doubleNode[i]);
free(doubleNode);
```
|
When moving an application from 32bit to 64bit, where will increased memory usage occur?
I understand that pointers will double in size, I suspect that the chars in a string are 'bunched' to use memory more efficiently (so will not use much more memory).
Where else would memory usage increase? Is there anywhere that it would decrease, or where non-arithmetic operations would see a speed benefit?
|
You may see additional alignment to cost a few extra bytes here and there. Code will probably be larger due to 64 bit constants in operands.
As for speed, you may experience slowdowns due to the increased memory usage. The CPU cache will fill up more quickly.
I have seen significant speed benefits going from x86 going to x64, because the x86 has far fewer registers than the x64 architecture. Compilers make use of the extra registers to better optimize your code. I saw 15% speedup on identical hardware.
|
How do i compile my c programs on mac os x, so they work on linux oses?, i've searched google for this but i seam to only get results the other way around?
|
Wouldn't it be easier to run a virtual Linux on your Mac? The reason why there are only results for the other way round is because it's not as easy to virtualise OS X in Linux.
|
Is there any way to Blit a zoomed (in) version of a certain image/sprite using SDL? (Besides manually saving a zoomed version of the image..)
Thanks :-)
|
Not with the SDL API itself.
I think there exist libraries (for SDL) who support zooming (so called resizing).
EDIT:http://www.ferzkopp.net/joomla/content/view/19/14/
|
What's the best way to sendfloat,double, andint16over serial on Arduino?
TheSerial.print()only sends values asASCIIencoded. But I want to send the values as bytes.Serial.write()accepts byte and bytearrays, but what's the best way to convert the values to bytes?
I tried to cast anint16to anbyte*, without luck. I also used memcpy, but that uses to many CPU cycles. Arduino uses plain C/C++. It's anATmega328microcontroller.
|
hm. How about this:
```
void send_float (float arg)
{
// get access to the float as a byte-array:
byte * data = (byte *) &arg;
// write the data to the serial
Serial.write (data, sizeof (arg));
}
```
|
In Photoshop there is a tool that allows the selection to be "Distorted". This allows easy shadow creation among other things. How could this sort of distortion be applied for a polygon (a bunch of points)?
Thanks
|
If your aim is to accomplish something like this (black original, red after distortion)
then you can:
fix a base for applying distortion (generally normal to the direction in which you want to distort, for example - here the direction of distortion is towards the right and the base is the bottom edge of the rectangle)displace each point on the figure by a distance proportional to its distance from the base, for example - point A (assuming it to be at 70% height) would be displaced by a distance of 0.7 * (displacement of top left corner point)
Using such a sequence of such distortion cycles, you can get the transformation that you want.
|
Lets say I have an int variable n = 8. On most machines this will be a 32 bit value. How can I only get the lower 8 bits (lowest byte) of this in binary? Also how can I access each bit to find out what it is?
|
```
unsigned n = 8;
unsigned low8bits = n & 0xFF;
```
Note a few things:
For bitwise operations, always use theunsignedtypesBits can be extracted from numbers using binary masking with the&operatorTo access the low 8 bits the mask is0xFFbecause in binary it has its low 8 bits turned on and the rest 0The low 8 bits of the number 8 are... 8 (think about it for a moment)
To access a certain bit of a number, say thekth bit:
```
unsigned n = ...;
unsigned kthbit = (1 << k) & n;
```
Now,kthbitwill be 0 if thekth bit ofnis 0, and some positive number (2**k) if thekth bit ofnis 1.
|
I know how to move, rotate, and scale, but how does skewing work? what would I have to do to a set of verticies to skew them?
Thanks
|
Offset X values by an amount that varies linearly with the Y value (or vice versa).
Edit: Doing this with a rectangle:
Let's say you start with a rectangle(0, 0), (4, 0), (4, 4), (0, 4). Let's assume you want to skew it with a slope of 2, so as it goes two units up, it'll move one to the right, something like this (hand drawn, so the angle's undoubtedly a bit wrong, but I hope it gives the general idea):
To get this, each X value is adjusted like:
X = X + Y * S
where S is the inverse of the slope of the skew. In this case, the slope is 2, so S = 1/2. Working that for our four corners, we get:
```
(0, 0) => 0 + 0 / 2 = 0 => (0, 0)
(4, 0) => 4 + 0 / 2 = 4 => (4, 0)
(4, 4) => 4 + 4 / 2 = 6 => (6, 4)
(0, 4) => 0 + 4 / 2 = 2 => (2, 4)
```
|
I'm using OpenGL and drawing polygons in a 2D view. How could I blur a polygon, without using glsl, and only things like stencil buffer and stuff. Thanks
|
The normal method uses the accumulation buffer instead of the stencil buffer. You basically re-draw your polygon(s) a number of times, but change the viewing perspective slightly each time. Exactly what you change determines the style of blur you get. For example, if you want an effect like zooming a camera lens, you can change the view frustum slightly between frames. If you want motion blur, you change the camera view angle instead. With some extra work, you can do some slightly odd-looking effects, such as moving your viewpoint forward, and zooming back at the same time, so (most of) the scene remains roughly the same size, but the perspective you're viewing it from constantly changes.
|
I foundthis tutorial about ffmpegthe thing i do not get is how to encode video.
can any one, please provide a tutorial.. with explanations for that? (not that i dont get this officialonebut i'd love to see more comments)
|
FFmpeg's developers guiderefers toanapi samplefeaturing encoding and decoding of both audio and video.This answerlinks to it as well.
|
Is there a way to redirect stdout with low level API... haven't found a function or a way to actually do this....
|
Thedupsystem call should let you redirect stdout, as shown inthis example.
freopenalso will work, if you're redirecting to a file, butdupcan also be used
with pipes and sockets.
|
One can use a CRITICAL_SECTION variable to get mutual exclusion.
My question is: does CRITICAL_SECTION support copying? If I pass one by value to another thread, can I know for sure that mutual exclusion will work?
I wouldn't be surprised if the answer is "you cannot do that", but it'd be nice to have some sort of official confirmation. I wasn't able to find a statement either way in the documentation.
|
No. ACRITICAL_SECTIONcannot be copied.MSDN states this explicitly:
A critical section object cannot be moved or copied.
|
I'm making a vector drawing application. I use this algorithm to generate outlines.
This algorthm works well, except it does not close the outline as seen here:alt text http://img716.imageshack.us/img716/2633/noclosure.png
I'm not sure what I should do to ensure that it always closes the outline. I tried inserting the last vertex at position[0] in the std::vector but this did not help.
DOUBLEPOINT looks like:
```
struct DOUBLEPOINT {
double point[2];
};
```
How can I make it so it always properly closes the shape even on sharp corners?
Thanks
|
Try appending a copy of the first and second points to the end of the vector before plotting it. Your first and last line segment will overlap, but it should ensure that all the points are connected and all corners are rounded similarly.
|
I have an iPod touch and iPad with gcc installed on them. However, everytime I try to compile my programs they always fail. I am trying to write c programs for the terminal, not GUI. I am missing the standard c/c++ libraries (stdio.h, etc.). Can anyone tell me where I can find these libraries?
|
On my system, with a vanilla install, the headers are here:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/usr/include/
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.2.sdk/usr/include/
And the libraries are here:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/usr/lib/
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.2.sdk/usr/lib/
Edit:
The headers are not on the device. You will have to copy them over. The libraries should all be on the device.
|
```
#include <errno.h>
/* compress until end of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
errno; //<-----DEBUGGER "CXX0017: Error: symbol errno not found"
perror("Error:");
if (ferror(source)) //<--ferror = 32 but there is no string from perror?
{
//error handling
```
|
When you build with the DLL version of the CRT (/MDd for example), errno is a macro. Translating it to a function call to obtain the shared value of errno. Fix it like this:
```
int err = errno;
```
so you can inspect the value of err.
|
When trying to monitor a directory using inotify on Linux, as we know, we get notified as soon as the file gets created (before the other process finish writing to it)
Is there an effective way to make sure that the file is not read before writing to it is complete by the other process?
We could potentially add a delayed read; but as we all know, it is flawed.
For a little bit more clarity on the scenario; the two processes are running as different users; the load expected is about a few hundred files created per second.
|
Based on your question, it sounds like you're currently monitoring the directory with theIN_CREATE(and maybeIN_OPEN) flag. Why not also use theIN_CLOSEflag so that you get notified when the file is closed? From there, it should be easy to keep track of whether something has the file open and you'll know that you don't want to try reading it yet.
|
How can I make Xcode tell the compiler not to link?
I am making a library which may not link to anything. Where can I set in the target's properties that it mustnotlink to the standard library, as I can choosestaticordynamiconly, there is nonotoption.
|
You haveLink With Standard Librariescheckbox in the same section of project properties (LINK_WITH_STANDARD_LIBRARIES). Just uncheck it.
|
I am reading a program which contains the following function, which is
```
int f(int n) {
int c;
for (c=0;n!=0;++c)
n=n&(n-1);
return c;
}
```
I don't quite understand what does this function intend to do?
|
Itcounts number of 1'sin binary representation of n
|
```
?? fun()
{
int a[3]={3,3,4};
return &a;
}
```
what could be the compatible return type. Here the pointer is pointing to the array of 3 integers not just the pointer which points to integer array.
Aim is to return a pointer to array of 3 integers.
|
First, youreallyshouldnotreturn the address of a local variable. When the function exits, the arrayawill get destroyed.
As for your question, the type of&aisint (*)[].
|
I have an embedded python interpreter in my program. I'd like to export a module with values defined in my program and be able to change them from a python script. e.g.
in c:int x = 1;
in python:import embedded
embedded.x = 2in c:printf("%d",x);output:2
Is this possible or do I have to export functions to change anything in c?
|
There's no need to export functions, but the easiest way to do this would be to usePyModule_GetDict()withPyDict_GetItemString()to get the value assigned to thexattribute.
|
I want to sniff network packets without wincap library, kindly give me some hints or direction so that I can make it possible.
|
You know, libpcap exists for a reason: It does something that's necessary.
You need to set up a system-level hook for TCP/IP events, and the way global hooks work means you need to do this from a DLL.
Having hooked those events, you have to figure out the contents of the packets you get.
Are you sure you want to re-invent this wheel?
I found some introductory info on hooking Windows eventshere.
|
I am having a strange problem while returning a string.
it says can not convert int to const char*
```
#include<stdio.h>
#include<conio.h>
#include <string.h>
/*The above program shows that you can not return a string from a function normally*/
char check(char str[]);
void main(void)
{
char str[30],str2[30];
printf("Enter a sentence:");
gets(str);
strcpy(str2,check(str));
getch();
}
char check(char str[30])
{
return str;
}
```
|
You have to return a char* instead
|
Lately I've been getting interest in C standardization. I want to participate in development of C1X. I want to put forward my ideas (irrespective of they being accepted/rejected).
I want to know the procedure.WG14 documentsshows various documents sorted by mailing list. Where can I join one such mailing list? How to submit a proposal? I've seen some proposals, it seems that there is no particular format for initial proposals. At the end of the document,Status of approved proposals for C9Xit gives little information about all 6 stages involved in the process.
|
"If you want further information, or want to participate, please contact your national member body or one of the contact addresses of the WG." --http://www.open-std.org/jtc1/sc22/wg14/
Although I admire your interest, picture sitting at a staff meeting that lasts for a few years if you want to get a feel for ISO WG efforts.
|
I was curious to know how exactly typedef works.
```
typedef struct example identifier;
identifier x;
```
In above statement is 'identifier' just replaced (somethings like string replacement) with 'struct example' in code? If no, what does typedef do here?
please enlighten!
|
No, it is not a string replacement - that would be macros. It creates an alias for the type.
typedefs are preferred over macrosfor custom types, in part because they can correctly encode pointer types.
```
typedef char *String_t;
#define String_d char *
String_t s1, s2;
String_d s3, s4;
```
s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention.
|
I'm looking for a C implementation of a concurrent stack (like Cilk THE protocol) that would allow the main thread to push and pop (the pop operation would be at the begining of the stack for example) and a distant thread to pop (this pop operation would be at the end of the stack) with every precaution that has to be taken.
If no code, any implementation advice would be appreciated.
Thx!
|
I would take a regular stack and wrap the push and pop functions with mutexes.
In psuedo-C:
```
void push(void *data)
{
acquire_lock(mutex);
stack_push(data)
release_lock(mutex);
}
```
Add error checking and salt to taste.
|
The footer should update with current time and hour when a new Item added to the file.
Here is the sample file format,
ITEM1ITEM206/07/2010 10:20:22//footer line
The “item” has to append in the existing file, prior to the footer line, and the footer should be updated with new value.
I am having to variables, “item” and “time” which hold the respective values as string.
After adding a new item (ITEM3) the file looks like,
ITEM1ITEM2ITEM307/07/2010 17:20:12//changed footer
Help me to acheive this.
|
Since the footer line is a static length...
Seek to the beginning of the footer line, write the new item over it followed by a newline, then write out the new footer.
(Note that this procedure is dangerous if you can't guarantee that you will always write at least enough total bytes to overwrite the existing footer, but it looks like you have exactly that assurance here.)
|
For some reason I keep getting
```
error C3861: '__typeof': identifier not found
```
when I compile my program!
I'm including the following libraries:
```
<iostream>
<stdlib>
<stdio>
```
Any ideas?
thanks
Edit:
More example
```
User.h
class User{}
main.cpp
void f(User* p)
{
.
.
.
__typeof(p) ...
.
.
.
.
}
```
|
http://msdn.microsoft.com/en-us/library/x2xw8750%28VS.71%29.aspx
__typeofonly exists for /clr:oldSyntax. Are you trying to use Managed extensions to C++ or are you expecting__typeofto work like C++0x'sdecltype? If so, if you are using VS 2010 you can usedecltype.
|
Is it possible to clear the contents (ie. set EOF to the beginning/reset the file) in C++ knowing just the FILE*? I'm writing to a temp file with wb+ access and wish to sometimes clear it and truncate it without adding the calls to fclose and fopen. I dont think it's possible... but if not, why not?
Thanks in advance!
|
It will depend on your platform. The POSIX standard providesftruncate(), which requires a file descriptor, not aFILEpointer, but it also providesfileno()to get the file descriptor from theFILEpointer.
The analogous facilities will be available inWindowsenvironments - but under different names.
|
Everyone knows how awesome C language is and how much it sucks in text processing tasks. Given these facts. Regex definitelymustbe part of ISO C. But it isn't. I don't understand why? Are there people who think its not essential?
|
Regular Expressions don't belong in the C language proper any more than a sound library, a graphics library, or an encryption library does. Doing so would reduce the general purpose nature of the language and greatly inhibit its use as a small and efficient embedded language.
The philosophy of C was to have a very small and efficient language keyword set with standardized libraries for the next layer of functionality. Since things like regex, graphics, sound, encryption, etc. don't have a single platform or standard they don't fit in with the standard C library.
They fit best as user libraries which they currently are.
|
I'm trying to compile a code for bumper switches in my robot and i get this error:" Error - symbol 'tr' has multiple definitions." What does this mean? I'm painfully new to this...
|
It depends whether you see the error at compile time or link time.
If you see it at link time (when building the program from object files), it means you have two or more object files, and the variable 'tr' (or function 'tr') is defined several times in different files.If you see it at compile time (for a single file being converted to an object file), then you have defined the variable or function more than once in the given source file.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.