question
stringlengths
25
894
answer
stringlengths
4
863
Whenever I start a new project, I have to go through setting up the debugger with Eclipse time and time again before I can use it. Isn't there a default setting for all new C projects I can change?
I'm not sure exactly what you mean by "setting up the debugger" (perhaps you can clarify), but under "Preferences -> Run/Debug -> Launching -> Default Launchers" you should be able to select your preferred launcher for different kind of launch modes. This can also be selected individually for each launch configuration. Typically it is up to the toolchain and/or project to determine which debugger/launcher is suitable to use for that specific project, but I know there is a bug in CDT which prevents toolchains from properly specifying the default launcher to use.
``` short sho1, sho2; printf("Enter two shorts.\n"); scanf("%hd %hd", &sho1, &sho2); printf("%hd^%hd is %hd.\n", sho1, sho2, sho1^sho2); ``` When I enter '2 2', I get this output: 2^2 is 0. How come? I'm using the MinGW GCC compiler in Eclipse, in case that's of any importance.
^is not the mathematical power operator in C, it's thebitwise exclusive-OR operator. You probably want thepow function, which takes two doubles.
I was just listening to episode 57 of Software Engineering Radio (TRANSCRIPT:http://www.se-radio.net/transcript-57-compiletime-metaprogramming) I'm only 40 minutes in, but I'm wondering why C is the language of compilers- when a Scheme subset would seem to be a better fit? (or some other HLL) (excluding the obvious reason of not wanting to rewrite gcc) PS originally posted this at LtUhttp://lambda-the-ultimate.org/node/3754
I won't bother to listen to 40 minutes of radio to perhaps understand your question more thoroughly, but I would claim the exact opposite. Only a minority of compilers are written in C. I rather have the impression that (at least where appropriate), most compilers are implemented in the language they are meant to compile.
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.Closed10 years ago.Improve this question I see a lot of GD tutorials for PHP, even though GD was written in C, not PHP. Could you please suggest any good tutorial for GD in C?
A bit of googling turned up nothing for me either - this is one of those things, for now anyway, that you must study the API reference and make up your own toy test programs.
I'm writing command line utility for Linux. If the output (stdout) is going to a shell it would be nice to print some escapes to colorize output. But if the output is being redirected those bash escapes shouldn't be print, or the content might break parsers that rely on that output. There are several programs that do this (suck asack) but the ones I found were written in Perl and I couldn't find out how they did it. I wanted to use C/C++ to write my utility.
You can useisattyon linux. This function is obviously not standard C, since - for example - on many platforms you can't redirect the output to a file.
I have built a webservice into my companies self developed CRM system that we are in the process of integrating Outlook to the CRM for calendar sync and recording of emails related to clients. I want to build a plugin for the gnome evolution mail client as I use it for my work mail/calendar as I primarily run Linux. I am familiar with both C/C++ and to some extent Python but haven't done anything towards either evolution plugins or webservices connections in either so I am looking for some help. What language would be best to build an evolution plugin that can connect to webservices? Is there a simple "Hello world" style evolution plugin example somewhere I can use to get started?
I would start with thearchitectureof Evolution. Then I would look intoEPluginsand start off withthis. An example for writing a plugin would bethis. You will need some familiarity with XML. Hope this helps.
What is the formula for real world (latitude,longitude) conversion into (x,y) coordinates?
Latitudes and longitudes exist on a spherical globe. Map X and Y coordinates exist on a (theoretically) flat map. To convert between them, you need to "project" the spherical coordinates onto the flat map. There are many different ways to do projections. Some are optimised for particular regions. An earlier poster mentioned the Mercator projection. This is a popular one, but has its limitations (as all of them do). Stage one is probably to better understand your needs. What sort of latitude/longitude data do you have? What do you plan to do with it? Is your data confined to particular regions? What level of accuracy is needed? Is conversion speed important? (You may need to trade speed against accuracy). Wikipedia has a reasonable article on UTM (Mercator) projections.
I have aCprogram below: ``` #define f(g,g2) g##g2 main() { int var12=100; printf("%d",f(var,12)); } ``` when I run just the preprocessor it expands this as ``` { int var12=100; printf("%d",var12); } ``` which is the reason why the output is 100. Can anybody tell me how/why the preprocessor expandsvar##12 to var12?
nothing too fancy:##tells the preprocessor to concatenate the left and right sides seehttp://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation
I wrote a very simple C function to illustrate what I would like to simplify: ``` void main(int argc, char *argv[]) { char *me = "Foo"; char *you = "Bar"; char us[100]; memset(us, 100, 0x00); sprintf(us, "You: %s\n", you); sprintf(us + strlen(us), "Me: %s\n", me); sprintf(us + strlen(us), "We are %s and %s!\n", me, you); printf(us); } ``` Is there a standard library function to handle what I'm doing withsprintfand advancing the pointer?
sprintfreturns the number of non-NUL characters written. ``` int len = 0; len += sprintf(us+len, ...); len += sprintf(us+len, ...); ... ```
``` #define STRING(s) (((String*)s)-1) ``` what in the world is(((String*)s)-1)? ``` typedef struct String { int length; int capacity; unsigned check; char ptr[0]; } String; ```
You're castingsto aString *. Then you're subtracting one from it (making it point to the previous whatever). Anything more specific would need to know the definition ofString- but (WILD SPECULATION) I would guess the application uses dual VB/C-style strings (null terminated, preceded by the length), and this function changes it from a form suitable for C functions (pointer to the first character) into one usable for the other type (pointer to the length).
Why does each .h file starts with #ifndef #define #endif? We can certainly compile the program without those directives.
It's a so-called "include guard". The purpose is to prevent the file from having to be parsed multiple times if it is included multiple times.
"We write a .h file for every module in our design" what is the module referring to? and when do we write a separate .c file?
It is generally a good idea to declare one class per header (.h or .hpp) and implement its content in one .cpp file. In case of C, you group the functions by what they do or the context they are used in and also declare them in one header and implement in one .c file. For instance: math, such as square roots, trigonometry stuff (sine, cosine, tangent), powers, perhaps also min/max functions (although they're beter off as macros in most cases) would reside in their very own .h/.c or .hpp/.cpp pair of files. Of course, youcanignore this completely and stuff all your code in a single .c(pp) file, no header at all. It'll just become completely unreadable :).
When I alloc memory outside a while loop for example, is it okay to free it inside it ? Are these two codes equivalent ? ``` int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; free(memory); } int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; } free(memory); ```
Yes, they are equivalent. You do not have to callfree()if allocation did not succeed.Pay attention, thatmemoryis pointer tointand you have to dereference it to assign something to its memory block; ``` int* memory = NULL; memory = malloc(sizeof(int)); if (memory) *memory=10; free(memory); memory = NULL; ```
Just wonder if a literal string is an lvalue or an rvalue. Are other literals (like int, float, char etc) lvalue or rvalue?Is the return value of a function an lvalue or rvalue? How do you tell the difference?
string literals are lvalues, but you can't change themrvalue, but if it's a pointer and non-NULL, the object it points to is an lvalue The C standard recognizes the original terms stood forleftandrightas inL = R; however, it says to think of lvalue aslocator value, which roughly means you can get the address of an object and therefore that object has a location. (See 6.3.2.1 inC99.) By the same token, the standard has abandoned the term rvalue, and just uses "the value of an expression", which is practically everything, including literals such as ints, chars, floats, etc. Additionally, anything you can do with an rvalue can be done with an lvalue too, so you can think of all lvalues as being rvalues.
I recently came across this line in a code - ``` fprintf(logfile," |-IP Version : %dn",(unsigned int)iph->version); ``` Is "%dn" here a format string ? If so , what does it signify ?
It sounds a bit like someone wanted to write%d\nto terminate the line with a linefeed, but the backslash got lost somewhere. The format code, in any case, ends with the "d".
Why is the following code giving segmentation fault? ``` #include <stdio.h> #include <stdlib.h> int main() { FILE *file; file = fopen("text","r"); if (file == NULL) printf("Error READING FILE"); if (ferror(file)) printf("error reading file"); //line 9 return 0; } ``` Doing backtrace in gdb gives:- ``` > #0 0x00007ffff7ad9d30 in ferror () from /lib/libc.so.6 > #1 0x00000000004005fa in main () at test.c:9 ```
file is NULL. You're not seeing the first printf because the program crashes before stdout is flushed.
Is it possible to have one application simultaneously write to multiple syslog facilities? I have an application, written in C/C++, that I would like to write some messages to local0 and other messages to local1. I do not want the messages for local0 to appear in local1 or vice versa.
Looking at the man page forsyslog, I see the example: ``` syslog(LOG_INFO|LOG_LOCAL2, "foobar error: %m"); ``` Does ``` syslog(LOG_INFO|LOG_LOCAL0, "message for local0"); syslog(LOG_INFO|LOG_LOCAL1, "message for local1"); ``` work?
The Code used ``` #include<stdio.h> struct st { char a; short c; int b; }; struct st s1; int main() { printf("%p %p \n",(&s1.b)-1, &s1); } ``` If I print the address of&s1.bit prints0x804a01cand&s1.b-2prints0x804a018why it is printing same address0x804a01cif i select&s1.b-1?
There's probably something wrong with your printing code. ``` #include <stdio.h> struct st { char a; short c; int b; }; struct st s1; int main() { printf("%p\n", (void*)(&s1.b)); printf("%p\n", (void*)(&s1.b - 1)); printf("%p\n", (void*)(&s1.b - 2)); } ``` Output: ``` 0x403024 0x403020 0x40301c ```
I want to write a library for my Arduino(header and class files), but I don't know what tools to use for this job and how to test and debug them. The Arduino IDE just helps in writing plain programs for direct bootloading, not full project management thing (correct me if I am wrong and guide appropriately with relevant references). Please help.
The compiler supports the#includedirective, you can write your library, then#includeit. This is expanded onin this tutorial about writing libraries for the Arduino.
In C language, how to get struct's start address from its member's address? ``` struct type1 { //... int member1; //... }; struct type1 obj1; ``` Andptr1is the address of membermember1inobj1, how to definemacro#define start_add(ptr1, type1, member1)to get obj1'sstart address?
You can do this usingoffsetof: ``` #define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1))) ```
I don't understand why the ABI is important context of developing user-space applications. Is the set of system calls for an operating system considered an ABI? But if so then aren't all the complexities regarding system calls encapsulated within standard libraries? So then isABI compatibilityonly relevant for running statically linked applications on different platforms, since the system calls would be embedded into the binary?
AnABIdefines a set of alignment, calling convention, and data types that are common to a system. This makes an ABI awfully important if you're doing any sort of dynamic linking; as without it code from one application has no way of calling code provided by another. So, no. ABI compatibility is relevant for all dynamic linking (less so for static). Its worthemphasizing againthat a system's ABI affects inter-application work as well as application-to-operating-system work.
I'm currently trying to patch theTotem Youtube plug-inand I'd like to determine the best quality available for the current played video (&fmt parameter). It's possible inJavaScriptbut the plug-in is developped in C. Is that possible?
Are you playing the videos in the YouTube video player? If so, you can query the quality levels through theActionScriptor JavaScript API, seehttp://code.google.com/apis/youtube/js_api_reference.html#Playback_quality.
I'm trying to get the stack backtrace of a running process (PID and binary path are known) from another program. The program in question is written in C++ and compiled with g++ with gdb debugging symbols. I'm looking for a C or C++ library that works across Linux, HP-UX and Solaris that produces an output similar to the output of calling popen() with something like this: ``` gdb -batch -x /dev/stdin <BINARY> <PID> << EOF thread apply all bt EOF ``` I have found lsstack (http://sourceforge.net/projects/lsstack/), which is Linux only and know the pstack program for Solaris. Does anyone know of a reliable way of doing this cross Unix / POSIX?
You need libunwind
I want to compile an application with debug information using gcc and gdb. When I do the following, the debug (.dSYM) files are generated correctly: ``` gcc -ggdb src/test.c -o build/test ``` If I, however, split this into a compile step and a link step, like this: ``` gcc -ggdb -c src/test.c -o build/test.o gcc -ggdb build/test.o -o dist/bin/test ``` … no.dSYMfiles are generated at all, and thereforegdbdoes not show me the source line of code where a crash occurs, which makes debugging a lot more difficult. Since I have quite a bit of source files, compiling and linking them all in a singlegccinvocation is not possible. How can I let gcc generate the.dSYMfiles when using separate compile and link steps?
Check the second comment on the first answer inthis post. Its a quirk. Maybe you can run the "dsymutil" program manually to generate dSYM files.
On unix symlinks are pointers to another file. Not only the file but also the symlink has a ctime, mtime, …. I know the symlinks time can be accessed, aslsdisplays it. If I use one of ruby'sFile#ctime,File#mtime, …, I always get the attribute of the file the symlink is pointing to, not of the symlink. How can I read this values in ruby? If this is not possible in ruby, tell me how to do it in C. I would write my own c extension in that case.
UseFile#lstat(). Example: ``` # This is a dummy symlink; there's no file named "foo". ln -s foo bar # Run irb. irb(main):001:0> File.lstat("bar") => #<File::Stat dev=0x801, ino=90113, mode=0120777, nlink=1, uid=1000, gid=1000, rdev=0x0, size=3, blksize=4096, blocks=0, atime=2010-01-05 17:59:06 -0500, mtime=2010-01-05 17:59:05 -0500, ctime=2010-01-05 17:59:05 -0500> # Get the mtime of the link. irb(main):002:0> File.lstat("bar").mtime => 2010-01-05 17:59:05 -0500 ```
This question already has answers here:In which step of compilation are comments removed?(2 answers)Closed5 years ago. ``` /* #define FOO */ #ifdef FOO #define BAR "pirate" #else #define BAR "ninja" #endif int main() { printf(BAR); getchar(); } ``` In this code FOO is not defined (Visual Studio 2008). I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor? Is this part of a standard?
I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor? Sort of -- part of the preprocessor's jobisto remove comments. In this case, it doesn't care that you have the directive inside the comments; it's still removed just like any other comment.
Is it possible to embed git in the iPhone app? Only in a passive mode, i.e. to be able to read commit messages (with date and user) and diffs given some online git repository in order to present it in some readable table views?
I'm one of the co-authors ofcocoagit, which is currently an unfinished implementation of the core git functionality in Objective-C. There has not been much activity in the last 6 months. Unfortunately, it is not far quite far enough along to do everything you need. We can read commits, and have preliminary support for cloning repos, but we can't do diffs yet. Geoff and I would both like to have more time to work on it again, but in the meantime, we would gladly welcome any contributions. Alternatively, I second the recommendations of previous posters to consider using github, or building your own web service to provide the necessary data.
When reading/writing a file in my application, I want to exit(1) if the file is not closed correctly. On Windows it works well, but on Linux this error appears: ``` ‘exit’ was not declared in this scope ``` How can I solve that? Thanks.
If this is in C, did you#include <stdlib.h>?
I have MTL header files; I want to use those header files in Visual Studio 2008. How can I link those header files so that I can write a matrix program using the MTL library?
Maybe you're referring to how to tell the IDE to notice them? In that case, you can simply add them in a directory to your project. In VS, right-click the project, select Properties. Go to Configuration Properties -> C/C++ -> General. Add the MTL directory, and any sub-directory, to the Additional Include Directories field.
I don't know what data structure to use for this problem. I want the structure to have: Constant time insertion or deletion.Constant time retrieval by id. The actual system is: I've got a bunch of objects each with a unique id. My program will need to receive requests for an id and return the relevant object. Whenever it receives a request I want it to: search the structure to see if it's there. If it is, return it. If it isn't, load it from the disk into memory (put it in the structure so that next time it is requested it doesn't have to use the disk) and then return it. I'm using C. Here's asimilar questionbut I'm not sure how relevant it is.
AHash tablemight be a pretty good solution in your case -- even if it's not in O(1) when there's a colision : it's a quite efficient solution.
_fullpath API of windows takes relative path and gives the corresponding absolute path. But, it fails if the relative path is greater than 255 characters. Is there any other API available in Windows which can convert the relative path to absolute path and doesn't have the problem mentioned above?
I think the closest equivalent would be theGetFullPathName function. You can explicitly call the Unicode version of it and prepend\\?\to the path to allow for more than MAX_PATH characters.
What is the Python API equivalent ofPyErr_Print(), from the C interface? I'm assuming a call in either thesys, ortracebackmodules, but can't find any functions therein that make calls toPyErr_Print(). Addendum I'm after the Python call to get the same functionality asPyErr_PrintEx(), described as: ``` Print a standard traceback to sys.stderr and clear the error indicator. ``` That is I want to make thePythoncall that has this effect.
There's no Python function that's exactly equivalent toPyErr_PrintEx(the real name ofPyErr_Print;-), including for example settingsys.last_tracebackand friends (which are only supposed to be set to help a post-mortem debugging from the interactive interpreter for exceptions which havenotbeen caught). What exact combination of functionality are you looking for?
I have quite an embarrassing problem. The following code simply will not create a socket on Windows; it fails and displays the error message. Could anyone briefly explain why this might be? I'm incredibly confused and frustrated that something so simple is failing. Thank you. ``` int sock; if( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { printf("error opening socket"); } ``` EDIT: Also, printing out strerror(errno) simply shows "No error".
You need to callWSAStartup()before any other socket functions will work on Windows (and you're supposed to callWSACleanup()when you're done).
How to read the metadata of a MKV movie files in C# (or C or C++ or AS3)? for example such ``` creator metadatacreator hasKeyframes hasVideo hasAudio hasMetaData canSeekToEnd duration datasize videosize videocodecid audiosize audiocodecid audiosamplerate audiosamplesize stereo filesize lasttimestamp lastkeyframetimestamp lastkeyframelocation keyframes (filepositions, times) width height framerate videodatarate audiodatarate ```
There is always attempting to parsethe header yourself. Also I've seen references to theEBML library being used to decode MKV files.Good luck!
I wonder if there are some API to get the current process' command line arguments on Linux. I guess I was terribly unclear. The real purpose of the question was about passing unicode file names through command line arguments.
Read from file/proc/self/cmdline For example: ``` [wallyk@zf ~]$ od -a /proc/30651/cmdline 0000000 / u s r / s b i n / h t t p d nul 0000020 ``` Or, for a satisfyingly refreshing self-reference: ``` [wally@zf images]$ od -c /proc/self/cmdline 0000000 o d \0 - c \0 / p r o c / s e l f 0000020 / c m d l i n e \0 0000031 ```
So I just ran the example fromthis websiteand it says the the output should alternate like so: ``` threadFunc says: processing... main() is running... threadFunc says: processing... main() is running... ``` However on my machine it produces this: ``` threadFunc says: processing... threadFunc says: processing... main() is running... main() is running... ``` Is it because I have a single-core processor that isn't multithreaded? Note:I'm also getting this warning when compiling:implicit declaration of function ‘usleep’ I'm compiling with gcc like so:gcc new.c -o new -lpthread
You need to comment out line: ``` pthread_join(pth, NULL /* void ** return value could go here */); ``` Doing this will make it work as you expect Whats its doing is making the thread wait till the threadpthis finished before proceeding.
I have created a macro to make reserve memory for my strings inC. It looks like this: ``` #define newString(size) (char*)malloc(sizeof(char) + size) ``` So is there any reason I shouldn't use this macro in my own personal projects? I know I shouldn't do this in production code because it would require everyone to have that header file and everyone to know thatnewStringwas a macro.
(char*)malloc(sizeof(char) * (size+1))would be more appropriate (the +1 is to account for the NULL at the end of string, if applicable). If one is copying a string,strlen()doesn't account for the NULL terminating the string hence an additional memorycharis required.
I can't figure out how to display something (like hello world) in every 3 seconds. I'm writing in only C programming with gcc compiler in linux. We can stop it by Ctrl+c. I just want simplest and easiest way to manipulate thet code with my project. Thank you so much in advance!
``` while(1) { printf("something\n"); Sleep(3000); //this function counts in milliseconds, so this is what 3 seconds looks like. } ```
Came across this conditional in some uncommented Objective-C code: ``` if (w & (w - 1)) { i = 1; while (i < w) { i *= 2; } w = i; } ``` Wherewis asize_tgreater than1. Update:Added the code contained by the conditional for context.
It tests whether more than one bit is set inw, i.e. whether it's not an exact power of two. Seehere.
when you set a databreakpoint in MSVS, then you put in the address and the number of bytes and finally it lets you choose betwenn "C" and "C++". this last part i dont know what it is about? what is the difference of picking C and C++ in this situation? thanks!
It only matters if you use an expression instead of entering the address directly. Parsing rules for 'C' expressions are different from those for C++. Can't think of a great example beyond a C++ member expression like "&this->member". The debugger can't figure it out for itself, mixing 'C' and C++ code in one process is quite permissible.
I'm trying to get the stack backtrace of a running process (PID and binary path are known) from another program. The program in question is written in C++ and compiled with g++ with gdb debugging symbols. I'm looking for a C or C++ library that works across Linux, HP-UX and Solaris that produces an output similar to the output of calling popen() with something like this: ``` gdb -batch -x /dev/stdin <BINARY> <PID> << EOF thread apply all bt EOF ``` I have found lsstack (http://sourceforge.net/projects/lsstack/), which is Linux only and know the pstack program for Solaris. Does anyone know of a reliable way of doing this cross Unix / POSIX?
You need libunwind
I want to compile an application with debug information using gcc and gdb. When I do the following, the debug (.dSYM) files are generated correctly: ``` gcc -ggdb src/test.c -o build/test ``` If I, however, split this into a compile step and a link step, like this: ``` gcc -ggdb -c src/test.c -o build/test.o gcc -ggdb build/test.o -o dist/bin/test ``` … no.dSYMfiles are generated at all, and thereforegdbdoes not show me the source line of code where a crash occurs, which makes debugging a lot more difficult. Since I have quite a bit of source files, compiling and linking them all in a singlegccinvocation is not possible. How can I let gcc generate the.dSYMfiles when using separate compile and link steps?
Check the second comment on the first answer inthis post. Its a quirk. Maybe you can run the "dsymutil" program manually to generate dSYM files.
On unix symlinks are pointers to another file. Not only the file but also the symlink has a ctime, mtime, …. I know the symlinks time can be accessed, aslsdisplays it. If I use one of ruby'sFile#ctime,File#mtime, …, I always get the attribute of the file the symlink is pointing to, not of the symlink. How can I read this values in ruby? If this is not possible in ruby, tell me how to do it in C. I would write my own c extension in that case.
UseFile#lstat(). Example: ``` # This is a dummy symlink; there's no file named "foo". ln -s foo bar # Run irb. irb(main):001:0> File.lstat("bar") => #<File::Stat dev=0x801, ino=90113, mode=0120777, nlink=1, uid=1000, gid=1000, rdev=0x0, size=3, blksize=4096, blocks=0, atime=2010-01-05 17:59:06 -0500, mtime=2010-01-05 17:59:05 -0500, ctime=2010-01-05 17:59:05 -0500> # Get the mtime of the link. irb(main):002:0> File.lstat("bar").mtime => 2010-01-05 17:59:05 -0500 ```
This question already has answers here:In which step of compilation are comments removed?(2 answers)Closed5 years ago. ``` /* #define FOO */ #ifdef FOO #define BAR "pirate" #else #define BAR "ninja" #endif int main() { printf(BAR); getchar(); } ``` In this code FOO is not defined (Visual Studio 2008). I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor? Is this part of a standard?
I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor? Sort of -- part of the preprocessor's jobisto remove comments. In this case, it doesn't care that you have the directive inside the comments; it's still removed just like any other comment.
Is it possible to embed git in the iPhone app? Only in a passive mode, i.e. to be able to read commit messages (with date and user) and diffs given some online git repository in order to present it in some readable table views?
I'm one of the co-authors ofcocoagit, which is currently an unfinished implementation of the core git functionality in Objective-C. There has not been much activity in the last 6 months. Unfortunately, it is not far quite far enough along to do everything you need. We can read commits, and have preliminary support for cloning repos, but we can't do diffs yet. Geoff and I would both like to have more time to work on it again, but in the meantime, we would gladly welcome any contributions. Alternatively, I second the recommendations of previous posters to consider using github, or building your own web service to provide the necessary data.
When reading/writing a file in my application, I want to exit(1) if the file is not closed correctly. On Windows it works well, but on Linux this error appears: ``` ‘exit’ was not declared in this scope ``` How can I solve that? Thanks.
If this is in C, did you#include <stdlib.h>?
I have MTL header files; I want to use those header files in Visual Studio 2008. How can I link those header files so that I can write a matrix program using the MTL library?
Maybe you're referring to how to tell the IDE to notice them? In that case, you can simply add them in a directory to your project. In VS, right-click the project, select Properties. Go to Configuration Properties -> C/C++ -> General. Add the MTL directory, and any sub-directory, to the Additional Include Directories field.
I don't know what data structure to use for this problem. I want the structure to have: Constant time insertion or deletion.Constant time retrieval by id. The actual system is: I've got a bunch of objects each with a unique id. My program will need to receive requests for an id and return the relevant object. Whenever it receives a request I want it to: search the structure to see if it's there. If it is, return it. If it isn't, load it from the disk into memory (put it in the structure so that next time it is requested it doesn't have to use the disk) and then return it. I'm using C. Here's asimilar questionbut I'm not sure how relevant it is.
AHash tablemight be a pretty good solution in your case -- even if it's not in O(1) when there's a colision : it's a quite efficient solution.
_fullpath API of windows takes relative path and gives the corresponding absolute path. But, it fails if the relative path is greater than 255 characters. Is there any other API available in Windows which can convert the relative path to absolute path and doesn't have the problem mentioned above?
I think the closest equivalent would be theGetFullPathName function. You can explicitly call the Unicode version of it and prepend\\?\to the path to allow for more than MAX_PATH characters.
What is the Python API equivalent ofPyErr_Print(), from the C interface? I'm assuming a call in either thesys, ortracebackmodules, but can't find any functions therein that make calls toPyErr_Print(). Addendum I'm after the Python call to get the same functionality asPyErr_PrintEx(), described as: ``` Print a standard traceback to sys.stderr and clear the error indicator. ``` That is I want to make thePythoncall that has this effect.
There's no Python function that's exactly equivalent toPyErr_PrintEx(the real name ofPyErr_Print;-), including for example settingsys.last_tracebackand friends (which are only supposed to be set to help a post-mortem debugging from the interactive interpreter for exceptions which havenotbeen caught). What exact combination of functionality are you looking for?
I have quite an embarrassing problem. The following code simply will not create a socket on Windows; it fails and displays the error message. Could anyone briefly explain why this might be? I'm incredibly confused and frustrated that something so simple is failing. Thank you. ``` int sock; if( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { printf("error opening socket"); } ``` EDIT: Also, printing out strerror(errno) simply shows "No error".
You need to callWSAStartup()before any other socket functions will work on Windows (and you're supposed to callWSACleanup()when you're done).
How to read the metadata of a MKV movie files in C# (or C or C++ or AS3)? for example such ``` creator metadatacreator hasKeyframes hasVideo hasAudio hasMetaData canSeekToEnd duration datasize videosize videocodecid audiosize audiocodecid audiosamplerate audiosamplesize stereo filesize lasttimestamp lastkeyframetimestamp lastkeyframelocation keyframes (filepositions, times) width height framerate videodatarate audiodatarate ```
There is always attempting to parsethe header yourself. Also I've seen references to theEBML library being used to decode MKV files.Good luck!
I wonder if there are some API to get the current process' command line arguments on Linux. I guess I was terribly unclear. The real purpose of the question was about passing unicode file names through command line arguments.
Read from file/proc/self/cmdline For example: ``` [wallyk@zf ~]$ od -a /proc/30651/cmdline 0000000 / u s r / s b i n / h t t p d nul 0000020 ``` Or, for a satisfyingly refreshing self-reference: ``` [wally@zf images]$ od -c /proc/self/cmdline 0000000 o d \0 - c \0 / p r o c / s e l f 0000020 / c m d l i n e \0 0000031 ```
So I just ran the example fromthis websiteand it says the the output should alternate like so: ``` threadFunc says: processing... main() is running... threadFunc says: processing... main() is running... ``` However on my machine it produces this: ``` threadFunc says: processing... threadFunc says: processing... main() is running... main() is running... ``` Is it because I have a single-core processor that isn't multithreaded? Note:I'm also getting this warning when compiling:implicit declaration of function ‘usleep’ I'm compiling with gcc like so:gcc new.c -o new -lpthread
You need to comment out line: ``` pthread_join(pth, NULL /* void ** return value could go here */); ``` Doing this will make it work as you expect Whats its doing is making the thread wait till the threadpthis finished before proceeding.
I have created a macro to make reserve memory for my strings inC. It looks like this: ``` #define newString(size) (char*)malloc(sizeof(char) + size) ``` So is there any reason I shouldn't use this macro in my own personal projects? I know I shouldn't do this in production code because it would require everyone to have that header file and everyone to know thatnewStringwas a macro.
(char*)malloc(sizeof(char) * (size+1))would be more appropriate (the +1 is to account for the NULL at the end of string, if applicable). If one is copying a string,strlen()doesn't account for the NULL terminating the string hence an additional memorycharis required.
I can't figure out how to display something (like hello world) in every 3 seconds. I'm writing in only C programming with gcc compiler in linux. We can stop it by Ctrl+c. I just want simplest and easiest way to manipulate thet code with my project. Thank you so much in advance!
``` while(1) { printf("something\n"); Sleep(3000); //this function counts in milliseconds, so this is what 3 seconds looks like. } ```
Does anyone know how to calculate the error of quantizing from 16bit to 8bit? I have looked at the Wikipedia article aboutQuantization, but it doesn't explain this. Can anyone explain how it is done? Lots of love, Louise Update: My function looks like this. ``` unsigned char quantize(double d, double max) { return (unsigned char)((d / max) * 255.0); } ```
I think you need to convert both the 16-bit value and the 8-bit value to their respective analog values that they represent and then take the difference between those. To stick with the wikipedia entries, here isonethat talks about it.
``` int *i; *i=123; ```
Yes. There is no allocated memory to place the value123. Like initializing a variable likeintis not guaranteed to be0, anint*isn't guaranteed to be a safe address. It also could potentially lead to data corruption.
I have installed visual studio 2008 and i want to create some simple applications using C language. I do this by creating c++ console applications but i want the compiler to work for C not C++. Any way to accomplish this or i need another compiler if i want to deal with C?
Use .c file extension instead of .cpp, those files will be compiled as C-only code by default in a C/C++ Visual Studio project.
The following program does not work as I intended. ``` #include <string.h> #include <stdio.h> int main() { const char *c = "abcdef"; // prints 'f' as expected printf("%c\n", c[5]); // comparison fails, does not print "yes" if (c[5] == 'f') printf("yes"); return 0; } ``` How can I compare a character in a string literal to a character value? Is it possible without using ASCII related functions i.e. chr() or ord() suppose those exist. ( I remember using them back in Pascal days) Thanks
There must be something else going on with your environment. I just threw that into gcc and it prints out "yes" as expected. Are you sure you aren't just missing the "yes" because printf does not add a new line by default, so it could be "yes[your shell prompt]" and you're just overlooking the yes?
My code is as follows: ``` #include <stdio.h> struct MyData { int id; char msg[255]; }; int main ( int argc, const char * argv[] ) { struct MyData item; item.id = 3; item.msg = "something else"; printf("Msg: %d", item.msg); return 0; } ``` I get an error of incompatible types in assignment on the line: item.msg = "something else"; I have no worries setting the id property, but I can't figure out how to set the string property "msg". Any ideas what I'm doing wrong ?
Usestrncpy()to copy the string into the character buffer. Don't forget to assign\0to the last element just in case.
Just trying out some C on some of the project euler questions. My question is why am I getting a floating point exception at run time on the following code? ``` #include <stdio.h> main() { int sum; int counter; sum = 0; counter = 0; for (counter = 0; counter <= 1000; counter++) { if (1000 % counter == 0) { sum = sum + counter; } } printf("Hello World"); printf("The answer should be %d", sum); } ``` Thanks, Mike
You start with counter = 0 and then do a "mod" with counter. This is a division by zero. Hope this helps!
I just looked at the definition ofHRESULTin VS2008. WinNT.h has the following line: ``` typedef __success(return >= 0) long HRESULT; ``` What exactly does it mean? It doesn't even look like C or C++ to my untrained eye
It is an annotation. In short, ``` __success(expr) ``` means thatexprdescribes the conditions under which a function is considered to have succeeded. For functions returningHRESULT, that condition is that the return value (sinceHRESULTis along) is non-negative. All functions returningHRESULThave this annotation applied to them because of thistypedef. Probably way more detail than you will ever want in MSDN onSAL Annotations,The Evolution of HRESULT From Win32andSuccess and Failure Annotations.
In windows is it possible to know what kind of disk we are dealing with from a c/c++ program? forget about gpt or mbr, how to know whether it is basic or dynamic? Program input can be drive letter or any info related to disk, output should be dynamic or basic. No need of a direct way of doing, even if it is lengthy process, its okay. I couldn't find much in msdn. Please help me out.
There is a way in windows, but it's not straight forward. There is no direct API to determine if a disk is Basic or Dynamic, however all dynamic disks will have LDM Information. So if a drive has a partion with LDM information on it, then it's going to be a dynamic disk. the DeviceIoControl() method with the IOCTL_DISK_GET_DRIVE_LAYOUT_EX control code can be used to get this information. Here is a post with a sample console application to do what you're asking for.
I am using GCC, what switches do I need to add to link with Xlib? After searching, all I could find was-lX11, but that gave meld: library not found for -lX11 I am using a mac (10.6), but I would not like anything that is Mac specific.
You can usually usepkg-configto determine the flags you need to pass: ``` gcc my-program.c $(pkg-config --cflags --libs x11) -o my-program ```
I'd like to check if a binary number has a '0' or a '1' at a specific position. example: if the binary number is: 101000100 checking at position zero (that is at the rightmost '0') should result in '0'.checking at position 2 should result in '1'.checking at position 3 should result in '0'.checking at position 6 should result in '1'.etc... I'm coding in C, so obviously I could use sprintf / scanf and the likes, but I guess there must be something better (read: more time efficient / easier)! What would be a good mechanism to do this?
This will filter out the bit you're looking for: ``` number & (1 << position) ``` If you really need a 1 or 0 response, you can use this to make it a boolean value: ``` !!(number & (1 << position)) ``` Or even better (thanksVadim K.): ``` (number >> position) & 1 ```
The following program cannot compile in gcc. But it compiles OK with g++ and MSC++ with.cextension. ``` #include <math.h> #include <stdio.h> int main() { double t = 10; double t2 = 200; printf("%lf\n", sqrt(t*t2)); return 0; } ``` My system is CentOS, the version info. ``` > gcc --version gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46) Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ``` The error info: ``` > gcc test.c /tmp/ccyY3Hiw.o: In function `main': test.c:(.text+0x55): undefined reference to `sqrt' collect2: ld returned 1 exit status ``` Is this a bug? Any one can do a test for me?
Have you linked the math library? ``` gcc -lm test.c -o test ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question I'm usinglong double ina C program to compute 2D images of the Mandelbrot Set but wish to have further precision to zoom deeper. Are there any performance gains to be had from an arbitrary precision maths library that can restrict the amount of precision as required, rather than leaping fromlong doubleprecision straight into arbitrary precision? Which is the fastest of the arbitrary precision maths libraries?
'fastest' is going to be somewhat dependent on your platform and intended use. The MPFR Library GMP Thiswiki articlecontains links to several libraries.
Is there a Linux library that will enable me to tell what IP sockets are owned by what processes? I guess I'm looking for the programmatic equivalent oflsof -i. Ultimately, I want to correlate packets seen throughlibpcapto processes. UPDATE:A couple of people have suggested using/proc/<pid>/net/tcpandudp, but on my system, the same data is shown for every process, so it doesn't help.
I think you first have to look through the open fds in /proc/*/fd, e.g. ``` 4 -> socket:[11147] ``` and then look for the referenced sockets (by the inode) in /proc/net/tcp (or /proc/net/udp), e.g. ``` 12: B382595D:8B40 D5C43B45:0050 01 00000000:00000000 00:00000000 00000000 1000 0 11065 1 ffff88008bd35480 69 4 12 4 -1 ```
Does anyone know how to calculate the error of quantizing from 16bit to 8bit? I have looked at the Wikipedia article aboutQuantization, but it doesn't explain this. Can anyone explain how it is done? Lots of love, Louise Update: My function looks like this. ``` unsigned char quantize(double d, double max) { return (unsigned char)((d / max) * 255.0); } ```
I think you need to convert both the 16-bit value and the 8-bit value to their respective analog values that they represent and then take the difference between those. To stick with the wikipedia entries, here isonethat talks about it.
``` int *i; *i=123; ```
Yes. There is no allocated memory to place the value123. Like initializing a variable likeintis not guaranteed to be0, anint*isn't guaranteed to be a safe address. It also could potentially lead to data corruption.
I have installed visual studio 2008 and i want to create some simple applications using C language. I do this by creating c++ console applications but i want the compiler to work for C not C++. Any way to accomplish this or i need another compiler if i want to deal with C?
Use .c file extension instead of .cpp, those files will be compiled as C-only code by default in a C/C++ Visual Studio project.
The following program does not work as I intended. ``` #include <string.h> #include <stdio.h> int main() { const char *c = "abcdef"; // prints 'f' as expected printf("%c\n", c[5]); // comparison fails, does not print "yes" if (c[5] == 'f') printf("yes"); return 0; } ``` How can I compare a character in a string literal to a character value? Is it possible without using ASCII related functions i.e. chr() or ord() suppose those exist. ( I remember using them back in Pascal days) Thanks
There must be something else going on with your environment. I just threw that into gcc and it prints out "yes" as expected. Are you sure you aren't just missing the "yes" because printf does not add a new line by default, so it could be "yes[your shell prompt]" and you're just overlooking the yes?
My code is as follows: ``` #include <stdio.h> struct MyData { int id; char msg[255]; }; int main ( int argc, const char * argv[] ) { struct MyData item; item.id = 3; item.msg = "something else"; printf("Msg: %d", item.msg); return 0; } ``` I get an error of incompatible types in assignment on the line: item.msg = "something else"; I have no worries setting the id property, but I can't figure out how to set the string property "msg". Any ideas what I'm doing wrong ?
Usestrncpy()to copy the string into the character buffer. Don't forget to assign\0to the last element just in case.
Just trying out some C on some of the project euler questions. My question is why am I getting a floating point exception at run time on the following code? ``` #include <stdio.h> main() { int sum; int counter; sum = 0; counter = 0; for (counter = 0; counter <= 1000; counter++) { if (1000 % counter == 0) { sum = sum + counter; } } printf("Hello World"); printf("The answer should be %d", sum); } ``` Thanks, Mike
You start with counter = 0 and then do a "mod" with counter. This is a division by zero. Hope this helps!
I just looked at the definition ofHRESULTin VS2008. WinNT.h has the following line: ``` typedef __success(return >= 0) long HRESULT; ``` What exactly does it mean? It doesn't even look like C or C++ to my untrained eye
It is an annotation. In short, ``` __success(expr) ``` means thatexprdescribes the conditions under which a function is considered to have succeeded. For functions returningHRESULT, that condition is that the return value (sinceHRESULTis along) is non-negative. All functions returningHRESULThave this annotation applied to them because of thistypedef. Probably way more detail than you will ever want in MSDN onSAL Annotations,The Evolution of HRESULT From Win32andSuccess and Failure Annotations.
In windows is it possible to know what kind of disk we are dealing with from a c/c++ program? forget about gpt or mbr, how to know whether it is basic or dynamic? Program input can be drive letter or any info related to disk, output should be dynamic or basic. No need of a direct way of doing, even if it is lengthy process, its okay. I couldn't find much in msdn. Please help me out.
There is a way in windows, but it's not straight forward. There is no direct API to determine if a disk is Basic or Dynamic, however all dynamic disks will have LDM Information. So if a drive has a partion with LDM information on it, then it's going to be a dynamic disk. the DeviceIoControl() method with the IOCTL_DISK_GET_DRIVE_LAYOUT_EX control code can be used to get this information. Here is a post with a sample console application to do what you're asking for.
I am using GCC, what switches do I need to add to link with Xlib? After searching, all I could find was-lX11, but that gave meld: library not found for -lX11 I am using a mac (10.6), but I would not like anything that is Mac specific.
You can usually usepkg-configto determine the flags you need to pass: ``` gcc my-program.c $(pkg-config --cflags --libs x11) -o my-program ```
I'd like to check if a binary number has a '0' or a '1' at a specific position. example: if the binary number is: 101000100 checking at position zero (that is at the rightmost '0') should result in '0'.checking at position 2 should result in '1'.checking at position 3 should result in '0'.checking at position 6 should result in '1'.etc... I'm coding in C, so obviously I could use sprintf / scanf and the likes, but I guess there must be something better (read: more time efficient / easier)! What would be a good mechanism to do this?
This will filter out the bit you're looking for: ``` number & (1 << position) ``` If you really need a 1 or 0 response, you can use this to make it a boolean value: ``` !!(number & (1 << position)) ``` Or even better (thanksVadim K.): ``` (number >> position) & 1 ```
The following program cannot compile in gcc. But it compiles OK with g++ and MSC++ with.cextension. ``` #include <math.h> #include <stdio.h> int main() { double t = 10; double t2 = 200; printf("%lf\n", sqrt(t*t2)); return 0; } ``` My system is CentOS, the version info. ``` > gcc --version gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46) Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ``` The error info: ``` > gcc test.c /tmp/ccyY3Hiw.o: In function `main': test.c:(.text+0x55): undefined reference to `sqrt' collect2: ld returned 1 exit status ``` Is this a bug? Any one can do a test for me?
Have you linked the math library? ``` gcc -lm test.c -o test ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question I'm usinglong double ina C program to compute 2D images of the Mandelbrot Set but wish to have further precision to zoom deeper. Are there any performance gains to be had from an arbitrary precision maths library that can restrict the amount of precision as required, rather than leaping fromlong doubleprecision straight into arbitrary precision? Which is the fastest of the arbitrary precision maths libraries?
'fastest' is going to be somewhat dependent on your platform and intended use. The MPFR Library GMP Thiswiki articlecontains links to several libraries.
Is there a Linux library that will enable me to tell what IP sockets are owned by what processes? I guess I'm looking for the programmatic equivalent oflsof -i. Ultimately, I want to correlate packets seen throughlibpcapto processes. UPDATE:A couple of people have suggested using/proc/<pid>/net/tcpandudp, but on my system, the same data is shown for every process, so it doesn't help.
I think you first have to look through the open fds in /proc/*/fd, e.g. ``` 4 -> socket:[11147] ``` and then look for the referenced sockets (by the inode) in /proc/net/tcp (or /proc/net/udp), e.g. ``` 12: B382595D:8B40 D5C43B45:0050 01 00000000:00000000 00:00000000 00000000 1000 0 11065 1 ffff88008bd35480 69 4 12 4 -1 ```
I'm getting a strange compile warning. It's intermittent, and doesn't appear every build. I get the warning "initialization makes pointer from integer without a cast" for the following line: ``` callbackTable *callbacks = generateLoggingCallback(); ``` and, for completeness, this gives the same outcome ``` callbackTable *callbacks; callbacks = generateLoggingCallback(); ``` the function prototype for that is: ``` callbackTable *generateLoggingCallback(); ``` and the implementation is ``` callbackTable *generateLoggingCallback() { ... } ``` So, I'm not quite sure what the problem is. Ideas?
If it's pure C, isn't there a warning about 'unknown' function? if yes, then the compiler decides that the unknown function returns int, and continues on.. check if proper headers are included, and the function is declared before it's used.
For practice I decided to rewrite string.c in C. I can not find online (via google or other search engines) a test suite for either the entire standard or for specifically string.h More specifically I am looking to see if my strcat(), strncat(), strchr(), strrchr(), strcmp(), strncmp(), strcpy(), strncpy(), strlen(), and strstr() functions conform to ISO/IEC 9899:1990 (``ISO C90''). Can anyone recommend a good way to test these functions? edit: the title and paragraph above used to say string.h - I meant string.c
P.J. Plauger, in his bookThe Standard C Library(which covers implementing the whole library) presents test programs for each part of the library. These are not exhaustive, and I don't have an on-line source for them, but the book is definitely of interest to anyone implementing the library.
I have two threads in my application. Is it possible to execute both the threads simultaneously without sleeping any thread?
You can run the threads parallel in your application especially if they are not waiting on each other for some inputs or conditions. For example: One thread may be parsing a file and other maybe playing a song in your application. Generally OS takes care of the thread time slicing. So at the application level it would look like these threads are running parallel but the OS does the time slicing giving each thread certain execution time. With multi-core processors/cores it is possible to run the threads parallel in realtime, however the OS decides which threads to run unless you specifically code at lower level to ensure which threads you want to run in parallel.
linux gcc 4.4.1 C99 I am wondering what is the best way to test the performance of a C program. I have some functions that I have implemented. However, I could have used a different design for each function. Basically, I should want to test to see which design gives better performance. Many thanks,
Take a look atthis poston code profilers.
Why isn't the size of an array sent as a parameter the same as within main? ``` #include <stdio.h> void PrintSize(int p_someArray[10]); int main () { int myArray[10]; printf("%d\n", sizeof(myArray)); /* As expected, 40 */ PrintSize(myArray);/* Prints 4, not 40 */ } void PrintSize(int p_someArray[10]){ printf("%d\n", sizeof(p_someArray)); } ```
An array-type isimplicitlyconverted into pointer type when you pass it in to a function. So, ``` void PrintSize(int p_someArray[10]) { printf("%zu\n", sizeof(p_someArray)); } ``` and ``` void PrintSize(int *p_someArray) { printf("%zu\n", sizeof(p_someArray)); } ``` are equivalent. So what you get is the value ofsizeof(int*)
What's this easiest / most efficient way to initialize these blocks of doubles, preferably at compile time: ``` #define N 1000 double mul1[N][N] __attribute__ ((aligned (64))); double mul2[N][N] __attribute__ ((aligned (64))); ``` They're used for "const" read only test data.
There is a GCC (not standard C!) feature calledDesignated Initializers For 1D array it would be just: ``` double array[N] = {[0 ... (N-1)] = MY_DOUBLE_VALUE}; ``` For 2D a bit trickier: ``` double array[N][N] = { [0 ... (N-1)] = {[0 ... (N-1)] = MY_DOUBLE_VALUE}}; ```
I have C++ objects and I haveLuaobjects/tables. (Also haveSWIGC++ bindings.) What I need to be able to do is associate the two objects so that if I do say ``` CObject* o1 = getObject(); o1->Update(); ``` it will do the equivalent Lua: ``` myluatable1.Update(); ``` So far I can imagine that CObject::Update would have the following code: ``` void CObject::Update(){ // Acquire table. // ??? // Do the following operations on the table. lua_getfield(L, -1, "Update"); lua_pcall(L, 0, 0, 0); } ``` How would I store/set the Lua table to be used, and what would go in the// ???above to make the Update call work?
I cant believe nobody noticed this! http://www.lua.org/pil/27.3.2.html A section of the Lua API for storing references to lua objects and tables and returning references for the purposes of being stored in C structures!!
Hi I am writing a simple client-server program. In this program I have to usegetopt()to get the port number and ip address like this: server -i 127.0.0.1 -p 10001 I do not know how can I get values from optarg, to use later in the program.
You use a while loop to move through all the arguments and process them like so ... ``` #include <unistd.h> int main(int argc, char *argv[]) { int option = -1; char *addr, *port; while ((option = getopt (argc, argv, "i:p:")) != -1) { switch (option) { case 'i': addr = strdup(optarg); break; case 'p': port = strdup(optarg); break; default: /* unrecognised option ... add your error condition */ break; } } /* rest of program */ return 0; } ```
I have used this type of convention many times in my code in the past: ``` strcpy ( cTmpA, "hello" ); sprintf ( cTmpA, "%s world", cTmpA ); ``` Recently I switched my legacy C compiler to Visual Studio 2005, and found I got a garbled string resulting from the above code. It then occurred to me that perhaps the behaviour of sprintf() is not rigidly defined where one of the inputs matches the output string. Is the above code valid K&R C? If not, how do I find all the places in my code where this type of call to sprintf() has occurred?
While it is valid K&R C, you probably want to rather know if it's valid POSIX - seesprintf Specification. We read: If copying takes place between objects that overlap as a result of a call to sprintf() or snprintf(), the results are undefined.
I want to create a thread in C so that the thread automatically call after two seconds. I am using Visual Studio and Windows platform for development. How do I get started?
You are going to need to use OS specific libraries to do threading. On Posix, you will want to look intopthreads(and specificallypthread_create). On Windows, you'll wantCreateThreador _beginthreadex.
I can do this in c++/g++: ``` struct vec3 { union { struct { float x, y, z; }; float xyz[3]; }; }; ``` Then, ``` vec3 v; assert(&v.xyz[0] == &v.x); assert(&v.xyz[1] == &v.y); assert(&v.xyz[2] == &v.z); ``` will work. How does one do this in c with gcc? I have ``` typedef struct { union { struct { float x, y, z; }; float xyz[3]; }; } Vector3; ``` But I get errors all around, specifically ``` line 5: warning: declaration does not declare anything line 7: warning: declaration does not declare anything ```
according tohttp://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields -fms-extensionswill enable the feature you (and I) want.
hi i have the following code... ``` int *a, *b; int *d; int N = 2000; size_t size = N*sizeof(int); a = (int *) malloc(size); b = (int *) malloc(size); ... cudaMalloc((void **) &d, size); ``` it works just fine... now assume I have the following ``` char **t = malloc(2000* sizeof *t); for(...) { ... t[i] = (char *)malloc(sizeof(char)*changing_length); ... } ``` how to do cudaMalloc for t as if it is one dimensional array (taking into account that each element has different size) ?
If you have a regular 2D array of chars you can calculate the size with... ``` width * height * sizeof(char) ``` If you have an irregular 2D array (some rows have different lengths) then you'll have to either keep track of the total number of chars somewhere else or loop through and count how many chars you have before you do the cudaMalloc.
Some example code to start the question: ``` #define FOO_COUNT 5 static const char *foo[] = { "123", "456", "789", "987", "654" }; ``` The way this would normally be iterated over, as for one example, is the following: ``` int i = FOO_COUNT; while (--i >= 0) { printf("%s\n", foo[i]); ``` Is there anyway to do the above without explicitly having the human count the number 5? In the future I might add/remove elements and forget to update the size of the array, thus breaking my app.
``` int i = sizeof(foo)/sizeof(foo[0]); ```
I want to allocate shared memory as a 2D array using IPC. I tried the following: ``` id_shmem = shmget(ipc_key, sizeof(int)*rows*columns, IPC_CREAT|0666); matrix = (int **)shmat(id_shmem, 0, 0); ``` The problem is that whenever I try to write something into the matrix, I get a segment fault.
int** is not 2D array, it is rather an array of pointers. You should not store pointers in shared memory, as shared memory segment may be allocated at different addresses in different processes. Try to use simple, flat 1D array, which will "emulate" 2D array with some index magic, ie. ``` x,y -> y*width+x ```
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago. Rather than possibly reinventing the wheel (by "rolling my own") - I thought I'd ask in here first. Anyone knows where I can download a good C/C++ RESTful framework?. I have had a quick look on google, but there is nothing too impressive so far - maybe someone in here has written one already (that they dont mind sharing), or may know a lik to a good one (preferably, they have already used it before)
I've just seenthis, it may be what I'm looking for. Could be useful for others too
I need to set additional options for C compiler, e.g. add flag to turn all warnings ON, depending on the type of the compiler. E.g. for MSVC I should use ``` env.Append(CPPFLAGS = "/Wall") ``` but for mingw (gcc) I need to use: ``` env.Append(CCFLAGS = "-Wall") ``` How can I do this in scons way?
You could just check for the name of the compiler: ``` cc = env['CC'] if cc == 'cl': env.Append(CPPFLAGS = '/Wall') elif cc == 'gcc': env.Append(CCFLAGS = '-Wall') ```
Usingmemcpy()when source and destination overlap can lead to undefined behaviour - in those cases onlymemmove()can be used. But what if I know for sure buffers don't overlap - is there a reason to use specificallymemcpy()or specificallymemmove()? Which should I use and why?
Assuming a sane library implementor,memcpywill always be at least as fast asmemmove. However, on most platforms the difference will be minimal, and on many platformsmemcpyis just an alias formemmoveto support legacy code that (incorrectly) callsmemcpyon overlapping buffers. Bothmemcpyandmemmoveshould be written to take advantage of the fastest loads and stores available on the platform. To answer your question: you should use the one that is semantically correct. If you can guarantee that the buffers do not overlap, you should usememcpy. If you cannot guarantee that the buffers don't overlap, you should usememmove.
I am reading a file with fgetc, so each time it reads a character, the cursor positio gets changed. Is it possible to know, after each read, the "coordinates" of the cursor on the file in terms of column and line number? Thanks
You can useftell It does not give you the position in terms of row and column but gives the current position in the stream from the start.