question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
there has been many previous questions about redirecting stdout/stderr to a file. is there a way to redirect stdout/stderr to a string?
|
Yes, you can redirect it to anstd::stringstream:
```
std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());
std::cout << "Bla" << std::endl;
std::string text = buffer.str(); // text will now contain "Bla\n"
```
You can use a simple guard class to make sure the buffer is always reset:
```
struct cout_redirect {
cout_redirect( std::streambuf * new_buffer )
: old( std::cout.rdbuf( new_buffer ) )
{ }
~cout_redirect( ) {
std::cout.rdbuf( old );
}
private:
std::streambuf * old;
};
```
|
I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that?
|
%Lgis probably what you want: seehttp://developer.apple.com/library/ios/#DOCUMENTATION/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html.
|
I have two floating point numbers. If I add that 2 numbers means. It will displaying the answer as 4.50000 (I used just %f). If I used (2.%f) means the answer is just 4.
I want the answer as 4.5. What do I have to modify in this?
|
Try the format string%2.1f:
```
$ printf "%2.1f\n" 4.5
4.5
```
The.1says "one character after the radix".
|
The GNU coding standards document says:
It is also important for function definitions to start the name of the function in column one. This helps people to search for function definitions, and may also help certain tools recognize them. Thus, using Standard C syntax, the format is this:
```
static char *
concat (char *s1, char *s2)
{
...
}
```
Are tools that benefit from this convention, currently in significantly widespread use?
Note that I'mnotasking whether this convention is better than others in terms of readability or aesthetics - that's largely a matter of opinion - only whether tools that benefit from it, are still used.
|
grepmay use this convention:
```
$ grep '^concat (' *.c
```
And similarly for other regex-based tools, including every serious editor on Unix.
|
I have a single client that is trying to connect to my main server using socket s1. The client needs to keep trying to connect to main server with s1, but at the same time connect and keep sending "trying" messages to my secondary server. Is it a good idea to create 2 sockets,reuse port and create 2 binds for those 2 sockets or there are better ways to achieve this? This is a client side and using C sockets. Thanks.
|
If your program is a client to multiple servers, use one socket per server. You don't needbindfor a client socket at all, justconnect.
|
How to convert from anexposure valuetolux? Thanks!
i.e. what's the formula behindthis chart?
|
Forget the math on Wikipedia. By inspecting the table to which you linked, it's possible to see a pattern:
```
EV Lux
-1 1.25
-0.5 1.75
0 2.50
0.5 3.50
1 5.00
1.5 7.00
2 10.00
2.5 14.00
3 20.00
3.5 28.00
4 40.00
...
```
1 EV is 5 Lux. 2 EV is 10 Lux. 3 EV is 20 Lux. So, it looks logarithmic:
```
lux = (2 ^ ev) * 2.5;
```
(2 to the power of EV, times 2.5)
C-like:
```
#include <math.h>
double evToLux(double ev) {
return pow(2, ev) * 2.5;
}
```
Update
Wikipediahas this formula:
Update 2
It is important to point out that EV is dependent on the film speed (ISO). All above is true only for ISO 100. It is easy to convert to other speeds, though:EV(at ISO 100) == EV(at ISO 200) - 1
(H/T Nikolai Ruhe)
|
For example,inttakes 4 bytes on a 32-bit OS, but 8 bytes on a 64-bit OS, does this kind of thing exist in C?
|
Yes. This is precisely what is meant by "platform-specific definitions" for things like the size ofintand the meaning of system calls.
They depend not just on the OS, but also on the target hardware and compiler configuration.
|
```
void (assert)(int e)
{
assert(e);
}
```
How does it work here?
|
void (assert)(int e)is equivalent tovoid assert(int)
Why would you need it?
Consider the following example
```
#include<stdio.h>
void foo(int a)
{
printf("%d", a);
}
#define foo(a) {/*I do nothing*/}
int main()
{
foo(5); // won't call `foo`
}
```
How would you make sure when you callfoo, its the function that is called and not the macro-definition substituted at the place of call?
The solution is to put an extra parenthesis like(foo)(5)
Similarlyassertis already known to be a macro. That's the reason I can think of.
|
I want to simplify the following code in C. Is there any hash table in C to make it simple? For example "dict" in Python.
```
int a, b, c, d ......
a = get_value_from_sth( A_NAME )
b = get_value_from_sth( B_NAME )
c = get_value_from_sth( C_NAME )
d = get_value_from_sth( D_NAME )
......
```
|
No, C does not have a built-in hash table type like Python's dicts. You may be able to get by with an array, depending on your needs.
|
I need a program, that will make my CPU run at 100%.
Preferably in C, a tiny program, that will make the CPU run at 100%, and one, that is not "optimized" by the compiler, so it does nothing.
Suggestions?
|
```
int main(void) {
volatile unsigned x=0, y=1;
while (x++ || y++);
return 0;
}
```
Or, if you have a multi-core processor --untested ... just like the one above :)
```
int main(void) {
#pragma omp parallel
{
volatile unsigned x=0, y=1;
while (x++ || y++);
}
return 0;
}
```
|
I am thinking about an idea , where a lagacy application needing To run on full performance on Core i7 cpu. Is there any linux software / utility to combine all cores for that application, so it can process at some higher performance than using only 1 core?
the application is readpst and it only uses 1 Core for Processing outlook PST files.
Its ok if i can't use all cores , it will be fine if can use like 3 cores.
Possible? or am i drunk?
I will rewrite it to use multiple cores if my C knowledge on multi forking is good.
|
Intel Nehalem-based CPUs (i7, i5, i3) already do this to an extent.
By using their Turbo Boost mode, when a single core is being used it is automatically over-clocked until the power and temperature limits are reached.
The newer versions of the i7 (the 2K chips) do this even better.
Readthis, andthis.
|
I want to use C with templates on a embedded environment and I wanted to know what is the cost of compiling a C program with a C++ compiler?
I'm interested in knowing if there will be more code than the one the C compiler will generate.
Note that as the program is a C program, is expect to call the C++ compiler without exception and RTTI support.
Thanks,
Vicente
|
The C++ compiler may take longer to compile the code (since it has to build data structures for overload resolution, it can't know ahead of time that the program doesn't use overloads), but the resulting binary should be quite similar.
Actually, one important optimization difference is that C++ follows strict aliasing rules by default, while C requires therestrictkeyword to enable aliasing optimizations. This isn't likely to affect code size much, but it could affect correctness and performance significantly.
|
I'm working one a Visual Studio solution which was generated using CMake (not sure if this is relevant).
In this solution there a c file, I wanted to change it into a cpp file, so I renamed it and changed the extension.
However, Visual Studio still treats it like a c file and gives compiler errors whenever I add any c++ style code.
I'm stuck, any advice would be much appreciated.
|
Project Properties, Configuration, C/C++, Advanced, change "Compile As".
|
I am using C and MPI. How is memory allocated for arrays if the program runs on multiple processors on the same machine? Is that array being shared between all participating tasks or every task has it's own copy?
|
Everyrankhas its own copy of the data. They are generally run in separate processes, and so do not share a virtual address space.
Implementations likeAdaptive MPIandPhoenixput multiple ranks on threads in a common process, but they take steps to isolate each rank so that thinks it's running as a separate process.
|
The question is self-explanatory. I'm using the C API.
|
No, but it's easy to implement. It's just:
```
UChar *u_strdup(UChar *in) {
uint32_t len = u_strlen(in) + 1;
UChar *result = malloc(sizeof(UChar) * len);
u_memcpy(result, in, len);
return result;
}
```
|
I have two floating point numbers. If I add that 2 numbers means. It will displaying the answer as 4.50000 (I used just %f). If I used (2.%f) means the answer is just 4.
I want the answer as 4.5. What do I have to modify in this?
|
Try the format string%2.1f:
```
$ printf "%2.1f\n" 4.5
4.5
```
The.1says "one character after the radix".
|
The GNU coding standards document says:
It is also important for function definitions to start the name of the function in column one. This helps people to search for function definitions, and may also help certain tools recognize them. Thus, using Standard C syntax, the format is this:
```
static char *
concat (char *s1, char *s2)
{
...
}
```
Are tools that benefit from this convention, currently in significantly widespread use?
Note that I'mnotasking whether this convention is better than others in terms of readability or aesthetics - that's largely a matter of opinion - only whether tools that benefit from it, are still used.
|
grepmay use this convention:
```
$ grep '^concat (' *.c
```
And similarly for other regex-based tools, including every serious editor on Unix.
|
I have a single client that is trying to connect to my main server using socket s1. The client needs to keep trying to connect to main server with s1, but at the same time connect and keep sending "trying" messages to my secondary server. Is it a good idea to create 2 sockets,reuse port and create 2 binds for those 2 sockets or there are better ways to achieve this? This is a client side and using C sockets. Thanks.
|
If your program is a client to multiple servers, use one socket per server. You don't needbindfor a client socket at all, justconnect.
|
How to convert from anexposure valuetolux? Thanks!
i.e. what's the formula behindthis chart?
|
Forget the math on Wikipedia. By inspecting the table to which you linked, it's possible to see a pattern:
```
EV Lux
-1 1.25
-0.5 1.75
0 2.50
0.5 3.50
1 5.00
1.5 7.00
2 10.00
2.5 14.00
3 20.00
3.5 28.00
4 40.00
...
```
1 EV is 5 Lux. 2 EV is 10 Lux. 3 EV is 20 Lux. So, it looks logarithmic:
```
lux = (2 ^ ev) * 2.5;
```
(2 to the power of EV, times 2.5)
C-like:
```
#include <math.h>
double evToLux(double ev) {
return pow(2, ev) * 2.5;
}
```
Update
Wikipediahas this formula:
Update 2
It is important to point out that EV is dependent on the film speed (ISO). All above is true only for ISO 100. It is easy to convert to other speeds, though:EV(at ISO 100) == EV(at ISO 200) - 1
(H/T Nikolai Ruhe)
|
For example,inttakes 4 bytes on a 32-bit OS, but 8 bytes on a 64-bit OS, does this kind of thing exist in C?
|
Yes. This is precisely what is meant by "platform-specific definitions" for things like the size ofintand the meaning of system calls.
They depend not just on the OS, but also on the target hardware and compiler configuration.
|
```
void (assert)(int e)
{
assert(e);
}
```
How does it work here?
|
void (assert)(int e)is equivalent tovoid assert(int)
Why would you need it?
Consider the following example
```
#include<stdio.h>
void foo(int a)
{
printf("%d", a);
}
#define foo(a) {/*I do nothing*/}
int main()
{
foo(5); // won't call `foo`
}
```
How would you make sure when you callfoo, its the function that is called and not the macro-definition substituted at the place of call?
The solution is to put an extra parenthesis like(foo)(5)
Similarlyassertis already known to be a macro. That's the reason I can think of.
|
I want to simplify the following code in C. Is there any hash table in C to make it simple? For example "dict" in Python.
```
int a, b, c, d ......
a = get_value_from_sth( A_NAME )
b = get_value_from_sth( B_NAME )
c = get_value_from_sth( C_NAME )
d = get_value_from_sth( D_NAME )
......
```
|
No, C does not have a built-in hash table type like Python's dicts. You may be able to get by with an array, depending on your needs.
|
I need a program, that will make my CPU run at 100%.
Preferably in C, a tiny program, that will make the CPU run at 100%, and one, that is not "optimized" by the compiler, so it does nothing.
Suggestions?
|
```
int main(void) {
volatile unsigned x=0, y=1;
while (x++ || y++);
return 0;
}
```
Or, if you have a multi-core processor --untested ... just like the one above :)
```
int main(void) {
#pragma omp parallel
{
volatile unsigned x=0, y=1;
while (x++ || y++);
}
return 0;
}
```
|
I am thinking about an idea , where a lagacy application needing To run on full performance on Core i7 cpu. Is there any linux software / utility to combine all cores for that application, so it can process at some higher performance than using only 1 core?
the application is readpst and it only uses 1 Core for Processing outlook PST files.
Its ok if i can't use all cores , it will be fine if can use like 3 cores.
Possible? or am i drunk?
I will rewrite it to use multiple cores if my C knowledge on multi forking is good.
|
Intel Nehalem-based CPUs (i7, i5, i3) already do this to an extent.
By using their Turbo Boost mode, when a single core is being used it is automatically over-clocked until the power and temperature limits are reached.
The newer versions of the i7 (the 2K chips) do this even better.
Readthis, andthis.
|
I want to use C with templates on a embedded environment and I wanted to know what is the cost of compiling a C program with a C++ compiler?
I'm interested in knowing if there will be more code than the one the C compiler will generate.
Note that as the program is a C program, is expect to call the C++ compiler without exception and RTTI support.
Thanks,
Vicente
|
The C++ compiler may take longer to compile the code (since it has to build data structures for overload resolution, it can't know ahead of time that the program doesn't use overloads), but the resulting binary should be quite similar.
Actually, one important optimization difference is that C++ follows strict aliasing rules by default, while C requires therestrictkeyword to enable aliasing optimizations. This isn't likely to affect code size much, but it could affect correctness and performance significantly.
|
I'm working one a Visual Studio solution which was generated using CMake (not sure if this is relevant).
In this solution there a c file, I wanted to change it into a cpp file, so I renamed it and changed the extension.
However, Visual Studio still treats it like a c file and gives compiler errors whenever I add any c++ style code.
I'm stuck, any advice would be much appreciated.
|
Project Properties, Configuration, C/C++, Advanced, change "Compile As".
|
I am using C and MPI. How is memory allocated for arrays if the program runs on multiple processors on the same machine? Is that array being shared between all participating tasks or every task has it's own copy?
|
Everyrankhas its own copy of the data. They are generally run in separate processes, and so do not share a virtual address space.
Implementations likeAdaptive MPIandPhoenixput multiple ranks on threads in a common process, but they take steps to isolate each rank so that thinks it's running as a separate process.
|
Is there any way to find out the parent directory of a file using C program. I would like to give same permissions for the file that the directory has. So as to do so, i would like to know the parent directory of the file. Any help is appreciated.
|
If you have the path of the file, you can do it manually by making it an absolute path if it is relative (doesn't begin with a/on Unix, or aletter:\or\orletter:/or/on Windows) and then splitting it on file separator characters (/or\), but I am aware of no built-in function that will do all of this for you.
Thebasenameanddirnamefunctions may help, but you'll need to figure out enough of the path of the file yourself, as they only work with strings; they do not interrogate the file system.
|
I want to share my local saved image and formatted text on Twitter or Facebook using my application.
For example, I want to combine both image and bolded text in a single post.
Are there any APIs available for it?
|
I recommend usingShareKitin your iOS application.
It is very easy to integrate a variety of Social Networking sites.
|
(In c++)I want to make a process that will run on multiple computers that share the same file (on the same hard disk). And from each process I want to write to the end of a file, but only when no other process is using that file.
How can I lock that file when writing to it, or at least check if another process is using it?
|
When you will try to open the file, it will fail if it is already being used.
To see if opening has failed, you can either :
Checkios::fail()Callios::exceptions()before opening the file,
|
I have to replace the nano-X stuff in our linux embedded application and need some replacements for the drawing functionsArc, Rect, FillRect, Ellipse, FillEllipse, Line, Text, DrawImageFromFile.
Does anyone know of a suitable open source library that I can use to replace these? Ideally it should work with a pixel buffer in 16bit color, so that writing to the linux framebuffer device is possible.
I thought aboutlibcairobut that is a rather big package fro just this purpose. The use of Qt 4.7 is planned for the future and I'm sure it contains the necessary drawing functions. Should I go directly with that?
|
The first library that comes to mind isSDL. Also have a look atGGI(It is much simpler than SDL).FLTKtoo have a simple 2D/3D interface but it is C++.
|
I don't want the class to cause a crash due to too many values. I realize that it would take 268,435,456 integers (if I did my math correctly) to take up one gigabyte (which is pretty extreme). This value is merely an eighth of asignedinteger's maximum value (which is what I am currently using for the length. Should I put a cap on this? If so, what would be a reasonable number? Would an unsigned short be a reasonable length? Have you ever needed an array with more than 65,536 values?
|
Placing arbitrary limits on your classes is considered bad practice.
You should allow the user to put as many items as they want into your container; if they try to put too many in, it's their job to deal with thestd::bad_allocexception that will be thrown.
|
Is there a C API call to set/remove the relief around a GTK menu bar object? I can't locate it in the documentation. Can this only be done with a style file?
In this picture I've added a border of 5 pixels to the container holding the menu to highlight the relief - can I remove the relief altogether?
|
I think the solution is to change the value of the "shadow-type" style property of your GtkMenuBar object toGTK_SHADOW_NONE.
You may find on stackoverflow more information abouthow to change a style property.
|
i am required to produce something similar to ptree in solaris for my assignment.
to do something like that i would need the child PID of the processes.
i already have the list of processes running on the machine but the only information i have are the parent PID of each processes. is there any way to fetch the child PID of each process in the system?
the program will be ran on a solaris machine.
|
You said you already have the list of processes and their parents. To find the child PIDs of any process, simply loop over the processes looking for ones whose parent PID is the PID of the process you're investigating.
|
While trying to open the file in Class in function oninitdialog(),It throws exception.If I open the file globally , it works.
How to overcome this?
why the fopen command is behaving like these?
Regards,
karthik
|
Actually I made a mistake by creating file descriptor in OninitDialog function in mfc.To overcome this , I create the file descriptor in constructor of the class.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Magic numbers of the Linux reboot() system call
I was asked this question in an interview
When using the Linux-specific reboot()
system call to reboot the system, the
second argument, magic2, must be
specified as one of a set of magic
numbers (e.g., LINUX_REBOOT_MAGIC2).
What is the significance of these
numbers?
What is the correct answer to the above question?
|
The significance of the allowed set of magic2 numbers is that, when expressed in hexadecimal, they represent dates-of-birth (specifically, of Linus Torvalds and his three children).
Thisreallylowers the bar on silly interview questions!
|
I have developed (compiled) some (C/C++) applications on my local machine, which has the ext4 file system. I want to deploy the compiled binaries to my server - which has a ext3 file system format.
Can I simply create a package and deploy the binary on the server - or are the file systems incompatable?
BTW, both my local dev machine and the remote server are running Ubuntu 10.0.4 LTS
|
You absolutely can. File system formats are completely irrelevant to binary executable formats. You can transfer files from one system to another with no ill effects.
Of course, if your program has external dependencies (shared libraries) then the other system might not have all that's necessary to run your program -- but that's another problem altogether.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Why is the `gets' function is dangerous? Why should not be used?
Just started a tutorial in socket programming. But I got this error after compiling with gcc. How to overcome this gets dangerous?
```
In function `main':
tcpserver.c:(.text+0x1f3): warning: the `gets' function is dangerous and should not be used.
```
This line of code was obtained from internet (http://www.prasannatech.net/2008/07/socket-programming-tutorial.html):
```
printf("\n Your message (hit q or Q to quit): ");
gets(send_data);
```
|
gets()blindly writes data into the buffer you give it. It neither knows nor cares about the length of the buffer, making it abuffer overflowwaiting to happen. If you can, usefgets()instead.
For (slightly) more on the dangers of gets, seethe Linux gets/fgets manpage.
|
For example:
```
void func(const int i);
```
Here,theconstis unnecessary since all parameters are passed by value(including pointers).
Is that true?
|
All parameters in C are indeed passed by value, which means that the actual argument will not change regardless of whether you include thatconstor not.
However, that does not mean thatconsthere is "never necessary". Whether it is necessary or unnecessary depends on what you want to achieve.
If you want to prevent any attempts to modify the parameter inside the function, then theconstisnecessary, of course.
There is a fairly popular (and pretty reasonable) coding guideline that says that function parameters should never be modified inside the function, i.e. that at any point of function's execution all parameters must retain their original values. Under this guideline it would actually make perfect sense toalwaysinclude thatconstinallparameter declarations.
|
I'm developing some programs in C that intercommunicate through message queue.
So for example in the two programs there is a line like this:
msgget(key, 0666 | IPC_CREAT);
They share the same key and the same message structure.
However was wondering: What about the security?
If another program write messages on the same queue of the two above could be a problem for me.
Do you have any kind of suggestion for dealing with security in the meaning of authentication and authorization?
Thanks a lot,
Andrea
|
With0666permissions any process can access the message queue. You can make it more secure by using more restrictive permissions like0600so only the current user can access it.
|
I'm wondering if it is possible to implement the following logical under Linux and using POSIX thread library.
```
given a mutex
if (I can get the mutex) {
lock the mutex
call fun A
unlcok the mutex
}
else {
call fun B
}
```
I'm new to thread programming under Linux, so just use the pseudo-code to show the logic of the code snippet I'm looking for.
|
You're looking forpthread_mutex_trylock
|
```
#include <stdio.h>
#include <stdlib.h>
int main( void ) {
char *ptr1 = "Hello World\n";
char *ptr2;
ptr2 = ptr1 + 6;
ptr2 = "Test!\n";
printf("%s",ptr2);
printf("%s",ptr1);
return EXIT_SUCCESS;
}
```
Output:
```
Test!
Hello World
```
Why didn't I getHello Test!?
I thought id would overwrite theWorld-part fromptr1.
|
The line
```
ptr2 = "Test!\n";
```
Doesnotchange the contents of the buffer pointed at byptr2. Instead, it just changes whatptr2points at. In C, pointer assignment just says "I want this pointer to stop referencing what it used to reference, and to instead point at something else." If you actually want to change the value being pointed at, you either need to dereference the pointer or call a function that dereferences it (for example,strcpy,strcat, etc.)
Consequently, the output is what you've listed above, with "Hello World" intact.
|
I'm trying to write a program that uses tgkill to send a signal to a specific thread, but whenever I compile it with gcc I get an error about an undefined reference to 'tgkill'. I tried compiling with -lpthread but it didn't help. I've googled and googled and can't come up with any answers. How do I get it to compile??
|
From thetgkill()manpage:
Glibc does not provide wrappers for
these system calls; call them using
syscall(2).
|
My program has one background thread that fills and swaps the back buffer of a double buffer implementation.
The main thread uses the front buffer to send out data. The problem is the main thread gets more processing time on average when I run the program. I want the opposite behavior since filling the back buffer is a more time consuming process then processing and sending out data to the client.
How can I achieve this with C POSIX pthreads on Linux?
|
In my experience, if, in the absence of prioritisation your main thread is getting more CPU then this means one of two things:
it actually needs the extra time, contrary to your expectation, orthe background thread is being starved, perhaps due to lock contention
Changing the priorities will not fix either of those.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed12 years ago.
I'm using dev c++ but it has creating some problems while working with windows 7
So want the best compiler which is works with windows 7.
By best I mean whiich will give me the best performance.
|
well, there are many to choose from:
Visual Studio, works 'best' with MS
OSesEclipseorCode::BlockswithGCC, works 'best' with standard
C99 codePelles Cworks best at being simple
Your choice really boils down to what you require and what your working with, so just look at the above examples, pick what suites you best
|
I have a function that will pass a string and manipulate. in the function call i am passing the string as such likemyfunc ("hello");
In the function definition i have
```
myfunc (char *array)
{
xxxx
};
```
The program is working fine, but it throws a warning "pointer targets in passing argument 1 of 'myfunc' differ in signedness".
How to rectify this problem?
|
Strings are actually arrays ofconstantcharacters. That is, the type of"hello"isconst char[6].
What this means is you cannot modify it. However, due to a silly conversion in C++, the array (in string literal form) can be implicitly converted to anon-constpointer to the first element. This is misleading, and dangerous. (Indeed, a const-stripping implicit conversion doesn't exist anywhere else.)
You should make sure you have a modifiable buffer instead:
```
char buffer[] = "hello";
myfunc(buffer);
```
|
What is the output of the following code:
```
int main() {
int k = (k = 2) + (k = 3) + (k = 5);
printf("%d", k);
}
```
It does not give any error, why? I think it should give error because the assignment operations are on the same line as the definition ofk.
What I mean isint i = i;cannot compile.
But it compiles. Why? What will be the output and why?
|
int i = icompiles because 3.3.1/1 (C++03) says
The point of declaration for a name is immediately after its complete declarator and before its initializer
Soiis initialized with its own indeterminate value.
However the code invokes Undefined Behaviour becausekis being modified more than once between two sequence points. Read this FAQ onUndefined Behaviour and Sequence Points
|
Why does the following code compile? Which section of the language allows URLs to be added in C and C++ code?
```
int main()
{
http://www.stackoverflow.com
return 0;
}
```
Thanks in advance, Castro.
|
If you compiled with warnings, you would notice:
```
warning: label ‘http’ defined but not used
```
That should be indicative enough of the problem here.
Thehttp:text is treated as a label.
Followed by//negating the remaining text as a comment, ignoring it.
```
http://www.stackoverflow.com
```
Even the SO syntax colour schemes indicated as above show this to be true, as the section after the http, is treated as a comment (grayed out).
|
It seems to have no impact on the functionality of sbrk, but in sbrk()'s documentation it says that it requires an intptr_t parameter.
It works (or at least seems to work) when passing an int type as a parameter.
This is in regular C.
|
intptr_tchanges size depending on the architecture.intmay or may not change size depending on the architecture- that is, if you are on 64bit, thenintptr_tMUST be 64bits, whereasintmaybe 32bits.
|
I've tried this:
```
if (argc > 2) {
int i;
for(i = 0; i < argc; i++) {
if(i != 0) {
rename_file(argv[i]);
}
}
}
```
if I pass in two file names only the first is renamed, whats wrong with this loop?
EDIT: Heres the rename_file function (it should work I think)
```
void rename_file(char const *filename) {
struct tm *clock;
struct stat attrib;
const char *dot = strrchr(filename, '.');
const char *ext = NULL;
if (dot && *dot) {
ext = dot + 1;
}
stat(filename, &attrib);
clock = gmtime(&(attrib.st_mtime));
char newname[250];
if (!ext) {
printf("ERROR: No File Extenstion");
} else {
sprintf(newname, "%02d_%02d_%02d.%s", clock->tm_mday, clock->tm_mon, clock->tm_year + 1900, ext);
}
rename(filename, newname);
}
```
|
Try this:
```
if (argc > 2) {
for(int i = 1; i < argc; i++) {
rename_file(argv[i]);
}
}
```
|
Given the input ~Zw~~"iE^L I should get !w~"iE^L instead I am getting Zw~"iE^L
So it catch the ~~ just fine and replace it with ~ but I want to replace ~Z with !
Any ideas?
```
for (j = 0; j < dataCharCount; j++, k++)
{
if (inputData[j] == '~' && inputData[j + 1] == '~')
{
filteredInputData[k] = '~';
j++;
}
else if (inputData[j] == '~' && inputData[j + 1] == 'Z')
{
filteredInputData[k] = '!';
j++;
}
filteredInputData[k] = inputData[j];
}
```
|
```
} else {
filteredInputData[k] = inputData[j];
}
```
Without the else you're overwritingfilteredInputData[k]after the if statements.
|
This question was asked of me in an interview. How can we convert a BT such that every node in it has a value which is the sum of its child nodes?
|
Give each node an attached value. When you construct the tree, the value of a leaf is set; construct interior nodes to have the valueleaf1.value + leaf2.value.
If you can change the values of the leaf nodes, then the operation has to go "back up" the tree updating the sum values.
This will be a lot easier if you either include back links in the nodes, or implement the tree as a "threaded tree".
|
I define a structure in a header file like so:
```
typedef struct {
void *data;
} point;
```
I want to keep other people from accessing *data directly, so I thought I'd declare the structure in the .c file instead and use something likeextern typedef struct point;in the header file. That doesn't work however.
What's the best way to achieve this?
|
In your (public) header file:
```
typedef struct point point;
```
In your.cfile:
```
struct point
{
void *data;
};
```
Note that users of your code will no longer be able to create apointon the stack, as the compiler doesn't know how big it is. You may have to provide apoint_create()function which allocates memory and returns its address to the caller.
|
My target is to make a program (using C++) which would take C source code as input and check for"SYNTAX ERRORS ONLY".
Now for this, do i need to know about Regular Expressions, Grammar generation and Parsers??
I would like to use tools like Yacc/Flex/Bison - but the problems i am facing are -
How to use these tools? I mean i am only scratching at the surface when i read about these tools - i feel clueless.How can i use these tools in tandem with my C++ source code?How "The Hell" do i Get Started with this?
|
Use somebody else's C parser. For example, the parser used by the clang project.http://clang.llvm.org/
Then you can focus on the other hard part of your problem: detecting errors.
|
My target is to make a very simple and basic C syntax checker. (Not a full Compiler but just a basic Program which take a source code as Input and would print out the code back showing the errors). I want to use C++ as the language for this.
Can anyone guide me to write regular expression in 'c++' language for the following:
AssignmentForswitch
Any details/suggestions/guidance further would be much appreciated.
|
I don't think you can parseCwith regular expressions alone. You'll need to start looking into lexers, parsers, grammars, etc...
A good starting point could be this:Quick Starter on Parser Grammars - No Past Experience Required.
You can findCgrammars online foryacc/lex.
|
The ancient Egyptians only used fractions of the form1/nso any other fraction had to be represented as a sum of such unit fractions and, furthermore, all the unit fractions were different!
What is a good method to make any fraction an egyptian fraction (the less sums better) in C or java, what algorithm can be used, branch and bound, a*?
for example:
```
3/4 = 1/2 + 1/4
6/7 = 1/2 + 1/3 + 1/42
```
|
One way is the greedy algorithm. Given the fractionf, find the largest Egyptian fraction1/nless than or equal tof(i.e., n = ceil(1/f)). Then repeat for the remainderf - 1/n, untilf == 0.
So for 3/4, you'd compute:
n = ceil(4/3) =2; remainder = 3/4 - 1/2 =1/4n = ceil(4) =4; remainder = 1/4 - 1/4 = 03/4 = 1/2 + 1/4
And for 6/7:
n = ceil(7/6) =2; remainder = 6/7 - 1/2 =5/14n = ceil(14/5) =3; remainder = 5/14 - 1/3 =1/42n = ceil(42) =42; remainder = 1/42 - 1/42 = 06/7 = 1/2 + 1/3 + 1/42
|
I tried googling this and I couldn't find anything informative enough for my understanding.
```
int i;
char msg1[] = "odd";
char msg2[] = "even";
char *ptr;
__asm__(" \
movl i, %eax\n\
andl $1, %eax\n\
jz zero\n\
movl $msg1, %eax\n\
jmp done\n\
zero:\n\
movl $msg2, %eax\n\
done:\n\
movl %eax, ptr\n\
");
```
Why does some need$and the other (such as i) not have a$sign?
|
$1is constant one
```
`andl $1, %eax` this means do AND of 1 and EAX register.
```
$is prefixed infront of contants and immediate valued.
msg1 and msg1 are addresses of the two arrays. So they are too prefixed with$.
iis a c variable. Which is accessed using amemory access(Indirect reference).
Check thisreference.
|
I know, that everybody hates GOTO and nobody recommends it. But that's not the point. I just want to know, which code is the fastest:
thegotoloopint i=3;
loop:
printf("something");
if(--i) goto loop;thewhileloopint i=3;
while(i--) {
printf("something");
}theforloopfor(int i=3; i; i--) {
printf("something");
}
|
Generally speaking,forandwhileloops get compiled to the same thing asgoto, so it usually won't make a difference. If you have your doubts, you can feel free to try all three and see which takes longer. Odds are you'll be unable to measure a difference, even if you loop a billion times.
If you look atthis answer, you'll see that the compiler can generate exactly the same code forfor,while, andgoto(only in this case there was no condition).
|
```
$ gcc -m32 hw3.c -o hw3
Undefined symbols:
"i", referenced from:
_main in ccuNMbgT.o
_main in ccuNMbgT.o
(maybe you meant: _i, _main , cstring=hey, supposed to supply an integer argument , cstring=after multiply, value is %d
, _i$non_lazy_ptr , _printf , _environ , _atoi , _exit )
ld: symbol(s) not found
collect2: ld returned 1 exit status
```
I'm doing assembly with some C. I'm trying to compile an example that worked on Ubuntu compiled usinggcc, but its not working on my Mac terminal.
|
It told you the problem and gave you the solution ("maybe you meant: ..."). Whether C symbols get underscores prepended to them in assembler is one of those things that is highly platform-dependent; on OS X they do, so when referring to a variable named "i" in C you must call it "_i" in assembler.
|
I'm looking for an image manipulation library, preferably in .NET, that makes it easy to recognize and manipulate faces in images. Is there a library out there that does this?
|
There isOpenCV(Open Source Computer Vision), which is a is a library of programming functions for real time computer vision.
I'm not familiar with it, so I don't know if it will make "easy to recognize and manipulate faces in images", but you can give it a look. It's not in .Net, but you tagged your question with C++ and Python, and it works with those.
|
I used the write function to write some stuff into a file. now i want to insert a blank link into the file before the next write function, do anyone know how to do that?
```
Write(logs,log,strlen(log));
```
is my first write, so now is the new line going to be:
```
Write(logs,'/n',strlen(log));
```
or should I create a newchar[3] = '/n';?
|
Assuming that you mean the POSIXwrite()function, something like this should work:
```
write(logs,"\n",1);
```
Note that"\n"is a 1 character string - you may want"\r\n"depending on if you need a carriage return and a new line in the file.
|
Why does following program produce two output message at the same time, without asking for any input from the user???
```
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char input;
do {
printf("Enter a single character: \n");
scanf("%c", &input);
printf("The ordinal value is %d. \n",input);
} while(input != '#');
return 0;
}
```
The output is followings:
```
Enter a single character:
s
The ordinal value is 115.
Enter a single character:
The ordinal value is 10.
Enter a single character:
```
|
Terminal input is read line at a time unless you specify otherwise;scanfreads one character as specified, leaving the newline you typed afterward to send the line in the input buffer for the next pass of the loop. Consider reading input by lines and usingsscanf()or similar to parse those lines.
|
What's the trick to create a variadic macroFOO(a1, a2, a3,..., an)such that it expands toFOOn(a1, a2, a3,..., an)for values ofnin whatever preselected bounded range you choose? That is,FOO(a)should expand toFOO1(a),FOO(a, b, c)toFOO3(a, b, c), etc. I know there's a standard trick but I can't seem to find it.
Please feel free to mark this question as a duplicate and close it if there's another question with the answer. I suspect there is but I couldn't find it.
|
```
#define VA_NARGS_IMPL(_1, _2, _3, _4, _5, N, ...) N
#define VA_NARGS(...) VA_NARGS_IMPL(__VA_ARGS__, 5, 4, 3, 2, 1)
#define FOO_IMPL2(count, ...) FOO ## count (__VA_ARGS__)
#define FOO_IMPL(count, ...) FOO_IMPL2(count, __VA_ARGS__)
#define FOO(...) FOO_IMPL(VA_NARGS(__VA_ARGS__), __VA_ARGS__)
FOO(a)
FOO(a, b)
FOO(a, b, c)
```
The invocations are replaced by:
```
FOO1 (a)
FOO2 (a, b)
FOO3 (a, b, c)
```
|
For example:
```
int x[100];
void *p;
x[0] = 0x12345678;
x[1] = 0xfacecafe;
x[3] = 0xdeadbeef;
p = x;
((int *) p) ++ ;
printf("The value = 0x%08x", *(int*)p);
```
Compiling the above generates an lvalue required error on the line with the ++ operator.
|
The cast creates a temporary pointer of typeint *. You can't increment a temporary as it doesn't denote a place to store the result.
In C and C++ standardese,(int *)pis anrvalue, which roughly means an expression that can only occur on the right-hand side of an assignment.
pon the other hand is anlvalue, which means it can validly appear on the left-hand side of an assignment. Only lvalues can be incremented.
|
Is there anycorjavaexample implementingBayesian Net?
I want to solve some things but Do not where to start?.
|
Use Weka. It not only implements Bayes Nets, but also a lot of other ML algorithms.
|
Could someone help me with what the equivalent of this C code is in C#?
```
struct { int left, right; } stack[MAX];
```
Thanks!
|
```
public struct PickAName
{
public int left;
public int right;
}
private const int MAX = 666;
PickAName[] stack = new PickAName[MAX];
```
or:
```
Stack<PickAName> stack = new Stack<PickAName>();
```
|
I'm creating Java wrappers for some C code using JNI. There are dependencies on the C side that look like this:
```
a = make_a();
b = make_b(a);
```
On the Java side I useclass Aandclass Bto hold references to the output ofmake_a()andmake_b, along with various operations. Further,class Bdependsclass Asticking around.
How can I create a dependency between the two classes from within JNI?
Update
I need class A to not be GC'd while class B is in use, and I need to create this dependency from within JNI.
|
I think what you want is NewGlobalRef/DeleteGlobalRef. This will let your JNI hang on to an object reference. Be careful-- this is an easy way to create memory leaks as its up to you to delete the reference!
Here are some links to get you going:
What is 'JNI Global reference'Local and Global ReferencesJNI Functions
|
I use this for loop, which I want to have parallelizide automaticaly, it is used for count of PI number:
```
piece=1.0/100000;
for (t=0.0; t<1.0; t=t+piece){
x=t+piece/(float)2;
if(x<=1.0){
integral=4/(1+x*x);
sum=sum+integral;
}
}
```
This is doint partial sum for all values in interval 0-1. Then I made from it PI value. But this is not the problem, problem is, when I use automatic parallelization with pgcc, I set up number of processes but I am told that "Loop not vectorized/parallelized: not countable" when I am compiling my program. I have tried everything, but still no change. Any ideas? Thanks
|
Your loop variable is a double, try changing the code so it uses an integer:
```
for (int t = 0; t < 100000; t++) {
x=(t/100000.0)+piece/(float)2;
if(x<=1.0){
integral=4/(1+x*x);
sum=sum+integral;
}
}
```
|
do you know how to use gettimeofday for measuring computing time? I can measure one time by this code:
```
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
```
This one is made before computing, second one after. But do you know how to subtracts it?
I need result in miliseconds
|
To subtract timevals:
```
gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
```
This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:
```
long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;
```
|
OS: Windows Language: C#/C/C++
Does anyone know how to open a file in Remote computer.
I could find few samples for unix but not for windows.
Thanks for your help.
|
You simply specify the UNC name of the file in your fopen() statement. Like //server/share/filename. The remote machine must be configured to support file sharing and the user account under which your program runs must have sufficient access rights. If "remote" means through the Internet then you have to use one of the standard Internet protocols. FTP or HTTP are typical.
|
I'm using the picdem F184550, I want to read the value of the led, I'm using the mplab ide v8.63 with a C compiler. but I don't have a idea how to interface with the port RB7 where my led with a resistor is connected to. The question is, how can I read the port RB7 where my led is connected to in the program language C. thanks! (see picture
|
This depends on the compiling suite you are using.
Those provided by Microchip (C18 for 18F MCUs) usually define all available ports & registers in a header file specific to your device (something like p18F4550.h in your case).
In this header, you will have a structure definition corresponding to your specific port register.
You can access to your specific RB7 I/O,within the following field : PORTBbits.RB7
|
Why is empty struct in C a constraint violation? Why does this rule get changed in C++?
Are there any historical reasons?
|
since you don't have inheritance in C you don't need them. If you just want to have a distinguishable pointer type you can use pointers to incomplete types.
```
struct opaque;
struct opaque* stranger = 0;
```
should work fine.
|
```
fd1 = open("/dev/test_kft" "1",00);
```
What does"/dev/test_kft" "1"mean?
|
It's implicit concatenation as performed by the compiler. It results in"/dev/test_kft1".
|
I'm creating a tftp-like program but instead of stop and wait, I'm trying to use a go-back-n approach. I'm not exactly sure how to go about this as I have very little socket programming experience.
I have my client sending all of the data with sendto, and am currently just not calling recvfrom because it will wait until I get a response, but I don't want it to wait. I want to check if there was a response, but if not, keep sending data.
Can someone point me in the right direction? Please let me know if more information is needed, I'm having trouble elaborating.
Thanks!
|
Create a non-blocking socket and useselect()(orpoll()or whatever other mechanism you have at hand) to wait for both writability and readability of the socket. Then respond appropriately to each state independently when it arises.
I've never done this with UDP, but I see no reason that it shouldn't (a quick Google seems to reaffirm that).
|
I came across this piece of code:
```
void incme(double *p)
{
*p += 1;
}
int i = 1;
incme((double *)&i); /* WRONG */
```
When I try to execute it, I get core dump. What is wrong with this code. Can we not type cast an int pointer to a double type.
Thank you.
|
You're not casting anintto adouble, you're casting anint *to adouble *. That's not safe ifsizeof(double)andsizeof(int)aren't the same...
Even if you match up the storage sizes, what do you expect the output to be? Floating-point types and integers tend not to have any kind of compatible representations.
|
```
#include <stdio.h>
#define STR(x) #x
#define STR2(x) STR(x)
#define LINE_FILE ("Line " STR2(__LINE__) " of file " STR2(__FILE__))
int main(void)
{
const char *str = LINE_FILE;
printf("%s\n", str);
return 0;
}
```
Is this the only definition scheme that will make STR(x) to print the actualLINEandFILE???
|
```
STR2(__FILE__)
```
__FILE__is already a string literal: you don't need to useSTR2here.
You should also probably remove the parentheses from the macro so that it can be concatenated with other string literals, if you wanted to do that:
```
#define LINE_FILE "Line " STR2(__LINE__) " of file " __FILE__
```
|
For those who have compiled from source knows how much of a pain it is to run "./configure" only to find that X library or missing, worst yet it spits out a silly line saying a cryptic lib file is missing, which you then have to go to a web browser type in the missing file cross you fingers that Google can find the answer for you...
I find that very repetitive, so my question is:
Is there a way to work out all the required dependencies but without doing "./configure"
|
Read the README* or INSTALL* files in the source distribution, if there are any, or look for any documentation on the website where you downloaded it from. If the package is well documented, dependencies will usually be listed somewhere.
|
I am trying to add/replace album art of MP3 files. Is there an Objective-C framework that will allow me to do this? If not, what the best way to do this? I don't mind using C or C++ but it's better if it's in Objective-C. Thanks!
Update: I found an audio framework called SFBAudioEngine which can edit metadata of several audio formats but when I compile the sample project in it, I get 2094 errors.
|
Since Objective-C is a strict superset of C itself, I would suggest compiling a library that handles ID3 tags (id3liborlibid3tagcome to mind) and use their functions directly or build a class around what they provide. Good luck!
|
I am currently working on a linux daemon that needs to be single instance (i.e restricted to 1 user 1 process). What would be the best way of doing so without having to usegetpid()to manually write the pid out to/var/run/and then lock it usingflock()?
|
Wrap the start-up and shut-down withstart-stop-daemon.
|
In C, How can I reset a given pointer to have all values in an array be a specified value? Is it best using a for loop, or is there a function that I can use to set all values in an array to 0.
My code currently is something like this:
```
int main()
{
double *my_values = calloc(10, sizeof(double));
do_something_with_values(my_values);
free(my_values);
my_values = calloc(10, sizeof(double));
do_something_else_with_values(my_values);
free(my_values);
}
```
This (to me) seems hacky, how can I improve this code?
|
memset can set an array to all zero's or whatever value you want
|
Is it safe to do something like the following?
```
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void)
{
char* msg;
strcpy(msg, "Hello World!!!"); //<---------
printf("%s\n", msg);
return 0;
}
```
Or should the following be used?
```
char* msg = (char*)malloc(sizeof(char) * 15);
```
|
strdup does the malloc and strcpy for you
```
char *msg = strdup("hello world");
```
|
My code is full of calls toassert(condition).
In the debug version I useg++ -gwhich triggers my assertions.
Unexpectedly, the same assertions are also triggered in my release version, the one compiled without-goption.
How can I completely disable my assertions at compile time? Should I explicitly defineNDEBUGin any build I produce regardless of whether they are debug, release or anything else?
|
You must#define NDEBUG(or use the flag-DNDEBUGwithg++) this will disable assert as long as it's defined before the inclusion of the assert header file.
|
How do I concatenate Strings with C/C++?
I tried the following ways:
PS: errorInfo is a char * I should return it.
```
errorInfo = strcat("Workflow: ", strcat(
workflowToString(workflow).utf8(), strcat(" ERROR: ",
errorCode.utf8)));
sprintf(errorInfo, "Workflow %s ERROR: %s",
workflowToString(workflow).utf8(), errorCode.utf8());
errorInfo = "Workflow: " + workflowToString(workflow).utf8() + " ERROR: " + errorCode.utf8;
```
Just the sprintf compiles but when running my application crash.
PS: I'm using NDK from Android
|
ThereISN'Tsuch a language as C/C++. There is C, and there is C++.
In C++ you concatenatestd::string's by usingoperator+In C, you use strcat
I know this doesn't quite answer your question, this is just an outcry :)
|
I am doing some scientific work on a system with a queue. The cout gets output to a log file with name specified with command line options when submitting to the queue. However, I also want a separate output to a file, which I implement like this:
```
ofstream vout("potential.txt"); ...
vout<<printf("%.3f %.5f\n",Rf*BohrToA,eval(0)*hatocm);
```
However it gets mixed in with the output going to cout and I only get some cryptic repeating numbers in my potential.txt. Is this a buffer problem? Other instances of outputting to other files work... maybe I should move this one away from an area that is cout heavy?
|
You are sending the value returned byprintfin vout, not the string.
You should simply do:
```
vout << Rf*BohrToA << " " << eval(0)*hatocm << "\n";
```
|
I've implemented the codeherein C# to get the MSB of an int. I'm not certain what I need to do with the log reference table and the main code to extend the code to 64 bit.
The only thing the text says is it will take 2 more CPU ops, so I deduce the change is minor.
|
The table does not need to be changed. One more level ofif()is needed:
```
if (ttt = v >> 32)
{
if (tt = ttt >> 16)
r = (t = tt >> 8) ? 56 + LogTable256[t] : 48 + LogTable256[tt]
else
r = (t = ttt >> 8) ? 40 + LogTable256[t] : 32 + LogTable256[ttt]
}
else
{
if (tt = v >> 16)
r = (t = tt >> 8) ? 24 + LogTable256[t] : 16 + LogTable256[tt];
else
r = (t = v >> 8) ? 8 + LogTable256[t] : LogTable256[v];
}
```
|
I am translating some code from C to C#. I'm not sure how best to translate the following 2 lines:
```
if (tt = v >> 16)
{
r = (t = tt >> 8) ? 24 + LT[t] : 16 + LT[tt];
}
```
tt, v, and t are ulongs (not really relevant to the problem). The problem is I don't think C# allows the assign/conditional operation in one statement.
In C#, one cannot implicitly convert from ulong to bool. The following line doesn't compile either:
```
if ((bool)(tt = v >> 16))
```
|
Here is the one for yourifstatement.
```
(tt = v >> 16) != 0
```
You cant easily cast anintto abool.
|
I installed the build-essential package for ubuntu x86_64, compiling c programs and c++ programs work fine, but in the compiled binary, "Ubuntu linaro" appears. is there a way to remove this?
|
You can remove it using a hex editor. And may i ask why do you want to remove it??
|
I want the address of structure, but in my code I am only able to return the address of value the first member. Can I typecast the address of value to struct classifier? If yes how to type cast it ? For example, my function only returns the address ofvaluein the below mentionedstructcan I cast this address toclassifier?
```
struct classifier
{
int value;
struct packet_filter pktFltr;
struct classifier *next;
}
```
|
The standard states that the address of a structureclassifieris the same as the address of its first membervalueprovided that you are casting it correctly.
That is, following is equivalent, p points to the same address :
```
int *p;
struct classifier c;
p = (int*)c;
p = &c.value;
```
Meaning that
```
(int*) c == &c.value
```
And in your case, if I understand it correctly you would want:
```
c = (struct chassifier *) adress_of_my_first_member_in_struct_classifier;
```
|
Say I have a wrapper function for each file system related system calls e.g, open(), close(), creat() etc and inside each wrapper function I need to find out the process id of the process making the syscall. Would be gratefull for some pointers. Thanks....
|
You're probably looking for thegetpid(2)system call; but Jeremiah asks good questions. :)
|
I compiled gcc 4.5.2 on a 64bit Redhat enterprise 3 machine (2.4.21-20.ELsmp, glibc 2.3.2). It compiles ok but with a lot of warning message like
```
/tmp/ccbGRF5F.s: Assembler messages:
/tmp/ccbGRF5F.s:29: Warning: rest of line ignored; first ignored character is `d'
/tmp/ccbGRF5F.s:33: Warning: rest of line ignored; first ignored character is `d'
/tmp/ccbGRF5F.s:169: Warning: rest of line ignored; first ignored character is `i'
```
Then I try to compile code with the compiler, still it spits these asm warnings, and I'm not using any asm in my C code. How can I get rid of it? Fix or suppress warning are all fine.
|
It seems your binutils is too old to handle gcc-4.5's output - and in another project it might outright end in a compile failure. Given RHEL3, that would not surprise me at all.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:How to format a number from 1123456789 to 1,123,456,789 in C?
How can I format a large integral number with commas in C, such that the readability is improved?
222222 should be 222,222 and 44444444 should be 44,444,444.
|
You do not need to do the formatting yourself;printfin Unix has a'modifier:
```
printf("%'d\n", number);
```
It looks like Visual Studio doesn't support that. This syntax is locale-aware, however.
|
I've defined astruct itemin a .h file. Now I'm defining anotherstruct tPCBin another .h which is part of the same project, and I need thetPCBto have anitem. I thought that just making part of the same TurboC project would allow me to use item in the other header file, but the compiler throws me "undefined type: ite".
I guess I somehow have to include the first header on the second one, However I have seen the same a similar code which works without doing so.
Is there any other way than just adding an#includeline to make it work?
|
If your .c#includes the two .h files in the proper order, it will work. That's probably what happened in the case you remember. The safest course is to#includeevery file that defines your dependencies, and rely on the include guards in each .h to keep things from being multiply defined.
|
I am trying to do some tests on X86_64 Linux, and I want to know how to
make malloc() allocate return addresses in the range higher than 4 GiB
Do I have to override malloc with a separate/custom library
or is there any other simple way to do this?
Thanks.
----Edit----
What I am interested is in the address when taken asvalue(uintptr_t)
and it does not matter whether itsvirtualorphysicaladdress, because, all
that I want is the address must be avaluegreater than 4GiB
I am usinggcc(4.2.1) with-m64, on Linux x86_64
(hope I made the question clear)
|
malloc()is the wrong tool. You want tommap()/dev/zero(which is whatmalloc()is doing behind the scenes in modernglibc), IIRC. (On Unix. I believe there is a similar API for Win32, but I couldn't tell you what it is.)
|
Like, I think I'm close... just not sure what I'm doing wrong,
```
cfann : main.o
main.o -l libfann
main.o : main.c
gcc -c main.c
clean:
rm -rf *o cfann
```
I get this error:
```
main.o -l libfann
make: main.o: No such file or directory
make: *** [cfann] Error 1
```
|
Change:
```
cfann : main.o
main.o -l libfann
```
to:
```
cfann : main.o
gcc main.o -lfann -L/usr/local/lib -o cfann
```
This assumes that libfann.o is in /usr/local/lib - change the -L path above if it's actually somewhere else.
|
In C/CUDA, if I am passed a pointer, how can I programmatically determine whether the pointer points to memory on the CPU or the GPU? Is there a CUDA function for this purpose?
|
I don't know how it is with CUDA 4.0, but in 3.2 you simply cannot deduct if it is CPU or GPU pointer based solely on the address stored in it.
A way around it would be to create a classCudaPtr<T>, hide a pointer there and provide basic functionality (e.g.memset,memload,memstore,memallocetc. which would in turn use CUDA stuff).
Then, if you have a function which may operate on host or on device, you can easily overload it forT*andCudaPtr<T>.
Update: Since the Unified Memory Addressing and new CUDA toolkit things have changed a bit. It seems you can now make such distinction at run time viacuPointerGetAttribute
|
I want to delete an executable after I start the process.
I tried by puttingunlinkand it work fine, but I want my executable to continue running.
Is using theunlinkapproach correct? Are there any issues with using this approach?
|
On Unix, there shouldn't be any problems unlinking the executable of a running process.
When you unlink a file, the directory entry is removed, but the inode and the underlying data are not freed until all existing references to the file (i.e. hard links and open handles) are released.
|
What is the best way to organize matrix operations in CUDA (in terms of performance)?
For example, I want to calculateC * C^(-1) * B^T + C,CandBare matrices.
Should I write separate functions for multiplication, transposition and so on or write one function for the whole expression?
Which way is the fastest?
|
I'd recommend you to use the CUBLAS library. It's normally much daster and more reliable than everything you could write on your own. In addition it's API is similar to the BLAS library which is the standard library for numerical linear algebra.
|
```
main()
{
char s[] = "abcdef", *p;
for (p = &s[5]; p >= s; p--) --p*;
puts(s);
return 0;
}
```
The compiler says there is a problem with --p* (expected an expression)?????
|
--p*doesn't make any sense .
Probably you meant--*por--p?
Your code prints`abcdewhen the underlying representation is ASCII. BTW C99 mandates the return type ofmain()to beintin a hosted environment.
|
I am using a mutex for the critical section. I have a design constraint that,
1) If 2 reads occur in 2 different thread, then critical section should be available for both.
2) If there is a write happening, then read on other thread should be blocked
3) If there is a read happening, then write on other thread should be blocked.
I dont know to do this with Createmutex, openmutex, waitforsingleobject and releasemutex apis.
|
What you are looking for is aReader-Writer lock. There are some implementations of it on the internet, for examplethis one.
|
I'm currently using Eclipse as my main editor, and source browser for our C/C++ project. The only problem is, I have to switch to Visual C++ everytime I have to debug or trace. Is there a way to have Eclipse use the WinDbg tool to debug Windows native applications? I tried searching on the web but all the forum posts seem to trail off to nowhere around 2007/2008.
|
I think the answer is no. Because you will not have access to the Win Debug Symbols and libraries within the Eclipse runtime. However you could start building this as an Eclipse plugin for VS users.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.