question
stringlengths
25
894
answer
stringlengths
4
863
Can anyone suggest some learning materials to accomplish my question? I'm working with the Linux kernel. I'm planning on conducting an experiment, but need access to my process' page table, and so far have only found kernel space code to accomplish what I want. Thanks
You'll probably find the information you want in the proc filesystem, under/proc/self. In particular/proc/self/mapscontains the list of memory mappings in the process, with an indication of their permission and file when applicable. There is a little more information in/proc/self/smaps. You'll have to look in the kernel documentation for the format, specificallyDocumentation/filesystems/proc.txt.
What am I doing wrong here? ``` $ cat size.c #include<stdio.h> #include<math.h> int main() { printf ("sizeof unsigned int = %d bytes.\n", sizeof(unsigned int)); printf ("sizeof unsigned long long = %d bytes.\n", sizeof(unsigned long long)); printf ("max unsigned int = %d\n", (int)(pow(2, 32) - 1)); printf ("max unsigned long long = %lld\n", (unsigned long long)(pow(2, 64) - 1)); } $ gcc size.c -o size $ ./size sizeof unsigned int = 4 bytes. sizeof unsigned long long = 8 bytes. max unsigned int = 2147483647 max unsigned long long = -1 $ ``` I am expecting18446744073709551615as output instead of a-1at the last line. Okay, I completely missed that I was getting the wrong value for 232- 1, which should have been 4294967295, not 2147483647. Things make more sense now.
Just don't suppose that it has a certain value useULLONG_MAX
if i have both encrypted message and signature (let's say two different size files), i just want to append them and store inafile together but later i will use the same "only one file" to extract the files and verify in my code. in that way my code will get only one file as an input but can understand which is encrypted file and signature file... this file will be used in C or C++ program, will be get as an argument. thanks.
Why don't you just zip (or any other archive method: tar, 7z,...) them together?
This question already has answers here:Closed12 years ago. Possible Duplicates:const int = int const ?Const in C hi, I would like to know the exact meaning of "int const* " in C ,And also a small comparison between "const int*" and "int const*" in an embedded programming system. __kanu
What is the exact meaning of “int const* ” in C? It means a pointer to a constant integer. In other words, the pointer is not constant, but the value it points to is. And also a small comparison between "const int*" and "int const*" There is no difference. A similar construct isint * const. Here thereisa difference. This time the pointer is constant but the value it points to is not.
This question already has answers here:Closed12 years ago. Possible Duplicate:Converting a Uniform Distribution to a Normal Distribution Hello. I'd like to know of any algorithm implemented in C which can take a random value between 0 and 1, the mean and standard deviation and then return a normally distributed result. I have too little brainpower to figure this out for myself right now. I can't find anything useful on the internet. Thank you.
Box-Mulleris the transform you need.
PHP's C source can be found athttp://svn.php.net/viewvc/php/php-src/trunk/. If I want to find the implementation of a specific PHP function, how to quick locate it in that SVN source?
Checking out the repository (or extracting the tarball), and greppign forPHP_FUNCTION(functionname)should do it. For example: ``` $ grep -Rn "PHP_FUNCTION(implode)" * ext/standard/php_string.h:40:PHP_FUNCTION(implode); ext/standard/string.c:1131:PHP_FUNCTION(implode) ``` Line1131ofext/standard/string.cis whereimplodeis defined. Or you can usehttp://lxr.php.net/.
This question already has answers here:Closed12 years ago. Possible Duplicate:What is the difference between char s[] and char *s in C? I was wondering what is the difference between ``` char *p1 = "some string"; ``` and ``` char p2[] = "some string"; ``` in terms of memory, can these not be treated in the same way? e.g. ``` void foo(char *p); ``` ... ``` foo(p1); foo(p2); ```
All is explained here:http://c-faq.com/aryptr/aryptr2.html
My rectangle structure has these members: x, y, width, height. Given a point x, y what would be the fastest way of knowing if x, y is inside of the rectangle? I will be doing lots of these so speed is important.
This is how I usually do it. Given a point that is outside of the rectangle, this will do fewer tests in 3 out of 4 cases. And sometimes only one test is done. ``` if(point.x < rect.x) return false; if(point.y < rect.y) return false; if(point.x >= rect.x + rect.width) return false; if(point.y >= rect.y + rect.height) return false; return true; ``` Which one you use should be dependent upon whether you anticipate more collisions or more misses.
" Double pointers are also sometimes employed to pass pointers to functions by reference " can somebody can explain me the above statement, what exactly does point to function by reference means ?
I believe this example makes it clearer : ``` //Double pointer is taken as argument void allocate(int** p, int n) { //Change the value of *p, this modification is available outside the function *p = (int*)malloc(sizeof(int) * n); } int main() { int* p = NULL; //Pass the address of the pointer allocate(&p,1); //The pointer has been modified to point to proper memory location //Hence this statement will work *p=10; //Free the memory allocated free(p); return 0; } ```
I have a GtkButton inside a GtkHButtonBox that doesn't show the image I'm adding to it. It just shows the text. Here's the code: ``` GtkImage *image = (GtkImage *) gtk_image_new_from_file("Gateway-LT21-netbook-2-540x359"); GtkButton *button = (GtkButton *) gtk_button_new_with_label("test"); gtk_button_set_image(button, (GtkWidget *) image); ``` Is there something I'm missing?
Make sure that the "gtk-button-images" setting is set to true. ``` GtkSettings *default_settings = gtk_settings_get_default(); g_object_set(default_settings, "gtk-button-images", TRUE, NULL); ``` Note: This should follow the construction of the first window (and of course precede the main loop). If I'm not mistaken, this is a rather recent change in Gnome - for some reason, they decided for icons not to appear on buttons as default (this also seems to apply to the standard MS Windows theme).
The C99 standard describes them as so: The integer and real floating types are collectively called real types.Integer and floating types are collectively called arithmetic types. Does this mean they're the same thing in C? Or are there any differences between them?
Complex types are arithmetic types, but not real types.
I was wandering how could capture video from the built-in camera of my netbook, under Linux, ubuntu. The programming language could is not an issue (but I prefer Java or the old school c) Thanks in advance for your answers, Gian
You can look into OpenCV, for C/C++. It is very powerful.
``` typedef struct { employeeT *employees; int nEmployees; } *payrollT; typedef struct { string name; } *employeeT; ``` I need to do this without accessing it as an array: ``` employeeT e = payroll.employees[i]; ``` but this gives me an error(expected identifier before '(' token) : ``` employeeT e = payroll.(*(employee+i)); ``` before struct's I could interchange employees[i] and *(employee+i)
Why do you need to avoid array syntax? *(ptr+offset) == ptr[offset], strictly, every time. You have NO performance penalty and the array syntax is clearer. EDIT: I just got the real crux of the problem. Ifpayroll(in your example) is a pointer type, you need to use the arrow operator instead of the dot operator: ``` payroll->employees[0] ```
I'm drawing text on window at WM_PAINT message, is there any way i can refresh that window region before drawing a new line of text so the old text at the same location would get erased?
You need to callInvalidateRectfor the window with thebEraseparameter set toTRUEso that it will erase itself before the WM_PAINT is generated. This is often required when the window is a static text control, as those don't erase themselves automatically when you change their value. Make sure your window is handlingWM_ERASEBKGNDproperly and the window class doesn't have a NULL background brush, as this is the mechanism used by InvalidateRect to do the erasing.
``` #include<stdio.h> int main(void) { signed int a=-1; unsigned int b=1; int c= a+b; printf("%d\n",c); return 0; } ``` According to the rule of Implicit type conversion, if one operand isunsigned int,the other will be converted tounsigned intand the result will beunsigned intin a binary operation. so here asbisunsigned int,ashould be type casted tounsigned int.As unsigned int is always +ve , so the value ofawill be 1.soc=1+1=2.But the output is0.How ?
-1, when cast to unsigned will become the largest possible value for that type -- e.g. with a 32-bit unsigned, it'll be 4,294,967,295. When you add 1 to that, the value "wraps around" to 0.
``` struct mystruct s[10] = {{0}}; ``` This appears to initialize an array of structs to 0. How does the nested braces syntax work?
Any fields not specified are initialized to zero. So here you have an array of structs. You're initializing the first element of the array with a structure initializer that initializes the first element of the structure to zero. The rest of the first structure and the rest of the array elements will all be zero too. It's a nice idiom.
I am using structs in my project in this way: ``` typedef struct { int str1_val1; int str1_val2; } struct1; ``` and ``` typedef struct { int str2_val1; int str2_val2; struct1* str2_val3; } struct2; ``` Is it possible that I hack this definition in a way, that I would use only types with my code, like ``` struct2* a; a = (struct2*) malloc(sizeof(struct2)); ``` without using keywordstruct?
Yes, as follows: ``` struct _struct1 { ... }; typedef struct _struct1 struct1; struct _struct2 { ... }; typedef struct _struct2 struct2; ... struct2 *a; a = (struct2*)malloc(sizeof(struct2)); ```
How do I forward declareFILE *in C? I normally do this usingstruct MyType;, but naturally this doesn't appear to be possible. If behaviour differs between C standards or compilers and with C++, this is also of interest. Update0 Why I want to do this aside: What I'm asking is how to forward declare a non-struct/"typedef'd struct" type so that I can declare pointers to it. Obviously usingvoid *and casting it in the source file is a bit hackish.
You can't. The standard just states thatFILEis "an object type capable of recording all the information needed to control a stream"; it's up to the implementation whether this is atypedefof astruct(whose name you don't know anyway), or something else. The only portable way to declareFILEis with#include <stdio.h>(or<cstdio>in C++).
I've implemented a circular buffer, and I would like a concise means of updating the buffer pointer while properly handling the wrap-around. Assuming an array of size 10, my first response was something like: ``` size_t ptr = 0; // do some work... p = ++p % 10; ``` Static analysis, as well asgcc -Wall -Wextra, rightly slapped my wrist for unspecified behavior due to a sequence point violation. The obvious fix is something like: ``` p++; p %= 10; ``` However, I was looking for something more concise, (i.e., a one-liner) to "encapsulate" this operation. Suggestions? Other thanp++; p%= 10;:-)
``` p = (p + 1) % N; ``` or to avoid the modulo: ``` p = ((N-1) == p) ? 0 : (p+1); ```
I want to add a C file into my .NET application. How can I built this? How can i write unmanaged code in C#. Can someone explain with few lines code. Thanks
You either have to build the C file into it's own DLL and thenuse P/Invokein your C# code to call them or... You could also try to port the C code to C# which would give you a completely managed codebase.
``` #include<stdio.h> int main(void) { int i=1,j=-1; if((printf("%d",i))<(printf("%d",j))) printf("%d",i); else printf("%d",j); return 0; } ``` Asprintf()returns the number of characters successfully printed, the condition will beif(1<1)which is false but the if part is executed and the output is1 -1 1. Why this is happening?
I think it is rather obvious: '1' is one character, '-1' is two. One is less than two.
This might be an often repeated question, sorry for bringing it back again. I was unable to find a solution :( . I am writing a VM monitoring code in C in Linux. I want to get the read and write count of all the VM's every 10 seconds. Is there any C library that provides this feature(timer alone), blocking/non-blocking timer doesn't matter. Thanks !! Regards, Sethu
For a non-blocking timer (on POSIX systems), usealarm: ``` int main(void) { signal(SIGALRM, monitor); monitor(0); /* ... */ } void monitor(int signal) { /* ... */ alarm(10); } ``` But for a blocking timer, usesleepas described bylalli.
``` struct mystruct s[10] = {{0}}; ``` This appears to initialize an array of structs to 0. How does the nested braces syntax work?
Any fields not specified are initialized to zero. So here you have an array of structs. You're initializing the first element of the array with a structure initializer that initializes the first element of the structure to zero. The rest of the first structure and the rest of the array elements will all be zero too. It's a nice idiom.
I am using structs in my project in this way: ``` typedef struct { int str1_val1; int str1_val2; } struct1; ``` and ``` typedef struct { int str2_val1; int str2_val2; struct1* str2_val3; } struct2; ``` Is it possible that I hack this definition in a way, that I would use only types with my code, like ``` struct2* a; a = (struct2*) malloc(sizeof(struct2)); ``` without using keywordstruct?
Yes, as follows: ``` struct _struct1 { ... }; typedef struct _struct1 struct1; struct _struct2 { ... }; typedef struct _struct2 struct2; ... struct2 *a; a = (struct2*)malloc(sizeof(struct2)); ```
How do I forward declareFILE *in C? I normally do this usingstruct MyType;, but naturally this doesn't appear to be possible. If behaviour differs between C standards or compilers and with C++, this is also of interest. Update0 Why I want to do this aside: What I'm asking is how to forward declare a non-struct/"typedef'd struct" type so that I can declare pointers to it. Obviously usingvoid *and casting it in the source file is a bit hackish.
You can't. The standard just states thatFILEis "an object type capable of recording all the information needed to control a stream"; it's up to the implementation whether this is atypedefof astruct(whose name you don't know anyway), or something else. The only portable way to declareFILEis with#include <stdio.h>(or<cstdio>in C++).
I've implemented a circular buffer, and I would like a concise means of updating the buffer pointer while properly handling the wrap-around. Assuming an array of size 10, my first response was something like: ``` size_t ptr = 0; // do some work... p = ++p % 10; ``` Static analysis, as well asgcc -Wall -Wextra, rightly slapped my wrist for unspecified behavior due to a sequence point violation. The obvious fix is something like: ``` p++; p %= 10; ``` However, I was looking for something more concise, (i.e., a one-liner) to "encapsulate" this operation. Suggestions? Other thanp++; p%= 10;:-)
``` p = (p + 1) % N; ``` or to avoid the modulo: ``` p = ((N-1) == p) ? 0 : (p+1); ```
I want to add a C file into my .NET application. How can I built this? How can i write unmanaged code in C#. Can someone explain with few lines code. Thanks
You either have to build the C file into it's own DLL and thenuse P/Invokein your C# code to call them or... You could also try to port the C code to C# which would give you a completely managed codebase.
``` #include<stdio.h> int main(void) { int i=1,j=-1; if((printf("%d",i))<(printf("%d",j))) printf("%d",i); else printf("%d",j); return 0; } ``` Asprintf()returns the number of characters successfully printed, the condition will beif(1<1)which is false but the if part is executed and the output is1 -1 1. Why this is happening?
I think it is rather obvious: '1' is one character, '-1' is two. One is less than two.
This might be an often repeated question, sorry for bringing it back again. I was unable to find a solution :( . I am writing a VM monitoring code in C in Linux. I want to get the read and write count of all the VM's every 10 seconds. Is there any C library that provides this feature(timer alone), blocking/non-blocking timer doesn't matter. Thanks !! Regards, Sethu
For a non-blocking timer (on POSIX systems), usealarm: ``` int main(void) { signal(SIGALRM, monitor); monitor(0); /* ... */ } void monitor(int signal) { /* ... */ alarm(10); } ``` But for a blocking timer, usesleepas described bylalli.
``` int i=2; i = ++i + ++i + ++i; ``` Which is more correct? Java's result of 12 or C = 13. Or if not a matter of correctness, please elaborate.
Java guarantees (§15.7.1) that it will be evaluated left-to-right, giving 12. Specifically,++has higher precedence that+. So it first binds those, then it associates the addition operations left to right ``` i = (((++i) + (++i)) + (++i)); ``` §15.7.1 says the left operand is evaluated first, and§15.7.2says both operands are evaluated before the operation. So it evaluates like: ``` i = (((++i) + (++i)) + (++i)); i = ((3 + (++i)) + (++i)); // i = 3; i = ((3 + 4) + (++i)); // i = 4; i = (7 + (++i)); // i = 4; i = (7 + 5); // i = 5; i = 12; ``` In C, it is undefined behavior to modify a variable twice without a sequence point in between.
WHen specifying library_dirs in a Python distutils.core.Extension I get this error when trying to build: ``` /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py:263: UserWarning: Unknown distribution option: 'library_dirs' warnings.warn(msg) ``` Why is this? I am using Python 2.5 on Mac OS X.
The error means you're not passinglibrary_dirstodistutils.core.Extension, but to thedistutils.core.setupfunction.
I have a program that generates a variable amount of data that it has to store to use later. When should I choose to use mallod+realloc and when should I choose to use temporary files?
mmap(2,3p)(orfile mappings) means never having to choose between the two.
Hello I'm using Gtk on C, I need to have a GtkTextView in the middle of my window with many other widgets, I can't make the widget wrap lines. This is a very annoying behavior, anyone have any idea of what am I missing? This is the code I'm using to set it's properties: ``` gtk_text_view_set_left_margin(GTK_TEXT_VIEW(commentsTextView),20); gtk_text_view_set_right_margin(GTK_TEXT_VIEW(commentsTextView),290); gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(commentsTextView),GTK_WRAP_WORD); gtk_text_view_set_pixels_inside_wrap(GTK_TEXT_VIEW(commentsTextView),0); gtk_widget_set_size_request(commentsTextView,300,300); ``` Edit: I solved this in a different way, still the problem remains unsolved :S
Did you put your text view into aGtkScrolledWindow?
How exactly does one find out the status of the lock keys on Linux (2.6.x), using C? (I have acrappykeyboard without LED's for this stuff, and I need to write an X11 app to do this) If such an app exists (and is DE agnostic- I run e16), I'd also like to hear it as well.
You can use the led addon to gkrellm. If you want to develop your own app, you can always look a thegkrellm-led sources(Ubuntu). And, of course, you can always go with xkbvleds(source). Anyway, you can always useXkbGetIndicatorStateto read the indicators from your keyboard.
I'm trying to save a void* pointer (or any pointer) into a tcl Object so I can retrieve it later. I saw SWIG convert it to a string with some encoding and later decode it. But in order to make it more efficient, I want to directly get the pointer in and out of the tcl obj. Something like a Tcl_GetPointerFromObj(). Is there anyway to do it? Do I need to dig into the Tcl_Obj structure and do some dirty work?
I suggest readingthis page on the Tcler's Wikiwhich is on the topic.
I am currently trying to print a message from a child process after calling execlp() within the child. However, nothing appears on the terminal after the call to execlp(). What causes my printf() calls to not display anything, and how can this be resolved?
After a successfulexeclp()call, no code in your previous program will ever run again. The process's memory space is overwritten with the new process. If you still need to do some management with the child, then you will want to callfork()before you callexeclp(). This will give you two processes, and you can then do some communication between the two.
I have written some code in C++ with a corresponding C interface (i.e C-function wrappers around the classes) that a friend wants to use in an iPhone application. Since I heard you can compile C++ for the plattform, but not use the iPhone sdk at the same time (sic) I thought that compiling all the code into a static library that my friend then can link together with his project in xcode. So the question is, What is, if possible the command line for compiling all my cpp files into a static library for the iPhone os? Thanks!
Xcode will happily compile C++ code along with C and Objective-C in a single iPhone project.
I had found a strange output when I write the following lines in very simple way: Code: ``` printf("LOL??!\n"); printf("LOL!!?\n"); ``` Output: It happens even the code is compiled under both MBCS and UNICODE. The output varies on the sequence of "?" and "!"... Any idea?
??!is atrigraphthat gets replaced by|. As a rule, you should never place two question mark characters together anywhere in a source file.
``` #define STRLEN 65 /*Create linked list */ struct node { char str[STRLEN]; struct node *next; }; newInput = malloc(sizeof(struct node)); strcpy(newStr, newInput->str); ``` I left the other parts of the code, but it doesnt seem to be copying the string into newInput->str. The string accepted is only 64 bytes. It's just blank when I print it out after the copy. Any clue why?
You have the arguments tostrcpyreversed, the first argument is the destination, the second argument is the source. Try: ``` strcpy(newInput->str, newStr); ```
This question already has answers here:What is an opaque value in C++?(5 answers)Closed9 years ago. I notice in several API's, that you may create a struct which is used internally and has nothing. ex: ``` ALLEGRO_BITMAP *bmp; ... bmp->(intellesense shows nothing) ``` how do these types of structures work? are they simply handled like this internally? ``` REAL_ALLEGRO_BITMAP *realbmp = (REAL_ALLEGRO_BITMAP*)bmp; ``` or is there a cleaner solution? Thanks
What you're looking at is anopaque pointeroropaque data type(linkandlink). Here's an SO thread discussing these:What is an opaque value?
Under Linux, C++, and GCC, can I get a physical address for a given virtual address? I know I won't be able to manipulate the physical address as a physical address.
Nope. There's no guarantee that a virtual address is based off a physical address (it may be a mapped file with no representation in RAM, for instance.) As well, the OS is free to move virtual addresses around in physical memory at any time, so there's no guarantee that a physical address will remain correct or valid. Why do you think you need a physical address? What are you trying to accomplish?
I am building an application that consists of both a windows driver written inCand a user mode executable in C++. They both use a shared header file to define several macros, constants, enums, etc. In the C++ version, I want to include everything within a namespace, which a feature not supported by theCcompiler. Is there certain variable I can check for to use as a preprocessor directive with Visual Studio like in the following example? ``` #ifdef USING_CPLUSPLUS namespace mynamespace{ #endif struct mystruct{ ... }; #ifdef USING_CPLUSPLUS } #endif ```
The closest macro I can think of is: ``` #if defined(__cplusplus) ```
I'm looking for a good way to do something like this: ``` typedef struct user { unsigned long id; //userList defined below userList friends; } typedef struct { //userList contains users user * list; int count; } userList; ``` Is there a legal way to do this or something similar?
Do it like: ``` typedef struct user user; typedef struct { //userList contains users user * list; int count; } userList; struct user { unsigned long id; //userList defined above userList friends; }; ```
I have come across a few lines of coding I do not understand, and would be grateful for clarification: if(!(counter&7))ds->direction = ts->direction;
ifcounteris a multiple of 8set thedirectionelement of*dsequal to thedirectionelement of*ts
In my application I have to resize forms and all its control on mouse drag effect and forms should have drop shadow effect the problem is that all my forms are custom one (with no boarder). Thanks in advance
i think u have to implement by yourself on mouse down start bind on mouse drag + change cursor to resize iconon mouse drag, just simply reduce your form sizeon mouse up unbind mouse drag event the reason i suggest dynamic event binding so u can specified which control or area should have mouse down
I have a old school c program that now and then need to tell a C++ Qt based application about some "events" that has occurred on my system. But when I started to work with this problem I noticed that some ipc techniques is quite easy to use in the c program. And then we have some Qt specific styles that works quite well in the "Qt world", but they will not work well in the ansi c program. Do you have any advice on ipc techniques that works well and are easy to use in both a Qt C++ and a c program? Thanks Johan
If you are familiar with network programming, Unix domain sockets should be easy also. They work kind of like bidirectional named pipes and the network API in Qt should make it easy to receive "events" delivered as network messages.
I'm making an application and would like to test the toString method I just made. I'm using Visual c++ 2008. Is there a way to see console output without having a console window? Such as in the Output panel? Thanks
If you callOutputDebugString, it will display the string in the output window when you run the program under VS++. Most other debuggers (and a number of other monitoring applications and such) can/will display such strings as well, but when you run the program without a debugger (or something similar) that output will simply be ignored.
So lets say I have this code ``` int my_static_int = 4; func(&my_static_int); ``` I passed the function a pointer to my_static_int, obviously. But what happens when the code is compiled? Avenue I've considered: 1) When you declare a non-pointer variable, C automatically creates its pointer and does something internally like typedefs my_static_int to be *(internal_reference) Anyway, I hope that my question is descriptive enough
Pointers are just a term to help us humans understand what's going on. The & operator when used with a variable simply means address of. No "pointer" is created at runtime, you are simply passing in the address of the variable into the function. If you have: ``` int x = 3; int* p = &x; ``` Then p is a variable which holds a memory address. Inside that memory address is an int.
When using va_start(), va_arg() and va_end() to read parameters passed to a method, is there a way to count how many arguments there are? According to the man page if you call va_arg() too many times you get "random errors": If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.
No. a Variable Argument function (such asprintf), must "know" when to stop looking for more arguments. printfknows by the number of%d,%sand other symbols in its format string. Other functions sometimes use Sentinel values: ``` sumValues(1, 3, 5, 7, 6, 9, -1); // will add numbers until it encounters a -1 ``` Other functions may have the number of parameters stated up front: ``` AddNames(4, "Bill", "Alice", "Mike", "Tom"); ```
In C++: ``` int main() { cout << setfill('#') << setw(10) << 5 << endl; return 0; } ``` Outputs: ``` #########5 ``` Is there anysetfill()alternative for C? Or how to do this in C without manually creating the string?
``` int x= 5; printf("%010d",x); ``` will output : 0000000005 Now if you really want '#' instead of '0' you'll have to replace them manually in the string. Maybe : ``` char buf[11], *sp = buf; snprintf(buf, 11, "%10d", x); while( (sp = strchr(sp, ' ')) != '\0'){ *sp = '#'; } puts(buf); ```
Is there a C library available for operations such as file operations, getting system information and the like which is generic, which can be used when compiled in different platforms and which behaves in a similar way? Edit: Something like Java or .NET platform abstracting the hardware.
Have you tried the standard library? It should be implemented on any system that has an ISO compliant C runtime.
I'm usingWinHTTPto write an an app that needs access to the internet, and is potentially behind a proxy. Everything works (almost) out of the box is the user is on a domain, but if he or she isn't then I need a way to ask for credentials. Is there a standard way of doing that, or should I write my own dialog? Ideally I'd like something that mimics IE's username/password dialog. Thanks.
CredUIPromptForCredentials()(or one of its variants) is probably what you're looking for. This provides a consistent look and feel with the version of Windows your software is running on.
I have a XML document which is received as a character stream. I wish to parse this using libxml2. Well one way would be to save it as an .xml and then open it using one of the libxml2 API's. Is there a way i can directly build a tree on this stream and parse it ? Env is purely c++/c. Cheers!
You can usexlmCtxtReadFdfrom parser.h. There's alsoxmlCtxtReadMemory, if you would rather use a block of memory than a stream.
This question already has answers here:sizeof single struct member in C(9 answers)Closed9 years ago. How can I get the size of a member in a struct in C? ``` struct A { char arr[64]; }; ``` i need something like that: sizeof(A::arr) thanks
``` sizeof(((struct A*)0)->arr); ``` Briefly, cast a null pointer to a type ofstruct A*, but since the operand ofsizeofis not evaluated, this is legal and allows you to get size of struct members without creating an instance of the struct. Basically, we are pretending that an instance of it exists at address 0 and can be used for offset andsizeofdetermination. To further elaborate, read this article: http://www.embedded.com/design/prototyping-and-development/4024941/Learn-a-new-trick-with-the-offsetof--macro
I am currently trying to print a message from a child process after calling execlp() within the child. However, nothing appears on the terminal after the call to execlp(). What causes my printf() calls to not display anything, and how can this be resolved?
After a successfulexeclp()call, no code in your previous program will ever run again. The process's memory space is overwritten with the new process. If you still need to do some management with the child, then you will want to callfork()before you callexeclp(). This will give you two processes, and you can then do some communication between the two.
I have written some code in C++ with a corresponding C interface (i.e C-function wrappers around the classes) that a friend wants to use in an iPhone application. Since I heard you can compile C++ for the plattform, but not use the iPhone sdk at the same time (sic) I thought that compiling all the code into a static library that my friend then can link together with his project in xcode. So the question is, What is, if possible the command line for compiling all my cpp files into a static library for the iPhone os? Thanks!
Xcode will happily compile C++ code along with C and Objective-C in a single iPhone project.
I had found a strange output when I write the following lines in very simple way: Code: ``` printf("LOL??!\n"); printf("LOL!!?\n"); ``` Output: It happens even the code is compiled under both MBCS and UNICODE. The output varies on the sequence of "?" and "!"... Any idea?
??!is atrigraphthat gets replaced by|. As a rule, you should never place two question mark characters together anywhere in a source file.
Sometimes, when I have a multi-caseif, or a very simplefor, with only two statements, I will forgo braces, instead using the comma. Is this a bad exploitation of the feature, and is it ugly and bad form? Or is it an acceptable way to save time and space? For example: ``` if (something) b = y, c = z--; ``` instead of: ``` if (something) { b = y; c = z--; } ```
It's indeed a clever way to use that syntactic feature of most C-like languages. Personally, I try to stay theleast ambiguous as possiblewhen I code, so I always include{and}in all of myifstatements. It may save time, but I preferclarity: it doesn'tspeed uporslow downthe code execution.
C is always pretty awkward with strings, but it's usually okay to just allocate a char array of size 256 for your string and be on with it. However, what if you want the function to return a string and you don't know the size, since you will be concatenating strings together dozens or hundreds of times? Obviously something like this won't work: ``` char * my_function(int n, char *string){ if (n < 20) { return string; } else { char *new_string = "abcdefghijklmnop"; strcat(string, new_string); return my_function(n--, string); } } ``` So how is this handled in c?
The most straightforward way to do a function that concatenates an arbitrary number of strings is to: Loop through all of the strings and add up theirstrlen().malloc()for the total length.Do all of the concatenation within themalloc'd string and then return it.
I am getting this error whenever I try to run GCC outside of its installation directory (E:\MinGW\bin). So, let's say I am inE:\codeand have a file calledone.c. Running:gcc one.c -o one.exewill give me this error: ``` gcc: CreateProcess: No such file or directory ``` The only workaround is to navigate to its installation directory, run gcc from there, and specify all the other paths. My environmental variablePathcontainsE:\MinGW\bin. Any suggestions to fixing this problem? I am running Windows XP SP3.
According toCode::Blocks wiki, you need to addC:\MinGW\libexec\gcc\mingw32\MinGW-Versionto yourPATH. There is no need to restart, but you need to open another terminal in order to get the newestPATHsettings. For MinGW-w64, that's<mingw install directory>\libexec\gcc\x86_64-w64-mingw32\4.7.0\
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... I made the program but my answer doesnt match. ``` #include<stdio.h> int main() { long unsigned int i,sum=0,x=1,y=2,num; for(i=0;i<4000000;i++) { num=x+y; if(i%2==0) sum+=num; x=y; y=num; } printf("%lu\n",sum); getchar(); return 0; } ```
Three problems I can see: You should start withx = 1, y = 1, since otherwise you skip the first even-valued Fibonacci;Your loop condition should be(x + y) <= 4000000You should testnumfor even-ness, noti. (After these changes, it should be obvious that you can omitientirely, and therefore replace theforloop with awhileloop)
I have some question about header files(I'm talking about c, but I think it will be the same for c++), let's assume I have somemy_ADT.cfile (inside I have implementation of the functions and actualstruct) and alsomy_ADT.hinside I havepointer for my structQuestion:if I use ADTSetfor implementationmy_ADTdo I need to includeset.hto both filesmy_ADT.h and my_ADT.cor including only tomy_ADT.hwill be sufficient (inside my_ADT.c I have#include "my_ADT.h") thanks in advance
There are 3 scenarios set.his needed ONLY inmy_ADT.hset.his needed ONLY inmy_ADT.cset.his needed in bothmy_ADT.handmy_ADT.cset.his not needed at all :-) For scenario 3) add the#include "set.h"to the filemy_ADT.h,document that fact, and#include "my_ADT.h"inmy_ADT.c(with proper include guards, you lose nothing by includingset.halso to the C file). For scenario 2) includeset.honly inmy_ADT.c For scenario 1) includeset.honly inmy_ADT.h
If I have structure definitions, for example, like these: ``` struct Base { int foo; }; struct Derived { int foo; // int foo is common for both definitions char *bar; }; ``` Can I do something like this? ``` void foobar(void *ptr) { ((struct Base *)ptr)->foo = 1; } struct Derived s; foobar(&s); ``` In other words, can I cast the void pointer toBase *to access itsfoomember when its type is actuallyDerived *?
You should do ``` struct Base { int foo; }; struct Derived { struct Base base; char *bar; }; ``` to avoid breaking strict aliasing; it is a common misconception that C allows arbitrary casts of pointer types: although it will work as expected in most implementations, it's non-standard. This also avoids any alignment incompatibilities due to usage of pragma directives.
I have the simplest code "Hello world" ``` #include <stdio.h> /* printf and BUFSIZ defined there */ #include <stdlib.h> /* exit defined there */ #include <mpi.h> /* all MPI-2 functions defined there */ int main(argc, argv) int argc; char *argv[]; { int rank, size, length; char name[BUFSIZ]; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Get_processor_name(name, &length); printf("%s: hello world from process %d of %d\n", name, rank, size); MPI_Finalize(); exit(0); } ``` I have compiled it ``` mpicc -o hello hello.c ``` and tried to run it with 4 processes ``` mpirun -np 4 hello ``` it returns; ``` chasan@ubuntu:~/MpiProgrammes$ mpicc -o hello Hello.c chasan@ubuntu:~/MpiProgrammes$ mpirun -np 4 hello Alarm clock chasan@ubuntu:~/MpiProgrammes$ ``` What could it be ?
try using the command "mpd &"
So my code has in it the following: unsigned short num=0; num=*(cra+3); printf("> char %u\n",num); cra is a char* The problem is that it is getting odd output, sometimes outputting numbers such as 65501 (clearly not within the range of a char). Any ideas? Thanks in advance!
Apparently*(cra+3)is acharof value'\xdd'. Since acharis signed, it actually means -35 (0xddin 2's complement), i.e. 0x...fffffdd. Restricting this to 16-bit gives 0xffdd, i.e. 65501. You need to make it anunsigned charso it gives a number in the range 0–255: ``` num = (unsigned char)cra[3]; ``` Note:1. the signedness ofcharis implementation defined, but usually (e.g. in OP's case) it is signed.2. the ranges ofsigned char,unsigned charandunsigned shortare implementation defined, but again commonly they are -128–127, 0–255 and 0–65535 respectively.3. the conversion fromsigned chartounsigned charis actually -35 + 65536 = 65501.
``` #include <stdio.h> int main(void){ char x [] = "hello world."; printf("%s \n", &x[0]); return 0; } ``` The above code prints out"hello world." How would i print out just"h"? Shouldn't the accessx[0]ensure this?
You should do: ``` printf("%c \n", x[0]); ``` Theformat specifierto print a char isc. So the format string to be used is%c. Also to access an array element at a valid indexiyou need to sayarray_name[i]. You should not be using the&. Using&will give you the address of the element.
If I write ``` #include <stdio.h>; ``` there no error but a warning comes out during compilation pari.c:1:18: warning: extra tokens at end of #include directive What is the reason ?
The reason is that preprocessor directives don't use semicolons. This is because they use a line break to delimit statements. This means that you cannot have multiple directives per line: ``` #define ABC #define DEF // illegal ``` But you can have one on multiple lines by ending each line (except the last) with a \ (or /, I forget).
I can attach a file with libesmtp? Does anyone have a sample code? Thanks FrankIT
No. The library only covers the SMTP protocol, the communication with the server. It does nothing to help you construct a valid MIME document.
What is the proper way to name my revisions? ``` v1.0.3.20 Alpha ``` or ``` Alpha v1.0.3.20 ```
There isn't really any "proper" way. While most people use the dot pattern "x.x.x", it isn't necessarily the proper way to do it. Likewise with your question, it is up to you. I would suppose that the former is more natural to say, and I would prefer it, but it doesn't really matter either way.
I was wondering how to, using C, find out what port a client is currently listening to. ie, I want to know what the source port is, not the destination port. Thanks in advance!
The socket address structure should be filled-in by the connect() system-call. Check it after a successful return from that call.
I saw the code on the top of a GLUT demo and I'm curious about its functionality. Why would someone want to write a #pragma instead of just including the library?
This pragma allows the library author to define library imports based on a range of criteria that can be analysed at compile-time. For instance, you can link against different libs, based on whether you want to link with: multithreading on or off;the shared or static version of the library in question;the shared or static version of the standard runtime library;the debug or release library;the 32-bit or 64-bit library. With the pragma form, all this can be decided via#ifdefpreprocessor tests in one of the library's header files.
I was wondering if there is a way to intercept and modify mouse input before it gets to windows? What I'm wanting to do is intercept mouse motion events, apply some custom scaling and acceleration to the values, and then continue passing them along. I'd need something that can do this before the inputs get to the raw input API or DirectInput.
In order to affect all mouse input, including DirectInput, during logon and the SAS screen, etc., you'll need to load a filter driver into the mouse driver stack. Other people have done it, for examplehttp://www.maf-soft.de/mafmouse/ There should be amoufiltrsample in the Windows DDK which you can use as a starting point. You will most likely want to use a virtual machine for development since errors in a driver on your development machine could be difficult to recover from.
error: dereferencing pointer to incomplete typeThe problem line is "gl->point[0] = (struct list *)&foo;"I read somewhere that I could be storing a declaration. If that is the case I need that explained to me. ``` struct ref { char **name; struct list **point; }; int main ( ) { typedef struct { char **name; struct list **point; } temp; struct ref *gl; gl->name = malloc ( 1024 * sizeof(char *) ); gl->name[0] = "A"; temp foo; foo.name = malloc ( 1024 * sizeof(char *) ); foo.name[0] = "B"; gl->point[0] = (struct list *)&foo; printf ( "!%s!\n" , gl->point[0]->name[0] ); } ```
What'sstruct list? There is no type namedstruct list(at least in what you've shown). Maybe you meantstruct ref?
Given the files: ``` // file: q7a.h static int err_code = 3; void printErrCode (); ///////////// END OF FILE ///////////////// // file: q7a.c #include <stdio.h> #include "q7a.h" void printErrCode () { printf ("%d ", err_code); } ///////////// END OF FILE ///////////////// // file: q7main.c #include "q7a.h" int main() { err_code = 5; printErrCode (); return 0; } ///////////// END OF FILE ///////////////// ``` The output is: ``` 3 ``` My Question is why the output is not 5? Thanks.
static global objects have scope limited to the current compilation unit. In this case you have two compilation units, one for each .c file, and each one has its own err_code.
I'm writing a C++ application which shall be locale independent, so I decided to use UTF-16 as my in-memory representation for strings/texts (the application should be as platform independent as possible). For localize the application's messages i want to use GNU's gettext library. Since this library seems to useGNU's libunistringlibrary internally, i want to use this one too. Is this a good solution for i18n, l10n? I mean it will be a lot of C code in my C++ classes (I don't found a C++ Wrapper for the libunistring library). Stefan PS: It's my first big C++ application.
Use UTF8 instead. see : Should UTF-16 be considered harmful?- YesUTF8, UTF16, and UTF32
Sometimes, when I have a multi-caseif, or a very simplefor, with only two statements, I will forgo braces, instead using the comma. Is this a bad exploitation of the feature, and is it ugly and bad form? Or is it an acceptable way to save time and space? For example: ``` if (something) b = y, c = z--; ``` instead of: ``` if (something) { b = y; c = z--; } ```
It's indeed a clever way to use that syntactic feature of most C-like languages. Personally, I try to stay theleast ambiguous as possiblewhen I code, so I always include{and}in all of myifstatements. It may save time, but I preferclarity: it doesn'tspeed uporslow downthe code execution.
C is always pretty awkward with strings, but it's usually okay to just allocate a char array of size 256 for your string and be on with it. However, what if you want the function to return a string and you don't know the size, since you will be concatenating strings together dozens or hundreds of times? Obviously something like this won't work: ``` char * my_function(int n, char *string){ if (n < 20) { return string; } else { char *new_string = "abcdefghijklmnop"; strcat(string, new_string); return my_function(n--, string); } } ``` So how is this handled in c?
The most straightforward way to do a function that concatenates an arbitrary number of strings is to: Loop through all of the strings and add up theirstrlen().malloc()for the total length.Do all of the concatenation within themalloc'd string and then return it.
I am getting this error whenever I try to run GCC outside of its installation directory (E:\MinGW\bin). So, let's say I am inE:\codeand have a file calledone.c. Running:gcc one.c -o one.exewill give me this error: ``` gcc: CreateProcess: No such file or directory ``` The only workaround is to navigate to its installation directory, run gcc from there, and specify all the other paths. My environmental variablePathcontainsE:\MinGW\bin. Any suggestions to fixing this problem? I am running Windows XP SP3.
According toCode::Blocks wiki, you need to addC:\MinGW\libexec\gcc\mingw32\MinGW-Versionto yourPATH. There is no need to restart, but you need to open another terminal in order to get the newestPATHsettings. For MinGW-w64, that's<mingw install directory>\libexec\gcc\x86_64-w64-mingw32\4.7.0\
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... I made the program but my answer doesnt match. ``` #include<stdio.h> int main() { long unsigned int i,sum=0,x=1,y=2,num; for(i=0;i<4000000;i++) { num=x+y; if(i%2==0) sum+=num; x=y; y=num; } printf("%lu\n",sum); getchar(); return 0; } ```
Three problems I can see: You should start withx = 1, y = 1, since otherwise you skip the first even-valued Fibonacci;Your loop condition should be(x + y) <= 4000000You should testnumfor even-ness, noti. (After these changes, it should be obvious that you can omitientirely, and therefore replace theforloop with awhileloop)
I have some question about header files(I'm talking about c, but I think it will be the same for c++), let's assume I have somemy_ADT.cfile (inside I have implementation of the functions and actualstruct) and alsomy_ADT.hinside I havepointer for my structQuestion:if I use ADTSetfor implementationmy_ADTdo I need to includeset.hto both filesmy_ADT.h and my_ADT.cor including only tomy_ADT.hwill be sufficient (inside my_ADT.c I have#include "my_ADT.h") thanks in advance
There are 3 scenarios set.his needed ONLY inmy_ADT.hset.his needed ONLY inmy_ADT.cset.his needed in bothmy_ADT.handmy_ADT.cset.his not needed at all :-) For scenario 3) add the#include "set.h"to the filemy_ADT.h,document that fact, and#include "my_ADT.h"inmy_ADT.c(with proper include guards, you lose nothing by includingset.halso to the C file). For scenario 2) includeset.honly inmy_ADT.c For scenario 1) includeset.honly inmy_ADT.h
If I have structure definitions, for example, like these: ``` struct Base { int foo; }; struct Derived { int foo; // int foo is common for both definitions char *bar; }; ``` Can I do something like this? ``` void foobar(void *ptr) { ((struct Base *)ptr)->foo = 1; } struct Derived s; foobar(&s); ``` In other words, can I cast the void pointer toBase *to access itsfoomember when its type is actuallyDerived *?
You should do ``` struct Base { int foo; }; struct Derived { struct Base base; char *bar; }; ``` to avoid breaking strict aliasing; it is a common misconception that C allows arbitrary casts of pointer types: although it will work as expected in most implementations, it's non-standard. This also avoids any alignment incompatibilities due to usage of pragma directives.
I have the simplest code "Hello world" ``` #include <stdio.h> /* printf and BUFSIZ defined there */ #include <stdlib.h> /* exit defined there */ #include <mpi.h> /* all MPI-2 functions defined there */ int main(argc, argv) int argc; char *argv[]; { int rank, size, length; char name[BUFSIZ]; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Get_processor_name(name, &length); printf("%s: hello world from process %d of %d\n", name, rank, size); MPI_Finalize(); exit(0); } ``` I have compiled it ``` mpicc -o hello hello.c ``` and tried to run it with 4 processes ``` mpirun -np 4 hello ``` it returns; ``` chasan@ubuntu:~/MpiProgrammes$ mpicc -o hello Hello.c chasan@ubuntu:~/MpiProgrammes$ mpirun -np 4 hello Alarm clock chasan@ubuntu:~/MpiProgrammes$ ``` What could it be ?
try using the command "mpd &"
So my code has in it the following: unsigned short num=0; num=*(cra+3); printf("> char %u\n",num); cra is a char* The problem is that it is getting odd output, sometimes outputting numbers such as 65501 (clearly not within the range of a char). Any ideas? Thanks in advance!
Apparently*(cra+3)is acharof value'\xdd'. Since acharis signed, it actually means -35 (0xddin 2's complement), i.e. 0x...fffffdd. Restricting this to 16-bit gives 0xffdd, i.e. 65501. You need to make it anunsigned charso it gives a number in the range 0–255: ``` num = (unsigned char)cra[3]; ``` Note:1. the signedness ofcharis implementation defined, but usually (e.g. in OP's case) it is signed.2. the ranges ofsigned char,unsigned charandunsigned shortare implementation defined, but again commonly they are -128–127, 0–255 and 0–65535 respectively.3. the conversion fromsigned chartounsigned charis actually -35 + 65536 = 65501.
``` #include <stdio.h> int main(void){ char x [] = "hello world."; printf("%s \n", &x[0]); return 0; } ``` The above code prints out"hello world." How would i print out just"h"? Shouldn't the accessx[0]ensure this?
You should do: ``` printf("%c \n", x[0]); ``` Theformat specifierto print a char isc. So the format string to be used is%c. Also to access an array element at a valid indexiyou need to sayarray_name[i]. You should not be using the&. Using&will give you the address of the element.
If I write ``` #include <stdio.h>; ``` there no error but a warning comes out during compilation pari.c:1:18: warning: extra tokens at end of #include directive What is the reason ?
The reason is that preprocessor directives don't use semicolons. This is because they use a line break to delimit statements. This means that you cannot have multiple directives per line: ``` #define ABC #define DEF // illegal ``` But you can have one on multiple lines by ending each line (except the last) with a \ (or /, I forget).
I can attach a file with libesmtp? Does anyone have a sample code? Thanks FrankIT
No. The library only covers the SMTP protocol, the communication with the server. It does nothing to help you construct a valid MIME document.
What is the proper way to name my revisions? ``` v1.0.3.20 Alpha ``` or ``` Alpha v1.0.3.20 ```
There isn't really any "proper" way. While most people use the dot pattern "x.x.x", it isn't necessarily the proper way to do it. Likewise with your question, it is up to you. I would suppose that the former is more natural to say, and I would prefer it, but it doesn't really matter either way.
I was wondering how to, using C, find out what port a client is currently listening to. ie, I want to know what the source port is, not the destination port. Thanks in advance!
The socket address structure should be filled-in by the connect() system-call. Check it after a successful return from that call.
Is there a way to find out if the machine is 32-bit or 64-bit by writing some code in C?
``` #include <limits.h> /* ... */ printf("This machine's pointers to void, in a program " "compiled with the same options as this one and " "with the same compiler, use %d bits\n", (int)sizeof (void*) * CHAR_BIT); ```
Consider the following code: ``` char* str = "Hello World"; memcpy(str, "Copy\0", 5); ``` A segmentation fault occurs during the memcpy. However, using this code: ``` char str[12]; memcpy(str, "Hello World\0", 12); memcpy(str, "Copy\0", 5); ``` The program does not produce a segmentation fault. Does the problem arise from allocating the memory on the stack versus the data section?
When you use a string literal in gcc the value is placed in read-only memory and cannot be modified. Trying to modify it leads to undefined behaviour. Usually you will get a segmentation fault on Linux when you try to do this. The second example works because you aren't modifying the string literal, you are modifying a copy of it that is stored in variable that is not read-only.
I have created a user interface using GTK+ and C. I was wondering if there are any testing frameworks for testing this interface, similar to how selenium (a software testing framework for web applications) can be used for testing the interfaces of web applications. I want to create some regression tests for my GTK+ interface. Thanks!
I know it has been answered already. However ... Dogtail is very usefull, however Dogtail isn't aunittest framework. From it's own description: dogtail is a GUI test tool and automation framework written in ​Python. It uses Accessibility (a11y) technologies to communicate with desktop applications. dogtail scripts are written in Python and executed like any other Python program. If you want to unit test your GTK applications you should look atGLIB TESTING. A unit testing framework for GLIB written in C for C applications.
Is it safe to convert anint pointertovoid pointerand then back toint pointer? ``` main() { ... int *a = malloc(sizeof(int)); ... *a=10; func(a); ... } void func(void *v) { int x=*(int *)v; ... } ``` Is this a valid way of getting the integer value back in the function?
Yes, it is safe. The Standard says so (6.3.2.3/1) A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
Is it possible to change a process parent?ex: parent A has Child B can I make the parent of B is the Init process without killing A?
Not from outside of process B. From inside process B, you can call fork which makes a copy of your process, then let the original exit. When that happens the new copy B2 will not be a child of A, its parent will be set to 1 (the init process).
Why would I want to do this? ``` typedef struct Frame_s { int x; int y; int z; } Frame_t; ``` Also if I want to create an object what do I use Frame_s or Frame_t?
You would useFrame_t. Withtypedefyou are saying thatFrame_tandstruct Frame_sarethe exact same type. So these are equivalent sentences: ``` // 1 Frame_t f; // 2 struct Frame_s f; ``` I would use: ``` typedef struct { int x; int y; int z; } Frame_t; ``` And always declare my vars like this: ``` Frame_t f1, f2, f3; ``` Confusion usually comes from places where you use that sentence in aC++piece of code. If you useC++with thattypedefyou can use either: ``` // 1 Frame_t f; // 2 Frame_s f; ``` But if you use a plainCcompiler, then//2is invalid.
Assuming that a memory address occupies 4 bytes and a char occupies 1 byte: ``` char** t; t = malloc(5 * sizeof(char*)); int i; for (i = 0; i < 5; i++) t[i] = malloc(sizeof(char) * (i+1)); ```
A minimum of around 35 bytes -- but a typical implementation of malloc will have some minimum allocation size it supports, so in reality, you can expect it to use more memory than that (though exactly how much more will vary). In a typical case, the minimum allocation will be something like 16 or even 32 bytes, in which case most of the sizes you specified above don't really make any difference -- the last 5 allocations will all be of whatever the minimum happens to be. In a typical case, sizes larger than that will be rounded up to the next power of 2 as well. That would give 32 bytes for your first allocation, and either 16 or 32 (i.e., the minimum supported size) for each of your other five, for a total of either 112 or 192 bytes.
Is there any standardized function in GCC or glibc to allocate memory block at aligned pointer? Like_align_malloc()in MSVC?
Since the question was asked, a new function was standardized by C11: ``` void *aligned_alloc(size_t alignment, size_t size); ``` and it is available in glibc (not on windows as far as I know). It takes its arguments in the same order asmemalign, the reverse of Microsoft's_aligned_malloc, and uses the samefreefunction as usual for deallocation. A subtle difference is thataligned_allocrequiressizeto be a multiple ofalignment.
``` int main() { float x=3.4e2; printf("%f",x); return 0; } ``` Output: ``` 340.000000 // It's ok. ``` But if writex=3.1234e2the output is312.339996and ifx=3.12345678e2the output is312.345673. Why are the outputs like these? I think if I writex=3.1234e2the output should be312.340000, but the actual output is312.339996using GCC compiler.
Not all fractional numbers have an exact binary equivalent so it is rounded to the nearest value. Simplified example, if you have 3 bits for the fraction, you can have: ``` 0 0.125 0.25 0.375 ... ``` 0.5 has an exact representation, but 0.1 will be shown as 0.125. Of course the real differences are much smaller.
How to safety parse tab-delimiter string ? for example: test\tbla-bla-bla\t2332 ?
strtok()is a standard function for parsing strings with arbitrary delimiters. It is, however, not thread-safe. Your C library of choice might have a thread-safe variant. Another standard-compliant way (just wrote this up, it isnot tested): ``` #include <string.h> #include <stdio.h> int main() { char string[] = "foo\tbar\tbaz"; char * start = string; char * end; while ( ( end = strchr( start, '\t' ) ) != NULL ) { // %s prints a number of characters, * takes number from stack // (your token is not zero-terminated!) printf( "%.*s\n", end - start, start ); start = end + 1; } // start points to last token, zero-terminated printf( "%s", start ); return 0; } ```
While I'm using%gas format specifier inprintf(), sometimes it rounds up upto 2 places after decimal point, sometimes upto 3 places , someimes upto 4 places...how it does so? Actually where we should use%ginstead of%for%efor floating point numbers?
The%gformat specifier does its rounding just like%fwould do, but if%fwould result in4.234000, then%gwill omit the trailing zeros and print4.234. %gshould be used when it makes the most sense in your output format that some numbers are printed as12345.6, while a slightly bigger number would be printed as1.235e04.
``` int main() { int main=5; printf("%d",main); return 0; } ``` In this case there is no error and the gcc compiler prints 5. But if I write ``` int main() { int printf=5; printf("%d",printf); return 0; } ``` the compiler shows an error..why ?
In your 1st example you "hide" themainfunction, replacing it with anintobject. In your 2nd example you "hide" theprintffunction, replacing it with anintobject. Trying to call anintis illegal. ``` 5("foo"); /* illegal to call "function" 5 */ ```