question
stringlengths
25
894
answer
stringlengths
4
863
``` #include <stdio.h> #include <stdlib.h> typedef int element; struct cell { element e; struct cell *p; }; typedef struct cell* CELL; int main() { CELL* p; p = (CELL*) malloc (sizeof(struct cell)); p->e = 8; /* This ain't working */ *p.e = 8; /* This doesn't help anything either */ return 0; } ``` I'm just getting started withmallocand I just made a pointer to a newly createdCELL, which is astruct. Now I'm trying to fill it with some values, but I'm greeted by an unfriendly "request for member e" in something not a structure or union". I did make a pointer to astructthat contains a member called e, or at least that's what I think I did. Why does this fail?
I think this nicely illustrates a rule of good C style - do not create typedefs that hide the fact that something is a pointer.
In an Xcode project I have a C file with functions, it compiles and works OK I want to wrap my C code in struct(s), how will I be able to call them in Objective-C?
Objective-C is a proper superset of C. Anything you can do in C can be done identically in Objective-C. So, you really don't need to think of them as different languages; Objective-C is simply "C plus some more stuff". ``` // this struct is compatible with C and Obj-C struct fruit { int a; }; int main() { struct fruit apple; apple.a = 1; return 0; } ``` Then, any C or Objective-C source file can access that struct. There aren't any additional complications introduced by Objective-C.
The reason why it should beemptyis because I need to write it in C: https://stackoverflow.com/questions/951516/what-good-ides-are-availble-for-c/951582#951582 But how to write a dll from scratch?
UseFile -> New project -> Visual C++ -> Win32 projectSelect application typeDLLand additional optionsEmpty project. Edit: To get a C template the easiest way is to not checkEmpty projectand then convert the project: Rename the CPP-files to C (right click on them in the solution explorer)Remove StdAfx.cppIn Project -> {project} Properties changeConfiguration Properties -> C/C++ -> Precompiled headersYou can choose to not use pre-compiled headers or you can change it to Create new ones.Build your projectAdd the meat to the template For pointers on how to write the DLL code google fordll sample code
For example, given string "abc fghi bc kl abcd lkm abcdefg", the function should return string "abcd" and the count of 2. A O(n^2) solution seems easy but I am looking for a better solution. Edited:If nothing better than O(n^2) is possible than which approach would be best performance wise.
You can solve this in linear time by building asuffix treeand taking a path from the root to the deepest internal node; this will give you the longest repeated string. Once you have that string, it's trivial to count the number of times it appears.
Suppose I have an array of size 10 characters (memset to 0), which I am passing to strncat as destination, and in source I am passing a string which is say 20 characters in length (null terminated), now should I pass the 'count' as 10 or 9? The doubt is, does strncpy considers the 'count' as size of destination buffer or does it just copy 10 characters to the destination and then append a NULL terminating character in the 11th position. Sorry if the question appears too trivial, but I was unable to make this out from the help documentation of strncpy.
You should probably justread the man pagea bit more. The operative sentence seems to be this one: The strncat() function is similar, except that it will use at most n characters from src. Since the result is always terminated with '\0', at most n+1 characters are written.
Is it possible to have a class inheriting from a struct? More specifically, how can I wrap a C struct with a class, so that I can pass class pointers to methods that requires struct ptr and cast back when I receive the pointer in e.g. callbacks? (Or even more specifically, the address of the class should be same same address as the struct...)
You just derive from the C struct. In C++, the only difference between astructand aclassis that the latter's default member accessibility isprivate, while the former's ispublic. If only single inheritance is involved, theclass's address should be the same as thestruct's which acts as a base class. If the inheritance only serves the implementation (that is, there is no Is-A relationship between the two), consider using private inheritance.
Given two sorted linked lists, L1 and L2, a solution to compute their intersectionL1 intersection L2.
``` L1_node = L1.head; L2_node = L2.head; Result = new SList; while L1_node != NULL and L2_node != NULL: if L1_node.value == L2_node.value: Result.append(L1_node.value) L1_node = L1_node.next L2_node = L2_node.next elif L1_node.value < L2_node.value: L1_node = L1_node.next else L2_node = L2_node.next ``` (Translate to C yourself.)
``` int x[10],y[10]; x = y; ``` I am thinking of a simple hack, which would enable me to get this effect.
You can wrap them instructs to use simple assignment: ``` struct foo { int a[10]; } x, y; x = y; ``` But really, just usememcpy.
Insomuch as I understand "for(;;)" has no initial condition, no test condition and no increment condition, and therefore loops forever, I am curious why the test condition succeeds each loop. Does the empty expression ";" evaluate as true in C? Or is this a special case handled by compilers? A similar, but unrelated question.
This is by the definition of theforstatement in the C language. 6.8.5.3/2 "Theforstatement": Both clause-1 and expression-3 can be omitted.An omitted expression-2 is replaced by a nonzero constant.
I've compiled my C program usinggcc 4.4.1using the flag-g, but when I try to step through one of my functions ingdb version 7.0, I get the message: ``` "Single stepping until exit from function _DictionaryTree_getNodeList, which has no line number information." ``` Can someone tell me why this is happening?
Just guessing, but is _DictionaryTree_getNodeList in another file that wasn't compiled with -g?
How can I create a basic C app in Visual Studio, be it 2010 Ultimate or 2008 Professional? I have searched through the project templates, and can find plenty for C++, but none for C. (I'm hoping that the compiler and debugger will be built in.)
New project/Win32 Console Application/Empty project. Add a file called "hello.c" (important that it's .c) Type out a basic hello-world: ``` #include <stdio.h> int main() { printf("Hello world\n"); return 0; } ``` Compile, execute... PROFIT!
I'm trying to learn how to use Lua with C, so by now I want to try running a script without loading it from a file, since I don't want to be bothered with messing up with files. Can anybody tell me which functions do I need to call for executing a simple string or what ever?
You can useluaL_dostringto execute a script from a string. If you need help with the basics (creating a Lua state, etc.), read part IV ofProgramming in Lua.
Given a stack S, need to sort the stack using onlyPush,Pop,Top,IsEmpty,IsFull. Looking for most simple solution. Edited: Removed in place condition. Can't use another stack or queue.
For this problem, can we consider using system stack? Make several recursive calls. ``` public static void sort(Stack<Integer> s) { if (!s.isEmpty()) { Integer t = s.pop(); sort(s); insert(t, s); } } private static void insert(Integer x, Stack<Integer> s) { if (s.isEmpty()) { s.push(x); return; } if (x < s.peek()) { Integer t = s.pop(); insert(x, s); s.push(t); } else { s.push(x); } } ```
I am trying to solve this problem: In an integer array all numbers occur exactly twice, except for a single number which occurs exactly once. A simple solution is to sort the array and then test for non repetition. But I am looking for better solution that has time complexity of O(n).
You can use "xor" operation on the entire array. Each pair of numbers will cancel each other, leaving you with the sought value. ``` int get_orphan(int const * a, int len) { int value = 0; for (int i = 0; i < len; ++i) value ^= a[i]; // `value` now contains the number that occurred odd number of times. // Retrieve its index in the array. for (int i = 0; i < len; ++i) { if (a[i] == value) return i; } return -1; } ```
I was reading the nmap source code because I'd like to find out how does it discover that certain ports are filtered or firewalled. I have some experience with sockets in c and i've built simple port scanners, that's easy - if the connection succeeds, the port is open, otherwise it's closed (because of the RST returned). But in case with the firewalled ports, they don't return RST packet back, and my port scanner just "waits" forever. If someone's got experience with this topic, please point me to the parts of the nmap code where the actual scanning and port-state determination occurs, or at least tell me if there are any other codes available which deal with this problem.
Use asynchronous socket API calls (i.e. don't wait for the connection to be established, and instead try the next port/address in parallel) and define a reasonable timeout (e.g. if the connection isn't established after a minute you can consider it filtered).
I was recently porting a project from GCC to clang(in which I fixed a number of C GNU-isms). This got me thinking: what C GNU-isms(extensions to the C language supported in GCC, which are not standardized) exist? Is there a comprehensive list anywhere?
Here is a pretty comprehensive list straight from GCC's website. There seems to be quite a lot, so I wish you the best of luck sifting through it! http://gcc.gnu.org/onlinedocs/gcc-4.2.0/gcc/C-Extensions.html
This seems super basic, but I'm having trouble finding documentation online to explain it. I have the Eclipse IDE for C/C++ 3.5.1. How can I create a simple Hello World program in C? (I have also downloaded cygwin.) Many tutorials online make reference to "Managed" and "Simple" types of projects, but I can't find that anywhere. Was that removed in 3.5.1?
Is there a specific reason you want to use Eclipse? For a beginner, probably the easiest way to get started with C on Windows is to use the freeMicrosoft Visual C++ Express Edition. It's a full IDE with built in compiler and debugger, and can do everything you might need to do for learning C. Although you have Eclipse and Cygwin right now, neither of those components actually include acompilerunless you specifically download that too. With that environment, you have to manually put the pieces together before you can compile and run your code.
I have the simplest of makefiles: ``` threads: gcc threads.c -o threads ``` but I get the error: 'make: Fatal error: Don't know how to make target' Any ideas what I am doing wrong? It's probably something simple - I made the makefile in emacs on the system which is trying to run it (Unix)
Do you have spaces instead of a tab on the second line there? Most common basic make mistake, I'd say.
I can do this: ``` int main(int argc, char** argv) { unsigned char cTest = 0xff; return 0; } ``` But what's the right way to get a hexadecimal number into the program via the command line? unsigned char cTest = argv[1]; doesn't do the trick. That produces ainitialization makes integer from pointer without a castwarning.
I think some people arriving here might just be looking for: ``` $ ./prog `python -c 'print "\x41\x42\x43"'` $ ./prog `perl -e 'print "\x41\x42\x43"'` $ ./prog `ruby -e 'print "\x41\x42\x43"'` ```
Why sometimes C code gets wrapped with curly braces without declaring a variable in them? e.g. (from FreeRTOS source code, file 'tasks.c'):portENTER_CRITICAL(); { xTicks = xTickCount; } portEXIT_CRITICAL();
This is just an inner scope. The benefit is that code shows your intent in that case. e.g. This scopeisthe critical section.
How can I print the source of a webpage, specified in curl_easy_setopt, without html tags? So, printing only the text in the source?
Curl/libcurl is just for fetching the HTML page. To extract information from it, you need other tools. The most general solution is to use a HTML parser. A good one in C isHTMLparser from libxml.
I have two enums in my code: ``` enum Month {January, February, March, April, May, June, July, August, September, October, November, December}; enum ShortMonth {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; ``` Mayis a common element in both enums, so the compiler says: Redeclaration of enumerator 'May'. Why does it say so? And how can I circumvent this?
Enum names are in global scope, they need to be unique. Remember that you don't need to qualify the enum symbols with the enum name, you do just: ``` Month xmas = December; ``` not: ``` Month xmas = Month.December; /* This is not C. */ ``` For this reason, you often see people prefixing the symbol names with the enum's name: ``` enum Month { Month_January, Month_February, /* and so on */ }; ```
I want to see implementation of java.util.zip.CRC32. But within this class its using native c library functions for core implementation.How can I get the native source code. I can see the java.util.zip.CRC32 source code, but this doesn't have the actual implementation.
You must ask SUN, I mean Oracle about having the source code... :-/ You can try the source code for Java 6 at thisdownload page. CRC32 should not have changed much between Java 1.4 and 6.
Is there a one-liner that lets me output the current value of an enum?
As a string, no. As an integer, %d. Unless you count: ``` static char* enumStrings[] = { /* filler 0's to get to the first value, */ "enum0", "enum1", /* filler for hole in the middle: ,0 */ "enum2", "enum3", .... }; ... printf("The value is %s\n", enumStrings[thevalue]); ``` This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.
i have strings like "folder1/file1.txt" or "foldername1/hello.txt" and i need to take the substring that identify the folder name with the slash (/) included(example: from "folder1/file1.txt" i need "folder1/").The folders name are not all with the same length. How can i do this in C?? thanks
First, find the position of the slash with strchr: ``` char * f = "folder/foo.txt"; // or whatever char * pos = strchr( f, '/' ); ``` then copy into a suitable place: ``` char path[1000]; // or whatever strncpy( path, f, (pos - f) + 1 ); path[(pos-f)+1] = 0; // null terminate ``` You should really write a function to do this, and you need to decide what to do if strchr() returns NULL, indicating the slash is not there.
I am trying to get cracking with my C module at uni, however I can't seem to get an IDE to work. I want to use Visual Studio though I guess I should be using Unix (I just don't understand Unix enough yet). How in Visual Studio 2008 do I set up a project to work with C? I have used Visual Studio for VB.net before and it was a doddle to use, this is proving somewhat harder for some reason. I just don't know what I am supposed to do in the setting-up stage to get to code if you know what I mean, all I could see was C++ as an option as it has many sub-sections, none of which I could see were relevant.
You can create a standard C++ console application (or a MFC/Win32 one, depending on what you need) and then make a change in the project settings, so it's treated as C code: Configuration -> C/C++ -> Advanced -> Compile As. Set this to "Compile as C code". Or simply pass the /TC flag to the compiler :)
I want to print out (or otherwise ascertain) the type of some variable in my program. Is there a good way to do it? By good, I mean a way that works, even if it means intentionally throwing compiler errors. For example: ``` client.c:55: error: incompatible types in assignment ``` is the error I'm getting right now. What I WANT is it to tell me something like: ``` client.c:55: error: attempting to assign type struct a to type struct b ``` or a function that I can use like so: ``` printf(gettype(x)); ``` which would output: ``` struct b ```
I have just discovered how to do this. ``` printf("%d", variable); ``` If variable is not an int thengcc -Wallwill complain that the types don't match - and will print out the type of the variable, which is exactly what you are looking for.
Interesting little bug here: ``` if (host != NULL) { printf("hi"); } else { printf("FAIL"); } return 0; ``` doesn't print anything at all, but: ``` if (host != NULL) { printf("hi"); } else { printf("FAIL"); } fprintf(stdout, "\n%s\n", (char *)&additionalargs); return 0; ``` prints hiabc Does anyone know why this is?
printf output to stdout is buffered. You might want to look atfflush
``` void main() { void *v; int integer=2; int *i=&integer; v=i; printf("%d",(int*)*v); } ``` this simple program will result in a compiler error saying: ``` Compiler Error. We cannot apply indirection on type void* ``` what exact does this error mean?
The error means exactly what it says. The error is triggered by the*vsubexpression used in your code. Unary operator*in C is often calledindirectionoperator ordereferenceoperator. In this case the compiler is telling you that it is illegal to apply unary*to a pointer of typevoid *.
I have a function that runs in C. I would like for it to timeout, or at least be non blocking. Is there a way to do that without running it as a thread?
select()(or one of its platform-specific equivalents) is what should be used if you don't know that there is input available from a blocking file or socket, and want to continue if there isn't.
I am allocating some float arrays (pretty large, ie 9,000,000 elements) on the GPU usingcudaMalloc((void**)&(storage->data), size * sizeof(float)). In the end of my program, I free this memory usingcudaFree(storage->data);. The problem is that the first deallocation is really slow, around 10 seconds, whereas the others are nearly instantaneous. My question is the following : what could cause this difference ? Is deallocation memory on a GPU usually that slow ?
As pointed out on the NVIDIA forums, it's almost certainly a problem with the way you are timing things rather than with cudaFree.
Is it possible to skin the GTK+ progress bar widget such that it shows a custom image (an AJAX style animated gif maybe)? If so how and if not, is there any other option/control which can achieve this effect?
Something likeGtkSpinner?
If I compile and link an executable with the -export-dynamic flag, it doesn't apply to symbols stored in archives that are linked. The flag only on exports symbols for objects that are linked that aren't in archives. Can someone explain why this would be?
The problem seems to be that .o files inside .a files are only linked if they are needed by the executable (apparently it's called "dead-stripping"). In my case, the symbols are only required by a shared library that is explicitly opened with dl commands. I can link with the --whole-archive option (on GNU, at least), which will force the linking of all the objects in the archive.
Is there a function or library that can convertany(default, octal, hex, ...) integer in C given as achar[]into anunsigned long long int? Examples: ``` 1 1l 1ul 42e+10 0x2aLL 01234u ... ``` atoihas some problems with 0x... and the suffixes u/l.
strtoullis about as close as it gets. This will stop at the suffix, but since you're always producing anunsigned long long, you don't really care about the suffix anyway. I don't believe it will work with42e+10either -- although the value that produces is an integer, C and C++ only define the 'e' notation for floating point numbers. Other than that, you need/want to pass0as the conversion base, in which case it implements the usual C convention that a leading0signals octal,0xsignals hexadecimal, and1-9signal decimal.
I'm looking for how to play back audio streams in these formats: MP3Ogg / VorbisWMA over MMS/ASFAAC / AAC+ target is the mac and iPhone. Maybe there is an open source library that I could look at, to understand how it works, and then port it to the cocoa frameworks somehow.
I'd take a look atFFmpeg. It's the most widely used opensource codec library and can be compiled for the iPhone. It has RTSP support (Microsoft deprecated MMS streams in 2003 and most current mms:// streams are actually just RTSP. You don't actually need to port C/C++ libraries to Cocoa to be able to use them with Cocoa/Objective-C. You can use C libraries directly and C++ ones with Objective-C++ or using a C wrapper. Or are you worrying about the license? Many parts of FFmpeg are LGPL and can be used from proprietary applications.
Are there solutions in C or Objective-C to receive and play back SHOUTcast audio streams on the mac or iphone?
Implement an M3U/PLS parser (which is just a text list of MP3 streams) and use the code here to play the MP3's http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html
I'm trying to avoid the redeclaration of self, in the following ``` picker2.peoplePickerDelegate = self; // showing the picker [self presentModalViewController:picker2 animated:YES]; ``` Why am i not able to just go like: ``` [picker2.peoplePickerDelegate presentModalViewController:picker2 animated:YES]; ``` Regards
Becausepicker2.peoplePickerDelegatemay not beselfbefore your assignment. (Also,picker2.peoplePickerDelegateis not aUIViewControllerso sending the-presentModalViewController:animated:message to it is wrong.)
The problem is simpler thanknapsack(or a type of it, without values and only positive weights). The problem consists of checking whether a number can be a combination of others. The function should returntrueorfalse. For example, 112 and a list with{ 17, 100, 101 }should returnfalse,469with the same list should returntrue,35should returnfalse,119should returntrue, etc... Edit: subset sum problem would be more accurate for this than knapsack.
This is a special case of the Subset Sum problem, with sets that only contain one negative number (i.e., express 112 and { 17, 100, 101 } as { -112, 17, 100, 101 }). There's a few algorithms on the Wikipedia page,http://en.wikipedia.org/wiki/Subset_sum_problem.
I am using a API that has a macro for success which is "NT_SUCCESS". However they don't have one for failure. So normally I have to do this. ``` if(something failed) return !NT_SUCCESS; else return NT_SUCCESS; ``` Having the !NT_SUCCESS I don't think is very readable. So I decided to do this: ``` #define SUCCESS NT_SUCCESS #define FAILURE (!NT_SUCCESS) ``` EDIT ============================= ``` #define ENT_NOERR 0 /* No error */ #define NT_SUCCESS ENT_NOERR /* synonym of ENT_NOERR */ ``` This is how NT_SUCCESS is declared, Would it still be ok to do what I have done. Would that be ok? Many thanks for any suggestions,
I would suggest to put the FAILURE define in parenthesis: ``` #define FAILURE (!NT_SUCCESS) ```
Python hasctypesto access libraries. In PHP you write extensions for everything. Popular extensions like the one for libgd are available almost everywhere. Is there any extension which works like Python's ctypes, letting you access libraries without the need to write an PHP extension?
You're looking forffi.
In general i see the process'spidwhich is running in the background and start dbx on that process using the commanddbx -a <pid> similarly how could i do it using gdb?
In addition to the previous you can directly use ``` gdb -p <pid> ```
I have a function that runs in C. I would like for it to timeout, or at least be non blocking. Is there a way to do that without running it as a thread?
select()(or one of its platform-specific equivalents) is what should be used if you don't know that there is input available from a blocking file or socket, and want to continue if there isn't.
I am allocating some float arrays (pretty large, ie 9,000,000 elements) on the GPU usingcudaMalloc((void**)&(storage->data), size * sizeof(float)). In the end of my program, I free this memory usingcudaFree(storage->data);. The problem is that the first deallocation is really slow, around 10 seconds, whereas the others are nearly instantaneous. My question is the following : what could cause this difference ? Is deallocation memory on a GPU usually that slow ?
As pointed out on the NVIDIA forums, it's almost certainly a problem with the way you are timing things rather than with cudaFree.
Is it possible to skin the GTK+ progress bar widget such that it shows a custom image (an AJAX style animated gif maybe)? If so how and if not, is there any other option/control which can achieve this effect?
Something likeGtkSpinner?
If I compile and link an executable with the -export-dynamic flag, it doesn't apply to symbols stored in archives that are linked. The flag only on exports symbols for objects that are linked that aren't in archives. Can someone explain why this would be?
The problem seems to be that .o files inside .a files are only linked if they are needed by the executable (apparently it's called "dead-stripping"). In my case, the symbols are only required by a shared library that is explicitly opened with dl commands. I can link with the --whole-archive option (on GNU, at least), which will force the linking of all the objects in the archive.
Is there a function or library that can convertany(default, octal, hex, ...) integer in C given as achar[]into anunsigned long long int? Examples: ``` 1 1l 1ul 42e+10 0x2aLL 01234u ... ``` atoihas some problems with 0x... and the suffixes u/l.
strtoullis about as close as it gets. This will stop at the suffix, but since you're always producing anunsigned long long, you don't really care about the suffix anyway. I don't believe it will work with42e+10either -- although the value that produces is an integer, C and C++ only define the 'e' notation for floating point numbers. Other than that, you need/want to pass0as the conversion base, in which case it implements the usual C convention that a leading0signals octal,0xsignals hexadecimal, and1-9signal decimal.
I'm looking for how to play back audio streams in these formats: MP3Ogg / VorbisWMA over MMS/ASFAAC / AAC+ target is the mac and iPhone. Maybe there is an open source library that I could look at, to understand how it works, and then port it to the cocoa frameworks somehow.
I'd take a look atFFmpeg. It's the most widely used opensource codec library and can be compiled for the iPhone. It has RTSP support (Microsoft deprecated MMS streams in 2003 and most current mms:// streams are actually just RTSP. You don't actually need to port C/C++ libraries to Cocoa to be able to use them with Cocoa/Objective-C. You can use C libraries directly and C++ ones with Objective-C++ or using a C wrapper. Or are you worrying about the license? Many parts of FFmpeg are LGPL and can be used from proprietary applications.
Are there solutions in C or Objective-C to receive and play back SHOUTcast audio streams on the mac or iphone?
Implement an M3U/PLS parser (which is just a text list of MP3 streams) and use the code here to play the MP3's http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html
I'm trying to avoid the redeclaration of self, in the following ``` picker2.peoplePickerDelegate = self; // showing the picker [self presentModalViewController:picker2 animated:YES]; ``` Why am i not able to just go like: ``` [picker2.peoplePickerDelegate presentModalViewController:picker2 animated:YES]; ``` Regards
Becausepicker2.peoplePickerDelegatemay not beselfbefore your assignment. (Also,picker2.peoplePickerDelegateis not aUIViewControllerso sending the-presentModalViewController:animated:message to it is wrong.)
The problem is simpler thanknapsack(or a type of it, without values and only positive weights). The problem consists of checking whether a number can be a combination of others. The function should returntrueorfalse. For example, 112 and a list with{ 17, 100, 101 }should returnfalse,469with the same list should returntrue,35should returnfalse,119should returntrue, etc... Edit: subset sum problem would be more accurate for this than knapsack.
This is a special case of the Subset Sum problem, with sets that only contain one negative number (i.e., express 112 and { 17, 100, 101 } as { -112, 17, 100, 101 }). There's a few algorithms on the Wikipedia page,http://en.wikipedia.org/wiki/Subset_sum_problem.
I am using a API that has a macro for success which is "NT_SUCCESS". However they don't have one for failure. So normally I have to do this. ``` if(something failed) return !NT_SUCCESS; else return NT_SUCCESS; ``` Having the !NT_SUCCESS I don't think is very readable. So I decided to do this: ``` #define SUCCESS NT_SUCCESS #define FAILURE (!NT_SUCCESS) ``` EDIT ============================= ``` #define ENT_NOERR 0 /* No error */ #define NT_SUCCESS ENT_NOERR /* synonym of ENT_NOERR */ ``` This is how NT_SUCCESS is declared, Would it still be ok to do what I have done. Would that be ok? Many thanks for any suggestions,
I would suggest to put the FAILURE define in parenthesis: ``` #define FAILURE (!NT_SUCCESS) ```
I'm trying to implement George Marsaglia's Complementary Multiply-With-Carry algorithm in C. It seems to work great under Win7 64 bit and Linux 32 bit, but seems to behave strangely under Win 7 32 bit. The random number it returns is 32 bit, but there's a temporary value used internally that's supposed to be 64 bits, and it's declared: ``` unsigned long long t; ``` I suspect thismightbe the cause of the misbehaviour, so my question is: Is the type "long long" 64 bits? Is it supported in 32 bit Windows?
If your compiler hasstdint.hI would suggest usinguint64_tinstead.
I need to compile several c++ projects using the version 6.0 compiler. Is there any way to compile my projects using the visual c++ 2008 express edition compiler. In java, there is a command to specify which version of the compiler to use on commandline, I was hoping that c++ 2008 has such a command as well. Kind regards.
No. there is no such command in visual studio. If you want to compile with VC6 you'll need to install VC6.Also, notice that the version of the compilercl.exeis usually different from the version of visual studio. For instance the compiler which comes with visual studio 2008 (which is version 9 if visual studio) is: ``` C:\Program Files\Microsoft Visual Studio 9.0\VC>cl Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86 ```
Now this is a silly puzzle I got from some exam paper,sadly I am unable to figure it out from last 15 minutes. ``` #include <stdio.h> int main(void){ /* <something> */ putchar(*(wer[1]+1)); return 0; } ``` What should we replace in place of something in order to get the outpute.Now we knowputchartakes aintas argument but this code assumes to give a pointer.Does this question is even valid ?
``` const char *wer[2] = { "failed", "test" }; ```
While i'm developing in C/C++ and Java, i simply make a compile.bat script that does everything, that's fine for me. Why should i use make and why should i use ant?
Suppose you have 1000 source files and change just one of them. With your .bat script you will have to recompile the lot, with make you recompile just the one that changed. This can save quite a bit (read hours on a big project) of time. Even better, if you change one of your header files, make will re-compile only the source files that use that header. These are the two main features that have meant make and its offspring are used for all serious software development with compiled languages.
Could someone explain what this code does ``` size = *(int *)data; // size of string plus header word off = (size + 3) & ~3; chan = *(int *)(data + off); data[size] = '\0'; // zero terminate ``` I think it's got something to do with making the data a multiple of 4?
Assuming thatdatais achar*... ``` size = *(int *)data; // size of string plus header word ``` datais interpreted as a pointer-to-int, then dereferenced and assigned tosize. ``` off = (size + 3) & ~3; ``` This roundssizeupwards to the nearest multiple of 4, and assigns tooff. ``` chan = *(int *)(data + off); ``` The value forchanapparently residesoffbytes fromdata. ``` data[size] = '\0'; // zero terminate ``` That one is obvious.
Is there an option I can change in Eclipse to make sure that my code has got to be ANSI C-compliant before it can be compiled?
Project > Properties > C/C++ Build > Tool Settings > Miscellaneous > "Support ANSI programs"
I have a function to print characters on the screen that is like this: ``` void print(int colour, int y, int x, const char *string) { volatile char *video=(volatile char*)0xB8000 + y*160 + x*2; while(*string != 0) { *video=*string; string++; video++; *video=colour; video++; } } ``` And I want to print the character254 in decimal, but I need to use stored on aconst char*. I can't tryprint(0x0F, 0, 0, 0xFE);, because this trows a error of pointer without cast, then how can I do this?
Embed the character in the string using C's hex notation: ``` print(0x0f, 0, 0, "\xfe"); ``` As folks have pointed out, you might want to pretty up the code a bit, perhaps by adding a symbolic name for theVGA framebuffer base address.
I'm using a header calledcolors.hto organize my source code. The header is like this: ``` #define DEFAULT 0x07 #define BLACK 0 #define GRAY 7 #define BLUE 9 #define GREEN 10 #define CYAN 11 #define RED 12 #define MAGENTA 13 #define YELLOW 14 ``` I'm putting the header at the same directory of the main source code, calledkernel.c, and including it like this: ``` #include <colors.h> ``` But when I try to compile, I'm getting this: ubuntu@eeepc:~/Development/Test$ gcc -o kernel.o -c kernel.c -Wall -Wextra -nostdlib -nostartfiles -nodefaultlibskernel.c:1:20: error: colors.h: No such file or directoryubuntu@eeepc:~/Development/Test$ What I can do to solve this?
Use quotes: ``` #include "colors.h" ``` Using quotes will look in the same directory first, and then in the specified include paths. Using angle brackets will look in the include paths only.
This question already has answers here:Closed13 years ago. Possible Duplicate:What is the arrow operator (->) synonym for in C++? I couldn't find documentation on the "->" which is used a lot in Gnome codebase. For example in gedit they have this: ``` loader->document = g_value_get_object (value) ``` What is document in relation to loader? There are many other examples as well with more basic widgets as well.
loaderis a pointer.->dereferences a pointer to a struct. It's the same as typing(*loader). Hence: ``` struct smth { int a; int b; }; struct smth blah; struct smth* pblah; ``` ...to get access toafromblah, you need to typeblah.a, from pblah you need to writepblah->a. Remember that it needs to point to something though!
gcc 4.4.2 c89 I have a file called main.c. I want the result of the pre-comiler and save it to a text file. I have done the following which creates a text file, but there is nothing in it. It is zero bytes. ``` gcc -E main.c | > main.txt ``` Many thanks for any suggestions,
Apart from the obvious error: ``` gcc -E main.c > main.txt ``` ... you can also use the C preprocessor directly: ``` cpp main.c > output.c ``` ...which has the added benefit of being independed of the compiler and possible to use in another toolchain. In both cases in case of problems, take a look at preprocessorcommand line options.
I'm currently working with a PLC that supports ANSI C, but uses its own flavour of the GNU compiler, which doesn't compile any variadic functions and things like itoa. So using sprintf & co. isn't an option for converting integers to strings. Can anyone guide me to a site where a robust, sprintf- free implementation of itoa is listed or post a suitable algorithm here? Thanks in advance.
This is from K&R: ``` void itoa(int n, char s[]) { int i, sign; if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } ``` reverse()just reverses a string.
I know this is really general, but I get "this" (see below) when I run my .c file in Visual C++ 2008 Express. It happens when I callmalloc (). Take my work on this - I dynamically allocate memory properly. HEAP[Code.exe]: HEAP: Free Heap block 211a10 modified at 211af8 after it was freed Windows has triggered a breakpoint in Code.exe.This may be due to a corruption of the heap, which indicates a bug in Code.exe or any of the DLLs it has loaded.This may also be due to the user pressing F12 while Code.exe has focus.The output window may have more diagnostic information. Why do I get this error? What does this even mean?
The error message tells you exactly why you got it: Free Heap block 211a10 modified at 211af8 after it was freed You had a heap allocated block that was freed then something wrote to that area of memory. It's not nice to write to a freed block of memory.
In my c/c++ files, there are multiple #define. As an example: ``` #ifdef LIBVNCSERVER_HAVE_LIBZ /* some code */ #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* some more code */ ``` Can you please tell me how can I modify my Makefile.in so that I have those #define inALLfiles during compilation? Thank you.
``` -DLIBVNCSERVER_HAVE_LIBZ -DLIBVNCSERVER_HAVE_LIBJPEG ``` You could pass those inCPPFLAGS, ``` CPPFLAGS = -DLIBVNCSERVER_HAVE_LIBZ -DLIBVNCSERVER_HAVE_LIBJPEG ``` or make new variable ``` CUSTOMDEFINES = -DLIBVNCSERVER_HAVE_LIBZ -DLIBVNCSERVER_HAVE_LIBJPEG ``` and pass it toCPPFLAGS = -DEXISTINGFLAGS $(CUSTOMDEFINES) Those are finally will pass togcc/g++ -D... ``` $(CC) $(CPPFLAGS) ```
Windows API/C/C++ ``` 1. .... 2. .... 3. .... 4. while (flag1 != flag2) 5. { 6. SleepEx(100,FALSE); //waiting for flags to be equal (flags are set from another thread). 7. } 8. ..... 9. ..... ``` If the flags don't equal each other after 7 seconds, I would like to continue to line 8. Any help is appreciated. Thanks.
If you are waiting for a particular flag to be set or a time to be reached, a much cleaner solution may be to use an auto / manual reset event. These are designed for signalling conditions between threads and have very rich APIs designed on top of them. For instance you could use the WaitForMultipleObjects API which takes an explicit timeout value.
What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dstirbutions?
These are c library calls, and as such are in the libc library.
Is it possible to have a piece of code like this in user space? I mean is it possible to read/write co-processor register in user space in Netbsd / Linux? ``` XYZ]# cat pmc.c static inline int arm11_pmc_ctrl_read(void) { unsigned int val; __asm volatile ("mrc p15, 0, %0, c15, c12, 0" : "=r" (val)); return val; } int main(){ unsigned int ctrl; ctrl = arm11_pmc_ctrl_read(); } ```
User space does not have access to privileged instructions or registers. Look in your assembler manual to find out if the instructions and registers you are using are privileged.
I would like to know how to create console applications with better control of input and output using C. For example, how does the text-editor nano display the file contents in a certain portion of the screen and then keep a list of commands stationary on the bottom. I know you can use the win32 api to do this in Windows, but what is the Unix/Linux equivalent?
More than likely there's ancursesinterface that controls the screen drawing and placement of items on the screen in a certain position. The api is standard across the linux systems and on unix also, some may be implementation defined depending on the variant of curses used under the commercial variants of unix but otherwise some standard ncurses functionality are compatible.
I perform some checks in my Window class constructor, and if they fail I want to display an error message and close the window. I'm getting crashes when calling Close() from the constructor or from Window_Loaded. Does that sounds normal or am I doing something wrong? If this is normal, when should I call Close()?
It turns out you can call Close() in the constructor or on Window_Loaded - I was just doing something wrong later on in the destructor.
For example, say we have a union ``` typedef union { unsigned long U32; float f; }U_U32_F; ``` When a variable of this union type is declared, is there a way to set an initial value? ``` U_U32_F u = 0xffffffff; // Does not work...is there a correct syntax for this? ```
Use an initializer list: ``` U_U32_F u = { 0xffffffff }; ``` You can set other members than the first one via ``` U_U32_F u = { .f = 42.0 }; ```
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed4 years ago.Improve this question I'm searching for a lib which can recognize the human language of a .txt document I already foundthis pagebut im more interested in source code which I can use offline some language which would be great to support english, french, german programming language which would be best c/c++, php, JS is also ok Any hints for libs or just how I could better search on this topic?
Have a look a this library:http://software.wise-guys.nl/libtextcat/
While closing sqlite3 using sqlite3_close function it returns error code 5 5 - database file is busy. How to fix this issue.
Thesqlite3_closedocumenationstates it clearly: Applications must finalize all prepared statements and close all BLOB handles associated with the sqlite3 object prior to attempting to close the object. If sqlite3_close() is called on a database connection that still has outstanding prepared statements or BLOB handles, then it returns SQLITE_BUSY.
I wish to wrap an existing C (pure C that is. No C++) library into Python so that I can call it from Python scripts. Which approach among the various available (C Api, SWIG etc.) would be the most suitable?
go with Ctypes, it is part of standard distribution and works very well. basically you can wrap C structures and types in python classes, as well as functions. Some types and functionality is already provided by library. ctypes couple caveats though: passing triple pointers to C routines is not obvious (if you have to), and I could not get it to work with static libraries on Linux, DLL and shared objects are fine.
Valgrind gives me the following leak summary on my code. However, I have freed all malloc'ed memory. Is this a bad thing, or is this normal? My program is in c. ==3513== LEAK SUMMARY:==3513== definitely lost: 0 bytes in 0 blocks.==3513== possibly lost: 0 bytes in 0 blocks.==3513== still reachable: 568 bytes in 1 blocks.==3513== suppressed: 0 bytes in 0 blocks.
The valgrind messagestill reachable: 568 bytes in 1 blocks.means that there was memory freed in your application which is still "reachable", which means that you still have a pointer to it somewhere. At shutdown, this probably means a global variable of some kind. However, since the number of bytes "definitely leaked" or "probably leaked" is zero, this condition is completely benign. Don't worry about it.
Fromcrypt(3) - Linux man page: ``` char *crypt(const char *key, const char *salt); ``` Return Value: A pointer to the encrypted password is returned. On error,NULLis returned. Since the return value is unknown unless key and salt is given, this should be dynamically allocated memory, but valgrind doesn't agree.
From the man page: The return value points to static data whose content is overwritten by each call. So this means it's not dynamically allocated - it's a single static allocation (just like a global variable).
I'm trying to implement George Marsaglia's Complementary Multiply-With-Carry algorithm in C. It seems to work great under Win7 64 bit and Linux 32 bit, but seems to behave strangely under Win 7 32 bit. The random number it returns is 32 bit, but there's a temporary value used internally that's supposed to be 64 bits, and it's declared: ``` unsigned long long t; ``` I suspect thismightbe the cause of the misbehaviour, so my question is: Is the type "long long" 64 bits? Is it supported in 32 bit Windows?
If your compiler hasstdint.hI would suggest usinguint64_tinstead.
I need to compile several c++ projects using the version 6.0 compiler. Is there any way to compile my projects using the visual c++ 2008 express edition compiler. In java, there is a command to specify which version of the compiler to use on commandline, I was hoping that c++ 2008 has such a command as well. Kind regards.
No. there is no such command in visual studio. If you want to compile with VC6 you'll need to install VC6.Also, notice that the version of the compilercl.exeis usually different from the version of visual studio. For instance the compiler which comes with visual studio 2008 (which is version 9 if visual studio) is: ``` C:\Program Files\Microsoft Visual Studio 9.0\VC>cl Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86 ```
Now this is a silly puzzle I got from some exam paper,sadly I am unable to figure it out from last 15 minutes. ``` #include <stdio.h> int main(void){ /* <something> */ putchar(*(wer[1]+1)); return 0; } ``` What should we replace in place of something in order to get the outpute.Now we knowputchartakes aintas argument but this code assumes to give a pointer.Does this question is even valid ?
``` const char *wer[2] = { "failed", "test" }; ```
While i'm developing in C/C++ and Java, i simply make a compile.bat script that does everything, that's fine for me. Why should i use make and why should i use ant?
Suppose you have 1000 source files and change just one of them. With your .bat script you will have to recompile the lot, with make you recompile just the one that changed. This can save quite a bit (read hours on a big project) of time. Even better, if you change one of your header files, make will re-compile only the source files that use that header. These are the two main features that have meant make and its offspring are used for all serious software development with compiled languages.
Could someone explain what this code does ``` size = *(int *)data; // size of string plus header word off = (size + 3) & ~3; chan = *(int *)(data + off); data[size] = '\0'; // zero terminate ``` I think it's got something to do with making the data a multiple of 4?
Assuming thatdatais achar*... ``` size = *(int *)data; // size of string plus header word ``` datais interpreted as a pointer-to-int, then dereferenced and assigned tosize. ``` off = (size + 3) & ~3; ``` This roundssizeupwards to the nearest multiple of 4, and assigns tooff. ``` chan = *(int *)(data + off); ``` The value forchanapparently residesoffbytes fromdata. ``` data[size] = '\0'; // zero terminate ``` That one is obvious.
Is there an option I can change in Eclipse to make sure that my code has got to be ANSI C-compliant before it can be compiled?
Project > Properties > C/C++ Build > Tool Settings > Miscellaneous > "Support ANSI programs"
I have a function to print characters on the screen that is like this: ``` void print(int colour, int y, int x, const char *string) { volatile char *video=(volatile char*)0xB8000 + y*160 + x*2; while(*string != 0) { *video=*string; string++; video++; *video=colour; video++; } } ``` And I want to print the character254 in decimal, but I need to use stored on aconst char*. I can't tryprint(0x0F, 0, 0, 0xFE);, because this trows a error of pointer without cast, then how can I do this?
Embed the character in the string using C's hex notation: ``` print(0x0f, 0, 0, "\xfe"); ``` As folks have pointed out, you might want to pretty up the code a bit, perhaps by adding a symbolic name for theVGA framebuffer base address.
I'm using a header calledcolors.hto organize my source code. The header is like this: ``` #define DEFAULT 0x07 #define BLACK 0 #define GRAY 7 #define BLUE 9 #define GREEN 10 #define CYAN 11 #define RED 12 #define MAGENTA 13 #define YELLOW 14 ``` I'm putting the header at the same directory of the main source code, calledkernel.c, and including it like this: ``` #include <colors.h> ``` But when I try to compile, I'm getting this: ubuntu@eeepc:~/Development/Test$ gcc -o kernel.o -c kernel.c -Wall -Wextra -nostdlib -nostartfiles -nodefaultlibskernel.c:1:20: error: colors.h: No such file or directoryubuntu@eeepc:~/Development/Test$ What I can do to solve this?
Use quotes: ``` #include "colors.h" ``` Using quotes will look in the same directory first, and then in the specified include paths. Using angle brackets will look in the include paths only.
This question already has answers here:Closed13 years ago. Possible Duplicate:What is the arrow operator (->) synonym for in C++? I couldn't find documentation on the "->" which is used a lot in Gnome codebase. For example in gedit they have this: ``` loader->document = g_value_get_object (value) ``` What is document in relation to loader? There are many other examples as well with more basic widgets as well.
loaderis a pointer.->dereferences a pointer to a struct. It's the same as typing(*loader). Hence: ``` struct smth { int a; int b; }; struct smth blah; struct smth* pblah; ``` ...to get access toafromblah, you need to typeblah.a, from pblah you need to writepblah->a. Remember that it needs to point to something though!
gcc 4.4.2 c89 I have a file called main.c. I want the result of the pre-comiler and save it to a text file. I have done the following which creates a text file, but there is nothing in it. It is zero bytes. ``` gcc -E main.c | > main.txt ``` Many thanks for any suggestions,
Apart from the obvious error: ``` gcc -E main.c > main.txt ``` ... you can also use the C preprocessor directly: ``` cpp main.c > output.c ``` ...which has the added benefit of being independed of the compiler and possible to use in another toolchain. In both cases in case of problems, take a look at preprocessorcommand line options.
I'm currently working with a PLC that supports ANSI C, but uses its own flavour of the GNU compiler, which doesn't compile any variadic functions and things like itoa. So using sprintf & co. isn't an option for converting integers to strings. Can anyone guide me to a site where a robust, sprintf- free implementation of itoa is listed or post a suitable algorithm here? Thanks in advance.
This is from K&R: ``` void itoa(int n, char s[]) { int i, sign; if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } ``` reverse()just reverses a string.
I know this is really general, but I get "this" (see below) when I run my .c file in Visual C++ 2008 Express. It happens when I callmalloc (). Take my work on this - I dynamically allocate memory properly. HEAP[Code.exe]: HEAP: Free Heap block 211a10 modified at 211af8 after it was freed Windows has triggered a breakpoint in Code.exe.This may be due to a corruption of the heap, which indicates a bug in Code.exe or any of the DLLs it has loaded.This may also be due to the user pressing F12 while Code.exe has focus.The output window may have more diagnostic information. Why do I get this error? What does this even mean?
The error message tells you exactly why you got it: Free Heap block 211a10 modified at 211af8 after it was freed You had a heap allocated block that was freed then something wrote to that area of memory. It's not nice to write to a freed block of memory.
In my c/c++ files, there are multiple #define. As an example: ``` #ifdef LIBVNCSERVER_HAVE_LIBZ /* some code */ #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* some more code */ ``` Can you please tell me how can I modify my Makefile.in so that I have those #define inALLfiles during compilation? Thank you.
``` -DLIBVNCSERVER_HAVE_LIBZ -DLIBVNCSERVER_HAVE_LIBJPEG ``` You could pass those inCPPFLAGS, ``` CPPFLAGS = -DLIBVNCSERVER_HAVE_LIBZ -DLIBVNCSERVER_HAVE_LIBJPEG ``` or make new variable ``` CUSTOMDEFINES = -DLIBVNCSERVER_HAVE_LIBZ -DLIBVNCSERVER_HAVE_LIBJPEG ``` and pass it toCPPFLAGS = -DEXISTINGFLAGS $(CUSTOMDEFINES) Those are finally will pass togcc/g++ -D... ``` $(CC) $(CPPFLAGS) ```
Windows API/C/C++ ``` 1. .... 2. .... 3. .... 4. while (flag1 != flag2) 5. { 6. SleepEx(100,FALSE); //waiting for flags to be equal (flags are set from another thread). 7. } 8. ..... 9. ..... ``` If the flags don't equal each other after 7 seconds, I would like to continue to line 8. Any help is appreciated. Thanks.
If you are waiting for a particular flag to be set or a time to be reached, a much cleaner solution may be to use an auto / manual reset event. These are designed for signalling conditions between threads and have very rich APIs designed on top of them. For instance you could use the WaitForMultipleObjects API which takes an explicit timeout value.
What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dstirbutions?
These are c library calls, and as such are in the libc library.
Is it possible to have a piece of code like this in user space? I mean is it possible to read/write co-processor register in user space in Netbsd / Linux? ``` XYZ]# cat pmc.c static inline int arm11_pmc_ctrl_read(void) { unsigned int val; __asm volatile ("mrc p15, 0, %0, c15, c12, 0" : "=r" (val)); return val; } int main(){ unsigned int ctrl; ctrl = arm11_pmc_ctrl_read(); } ```
User space does not have access to privileged instructions or registers. Look in your assembler manual to find out if the instructions and registers you are using are privileged.
I have a problem while executing a bash script from C++ using the system call command. The script catches aSIGPIPEsignal and exit with return code141. This problem has started to appear only in the last release of my code. My Questions are as follows: Why does this SIGPIPE occur now and didn't occur before?Is it safe to ignore the SIGPIPE and what are the consequences?
1) That's very hard to answer without knowing exactly what you changed.2) If a sequence of commands appears in a pipeline, and one of the reading commands finishes before the writer has finished, the writer receives a SIGPIPE signal. So whether you can ignore it depends on whether that is acceptable behavior for your script. More infohere
I am working in Ansi C, windows platform. I want to attach mysql database to my c program. Kindly guide me how I can make it possible.
Hereis a working example which sets up a connection and performs a query.
You are given an integer51234(say) we need to sort the digits of a number the output will be12345. How to do it without using array ?
You can use a loop and% 10to extract each digit. An outer loop from 0 to 9 could be used to test if the digit exists. If it exists, print it. In pseudo code: ``` n = integer // 51234 FOR digit = 0 TO 9 temp = n REPEAT IF temp % 10 = digit THEN PRINT digit temp /= 10 UNTIL temp = 0 ``` Edit:This test in gcc shows that it handles zeros and repeated digits: ``` $ cat sortdigits.c #include <stdio.h> main () { int n,digit,temp; n = 43042025; for (digit=0;digit<9;digit++) for (temp=n;temp>0;temp/=10) if (temp%10==digit) printf("%d",digit); printf("\n"); } $ ./sortdigits 00223445 ```
``` char x[16]; int y = 42 + 256; char* p = &y; int* q = p; char** r = &p; printf("%d %d %d\n", p, q, r); ``` why is the value of r always 12 units smaller than p and q? Thank you!
What you're printing there are three memory addresses. Since those are allocated on the stack (assuming they're not global) I would expect something like: ``` 2030 2026 2022 ``` assuming a 32 bit machine and 4 byte pointers. A double*is a pointer to a pointer. If you use correct types it becomes clearer. ``` char *str = "hello world"; ``` strin this case is a pointer to a null-terminated sequence of characters. ``` char **p = &str; ``` means a pointer to a pointer to a string of characters. I say "correct types" because you have, for example: ``` int y = 42 + 256; char* p = &y; ``` Really this should be: ``` int *p = &y; ``` The usual reason to use achar *in this instance is to examine the individual bytes.
I want to write this to only 1 line: ``` fprintf(stdout, "RCPT TO: <%s>\r\n", argv[argc-1]); fprintf(sockfd, "RCPT TO: <%s>\r\n", argv[argc-1]); ``` so i want to send the same string to stdout and to my open socket. How can I do this?
With ``` #include <stdarg.h> int fprintf_both(FILE *a, FILE *b, const char *fmt, ...) { FILE *f[2]; const int n = sizeof(f) / sizeof(f[0]); int i; int sum = 0; f[0] = a; f[1] = b; for (i = 0; i < n; i++) { va_list ap; int bytes; va_start(ap, fmt); bytes = vfprintf(f[i], fmt, ap); va_end(ap); if (bytes < 0) return bytes; else sum += bytes; } return sum; } ``` you can ``` fprintf_both(stdout, sockfd, "RCPT TO: <%s>\r\n", argv[argc-1]); ```
On linux, I'd like to know what "C" API to call to get the per-cpu stats. I know about and could read/proc/loadavgfrom within my app, but this is the system-wide load avarages, not the per-cpu information. I want to tell the individual CPUs or cores apart. As an example of an application that does this, When I runtopand press "1", I can see the 4 or 8 processors/cores like this: ``` Cpu0 : 4.5%us, 0.0%sy, 0.0%ni, 95.5%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu1 : 42.2%us, 6.2%sy, 0.5%ni, 51.2%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu2 : 3.0%us, 1.5%sy, 0.0%ni, 94.5%id, 0.0%wa, 0.0%hi, 1.0%si, 0.0%st Cpu3 : 7.0%us, 4.7%sy, 0.0%ni, 88.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st ``` I've tried tostrace topbut this led to a rat's nest.
The file you want is/proc/stat. (You might want to refer tofs/proc/stat.cin the Linux kernel source.)
I am using gcc 4.4.2 on linux I am just wondering does gcc automatically default to compiling with c99 as its the latest standard? How can I specify if I want to compile with c89 or c99? Many thanks for any advice,
One reason not to use C99 by default is because this standard is not fully implemented in the compiler yet. However, I believe that you can set the default mode when compiling gcc, so if the choice of standards really matters for you, it's better always to pass the option. The options are-std=c99and-std=c89respectively.
The following shows ♠♣♥♦ on windows xp, will it for all systems?? ``` #include <stdio.h> int main(int argc, char *argv[]) { for (int i = 3; i <= 6; ++i) printf("%c", (char)i); getchar(); return 0; } ```
Nope. Character encoding is a very platform dependent, in my experience. Consider, in ASCII those charactersdon't even exist. And I have no clue where they are in Unicode. And where ever they are, you would then be depending on how your platform outputs Unicode.
Is the following code valid ``` int main(){ int * a = 0; if ( !a ) { int b[500]; a = b; } //do something with a, //has the array a is //pointing too gone out //of scope and garbage //or is it still fine? } ```
No it is not, b has gone out of scope, accessing it (through the pointer) is undefined behavior.