question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I have to link dynamically with OpenSSL libeay32.dll.
I'm writing native c++ console application using Visual C++ Express 2008.
I'm including a header evp.h from OpenSSL distribution. Building and...:
```
error LNK2001: unresolved external symbol _EVP_aes_256_cbc
error LNK2001: unresolved external symbol _EVP_DecryptInit
error LNK2001: unresolved external symbol _EVP_CIPHER_CTX_init
```
How to make calls to libeay32.dll methods? I don't know where to specify it's filename
|
There is probably a .lib file you also need to add to your compiler's linker input. Check the documentation for the library you're using.
|
I'm using a library which has both a C interface and a C++ interface in my C++ program. The C++ one is a bit immature and I must stick with the C one. I was wondering, in more general terms, is there anything specific to keep in mind when mixing C-style binary object files with a C++ project?
|
For C functions to be called from C++, they have to be declared asextern "C". Usually something like this is used in headers:
```
#if defined(__cplusplus)
extern "C" {
#endif
void f();
void g();
#if defined(__cplusplus)
}
#endif
```
|
Where can I find the implementation of time.h in the C Standard Library, i.etime.c?
I tried with Google Code Searchtime.cIs the implementation in the Linux kernel?
|
time.his a header from the C standard library.
You will find implementations of the various functions this header provides in the c library implementation of your system.
For instance, the implementation for thedifftimefunction in thelibcused forNetBSDcan be found insrc/lib/libc/time/difftime.c.
|
if for example i have :
```
#define PRINT(x) fprintf(stderr, x);
```
and in code i append it :
```
PRINT(("print this"))
```
output is :
[print this]
if i append it :
```
PRINT(("print %s", "this"))
```
output is :
[this]
could someone explain me why it receives just the "this" argument and not the whole string ?
|
```
PRINT(("print %s", "this"))
```
becomes:
```
fprintf(stderr, ("print %s", "this"));
```
which is equivalent to:
```
fprintf(stderr, "this");
```
However,variadic macros(from C99) work:
```
#define PRINT(...) fprintf(stderr, __VA_ARGS__)
int main() {
PRINT("print %s", "this");
return 0;
}
```
|
My Hash Table implementation has a function to resize the table when the load reaches about 70%. My Hash Table is implemented with separate chaining for collisions.
Does it make sense that I should resize the hash table down at any point or should I just leave it like it is? Otherwise, if I increase the size (by almost double, actually I follow this:Link) when the load is 70%, should I resize it down when the load gets 30% or below?
|
Hash tables don't have to have prime-number lengths if you have a good quality hash function (seehere). You can make them powers of two, which substantially speeds up index computations.
Why is this relevant to the question? Because when you shrink a power-of-two hashtable, you can leave all entries in the bottom half where they are and simply append the linked list in sloti(from the upper half) onto the linked list in sloti - n/2.
|
for example:
```
void decrement(int counter) {
counter--;
}
int counter = 20;
for (int i = 0; i < counter; i++) {
for (int j = 0; j < counter, j++) {
decrement(counter);
}
}
```
ideally, what i'd like to see is thecountervar being decremented every time the for loop is run, so that it runs fewer than 20 iterations. but gdb shows that withindecrement()counteris decremented, but that going back to the for loopcounteractually stays the same.
|
Yes it is possible:
```
for (int i = 0; i < counter; i++) {
counter--;
}
```
The reason why it doesn't work in your example is because you are passing by value and modifying the copy of the value. It would work if you passed a pointer to the variable instead of just passing the value.
|
TheManualfor Clang seems to be work in progress, so could you help me formulate the definitive command line options for compiling ANSI-C (AKA C89, C90) with maximum strictness and relevant/helpful warnings?
Clang is a compiler front end for the
C, C++, and Objective-C programming
languages. It uses the Low Level
Virtual Machine (LLVM) as its back
end. It is still under development.
Its goal is to offer a replacement to
the GNU Compiler Collection (GCC)
|
Clang's command-line arguments are, for the most part, GCC-compatible, so-std=c90 -pedanticshould suffice.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I want a reallyfastalgorithm or code in C to do the following task: sum all numbers from 1 to N for any given integer N, without assuming N is positive. I made a loop summing from 1 to N, but it is too slow.
|
IfNis positive:int sum = N*(N+1)/2;
IfNis negative:int tempN = -N; int sum = 1 + tempN*(tempN+1)/2 * (-1);.
|
My directory structure looks like the following:
```
-xmllib
-libxml++-1.0.a
-main.cc
```
..and I issue the command:
```
cc -lstdc++ -L./xmllib -llibxml++-1.0.a main.cc
```
But then it tells me that it can't find the binary for the library...even though I issued the command from the root directory.
```
/usr/bin/ld: cannot find -llibxml++-1.0.a main.cc
collect2: ld returned 1 exit status
```
Is there any reason why cc can't find the binary library?
I'm using cc version 2.96 (yes, it's old).
|
Change this:
```
-llibxml++-1.0.a
```
to this:
```
-lxml++-1.0
```
On Posix, the linker's-loption wants neither thelibprefix or the.aextension.
|
All I can find using fopen() and fwrite() in C is to delete all contents and start writing again or append to the end of the file. What if I need to go to some offset in the file and overwrite a few bytes?
Is that possible with some function?
|
You can open the file with the"rb+"option and then usefseekwithSEEK_SETto go to a specific location. Therb+opens it for both reading and writing as a binary file (the file must exist in order for it to succeed - it will not create a new file).
|
I have a scientific application for which I want to input initial values at run time. I have an option to get them from the command line, or to get them from an input file. Either of these options are input to a generic parser that uses strtod to return a linked list of initial values for each simulation run. I either use the command-line argument or getline() to read the values.
The question is, should I be rolling my own parser, or should I be using a parser-generator or some library? What is the standard method? This is the only data I will read at run time, and everything else is set at compile time (except for output files and a few other totally simple things).
Thanks,
Joel
|
Also check out strtof() for floats, strtod() for doubles.
|
if an array of size n has only 3 values 0 ,1 and 2 (repeated any number of times) what is the best way to sort them. best indicates complexity. consider space and time complexity both
|
Count the occurences of each number and afterward fill the array with the correct counts, this isO(n)
|
If I have a function that produces a resultintand a resultstring, how do I return them both from a function?
As far as I can tell I can only return one thing, as determined by the type preceding the function name.
|
I don't know what yourstringis, but I'm going to assume that it manages its own memory.
You have two solutions:
1: Return astructwhich contains all the types you need.
```
struct Tuple {
int a;
string b;
};
struct Tuple getPair() {
Tuple r = { 1, getString() };
return r;
}
void foo() {
struct Tuple t = getPair();
}
```
2: Use pointers to pass out values.
```
void getPair(int* a, string* b) {
// Check that these are not pointing to NULL
assert(a);
assert(b);
*a = 1;
*b = getString();
}
void foo() {
int a, b;
getPair(&a, &b);
}
```
Which one you choose to use depends largely on personal preference as to whatever semantics you like more.
|
I was under the impression that this code
```
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
printf("WinMain\n");
return 0;
}
int main()
{
printf("main\n");
return 0;
}
```
would output WinMain, but of course nothing ever works how you expects.
Anyways, could somebody please tell me how to get this program to run WinMain first (I do have a reason for using both). I'm running windows 7 with mingw if that helps anything.
|
You need to put-mwindowson the command line when you call MinGw. Checkthisout as a gentle introduction to Windows programming with MinGW.
Also: you cannot have two entry points in an executable, so you probably can not do what you want to do.
|
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.Closed11 years ago.
Does anyone know of a library that will allow me to write an odt (Open Document Format, i.e. OpenOffice compatible) file from a C program?
|
ODT/ODF is basically zipped XML, so any XML library will do. You'll need to know the specification though if you're going to write a new ODT file from scratch. It's much easier to unpack an existing ODT and insert data into contained the content.xml file.
SeeOASIS OpenDocument Essentials(especially the "The Virtues of Cheating" paragraph)
|
I need to find a way to store 250 KB of plain text numbers inside my program's executable file.
Usually, I would put the data in a separate file and let the program read it while it is running, but that's not an option here. Instead, the program and the data need to be in one executable file.
I have absolutely no idea how to do it (except writing 250.000 #defines :-) and I'd appreciate any suggestions.
|
How about an array of some sort. Just put that definition in a file and compile it into your program:
```
int external_data[] =
{
...
};
```
you can have the compiler tell you how many elements are in external data:
```
size_t external_data_max_idx = sizeof(external_data) / sizeof(*external_data);
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been done so far to solve it.Closed9 years ago.Improve this question
I am looking for HTTP parsing library for C/C++.
I have looked curl library, but it seems it is a http client library.
I am looking for a library which parses HTTP header (e.g. a way to
get the query string, get cookie, get request url, get Post Data)?
Thank you.
|
About 6 months ago, I was looking for the same exact thing. Then I found this page:HTTP Made Really Really Easyand I just wrote my own... Works great, surprisingly simple to implement...
|
If I have a global static variable x like in this code
```
#include <stdio.h>
#include <stdio.h>
static int x;
int main(void)
{
DO SOMETHING WITH x HERE
x++;
}
```
What will be difference if I opted to initialize x to a value first say as in
```
static int x = 0;
```
before entering "main"?
In my first case where I didn't assign a value to x, does the compiler implicitly know that x is to be set to zero as it's a static variable? I heard that we can do this with static variables.
Thanks a lot...
|
Static variables with explicit initialization are always initialized to zero (or null-pointer, depending on the type). The C standard §6.7.8/10 has description on this. But explicitly setting it to 0 can help others no need to wonder about the same question :).
|
Imagine I have a csv with and each value is an integer. so the first value is the INTEGER100.
I want fscanf() to read this line, and either tell me it's an integer ONLY, or not. So, it would pass100but fail on100t. What i've been trying to get work is "%d," where the comma is the delimiter of my CSV. so the whole function is
```
fscanf(fp, "%d,", &count)
```
Unfortunately, this fails to fail on '100t,' works on '100' and works on 't'. so it just isn't distinguishing between100and100t(all of these numbers are followed by commas, of course
|
Usestrtolinstead.
|
I get an "undefined reference to 'typeof'"-error compiling and linking this:
```
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
int main() {
typeof(5);
return 0;
}
```
Version of gcc is 4.3.3, command line is "gcc.exe -std=c99 1.c -o 1.exe".
|
By passing the option-std=c99to GCC you've asked it to compile according to the C99 standard, which doesn't support thetypeofkeyword.
You may want to use-std=gnu99instead.
|
i have achar buffer[100]and i'm trying to use gdb to read the contents out of it at various stages of runtime.
i usep bufferand i get
```
"/*\000\000\000\000\000\000????X?o\000\025\202\004\b", '\0' <repeats 12 times>, ".N=?", '\0' <repeats 24 times>, "`\203\004\b\000\000\000\000L\227\004\bX????\202\004\b?\017\204\000\f?\203\000\210???i\205\004\b??r"
```
how do i getpto convert it into a readable format???
|
x/s buffershould display the contents of the array as a null terminated string (which is what I assume you'd like).
|
I have developed a python C-extension that receives data from python and compute some cpu intensive calculations.
It's possible to profile the C-extension?
The problem here is that writing a sample test in C to be profiled would be challenging because the code rely on particular inputs and data structures (generated by python control code).
Do you have any suggestions?
|
After the comment by pygabriel I decided to upload a package to pypi that implements a profiler for python extensions using the cpu-profiler from google-perftools:http://pypi.python.org/pypi/yep
|
How can I programmatically retrieve the current connection type (eg. LAN or Direct connection)?
InternetGetConnectedState()isn't very reliable.
For instance, I'm connected to a wireless network, but ConTypeRet is 18, which is INTERNET_CONNECTION_LAN & INTERNET_RAS_INSTALLED. Isn't there any way to make sure that ConTypeRet is either INTERNET_CONNECTION_LAN or INTERNET_CONNECTION_MODEM?
|
I'm confused by your "It is unreliable" statement. You can just check for both:
```
bool IsLanOrModem() {
DWORD result;
if (!InternetGetConnectedState(&result, 0))
throw GetLastError();
return result & INTERNET_CONNECTION_LAN || result & INTERNET_CONNECTION_MODEM;
}
```
|
Can anyone tell me in simple words that what this L value is and why I'm coming across the error "L Value required in function main()"?
|
Lvalue is something which can be assigned to, or taken a pointer of.It's something that has an address.
Example:
```
int f()
{
return 5;
}
f() = 8; // doesn't compile, f() is not an lvalue
int* g()
{
int* pv = malloc(sizeof(int));
*pv = 5;
return pv;
}
*g() = 8; // compiles, as *g() is a lvalue
```
If you post your code, we will be able to tell you why are you getting the error message about the missing lvalue.
|
What is the difference between
```
void *bytes = alloca(size);
```
and
```
char bytes[size]; //Or to be more precise, char x[size]; void *bytes = x;
```
...wheresizeis a variable whose value is unknown at compile-time.
|
alloca()does not reclaim memory until the current function ends, while the variable length array reclaims the memory when the current block ends.
Put another way:
```
void foo()
{
size_t size = 42;
if (size) {
void *bytes1 = alloca(size);
char bytes2[size];
} // bytes2 is deallocated here
}; //bytes1 is deallocated here
```
alloca()can be supported (in a fashion) on any C89 compiler, while the variable length array requires a C99 compiler.
|
Is there any reliable and simple priority queue (linked list preferred, not necessary) implementation for C?
More generally, what C standard libraries do you use?
|
PQLib(the current accepted answer)is incompleteand the functionality doesn't match the documentation as of this posting. E.g., the pq_dequeue documentation says it returns an entry. The implementation returns NULL. There are many "TO DO" comments in the code, such as, "remove node containing highest priority entry from its heap." Essential logic is missing.
To anyone looking for a priority queue: I recommend finding some code that has good, passing unit tests. I don't recommend PQLib unless it's updated and includes tests.
To the owner of PQLib or anyone recommending it: I assumed this code was complete and spent a fair bit of time debugging until I realized it wasn't, which was frustrating. Please don't recommend code you haven't tried or know to be a work in progress.
|
I wanted to know why the following code crashes.
```
int main( )
{
int arr = 1 && arr;
return 0;
}
```
BUT not with the below code
```
int main( )
{
int arr = 0 && arr;
return 0;
}
```
Thanks in advance
|
0 && arrThe above expression isfalsebecause of0, soarris not checked unlike1 && arrwherearrhas to be checked to evaluate the value for expression.
You should try:
```
int main(){
int a = 0 && printf("a"); //printf returns number of characters printed, 1
int b = 1 && printf("b");
return 0;
}
```
|
I need to extract the RSA public key from a RSA private key using OpenSSL.
I'm currently usingRSAPublicKey_dup()passing theRSA*private key to get the public key. However, while the call seems to work, I cannot load (or use) this public key using the openssl command-line tool.
If I generate the public key using the command-line tool ("$ openssl rsa -in private.pem -pubout > public.pem"), I can use it and it works like a charm.
Do you guys know how I can get this work ? Maybe another function ? The OpenSSL documentation is quite hard to browse...
Thank you.
|
I managed to make this work usingPEM_write_bio_RSA_PUBKEY()to write the PEM data to a in-memory buffer, then usingPEM_read_bio_RSA_PUBKEY()to get a newRSA*.
Now the generated public key can be used ;)
|
main()
{
char a,b,c;
a=6;
b=-5;
c = a+b ;
printf ("%d %d %d \n" , a, b,c ) ;
}
```
Here , what actually happens
00000110
10000101
--------
10000111
--------
So values c will -11 , then how come it is 1.
```
|
Your error is: -5 in two's complement is not10000101. In 32-bit it is:11111111111111111111111111111011
6, is:
00000000000000000000000000000110
The sum is:
```
11111111111111111111111111111011
+ 00000000000000000000000000000110
--------------------------------
00000000000000000000000000000001
```
I recommend you readthis Wikipedia pageabout signed number representation. Modern CPUs use two's complement.
|
In C++, I can change the operator on a specific class by doing something like this:
```
MyClass::operator==/*Or some other operator such as =, >, etc.*/(Const MyClass rhs) {
/* Do Stuff*/;
}
```
But with there being no classes (built in by default) in C. So, how could I do operator overloading for just general functions?
For example, if I remember correctly, importing stdlib.h gives you the -> operator, which is just syntactic sugar for (*strcut_name).struct_element.
So how can I do this in C?
Thank you.
|
Plain old C does not have operator overloading in any form. The->"operator" to access a member of a pointer is standard C and is not introduced by any header file.
|
I need to work with a binary number.
I tried writing:
```
const char x = 00010000;
```
But it didn't work.
I know that I can use a hexadecimal number that has the same value as00010000, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?
|
If you are using GCC then you can usea GCC extension(which is included inthe C++14 standard) for this:
```
int x = 0b00010000;
```
|
I'm considering picking up some very rudimentary understanding of assembly. My current goal is simple:VERY BASICunderstanding of GCC assembler output when compiling C/C++ with the -S switch for x86/x86-64.
Just enough to do simple things such as looking at a single function and verifying whether GCC optimizes away things I expect to disappear.
Does anyone have/know of a truly concise introduction to assembly, relevant to GCC and specifically for the purpose of reading, and a list of the most important instructions anyone casually reading assembly should know?
|
You should use GCC's-fverbose-asmoption. It makes the compiler output additional information (in the form of comments) that make it easier to understand the assembly code's relationship to the original C/C++ code.
|
```
for (;;) {
//Something to be done repeatedly
}
```
I have seen this sort of thing used a lot, but I think it is rather strange...
Wouldn't it be much clearer to saywhile(true), or something along those lines?
I'm guessing that (as is the reason for many-a-programmer to resort to cryptic code) this is a tiny margin faster?
Why, and is itreallyworth it? If so, why not just define it this way:
```
#define while(true) for(;;)
```
See also:Which is faster: while(1) or while(2)?
|
It's not faster.If you really care, compile with assembler output for your platform and look to see.It doesn't matter. This never matters. Write your infinite loops however you like.
|
I need to pass a string literal to a function
```
myfunction("arg1" DEF_CHAR "arg1");
```
now part of that constructed string literal needs to be a function return
```
stmp = createString();
myfunction("arg1" stmp "arg2"); //oh that doesn't work either
```
is there any way to do this in one line?
```
myfunction("arg1" createString() "arg2"); //what instead?
```
NOTE: C only please.
My goal is to avoid initializing a new char array for this =/
|
You cannot build string literal at runtime, but you can create the string, like this:
```
char param[BIG_ENOUGH];
strcpy(param, "arg1");
strcat(param, createString());
strcat(param, "arg2");
myfunction(param);
```
|
I have a small daemon that I'm writing in C and I need a way to get the current CPU time on a thread. Linux apparently supplies a number of ways to go about doing this, clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...), pthread_getcpuclockid(), getrusage(RUSAGE_THREAD, ...) but none of these seem to be supported under OpenSolaris 2009.06.
Is there a cross-platform friendly way to get the current CPU time for a thread? If not, is there any way to do it in OpenSolaris at all? At this point, I'm even willing to put in a bunch of ugly compiler directives to make this work.
|
According to"Thread Priority on the Solaris Platform", Solaris 9 and above default to a one-to-one correspondence between threads and LWPs (Light-Weight Processes). Therefore, according togetrusage's manpage, you should be able to callgetrusage(RUSAGE_LWP, ...).
|
Is there a C or C++ compatible library for reading and writing Java class files?
I.e. something like Apache BCEL.
|
None that I'm aware of. However, you can call Java from C++. That will let you use BCEL from C++. If you're on one of gcj's supported platforms, you could try using it to compile BCEL to native code.
|
Can we have a nested function in C? What is the use of nested functions? If they exist in C does their implementation differ from compiler to compiler?
|
You cannot define a function within another function in standard C.
You candeclarea function inside of a function, but it's not a nested function.
gcc hasa language extension that allows nested functions. They are nonstandard, and as such are entirely compiler-dependent.
|
I was making a VB.NET application that can be used to edit, compile and run C programs. I used the Process.StartInfo.RedirectStandardOutput property. But I'm unable to redirect it to a textbox, since it is not of the string type.
How do I redirect the output coming from the cl.exe process to my textbox?
|
You need to redirect into the TextBox's Text property. For example:
```
Dim proc As New Process
proc.StartInfo = New ProcessStartInfo("tracert.exe", "10.0.0.138") _
With {.RedirectStandardOutput = True, .UseShellExecute = False}
proc.Start()
TextBox1.Text = proc.StandardOutput.ReadToEnd
```
|
Why do we use _PROTOTYPE e.g. _PROTOTYPE( void *memset, (void *_s, int _c, size_t _n) I saw it inMINIX3 source code
|
Because as the header block says, they didn't know if an ANSI compiler or K&R was going to be used, and this marco allows them to keep the parameters in an ANSI build, and throw them away in a K&R build.
```
00033 /* Keep everything for ANSI prototypes. */
00034 #define _PROTOTYPE(function, params) function params
```
verse
```
00045 /* Throw away the parameters for K&R prototypes. */
00046 #define _PROTOTYPE(function, params) function()
```
which means
```
00483 _PROTOTYPE( void _exit, (int _status) );
```
becomes under ANSI:
```
void _exit(int _status);
```
and under K&R:
```
void _exit();
```
|
Can anybody explain me this statement!
```
pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
```
|
Takeshp->h_addr, and casts it tostruct in_addr*. The cast may have different reasons. Perhapshp->h_addrisvoid*and the cast is needed to tell the compiler what type it should use for findings_addr. It may also be another struct that has anin_addras its first member
```
struct in_addr {
struct saddr_t s_addr;
};
struct socket {
struct in_addr addr;
};
struct server {
struct socket *h_addr;
};
server *hp;
```
Then, castingsocket*toin_addr*would be valid because on its address there is ain_addrat the beginning. After the cast, the members_addris accessed. These types are common in network programming under POSIX, and don't look like in my above example, but the above could have been the situation at hand.
|
it is possible to display a picture on a window created by winmain i mean using GDI,
i want do create a window that captures my whole screen i have done that by using GDI but unable to show an image on it how can i do so?
|
There arelotsofgoodtutorialson theweb.
|
String.h
I found this while searching aboutstring.h. Where can I find the source code of functions defined instring.h?
i.e [say] source code of
```
void *memcpy(void *, const void *, size_t);
```
Also I want to ask how to make your functions as an interface with its implmentation hidden from developer asstring.hfunctions has.
|
Here's memmovefrom Ohloh's code search.
|
some times i see that functions are defined as below:
```
read_dir(dir)
char *dir;
{
DIR * dirp;
struct dirent *d;
/* open directory */
dirp = opendir(dir);
......... so on
```
here what is the importance of the statement
```
char *dir;
```
what is the intension behind declaring the pointer soon after the function name and then starting the function body.
|
It's an older C syntax, kalled "K&R C" since it's how it appeared in the original version of thelegendary book.
What used to be written like this:
```
foo(a, b)
int a;
int b;
{
}
```
is now
```
int foo(int a, int b)
{
}
```
|
Is there any way to find out the list of undefined symbols in windows static library compiled using VC6?
I know the nm command will list all the symbols in linux and symbols with a tag of "U" can be identified as undefined. But, how to do it Windows?
|
You can use dumpbin.exe /symbols on the .lib file. That lists all the symbols used, the external ones have the "External" prefix.
|
I have two pointers,
```
char *str1;
int *str2;
```
If I look at the size of both the pointers let’s assume
```
str1=4 bytes
str2=4 bytes
```
str1++ will increment by 1 byte, but if str2++ it will increment 4 bytes.
What is the concept behind this?
|
Simple, in the provided scenario:
char is 1 byte longint (in your platform) is 4 bytes long
The++operator increments the pointer by the size of the pointed type.
|
I have seen source codes always having a typedef for a structure and using the same everywhere instead of using the structure name as "struct sname" etc directly?
What is the reason behind this? Are there any advantages in doing this?
|
Its easier to readBox b;thanstruct boxtype b;
```
typedef struct _entry{
char *name;
int id;
} Entry, *EntryP;
```
Advantage:In the abovetypedef, bothEntry&EntryPare defined apart fromstruct _entry.So,EntryP firstentrycan be used in place ofstruct _entry *firstentryand is a little simpler to parse in mind.
Note: Its not like structure namesshouldbetypedefined, but evidently its easier to read. Also, use ofEntry *vsEntryPis totally user-dependent.
|
Quick c question: How to know the length of a char* foo[]?
Thanks.
|
You can't. Not without knowing something about what is inside of the pointers, or storing that data ahead of time.
|
I wanted to store 10 in 4th position of array of 5 positions. How to do ?
```
int main( )
{
int a[5] = {,,,,4} ;
return 0;
}
```
If i do that i get error. Please help.
Thanks in advance.
|
You can't do it with initialization, but you can leave the data uninitialized and then assign to the one you care about:
```
int a[5]; a[3] = 10;
```
I'm not surewhyyou'd want to do this, but that's a whole separate question...
Edit: I should add that in C99, youcanuse initialization:
```
int a[4] = { [3]=10 };
```
This is called designated initialization.
|
The prototype of memset isvoid *memset(void *s, int c, size_t n);. So why the third parameter is of typesize_t?memsetis just an example, I want more general reasons. Thanks in advance.
|
size_tis the return type of thesizeofoperator and is used to describe memory sizes. In the case ofmemset, it specifies the number of bytes (n) in the memory block (s) that should be set to the given value (c).
The size in bits ofsize_tvaries based on the address space of the target platform. It does not always correlate to the register size. For example, in a segmented memory architecture thesizeof (size_t)can be smaller than thesizeof (void *). Typically,size_twould be 4 bytes on a 32-bit machine, 8 bytes on a 64-bit machine, etc.
|
I'm implementing some code generators, i would like to know if there's any way in C, if a variable has already been declared ?
I was trying to find something using the preprocessor but without any success...
thanks.
|
C is strictly static, you can't "lookup" if a variable has already been declared. If you are creating a code generator, why not read lines of code and see what's been declared?
|
I am implementing, a distributed cache proxy server.I have an idea of the HTTP and related stuff, so i am rather concentrating on the sub part "Distributed data storage".
From some search on web i found that this could be done using Distributed Hash Tables(DHT).
I was wondering if there exists some kind of library for this preferably in C/C++.
Any better suggestions for the same will also be appreciated.
|
Have you looked atKademlia? There'sKadC(C) andmaidsafe-dht(C++) for it.
|
Does anyone see a problem with this, its not working saying bad file descriptor not sure why?
```
pipe(pipefd[0]);
if ((opid = fork()) == 0) {
dup2(pipefd[0][1],1);/*send to output*/
close(pipefd[0][0]);
close(pipefd[0][1]);
execlp("ls","ls","-al",NULL);
}
if((cpid = fork())==0){
dup2(pipefd[0][1],0);/*read from input*/
close(pipefd[0][0]);
close(pipefd[1][1]);
execlp("grep","grep",".bak",NULL);
}
close(pipefd[0][0]);
close(pipefd[0][1]);
```
|
Based on your code, I'm guessing pipefd is defined as:
```
int pipefd[2][2];
```
Now, when you do:
```
pipe(pipefd[0])
```
This only populatespipefd[0][0]andpipefd[0][1].
So when you do:
```
# Bad descriptor
close(pipefd[1][1]);
```
you are referencing random junk (you never setpipefd[1][0]orpipefd[1][1]).
From the code shown, I can't see why you aren't just doing:
```
int pipefd[2];
pipe(pipefd);
```
|
I am fairly new to C. (I have good knowledge of C# [Visual Studio] and Java [Eclipse]) I want to make a program that stores information. My first instinct was to use a database like SQL Server. But I don't think that it is compatible with C. So now I have two options:
Create a struct (also typedef) containing the data types.Find a way to integrate SQLite through a C header file
Which option do you think is best? Or do you have another option? I am kind of leaning toward making a struct with a typedef, but could be pursuaded to change my mind.
|
ODBC is a C libraryand permits access to databases in a mode very reminiscent of JDBC. Microsoft has an ODBC driver for SQLServer that is included in Windows or, for non-Windows, you can leverage something likeFreeTDS.
AlsoSQLiteprovides a mechanism for more direct C access to the database, which permits embedding, etc.
And, depending on your storage needs,BDBmight be worth investigating.
|
If I have two types of strings as:
```
const char *str1 = "This is a string with \"quotes escaped at the end\"";
const char *str2 = "This is a \"string\" without quotes at the end";
testFn(str1);
testFn(str2);
int testFn(const char *str)
{
// test & return 1 if ends on no quote
// test & return 0 if ends on quote
return;
}
```
I would like to test if the string ends with a quote " or not
What would be a good way of testing this? Thanks
|
Don't forget to make sure your string has at least 1 character:
```
int testFn(const char *str)
{
return (str && *str && str[strlen(str) - 1] == '"') ? 0 : 1;
}
```
|
The following outputs0.23. How do I get it to simply output.23?
```
printf( "%8.2f" , .23 );
```
|
The C standard says that for thefandFfloating point format specifiers:
If a decimal-point character appears, at least one digit appears before it.
I think that if you don't want a zero to appear before the decimal point, you'll probably have to do something like usesnprintf()to format the number into a string, and remove the0if the formatted string starts with "0." (and similarly for "-0."). Then pass that formatted string to our real output. Or something like that.
|
What does this line of code mean?
```
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
```
The?and:confuse me.
|
This is the Cternary operator(Objective-C is a superset of C):
```
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
```
is semantically equivalent to
```
if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}
```
The ternary with no first element (e.g.variable ?: anotherVariable) means the same as(valOrVar != 0) ? valOrVar : anotherValOrVar
|
I cant find an expression to evaluate a part of a string.
I want to get something like that:
```
if (string[4:8]=='abc') {...}
```
I started writing like this:
```
if (string[4]=='a' && string[5]=='b' && string[6]=='c') {...}
```
but if i need to evaluate a big part of string like
```
if (string[10:40] == another_string) {...}
```
then it gets to write TOO much expressions. Are there any ready-to-use solutions?
|
You could always usestrncmp(), sostring[4:8] == "abc"(which isn't C syntax, of course) could becomestrncmp(string + 4, "abc", 5) == 0.
|
Does anyone see a problem with this, its not working saying bad file descriptor not sure why?
```
pipe(pipefd[0]);
if ((opid = fork()) == 0) {
dup2(pipefd[0][1],1);/*send to output*/
close(pipefd[0][0]);
close(pipefd[0][1]);
execlp("ls","ls","-al",NULL);
}
if((cpid = fork())==0){
dup2(pipefd[0][1],0);/*read from input*/
close(pipefd[0][0]);
close(pipefd[1][1]);
execlp("grep","grep",".bak",NULL);
}
close(pipefd[0][0]);
close(pipefd[0][1]);
```
|
Based on your code, I'm guessing pipefd is defined as:
```
int pipefd[2][2];
```
Now, when you do:
```
pipe(pipefd[0])
```
This only populatespipefd[0][0]andpipefd[0][1].
So when you do:
```
# Bad descriptor
close(pipefd[1][1]);
```
you are referencing random junk (you never setpipefd[1][0]orpipefd[1][1]).
From the code shown, I can't see why you aren't just doing:
```
int pipefd[2];
pipe(pipefd);
```
|
I am fairly new to C. (I have good knowledge of C# [Visual Studio] and Java [Eclipse]) I want to make a program that stores information. My first instinct was to use a database like SQL Server. But I don't think that it is compatible with C. So now I have two options:
Create a struct (also typedef) containing the data types.Find a way to integrate SQLite through a C header file
Which option do you think is best? Or do you have another option? I am kind of leaning toward making a struct with a typedef, but could be pursuaded to change my mind.
|
ODBC is a C libraryand permits access to databases in a mode very reminiscent of JDBC. Microsoft has an ODBC driver for SQLServer that is included in Windows or, for non-Windows, you can leverage something likeFreeTDS.
AlsoSQLiteprovides a mechanism for more direct C access to the database, which permits embedding, etc.
And, depending on your storage needs,BDBmight be worth investigating.
|
If I have two types of strings as:
```
const char *str1 = "This is a string with \"quotes escaped at the end\"";
const char *str2 = "This is a \"string\" without quotes at the end";
testFn(str1);
testFn(str2);
int testFn(const char *str)
{
// test & return 1 if ends on no quote
// test & return 0 if ends on quote
return;
}
```
I would like to test if the string ends with a quote " or not
What would be a good way of testing this? Thanks
|
Don't forget to make sure your string has at least 1 character:
```
int testFn(const char *str)
{
return (str && *str && str[strlen(str) - 1] == '"') ? 0 : 1;
}
```
|
The following outputs0.23. How do I get it to simply output.23?
```
printf( "%8.2f" , .23 );
```
|
The C standard says that for thefandFfloating point format specifiers:
If a decimal-point character appears, at least one digit appears before it.
I think that if you don't want a zero to appear before the decimal point, you'll probably have to do something like usesnprintf()to format the number into a string, and remove the0if the formatted string starts with "0." (and similarly for "-0."). Then pass that formatted string to our real output. Or something like that.
|
What does this line of code mean?
```
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
```
The?and:confuse me.
|
This is the Cternary operator(Objective-C is a superset of C):
```
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
```
is semantically equivalent to
```
if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}
```
The ternary with no first element (e.g.variable ?: anotherVariable) means the same as(valOrVar != 0) ? valOrVar : anotherValOrVar
|
I cant find an expression to evaluate a part of a string.
I want to get something like that:
```
if (string[4:8]=='abc') {...}
```
I started writing like this:
```
if (string[4]=='a' && string[5]=='b' && string[6]=='c') {...}
```
but if i need to evaluate a big part of string like
```
if (string[10:40] == another_string) {...}
```
then it gets to write TOO much expressions. Are there any ready-to-use solutions?
|
You could always usestrncmp(), sostring[4:8] == "abc"(which isn't C syntax, of course) could becomestrncmp(string + 4, "abc", 5) == 0.
|
Hi I have an enum declared like this:
```
typedef enum {
Top,
Bottom,
Center
} UIItemAlignment;
```
In my code I try to use it like this:
```
item.alignment = UIItemAlignment.Top;
```
I get an error like this: " Expected expression before 'UIItemAlignment' "
If I use only:
```
item.alignment = Top;
```
everything works fine but why do I get this error if I try to use it the other way?
_alignmentis anNSIntegerand it has a property declared like this
@property (readwrite) NSInteger alignment;and I synthesized it in my implementation file.
So my question is, why do I get this error?
|
Enum values are not specified via their type in objective-c nor c++. The syntax you are trying to use is how C# handles it though.
|
I'm working with libpcap in C on linux (centos) and I'm followingthis guideI want to simply print out the entire packet in ascii and i'v managed to get it working by casting it a u_char* in the "my_callback" function. But I can't figure out how to get the length of the data. strstr didn't work. the header has a len member that you can access to get the size but I can't find anything similar for the *packet being passed. Any help is appreciated.
|
In your callback the caplen member of the pkthdr variable (see struct pcap_pkthdr) contains the size of thecapturedpacket.
For example assume a packet is captured. The total length of the frame is 1024 bytes. However the capture driver only captured the first 128 bytes of the frame and made it available to your callback.
In this case you should expect pkthdr->caplen to be 128 and header->len to be 1024.
|
Does anyone know of a tool that I can use to find explicit C-style casts in code? I am refactoring some C++ code and want to replace C-style casts where ever possible.
An example C-style cast would be:
```
Foo foo = (Foo) bar;
```
In contrast examples of C++ style casts would be:
```
Foo foo = static_cast<Foo>(bar);
Foo foo = reinterpret_cast<Foo>(bar);
Foo foo = const_cast<Foo>(bar);
```
|
If you're using gcc/g++, just enable a warning for C-style casts:
```
g++ -Wold-style-cast ...
```
|
I have a macro definition in header file like this:
```
// header.h
ARRAY_SZ(a) = ((int) sizeof(a)/sizeof(a[0]));
```
This is defined in some header file, which includes some more header files.
Now, i need to use this macro in some source file that has no other reason to includeheader.hor any other header files included inheader.h, so should i redefine the macro in my source file or simply include the header fileheader.h.
Will the latter approach affect the code size/compile time (I think yes), or runtime (i think no)?
Your advice on this!
|
Include the header file or break it out into a smaller unit and include that in the original header and in your code.
As for code size, unless your headers do something incredibly ill-advised, like declaring variables or defining functions, they should not affect the memory footprint much, if at all. They will affect your compile time to a certain degree as well as polluting your name space.
|
What is the quickest way to find the number of elements in a static array and dynamic array?
|
There is no way of finding the number of elements in a dynamically created array. For a non-dynamic array, you can usesizeof(array)/sizeof(type). However, this is not as useful as it seems:
```
void f( int a[] ) {
// sizeof(a) will be the size of a pointer, probably 4
}
int main() {
int a[100];
// sizeof(a)/sizeof(int) will be 100
f( a );
}
```
This is because arrays decay into pointers when passed to functions. So in both cases, you probably need to remember the size of the array and pass it to functions as a separate parameter. So a function to sum an array (for example) would look like this:
```
int sum( int a[], int n ) {
int total = 0, i;
for ( i = 0; i < n; i++ ) {
total += a[i];
}
return total;
}
```
|
What does this do?
```
int *(*pfp) ();
```
|
int *(*pfp) ();
Creates a pointer to a function that returns int*. The function pointer name ispfp.
Here's an example:
```
int* myFunc(void)
{
return NULL;
}
int main(int argc, char**argv)
{
int *(*pfp) (void);
pfp = myFunc;
return 0;
}
```
Note: Since the parameters of the function pointer is not (void) that you gave, that means that the parameter list is not specified in C. In C++ it would mean that it's a function with no parameters exactly.
|
How can I implement chmod command on file by using exec? I would appreciate if anyone can provide me a code.
|
I'm not going to show you a working model, but execve() works like this:
```
char *args[] = {"foo", "argument1", "argument2", (char *)NULL};
```
... handle forking ....
```
res = execve("/sbin/foo", args, (char *)NULL);
```
... handle execve() failing ....
The third argument to execve() is left as an exercise for the reader to research, NULL may or may not be suitable for your assignment. Additionally, its up to you to determine what typeresshould be and what it should equal on success. Notice casting NULL.
Thesingle UNIX specificationis usually a good place to start.
|
As the title indicates, are there any C/C++ bytecode compilers/interpreters? I'm writing an application in an interpreted language that depends on certain libraries that are fully cross-compilable (there are no special flags to indicate code changes during compilation for a certain platform) but are written in C and C++. Rather than shipping n-platform-specific-libs with each platform, it would be nice to ship one set of libs which are interpreted by one platform specific interpreter.
Possible and/or available?
EDIT1:
The interpreted language in question is Python, though I may also use Ruby.
|
Which interpreted language are you using? If it has a .NET based implementation (e.g. IronPython) you could possibly use it with the C++/CLI compiler to produce byte code for the .NET CLR and Mono.
This is only likely to be feasible if you have full control over your C++ libraries.
|
I have a C program which has a function call that is defined inwindows.h(which I have included), however, when I try and compile it withgcc, I get the error:
```
warning: implicit declaration of function `LockWorkStation'
```
I looked at the MSDN documentation and I see that this function is theUser32library file, and I was wondering how I would go about linking that to my file.
|
LockWorkstation is available on Windows 2000 and up. You have to declare the version of Windows you are targeting. Make it look like this:
```
#define _WIN32_WINNT 0x500
#include <windows.h>
```
|
How do I inputDEADBEEFand outputDEADBEEFas four byte arrays?
|
```
void hexconvert( char *text, unsigned char bytes[] )
{
int i;
int temp;
for( i = 0; i < 4; ++i ) {
sscanf( text + 2 * i, "%2x", &temp );
bytes[i] = temp;
}
}
```
|
I am reading a book called "Teach Yourself C in 21 Days" (I have already learned Java and C# so I am moving at a much faster pace). I was reading the chapter on pointers and the->(arrow)operatorcame up without explanation. I think that it is used to call members and functions (like the equivalent of the.(dot) operator, but for pointers instead of members). But I am not entirely sure.
Could I please get an explanation and a code sample?
|
foo->baris equivalent to(*foo).bar, i.e. it gets the member calledbarfrom the struct thatfoopoints to.
|
What does the last function argument mean in C language?
Please, point to documentation where I can read about it.
```
void parse_options( int argc, char **argv, const OptionDef *options,
void (* parse_arg_function)(const char*) )
```
Thanks.
|
This is apointer to a functionthat takes aconst char*and returnsvoid.
For more information, seehere.
|
Is Test Driven Development limited to OO? Or is it possible/useful to use it in conjunction with a procedural language? I have to start a greater project in C the next few weeks and I'm thinking of ways how to the developing.
|
TDD is adesignparadigm and as such is not tied to any specific programming paradigm.
Simply put, you write a test for your code before writing your of code.
Seethisslide deck about TDD with C (the Bowling Game Kata).
|
I am trying to get the user defined global hot key for my application. Here is my application code,
user.rc
```
CONTROL "", IDC_MHOTKEY, HOTKEY_CLASS, WS_TABSTOP, 91, 86, 68, 14
```
function.cpp
```
WORD wHotKey = SendDlgItemMessage(hwnd, IDC_MHOTKEY, HKM_GETHOTKEY, 0, 0);
GLOBAL_HOTKEY= wHotKey;
RegisterHotKey ( NULL, TURN_OFF_HOTKEY, HIBYTE(LOWORD(wHotKey)) , wHotKey);
```
main.cpp
```
if ( messages.message == WM_HOTKEY && ( HIWORD ( messages.lParam ) == GLOBAL_HOTKEY) )
alert("Coming only for Single Key");
```
This code works well, Only If the user selects a single key and not working when he selects multiple key combined like CTRL+F8.
|
You need to isolate the virtual key out of the wHotKey value:
```
RegisterHotKey ( NULL,
TURN_OFF_HOTKEY,
HIBYTE(LOWORD(wHotKey)), // Modifiers
LOBYTE(LOWORD(wHotKey)) // Virtual key
);
```
|
can every if...then...else statement be converted into an equivalent statement using only ?:
|
The code:
```
if ( flag ) {
exit(1);
}
else {
return 0;
}
```
cannot be converted into:
```
flag ? exit(1) : return 0;
```
A better example- this would be inside a loop:
```
if ( flag ) {
continue;
}
else {
break;
}
```
cannot be converted to:
```
flag ? continue : break;
```
|
I have a command line app and have the code
```
chdir("/var");
FILE *scriptFile = fopen("wiki.txt", "w");
fputs("tell application \"Firefox\"\n activate\n",scriptFile);
fclose(scriptFile);
```
and when I run it in Xcode I get an EXC_BAD_ACCESS when it gets to the firstfputs();call
|
Probably the call tofopen()failed because you don't have write permissions in/var. In this casefopen()returnsNULLand passingNULLtofputs()will cause an access violation.
|
I've got some custom metadata to put into a PNG file. It's being saved through libpng, and it's not difficult to write out a custom chunk. I just call png_write_chunk with the name, length and data. But I can't see how to get the data back out again. I'd expect there to be a png_read_chunk function that takes a chunk name and returns a pointer to the data or something like that, but there's nothing like that in png.h.
Does anyone know how to accomplish this?
|
Look forpng_set_read_user_chunk_fnin the manual. There are standard functions for accessing the standard chunks once they have been read, and custom chunks are handled by invoking a custom callback.
|
Linux'sstddef.hdefinesoffsetof()as:
```
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
```
whereas the Wikipedia article onoffsetof()(http://en.wikipedia.org/wiki/Offsetof) defines it as:
```
#define offsetof(st, m) \
((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
```
Why subtract(char *)0in the Wikipedia version? Is there any case where that would actually make a difference?
|
The first version converts a pointer into an integer with a cast, which is not portable.
The second version is more portable across a wider variety of compilers, because it relies on pointer arithmetic by the compiler to get an integer result instead of a typecast.
BTW, I was the editor that added the original code to the Wiki entry, which was the Linux form. Later editors changed it to the more portable version.
|
As the title described, how to use c library function fgets in assembly language? Indeed, I want to know how to get the file pointer to stdin. Thanks for your reply.
|
you can write a simple program using fgets and compile it with gcc -S to see how to do it
|
How to reverse bitwise AND (&) in C?
For example I have an operation in C like this:
```
((unsigned int)ptr & 0xff000000))
```
The result is0xbf000000. What I need at this moment is how to reverse the above, i.e. determineptrby using the result from the operation and of course0xff000000.
Is there any simple way to implement this in C?
|
Bitwise&can't be reversed:
```
0 & 1 = 0
0 & 0 = 0
```
|
I got errors when trying to use __sync_add_and_fetch:
```
test8.cpp:(.text+0x90e): undefined reference to `__sync_add_and_fetch_8'
collect2: ld returned 1 exit status
```
Please kindly advise how to rectify this.
Specs:
GCC/G++: 4.4.1
GNU/Linux 2.6.32 SMP i686
Many thanks!
EDIT:
In addition to the answer provided, one can use -march=i586 or -march=i686 to link successfully.
Note: This requires GCC/G++ 4.1.x and above!
|
That function is not supported on all x86 architectures. Try specifying your architecture, such as--with-arch=pentium4.
|
Suppose, I have aifstatement inside aforloop:
```
for( ; ; )
{
if( )
{
printf(" inside if");
break;
}//if
printf("inside for");
}//for
```
Now, will thebreakstatement cause the compiler to come out of theforloop or will it only come out of the body ofifonce the condition in theifbecomes satisfied?
|
Thebreakstatement breaks out ofthe nearest enclosinglooporswitchstatement.
breakdoes not break out of anifstatement, but the nearestlooporswitchthat contains thatifstatement. The reason for not breaking out of anifstatement is because it is commonly used to decide whether you want to break out of theloop.
Interestingly, a telephone switch misbehaved because the company that invented Cmade exactly this bug. They wanted to break out of anifstatement and they forgot that it would break out of the entireforstatement.
|
I have used the crypt function in c to encrypt the given string.
I have written the following code,
```
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("%s\n",crypt("passwd",1000));
}
```
But the above code threw an error ,"undefined reference to `crypt'".
What is the problem in the above code.
Thanks in advance.
|
If you want to use thecrypt()function, you need to link to the library that supplies it. Add-lcryptto your compile command.
Older versions of glibc supplied alibcryptlibrary for this purpose, and declared the function in<unistd.h>- to compile against this support, you may also need to define either_XOPEN_SOURCEor_GNU_SOURCEin your code before including<unistd.h>.
Newer versions of glibc don't supplylibcrypt- it is instead provided by a separatelibxcrypt. You still link with-lcrypt, but the function is instead declared in<crypt.h>.
|
I want to make a Windows application in ansi C but I am having trouble with the graphic usage. Is ansi C able to handle the graphics of Windows without using any extra libraries? Guide line required.
|
ANSI (or more modernly ISO) C is thelanguage standard. It doesn't deal with graphics,at all.
However, you sure can write graphical applications with C (the language). On Windows you have the Win32 API, and there are also cross-platform libraries like GTK, which you can use to create graphical applications on Windows (as well as on other OSes).
|
I have a program which places structures in a linked list based on the 'name' they have stored in them.
To find their place in the list, i need to figure out if the name im inserting is earlier or later in the alphabet then those in the structures beside it.
The names are inside the structures, which i have access to.
I don't need a full comaparison if that is more work, even just the first letter is fine.
Thanks for the help!
|
It's not clear to me what your question is, but something like this would work:
```
if (node1->name[0] <= node2->name[0]) {
...
} else {
...
}
```
This will compare the first letter of the name in each of the nodes.
|
i'm having an issue understanding why the following works:
```
void doubleAddr(double* source, double** dest)
{
*dest = source;
}
```
i get a pointer to a double and want to change the double that dest points to:
```
//usage:
int main()
{
double* num;
double* dest;
doubleAddr(num, &dest);
return 0;
}
```
thanks in advance
|
You're not using pointers correctly. To begin with, you're not initializing anything inmain(), so that's pretty dangerous. Your code fordoubleAddr()is correct, but it's copying a pointer, not a double. If you're trying to copy a number through a pointer, you want something like:
```
void copyDouble(double source, double *dest)
{
*dest = source;
}
int main()
{
double num = 5.6;
double dest;
copyDouble(num, &dest);
printf("%f\n", dest);
return 0;
}
```
You can add more*or&if you're trying to do something different.
|
Are there any alternatives to stat (which is found on most Unix systems) which can determine the file type? The manpage says that a call to stat is expensive, and I need to call it quite often in my app.
|
The alternative isfstat()if you already have the file open (so you have a file descriptor for it). Orlstat()if you want to find out about symbolic links rather than the file the symlink points to.
I think the man page is exaggerating the cost; it is not much worse than any other system call that has to resolve the name of the file into an inode. It is more costly thangetpid(); it is less costly thanopen().
|
Disassemblingprintfdoesn't give much info:
```
(gdb) disas printf
Dump of assembler code for function printf:
0x00401b38 <printf+0>: jmp *0x405130
0x00401b3e <printf+6>: nop
0x00401b3f <printf+7>: nop
End of assembler dump.
(gdb) disas 0x405130
Dump of assembler code for function _imp__printf:
0x00405130 <_imp__printf+0>: je 0x405184 <_imp__vfprintf+76>
0x00405132 <_imp__printf+2>: add %al,(%eax)
```
How is it implemented under the hood?
Why disassembling doesn't help?
What does*mean before0x405130?
|
Here's one particular implementation,http://ftp.fr.openbsd.org/pub/OpenBSD/src/lib/libc/stdio/printf.candhttp://ftp.fr.openbsd.org/pub/OpenBSD/src/lib/libc/stdio/vfprintf.c
|
```
main()
{
printf("Hello World.");
}
```
Why does no warning is produced in gcc compiler even though we declare main() with return type 'int'
|
Because you're not using the -Wall flag. When you do, you should get:
```
foo.c:1: warning: return type defaults to ‘int’
foo.c: In function ‘main’:
foo.c:1: warning: implicit declaration of function ‘printf’
foo.c:1: warning: incompatible implicit declaration of built-in function ‘printf’
foo.c:1: warning: control reaches end of non-void function
```
|
I recently came along this line of code:
```
CustomData_em_free_block(&em->vdata, &eve->data);
```
And I thought, isn't:
```
a->b
```
just syntactic sugar for:
```
(*a).b
```
With that in mind, this line could be re-written as:
```
CustomData_em_free_block(&(*em).vdata, &(*eve).data);
```
If that's the case, what is the point of passing in
&(*a), as a parameter, and not just a? It seems like the pointer equivalent of -(-a) is being passed in in, is there any logic for this?
Thank you.
|
This:
```
&(*em).vdata
```
is not the same as this:
```
em.vdata
```
It is the same as this:
```
&((*em).vdata)
```
The ampersand takes the address ofvdata, which is a member of the struct pointed to byem. The.operator has higher precedence than the&operator.
|
I have a command line app and have the code
```
chdir("/var");
FILE *scriptFile = fopen("wiki.txt", "w");
fputs("tell application \"Firefox\"\n activate\n",scriptFile);
fclose(scriptFile);
```
and when I run it in Xcode I get an EXC_BAD_ACCESS when it gets to the firstfputs();call
|
Probably the call tofopen()failed because you don't have write permissions in/var. In this casefopen()returnsNULLand passingNULLtofputs()will cause an access violation.
|
I've got some custom metadata to put into a PNG file. It's being saved through libpng, and it's not difficult to write out a custom chunk. I just call png_write_chunk with the name, length and data. But I can't see how to get the data back out again. I'd expect there to be a png_read_chunk function that takes a chunk name and returns a pointer to the data or something like that, but there's nothing like that in png.h.
Does anyone know how to accomplish this?
|
Look forpng_set_read_user_chunk_fnin the manual. There are standard functions for accessing the standard chunks once they have been read, and custom chunks are handled by invoking a custom callback.
|
Linux'sstddef.hdefinesoffsetof()as:
```
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
```
whereas the Wikipedia article onoffsetof()(http://en.wikipedia.org/wiki/Offsetof) defines it as:
```
#define offsetof(st, m) \
((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
```
Why subtract(char *)0in the Wikipedia version? Is there any case where that would actually make a difference?
|
The first version converts a pointer into an integer with a cast, which is not portable.
The second version is more portable across a wider variety of compilers, because it relies on pointer arithmetic by the compiler to get an integer result instead of a typecast.
BTW, I was the editor that added the original code to the Wiki entry, which was the Linux form. Later editors changed it to the more portable version.
|
As the title described, how to use c library function fgets in assembly language? Indeed, I want to know how to get the file pointer to stdin. Thanks for your reply.
|
you can write a simple program using fgets and compile it with gcc -S to see how to do it
|
How to reverse bitwise AND (&) in C?
For example I have an operation in C like this:
```
((unsigned int)ptr & 0xff000000))
```
The result is0xbf000000. What I need at this moment is how to reverse the above, i.e. determineptrby using the result from the operation and of course0xff000000.
Is there any simple way to implement this in C?
|
Bitwise&can't be reversed:
```
0 & 1 = 0
0 & 0 = 0
```
|
I got errors when trying to use __sync_add_and_fetch:
```
test8.cpp:(.text+0x90e): undefined reference to `__sync_add_and_fetch_8'
collect2: ld returned 1 exit status
```
Please kindly advise how to rectify this.
Specs:
GCC/G++: 4.4.1
GNU/Linux 2.6.32 SMP i686
Many thanks!
EDIT:
In addition to the answer provided, one can use -march=i586 or -march=i686 to link successfully.
Note: This requires GCC/G++ 4.1.x and above!
|
That function is not supported on all x86 architectures. Try specifying your architecture, such as--with-arch=pentium4.
|
Suppose, I have aifstatement inside aforloop:
```
for( ; ; )
{
if( )
{
printf(" inside if");
break;
}//if
printf("inside for");
}//for
```
Now, will thebreakstatement cause the compiler to come out of theforloop or will it only come out of the body ofifonce the condition in theifbecomes satisfied?
|
Thebreakstatement breaks out ofthe nearest enclosinglooporswitchstatement.
breakdoes not break out of anifstatement, but the nearestlooporswitchthat contains thatifstatement. The reason for not breaking out of anifstatement is because it is commonly used to decide whether you want to break out of theloop.
Interestingly, a telephone switch misbehaved because the company that invented Cmade exactly this bug. They wanted to break out of anifstatement and they forgot that it would break out of the entireforstatement.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.