question
stringlengths
25
894
answer
stringlengths
4
863
This does work ``` LLIST *mylist[10] = {NULL}; ``` But would if I wanted to do this I get errors: ``` int x=10; LLIST *mylist[x] = {NULL}; ``` xcan be any value I'm setting it to 10 for the time being.xis going to be used as a counter.
Support for variable length arrays (which your second example uses) came in the C99 standard, which your compiler may not support. For gcc, you should pass the-std=c99option when compiling.
Can I somehow tell GStreamer to look for plugins in a specified directory?
Use theGST_PLUGIN_PATHenvironment variable to point at the directory you want, or programatically just call: ``` GstRegistry *registry; registry = gst_registry_get(); gst_registry_scan_path(registry, directory); ```
I'm new to using C programming I was wondering if there is a function call that can be used to quickly determine the amount of rows in a text file.
``` #include <stdio.h> #include <stdint.h> uint32_t CountRows(FILE* fp, uint8_t line_delimiter){ uint32_t num_rows = 0; uint16_t chr = fgetc(fp); while(chr != EOF){ if(chr == line_delimiter){ num_rows++; } chr = fgetc(fp); } return num_rows; } ```
hi i am interested in those chars which are representable by ascii table. for that reason i am doing the following: ``` int t(char c) { return (int) c; } ... if(!(t(d)>255)) { dostuff(); } ``` so i am interested in only ascii table representable chars, which i assume after conversion to int should be less than 256, am i right? thanks!
Usually(not always) a char is 8-bits so all chars would typically have a value of less than 256. So your test would always succeed. Also,ASCIIonly goes up to 127, not 255. The characters after that are not standard ASCII, and can vary depending on code pages. If you are dealing with international characters you should probably usewide charactersinstead of char.
``` FILE *fd; if (fd=fopen(fileName,"r") == NULL) { printf("File failed to open"); exit(1); } ``` This is a code snippet. When I compile it with gcc, i get the following warning:- ``` warning: assignment makes pointer from integer without a cast ``` When I putfd=fopen(argv[2],"r")within brackets, the problem gets solved.. I am not able to understandwhere am i converting integer to pointerwhen the brackets are not put.
Due to operator precedence rules the condition is interpreted asfd=(fopen(fileName,"r") == NULL). The result of==is integer,fdis a pointer, thus the error message. Consider the "extended" version of your code: ``` FILE *fd; int ok; fd = fopen(fileName, "r"); ok = fd == NULL; // ... ``` Would you expect the last line to be interpreted as(ok = fd) == NULL, orok = (fd == NULL)?
I want to do some sound synthesis on Mac OS X (and ideally other Unix-like OS) using ANSI C. This is for learning purposes rather than "I need a solution, any solution, quick!" Say I have an 8-bit buffer in my C program that I update 22050 times a second. How can I get my speakers to output that as a waveform?
SDL can play sound buffers. But PortAudio may work better PA will call your C callback when it needs more data, and then you can hand it the next buffer. It's fairly easy actually.
I want to do something in C99 one way, otherwise to perform it another way. What is the#defineto check for? ``` #ifdef C99 ... #else ... #endif ```
There is not an specific#definevalue. Just check__STDC_VERSION__and define it yourself! ;-) ``` #if __STDC_VERSION__ >= 199901L /* C99 code */ #define C99 #else /* Not C99 code */ #endif #ifdef C99 /*My code in C99 format*/ #else /*My code in C99 format*/ #endif ``` EDIT:A more general snippet,from here. I've just changed the defined names, just in case you'll use them a lot on the code: ``` #if defined(__STDC__) # define C89 # if defined(__STDC_VERSION__) # define C90 # if (__STDC_VERSION__ >= 199409L) # define C94 # endif # if (__STDC_VERSION__ >= 199901L) # define C99 # endif # if (__STDC_VERSION__ >= 201112L) # define C11 # endif # endif #endif ```
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed12 years ago. We have to add a new interface to our existing C application. The new interface system requests to our C application and responses to interface will be XML files. We need find a way to read and write XML files. It seems there are many mapping tools available for Java and C++. I did not find anyone for C. Please let me know if there is anyone suitable for C. We will be okay if it's commercial API as well. Thanks
One of the most widely used is libxml2. You can take a lookhere.
What are the various mechanisms using which we can detect if a process execution is leading to memory fragmentation? Are there any tools available for the same? Suggestion for tools which work with 'C' code and can run on Windows, Linux and VxWorks will be helpful.
Just as a suggestion, you may want to try Valgrind. I'm not certain it's what you're looking for, but it may come in handy. http://valgrind.org/
I've got a menu in curses that I'd like to put multi-line descriptions onto. My code puts the description fields on but they don't display if they don't fit on the line. Curses is happy enough printing multi-line text as strings (not as menu descriptions) Any ideas how to get multi-line descriptions working ?
I've given up on this and render my own scrollable list of items instead.
I have a function which accepts a pointer to a struct and sets a member of that struct to a specific value. However, after that assignment code is executed, and my program exits without showing any errors. ``` void swn_addClassToInstance(struct instanceR *instance) { instance->classCount = 0; //nothing below here will run } ``` I'm new to C, and any help would be appreciated.
Most probable cause is thatinstanceis NULL or not initialized, thus causing an access violation. It would be help if you show the code where you allocate and initialize the memory for the structinstancepoints to.
I'm now really diving into my OS project, called ForestOS, but now I'm needing to dive more into some simple and basic things of C. As now I'm having many problems with the correct variable to use and functions. I want resources that only talk about variables, functions and how to develop without headers(stdio.h,math.hand all the others).
Best starting place is probably the bookThe C Programming Language. The book was central to the development and popularization of the C programming language and is still widely read and used today.
Hello I have anunsigned char *that looks (after printf) like this (it's a SHA-1 hash): ``` n\374\363\327=\3103\231\361P'o]Db\251\360\316\203 ``` I need to convert thisunsigned char *to anunsigned int, what do you think it would be the best way to do it ? I have some ideas, but I'm not a C expert so wanted to see someone else ideas before trying my own stuff.
Why would you need a conversion? It's a 160 bit long digest. Digests are used only in two ways: You print a digest with something like ``` for (i = 0; i < 20; ++i) { printf("%2x", digest[i]); } ``` and compare against another digest with something like ``` for (i = 0, equals = 1; i < 20; ++i) { if (a[i] != b[i]) { equals = 0; } } ``` It works just fine the way it is as a 20-byte long array of bytes. You don't have to worry about endianness, word length, nothing.
I have a C++ application that callsSQLite's (SQLite is in C)sqlite3_exec()which in turn can call my callback function implemented in C++. SQLite is compiled into a static library. If an exception escapes my callback will it propagate safely through the C code of SQLite to the C++ code calling sqlite3_exec()?
My guess is that this is compiler dependent. However, throwing an exception in the callback would be a very bad idea. Either it will flat-out not work, or the C code in the SQLite library will be unable to handle it. Consider if this is some code in SQLite: ``` { char * p = malloc( 1000 ); ... call_the_callback(); // might throw an exception ... free( p ); } ``` If the exception "works", the C code has no possible way of catching it, and p will never be freed. The same goes for any other resources the library may have allocated, of course.
What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?
_beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state. Thestrtok()function would be an example. That's been fixed, that state now gets dynamically initialized, at least since VS2005. UsingCreateThread()no longer causes problems.
The C language convention counts array indices from 0. Why do inode numbers start from 1 and not 0? If inode 0 is reserved is for some special use, then what is the significance of inode 0?
0 is used as asentinel valueto indicate null or no inode. similar to how pointers can be NULL in C. without a sentinel, you'd need an extra bit to test if an inode in a struct was set or not. more info here: All block and inode addresses start at 1. The first block on the disk is block 1. 0 is used to indicate no block. (Sparse files can have these inside them) http://uranus.chrysocome.net/explore2fs/es2fs.htm for instance, in old filesystems where directories were represented as a fixed array of file entries, deleting a file would result in setting that entry's inode val to 0. when traversing the directory, any entry with an inode of 0 would be ignored.
Does this... ``` char* myString = "hello"; ``` ... have the same effect as this? ``` char actualString[] = "hello"; char* myString = actualString; ```
No. ``` char str1[] = "Hello world!"; //char-array on the stack; string can be changed char* str2 = "Hello world!"; //char-array in the data-segment; it's READ-ONLY ``` The first example creates an array of size13*sizeof(char)on the stack and copies the string"Hello world!"into it.The second example creates achar*on the stack and points it to a location in the data-segment of the executable, which contains the string"Hello world!". This second string isREAD-ONLY. ``` str1[1] = 'u'; //Valid str2[1] = 'u'; //Invalid - MAY crash program! ```
I have a command line C program for which I use the calloc() function to assign some memory for a struct which also has a struct in it with some memory assigned. If I use the free() function to release the memory from the parent struct, will it also release the memory from the child struct? Or should I release the memory from the child struct first?
Its a simple rule, for every memory allocation you do, you have to explicitly release the memory yourself. So, you need to release the child memory yourself.
considering a pointer to a struct ``` struct a_struct { int A; }; ``` Is it ok to do : ``` struct a_struct *ptr; //... if( ptr != NULL && ptr->A == 1) { //work with ptr struct } ``` or should you Test if the pointer is valid before testing for on of its field. ``` if(ptr != NULL) { if(ptr->A == 1) { //work with ptr struct } } ```
Yes, that's ok. The&&operator short-circuits in C, soptr->A == 1will only be evaluated ifptris non-null.
I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?
You need a temporary variable: ``` void*temp = array[4]; array[4]=array[1]; array[1] = temp; ``` Edit Fixed first line.
I have below lines in my code written in C on unix platform. Please let me know why I am getting core dumped in closedir() function. I could successfully opened the directory specified by path. ``` if (opendir(MyDir) != NULL ) { closedir((DIR *) MyDir); exit 0; } ```
closedir()takes aDIR *, not achar *. Wishingclosedir()did that is not going to work. Try: ``` #include <sys/types.h> #include <dirent.h> DIR *dir; if ((dir = opendir(MyDir)) != NULL) closedir(dir); ``` Also, it seems you added a cast in(DIR *) MyDirto suppress a compiler warning. When a compiler gives you a warning, you should find out why it is doing so. Suppressing the warning is hardly the right thing to do.
Why do I get segmentation fault in this function: ``` #include <stdio.h> #include <stdlib.h> #include "math.h" vec_t mtrx_multiple (sparse_mat_t a, vec_t c) { vec_t result; int i; result.n = a.n; printf("result.n: %d\n", result.n); result.vec = malloc(a.n * sizeof *result.vec); for(i=0; i<a.n; i++) result.vec[i] = c.vec[i] * a.a[a.ja[i]]; return result; } ``` The structure is: ``` typedef struct { int n; int *vec; } vec_t; typedef struct { int *a; int *ia; int *ja; int n; } sparse_mat_t; ``` Thanks for help
I suspect the problem is witha.a[a.ja[i]], you should try verifying the valuesa.ja[i]before using them to indexa.a. It would be useful to know howais initialised, and also on which line the segfault occurs.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been done so far to solve it.Closed9 years ago.Improve this question Where can I find a C programming reference that will list the declaration of built-in functions?
"The C Programming Language"
I've got a menu in curses that I'd like to put multi-line descriptions onto. My code puts the description fields on but they don't display if they don't fit on the line. Curses is happy enough printing multi-line text as strings (not as menu descriptions) Any ideas how to get multi-line descriptions working ?
I've given up on this and render my own scrollable list of items instead.
I have a function which accepts a pointer to a struct and sets a member of that struct to a specific value. However, after that assignment code is executed, and my program exits without showing any errors. ``` void swn_addClassToInstance(struct instanceR *instance) { instance->classCount = 0; //nothing below here will run } ``` I'm new to C, and any help would be appreciated.
Most probable cause is thatinstanceis NULL or not initialized, thus causing an access violation. It would be help if you show the code where you allocate and initialize the memory for the structinstancepoints to.
I'm now really diving into my OS project, called ForestOS, but now I'm needing to dive more into some simple and basic things of C. As now I'm having many problems with the correct variable to use and functions. I want resources that only talk about variables, functions and how to develop without headers(stdio.h,math.hand all the others).
Best starting place is probably the bookThe C Programming Language. The book was central to the development and popularization of the C programming language and is still widely read and used today.
Hello I have anunsigned char *that looks (after printf) like this (it's a SHA-1 hash): ``` n\374\363\327=\3103\231\361P'o]Db\251\360\316\203 ``` I need to convert thisunsigned char *to anunsigned int, what do you think it would be the best way to do it ? I have some ideas, but I'm not a C expert so wanted to see someone else ideas before trying my own stuff.
Why would you need a conversion? It's a 160 bit long digest. Digests are used only in two ways: You print a digest with something like ``` for (i = 0; i < 20; ++i) { printf("%2x", digest[i]); } ``` and compare against another digest with something like ``` for (i = 0, equals = 1; i < 20; ++i) { if (a[i] != b[i]) { equals = 0; } } ``` It works just fine the way it is as a 20-byte long array of bytes. You don't have to worry about endianness, word length, nothing.
I have a C++ application that callsSQLite's (SQLite is in C)sqlite3_exec()which in turn can call my callback function implemented in C++. SQLite is compiled into a static library. If an exception escapes my callback will it propagate safely through the C code of SQLite to the C++ code calling sqlite3_exec()?
My guess is that this is compiler dependent. However, throwing an exception in the callback would be a very bad idea. Either it will flat-out not work, or the C code in the SQLite library will be unable to handle it. Consider if this is some code in SQLite: ``` { char * p = malloc( 1000 ); ... call_the_callback(); // might throw an exception ... free( p ); } ``` If the exception "works", the C code has no possible way of catching it, and p will never be freed. The same goes for any other resources the library may have allocated, of course.
What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?
_beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state. Thestrtok()function would be an example. That's been fixed, that state now gets dynamically initialized, at least since VS2005. UsingCreateThread()no longer causes problems.
The C language convention counts array indices from 0. Why do inode numbers start from 1 and not 0? If inode 0 is reserved is for some special use, then what is the significance of inode 0?
0 is used as asentinel valueto indicate null or no inode. similar to how pointers can be NULL in C. without a sentinel, you'd need an extra bit to test if an inode in a struct was set or not. more info here: All block and inode addresses start at 1. The first block on the disk is block 1. 0 is used to indicate no block. (Sparse files can have these inside them) http://uranus.chrysocome.net/explore2fs/es2fs.htm for instance, in old filesystems where directories were represented as a fixed array of file entries, deleting a file would result in setting that entry's inode val to 0. when traversing the directory, any entry with an inode of 0 would be ignored.
Does this... ``` char* myString = "hello"; ``` ... have the same effect as this? ``` char actualString[] = "hello"; char* myString = actualString; ```
No. ``` char str1[] = "Hello world!"; //char-array on the stack; string can be changed char* str2 = "Hello world!"; //char-array in the data-segment; it's READ-ONLY ``` The first example creates an array of size13*sizeof(char)on the stack and copies the string"Hello world!"into it.The second example creates achar*on the stack and points it to a location in the data-segment of the executable, which contains the string"Hello world!". This second string isREAD-ONLY. ``` str1[1] = 'u'; //Valid str2[1] = 'u'; //Invalid - MAY crash program! ```
I have a command line C program for which I use the calloc() function to assign some memory for a struct which also has a struct in it with some memory assigned. If I use the free() function to release the memory from the parent struct, will it also release the memory from the child struct? Or should I release the memory from the child struct first?
Its a simple rule, for every memory allocation you do, you have to explicitly release the memory yourself. So, you need to release the child memory yourself.
considering a pointer to a struct ``` struct a_struct { int A; }; ``` Is it ok to do : ``` struct a_struct *ptr; //... if( ptr != NULL && ptr->A == 1) { //work with ptr struct } ``` or should you Test if the pointer is valid before testing for on of its field. ``` if(ptr != NULL) { if(ptr->A == 1) { //work with ptr struct } } ```
Yes, that's ok. The&&operator short-circuits in C, soptr->A == 1will only be evaluated ifptris non-null.
I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?
You need a temporary variable: ``` void*temp = array[4]; array[4]=array[1]; array[1] = temp; ``` Edit Fixed first line.
I have below lines in my code written in C on unix platform. Please let me know why I am getting core dumped in closedir() function. I could successfully opened the directory specified by path. ``` if (opendir(MyDir) != NULL ) { closedir((DIR *) MyDir); exit 0; } ```
closedir()takes aDIR *, not achar *. Wishingclosedir()did that is not going to work. Try: ``` #include <sys/types.h> #include <dirent.h> DIR *dir; if ((dir = opendir(MyDir)) != NULL) closedir(dir); ``` Also, it seems you added a cast in(DIR *) MyDirto suppress a compiler warning. When a compiler gives you a warning, you should find out why it is doing so. Suppressing the warning is hardly the right thing to do.
I want to send a file in C++ over network (for a chat program) what should I do?
Take a look athttp://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/examples.html. The Iostreams example should give you the first good step. Asio is a portable network library of the boost project. Boost is available for most platforms available today. You can stream in the file and stream out it into the TCP stream.
How to split a string into tokens by'&'in C?
strtok / strtok_r ``` char *token; char *state; for (token = strtok_r(input, "&", &state); token != NULL; token = strtok_r(NULL, "&", &state)) { ... } ```
I have a bug where acharpointer is turning outNULL. I've been all over gdb with the program, watching read/write at the memory address, and stepping through the instructions, but so far the bug stumps me. I've ran valgrind and the only thing coming up is the read at the crash (strcmp). What else can I do to track this down?
You can try awatchpoint. You watch an expression and when the value of that expression changes, gdb will stop execution. You can watch a variable: ``` watch charptr ``` This will break every time charptr changes. If you just wanted to know when it changes from non-NULL to NULL (or vice versa), you can use: ``` watch charptr == 0 ```
In C, arrays are passed to functions as pointers. Structures can be passed to functions either by value or by address (pointer). Is there any specific reason why we can not pass array by value but we can pass structre by value ?
In C,everythingis passed by value. There is another rule that says that in most contexts, the name of an array is equivalent to a pointer to its first element. Passing an array to a function is such a context. So, the special case is not that arrays are passed by reference, the special case isthe rule about arrays decaying to pointers. This gives one the impression that an array is passed by reference (which it effectively is, but now you know why!) The post in my link above explains in more detail about the type of an array in different contexts.
I have two tasks for an assignment, one return the number of bits in type int on any machine. I thought I would write my function like so: ``` int CountIntBitsF() { int x = sizeof(int) / 8; return x; } ``` Does that look right? The second part is to return the number of any bits of any data type with a macro, and the macro can be taken from limits.h. I looked up limits.h on my machine, and alsohttp://www.opengroup.org/onlinepubs/007908799/xsh/limits.h.html, but I don't think I really understand how any of those would return the number of bits in any data type. Any thoughts? Thanks.
The fundamental unit of storage is a char. It is not always 8 bits wide. CHAR_BIT is defined in limits.h and has the number of bits in a char.
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse: Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.
If you are okay with the GPL license, you wantGNU getopt.
What's the most elegant way to return astd::listobject from a shared lib function (implemented by C++ code) to a C consumer? I know forstd::vector, we can return the address of the 1st element of the vector and have the consumer treat it as an array, but std::list is implemented as a linked lis.
Copy thestd::listto astd::vectorand return the address of the first element, as you already mentioned. (Of course, this may mean that you don't want to be using astd::listin the first place.) (This solution assumes that the object being accessed isownedby the C++ library -- If this isn't the case, you may need to consider allocating the memory from your C code and passing a pointer into the C++ library to copy the data.)
Hello I have been usingLibTomCryptto use SHA1 encryption ( for data integrity checking ) on mobile devices (iPhone OS and Android for the moment ). I was wondering if anyone is using anything else, things to consider are Portability ( C preferred but C++ is also an option ), and libraries size ( small == better for my particular needs ). Thanks
You might write a wrapper class that callsCommonCryptoroutines if you're on an iPhone, to reduce your library size requirements and enforce portability. Your wrapper, for example, would call other routines if compiled on another platform. The nice thing about CommonCrypto is that it is pre-built by Apple. Calls to it are also entirely in C.
On Windows, ``` char c; int i; scanf("%d", &i); scanf("%c", &c); ``` The computer skips to retrieve character from console because '\n' is remaining on buffer. However, I found out that the code below works well. ``` char str[10]; int i; scanf("%d", &i); scanf("%s", str); ``` Just like the case above, '\n' is remaining on buffer but why scanf successfully gets the string from console this time?
From the gcc man page (I don't have Windows handy): %c: matches a fixed number of characters, always. The maximum field width says how many characters to read; if you don't specify the maximum, the default is 1. It also does not skip over initial whitespace characters. %s: matches a string of non-whitespace characters.It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something.[ This clause should explain the behaviour you are seeing. ]
How do I get the list of all environment variables in C and/or C++? I know thatgetenvcan be used to read an environment variable, but how do I list them all?
The environment variables are made available tomain()as theenvpargument - a null terminated array of strings: ``` int main(int argc, char **argv, char **envp) { for (char **env = envp; *env != 0; env++) { char *thisEnv = *env; printf("%s\n", thisEnv); } return 0; } ```
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse: Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.
If you are okay with the GPL license, you wantGNU getopt.
What's the most elegant way to return astd::listobject from a shared lib function (implemented by C++ code) to a C consumer? I know forstd::vector, we can return the address of the 1st element of the vector and have the consumer treat it as an array, but std::list is implemented as a linked lis.
Copy thestd::listto astd::vectorand return the address of the first element, as you already mentioned. (Of course, this may mean that you don't want to be using astd::listin the first place.) (This solution assumes that the object being accessed isownedby the C++ library -- If this isn't the case, you may need to consider allocating the memory from your C code and passing a pointer into the C++ library to copy the data.)
Hello I have been usingLibTomCryptto use SHA1 encryption ( for data integrity checking ) on mobile devices (iPhone OS and Android for the moment ). I was wondering if anyone is using anything else, things to consider are Portability ( C preferred but C++ is also an option ), and libraries size ( small == better for my particular needs ). Thanks
You might write a wrapper class that callsCommonCryptoroutines if you're on an iPhone, to reduce your library size requirements and enforce portability. Your wrapper, for example, would call other routines if compiled on another platform. The nice thing about CommonCrypto is that it is pre-built by Apple. Calls to it are also entirely in C.
On Windows, ``` char c; int i; scanf("%d", &i); scanf("%c", &c); ``` The computer skips to retrieve character from console because '\n' is remaining on buffer. However, I found out that the code below works well. ``` char str[10]; int i; scanf("%d", &i); scanf("%s", str); ``` Just like the case above, '\n' is remaining on buffer but why scanf successfully gets the string from console this time?
From the gcc man page (I don't have Windows handy): %c: matches a fixed number of characters, always. The maximum field width says how many characters to read; if you don't specify the maximum, the default is 1. It also does not skip over initial whitespace characters. %s: matches a string of non-whitespace characters.It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something.[ This clause should explain the behaviour you are seeing. ]
How do I get the list of all environment variables in C and/or C++? I know thatgetenvcan be used to read an environment variable, but how do I list them all?
The environment variables are made available tomain()as theenvpargument - a null terminated array of strings: ``` int main(int argc, char **argv, char **envp) { for (char **env = envp; *env != 0; env++) { char *thisEnv = *env; printf("%s\n", thisEnv); } return 0; } ```
I usepthread_create(&thread1, &attrs, //... , //...);and need if some condition occured need to kill this thread how to kill this ?
First store the thread id ``` pthread_create(&thr, ...) ``` then later call ``` pthread_cancel(thr) ``` However, this not a recommended programming practice! It's better to use an inter-thread communication mechanism like semaphores or messages to communicate to the thread that it should stop execution. Note that pthread_kill(...) does not actually terminate the receiving thread, but instead delivers a signal to it, and it depends on the signal and signal handlers what happens.
How would I go about taking a number like123456and having it print as1 2 3 4 5 6?
The simplest way of doing this (though not the fastest) would probably be to firstsprintfthe number to a string buffer, and then loop through the bufferprintf-ing one character and one space at a time. There's no built-in way of doing this within the standardprintfformatting.
Really off the wall question here, but is there a way to compile a string of C code in GCC without any medium to hold that string (eg. a source file)? Something along the lines of: ``` $ gcc "#include <stdio.h> int main( void ){ printf('hello world'); return 0;}" -o test ``` Feels really dirty, but it would be really nice if there was some simple way to do that type of thing.
If you use-as the input file in the command line, gcc reads from standard input. Since there is no file name extension gcc could use to find out the language that should be compiled, it has to be specified with the-xflag: ``` $ gcc -x c -o tst - <<EOF > #include <stdio.h> > int main(void) { > printf("Hello world\n"); > } > EOF $ ./tst Hello world ```
The title says everything. I am talking about C/C++ specifically, because both consider this as "implementation issue". I think, defining a standard interface can ease building a module system on top of it, and many other good things.What could C/C++ "lose" if they defined a standard ABI?
The freedom to implement things in the most natural way on each processor. I imagine that c in particular has conforming implementations on more different architectures than any other language. Abiding by a ABI optimized for the currently common, high-end, general-purpose CPUs would require unnatural contortions on some the odder machines out there.
I know in C++, you're able to peek at the next character by using:in.peek();. How would I go about this when trying to "peek" at the next character of a file in C?
fgetc+ungetc. Maybe something like this: ``` int fpeek(FILE *stream) { int c; c = fgetc(stream); ungetc(c, stream); return c; } ```
I have a program. I want it to be able to mmap a particular region of memory over different runs. I have the source code of the program. C/C++I control how the program is compiled. gccI control how the program is linked. gccI control how the program is run (Linux). I just want to have this particular region of memory, say 0xabcdabcd to 0xdeadbeef that I mmap to a particular file. Is there anyway to guarantee this? (I have to somehow make sure that other things aren't loaded into this particular region). EDIT: How do Imakesure that nothing else takes this particular region in memory?
You need to do two things: Specify the starting address as the first argument to mmap.Include the MAP_FIXED flag. For the starting address, you need to make sure it's a multiple of the pagesize. To get the pagesize, use the callsysconf(_SC_PAGESIZE)(that's the appropriate call on Linux, other platforms may be different).
In my programming class, I don't understand what the value ofprintf("World")is (question my prof is asking)? What value doesprintfreturn? He says it is 5, but I don't know why.
Becauseprintf()returns the number of bytes that were output. For "World", that's 5: 5 characters, 5 bytes. Count 'em... When you're learning a new language, it's always a good idea to read the documentation for the new functions you're learning how to use. If you follow the link above, you'll find the following documented for the return value ofprintf(): Upon successful completion, the fprintf() and printf() functions shall return the number of bytes transmitted. If your professor is asking you this question, you'll probably find that this was documented in the class textbook as well.Readit,learnit,loveit!
gcc c89 I am came across this code. ``` typedef __int32 int32_t; typedef unsigned __int32 uint32_t; typedef __int64 int64_t; typedef unsigned __int32 uint64_t; ``` I am just wondering that is the __int32 I didn't think that was a type? Why the underscore? Does this mean I could do things like this? ``` typedef __int32 myInt32; ``` Many thanks for any advice,
The type is not standard, but is supported on your compiler. Symbols that begin with an underscore or contain two underscores are reserved by the standard for your compiler's implementation. SeeWhy do people use __(double underscore) so much in C++(The question is about C++ but the reason is the same)
Are there any portable open source libraries that support sample-based synthesis and encapsulate producing and mixing simple PCMs? I really need something minimalistic and decoupled from operating system audio output mechanisms.
csoundhas aC apiand can handle PCM.ffmpegcan also convert lots of popular formats in PCM.
here is a code sample ``` void something() { char c[100]; scanf("%s",c); char c2[100]=c; } ``` my problem is when i do this assignment an error says that i can't assign ``` char * "c" to char[] "c2"; ``` how can i achieve this assignment?
You'll have to usestrcpy()(or similar): ``` ... char c2[100]; strcpy(c2, c); ``` You can't assign arrays using the=operator.
``` #include <stdio.h> int main() { // Declarations int iCount1, iCount2; int iXXTest[4][3] = {{2, 3, 5}, {9, 8, 6}, {1, 8, 4}, {5, 9, 7}}; // Walk through 1st dimension for (iCount1 = 0; iCount1 < 4; iCount1++) { // Walk through 2nd dimension for (iCount2 = 0; iCount2 < 3; iCount2++) { printf("iXXTest[%d][%d] is at address %d and has a value of %d.\n", iCount1, iCount2, &iXXTest[iCount1][iCount2], iXXTest[iCount1][iCount2]); } } return 0; } ``` This line generates a warning: ``` printf("iXXTest[%d][%d] is at address %d and has a value of %d.\n", iCount1, iCount2, &iXXTest[iCount1][iCount2], iXXTest[iCount1][iCount2]); ``` int format, pointer arg (arg 4) What is this warning about and how can I resolve it?
It means that you've used the format of %d (for integer) but the argument is actually a pointer. Use %p instead.
I have a linux shared library (.so) compiled with a specific version of libc (GLIBC2.4) and I need to use it on a system with different version of libc. I do not have sources for the library in question so I cannot recompile for the new system. Is it somehow possible to change the dependencies in that library to a different libc?
If you need the .so on a system with an older glibc, you would need the source code and recompile/relink it with the older glibc. The alternative is to install the required glibc on the old system in a non-default location and adjust the LD_LIBRARY_PATH for the executable that needs this .so If there's a newer glibc rather, it should normally not be a problem as glibc tend to be backwards compatible.
What's the best practice to include existing C Libraries into an iPhone Project? I searched the Internet and actually found some pieces but nothing that explains the exact way to do it. I'm trying to include the followingCitrix XenServer SDK Library. Any help is appreciated. Thanks!
You could try to build a static library and link against that.I didn't try that myself yet, but as far as I could see, libxenserver has libxml2 as its only dependency.libxml2 is available on the iPhone so you might have a chance.To get started, create a Cocoa touch static library project and drag the C files into the project.Now you have to figure out where to place the include files.This might get a bit tricky and you will start with a lot of compile errors, but to me it seems possible to get it compiled.
This question already has answers here:Why is main() in java void?(4 answers)Closed5 years ago. With respect to C/C++ main() must always return an integer(zero to indicate success and non-zero to indicate failure). I can understand this as the program is run it becomes a process and every process should have an exit status, which we obtain by doing echo $? from shell after the process gets over. Now I don't understand why is the main method does not return anything in Java? Has it got anything to do with the fact that the program is run on JVM and the JVM process is reposnsible for the returning of exit status? Please clarify. Thanks,Roger
Designed when multi-threading was already a common thing, java said (by design) "good bye" to the idea that when 'main' returns the program is done. That's why there's no return value. As the others said useSystem.exitwhen you want to exit with return code.
How to calculate the length of a string in C efficiently (in time)? Right now I'm doing: ``` int calculate_length(char *string) { int length = 0; while (string[length] != '\0') { length++; } return length; } ``` But it's very slow compared to strlen() for example, is there any other way to do it? Thanks. EDIT: I'm working in a freestanding environment, I'm not allowed to use any external lib including "string.h".
From theFreeBSD source code: ``` size_t strlen(const char *str) { const char *s; for (s = str; *s; ++s); return(s - str); } ``` Compared to your code, this probably maps very nicely to an assembler instruction, which can explain a big performance difference.
I have a custom allocator function which uses sbrk() to obtain memory. How do I release this memory when it's no longer needed? Is there a function equivalent to free() for malloc() ? or do I have to use brk() to set the end of the data segment ?
You need to usebrkorsbrkagain to shrink. In the end the only way you have to modify the amount of memory(apart from mmap like syscalls), is to increase or decrease the heap, so you move it up withsbrkorbrkand you move it down withbrkorsbrkwith a negative increment.
Is there a possibility that strcat can ever fail? If we pass some incorrect buffer or string, then it might lead to memory corruption. But, apart from that is it possible that this function can return failure like strcat returning NULL even if destination string passed is Non-NULL? If no, why strcat has a return type specified at all? I have just mentioned strcat as an example. But, this question applies to many string and memory related (like memcpy etc) functions. I just want to know the reasoning behind some of these seemingly "always successful" functions having return types.
Returning a pointer to the target string makes it easy to use the output in this sort of (perhaps not-so-clever) way: ``` int len = strlen(strcat(firstString, secondString)); ```
In C, I want a block of statements to be executed repeatedly everytseconds. How do I do this?
This cannot be done in standard C, you need to use some platform-specific API. One popular choice is POSIX'alarm()function. This is a "pure" aynchronuous solution. It's of course possible to measure and handle time in other ways, but they're still platform-dependent. You could usesleep()(again, POSIX) to just block. If you combine that with your desired statements in a loop, that should work too.
Will the strlen() function below get called just once (with the value stored for further comparisons); or is it going to be called every time the comparison is performed? ``` for (i = 0; i < strlen(word); i++) { /* do stuff */ } ```
That's implementation-dependent. Usually, it gets called every time, but, if the compiler can see thatwordnever changes, and thatstrlenis a pure function (no side effects), it can lift the call. See:http://underhanded.xcott.com/?page_id=15for a well-known example of this being exploited. :-)
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.Closed11 years ago. A friend of mine was asked the following question a Yahoo interview: Given a string of the form "abbccc" print "a1b2c3". Write a function that takes a string and return a string. Take care of all special cases. How would you experts code it? Thanks a lot
``` if (0==strcmp(s, "abbccc")) return "a1b2c3"; else tip_the_interviewer(50); ``` Taken care of.
I wonder if we can get the file name including its path from the file object that we have created for the file name in C and in C++ respectively ``` FILE *fp = fopen(filename, mode); // in C ofstream out(filename); // in C++ ifstream in(filename); // in C++ ``` Thanks!
You can't, in general. The file may not ever have had a file name, as it may be standard input, output, or error, or a socket. The file may have also been deleted; on Unix at least, you can still read to or write from a file that has been deleted, as the process retains a reference to it so the underlying file itself is not deleted until the reference count goes to zero. There may also be more than one name for a file; you can have multiple hard links to a single file. If you want to retain the information about where a file came from, I would suggest creating your own struct or class that consists of a filename and the file pointer or stream.
I encountered a bug that has me beat. Fortunately, I found a work around here (not necessary reading to answer this q) - http://lists.apple.com/archives/quartz-dev/2009/Oct/msg00088.html The problem is, I don't understand all of it. I am ok with the event taps etc, but I am supposed to 'set up a thread-safe queue) using MPQueue, add events to it pull them back off later. Can anyone tell me what an MPQueue is, and how I create one - also how to add items and read/remove items? Google hasn't helped at all.
It'sone of the Multiprocessing Services APIs. … [A] message queue… can be used to notify (that is, send) and wait for (that is, receive) messages consisting of three pointer-sized values in a preemptively safe manner.
Does anyone know how to save gdb settings (like "set print pretty on" or "set print elements 0", both fromhere)? I don't want to set my configuration every time that I will use gdb :/ I searched in google and SO, but I found nothing.
Add any commands you want to auto run in the.gdbinitfile in your home directory.
I want to be able to determine at runtime what the sector size is for a give filesystem. C code is acceptable. for example I format my Data partitions with a 32k sector size that have lots of large video files. I want to be able to get this value at runtime.
I think you wantstatvfs(if by pagesize you mean sector size?) which from what I remember works linux and OSX. I think you need to use the f_bsize field but I unfortunately do not have a linux box to test against atm. For windows you want theGetDiskFreeSpacefunction.
I am new to GTK+ programming. I came across an API calledg_main_loop(). I have used it in my code but I am still unaware that how exactly it works. Can somebody explaing_main_loop()with small code snippet?
I recommendreading the documentation, starting with the linked-to functiong_main_loop_new(). Basically, letting glib "own" your application's main loop makes it easier to support things like "pluggable" event sources; where your application listens to both (for example) events coming from GTK+ widgets, and a network socket or Unix pipe. These are things that need to be hooked together at a fairly low level in an application's main loop, and letting glib own those parts makes it easier. There are glib data structures (likeIO channels) that are compatible with the main loop and allow you to add things to the set of inputs the loop manages. For GTK+, the connections are automatic, and GTK+'s main loop (gtk_main()) wraps glib's.
I saw this in some C code: ``` Wininfo W = { sizeof(Wininfo) }; ``` What the heck does this mean?
This code is initializing astructusing funky C initializer syntax to initialize each field in order of declaration, seehttp://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=421. An important side-effect in the case of this example is that remaining fields one doesnt specify values for get initialized to zeros. This trick is a relatively common one in Win32 APIs - the API requires the size to be pre-set as a way of indicating the version the client code is compiled against - in many of these cases, one is also expected to clear the buffer, which would ordinarily involve a separate call to e.g.memsetprior to initializing the size field with thesizeof. See alsoStruct initialization of the C/C++ programming language?for related examples
I have a program that accepts two file names as arguments: it reads the first file in order to create the second file. How can I ensure that the program won't overwrite the first file? Restrictions: The method must keep working when the file system supports (soft or hard) linksFile permissions are fixed and it is only required that the first file is readable and the second file writeableIt should preferably be platform-neutral (although Linux is the primary target)
On linux, open both files, and usefstatto check ifst_ino(edit:) andst_devare the same.openwill follow symbolic links. Don't usestatdirectly, to prevent race conditions.
is there an elegant way to start a 64 bit process from an 32 bit compiled application? The problem is that i need to compile one part in 32bit Sparc V8 mode. The other part is written for a faster 64 bit environment (no emulation on 64bit multiplication). I want to synchronize them using semaphore and communicate via shared memory. Man pages for fork, system etc. show that the parent process gets suspended until the child process terminates. Is there a better way to do so because i dont want to start the processes manually. best regard Bernhard
Use fork() then exec(). Generally multi-process stuff remains the same even in a mixed environment.
I know I can convert SQL timestamp to unix timestamp, using the following way. ``` SELECT extract(epoch FROM now()); ``` Now, I have a stored procedure function, which will directly return a table row to the caller. One of the row field is "timestamp" type. In my application, I am using libpq. I wish to use libpq functions (or any c/c++ function), to convert "2010-01-11 13:10:55.283" into unix timestamp. Off course, I can create another stored procedure named ``` SQLTimestamp2UnixTimestamp SELECT extract(epoch FROM $1); ``` But I just wish to accomplish this task with a single c/c++ function call, without involving stored procedure. Any suggestion? Thanks!
Why not simply (untested): ``` /* PostgreSQL sent "date" */ strptime(date, "%Y-%m-%d %H:%M:%S", &result); ``` then ``` strftime(epoch, MAX, "%s", result); /* print epoch */ ```
How can I lock a file for a specified period of time (10 seconds) using the C language in Ubuntu Linux ?
It works like this: ``` #include <io.h> #include <sys/file.h> ... int f = open ("filename", O_RDONLY); if (f < 0) error(); if (flock (f, LOCK_EX)) error(); sleep (10); if (flock (f, LOCK_UN)) error(); ... ```
I am trying to add a new IP address to a local network adapter in Windows using the Windows API. Are there functions to do this in the Windows API, and if so, what are they? I am not trying to create virtual network adapters, but simply trying to assign multiple IP addresses to the same adapter.
Take a look atAddIPAddressandDeleteIPAddress.
I have a function which is called explicitly by 4 other functions in my code base. Then in turn each of these functions is called by at least 10 other functions throughout my code. Iknowthat I could, by hand, trace one of these function calls to the main function of my program (which has 30 function calls) but it seems like this would be a better job for the computer. I just want to know which of the functions inmain()is calling this buried function. Does anyone know of any software that could help? Also, using a debugger is out of the question. That would have been too easy. The software only runs on a hand held device.
doxygen, correctly configured, is able to output an HTML document with navigable caller list and called-by list for every function in your code. You can generate call graphs as well.
I have a simple C DLL (not COM). I have also a C# 2.0 application that runs it (dllimport). The dll is placed in the exe of the application. I know that the dll is ok and also that my application that calls it success reading it, but when I move them to another computer it says that it can load the dll. The error : "Unable to load the dll name.dll . This application has failed to start because the application configuration is incorrect." I used visual studio 2005 to create the dll. The targer computer is a side by side one. When I took the folder of the side by side contains the CRT it didn't run. Thanks
The C Dll can have various dependencies. Try using Dependency Walker tool to determine if there are any of them.
I am trying to understand what the following line of the worst-ever-seen C code (fromubootproject) mean: ``` rc = ((ulong (*)(bd_t *, int, char *[]))addr) (bd, --argc, &argv[1]); ``` What is it? A function call? Can it be more readable? Thanks in advance for your help!
Yes, it's a function call. It casts the value inaddrto a function pointer which accepts(bd_t *, int, char *[])as arguments and returns aulong, and calls the function. It could be sugared into: ``` typedef ulong (*bd_function)(bd_t *bd, int argc, char *argv[]); bd_function bdfunc = (bd_function) addr; rc = bdfunc(bd, --argc, &argv[1]); ``` This might be overkill, to introduce atypedefif this only happens once, but I feel it helps a lot to be able to look at the function pointer's type separately.
Can someone explain how does less than op work in C? In particular how it works when types of left hand side and right hand side operands are different? Does it compare them based on type of the first one or the second one?
C specifies standard conversions for different types. The rules are a bit complex, but basically the "smaller" type gets temporarily converted to the larger type, So if you compare an int with a char, the char will be converted to an int, for the purposes of the comparison only.
A function returns an aray of integers and I want it to pass to another function which searches for some pattern. But the second function expects a string. Example: ``` int IArray = {1, 2, 3}; // should be coverted into "123" ``` Is there a direct function available? If not, how do I convert the array of integers into a string?
There is no direct function to do that. You'll have to usesprintf.
I am developing C++ in NetBeans 6.7.1. When I press CTRL + space for autocomplete there is shown only method's signature. I am using JavaDoc for commenting my code but NetBeans doesn't show it. I have installed Doxygen plugin but it is only for generating complete documentation. Is there any way how to force the IDE to show signature and JavaDoc for C++ please? I think that it should not be a problem because this functionality is currently implemented for Java. Thanks a lot.
So I asked on NetBeans forum thisquestion( using friend's account because I don't have my own ) and there is the conclusion: It is impossible and it is in requests.
Is it possible to distribute only the bytecode version (.pyc file) of a Python script instead of the original .py file? My app embeds the Python interpreter and calls PyImport_Import to load a script. How can I tell it to look for a .pyc file and import that?
Use thefreezetool, which is included in the Python source tree asTools/freeze. It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules. Note that freeze requires a C compiler. Other utilities: 1-PyInstaller 2-Py2Exe 3-Squeeze 4-cx_freeze more info on effbot.org
In the book "Complete Reference of C" it is mentioned thatcharis by default unsigned. But I am trying to verify this with GCC as well as Visual Studio. It is taking it assignedby default. Which one is correct?
The book is wrong. The standard does not specify if plaincharis signed or unsigned. In fact, the standard defines three distinct types:char,signed char, andunsigned char. If you#include <limits.h>and then look atCHAR_MIN, you can find out if plaincharissignedorunsigned(ifCHAR_MINis less than 0 or equal to 0), but even then, thethree types are distinctas far as the standard is concerned. Do note thatcharis special in this way. If you declare a variable asintit is 100% equivalent to declaring it assigned int. This is always true for all compilers and architectures.
how do you reverse and rotate hex numbers and return the number in C with bitwise operators? for example: ``` 0xabcd -> 0xdcba 0xabcd -> 0xdabc ```
It's hard to know where to begin with this question. Plus I smell homework. Some points: There is no such thing as a "hex number". Hex is just a notation. How do you reverse and rotate decimal numbers and return the number in C? For example:1776 -> 67711776 -> 6771?To solve this problem, you need a deep understanding of positional notation, whether it's base 10, base 16, base 2, or what have you.All you need can be had by adding, subtracting, multiplying, and dividing.Thoseare operations onnumbers. Modulus is also very helpful.If you happen to want to multiply or divide by a power of two, I commend to you the C left shift<<and right shift>>operators. These work perfectly for numbers that are represented using the C typesunsignedorunsigned long.
I tried doing this in C: ``` int val = 0xCAFE; int uc = val & 14; if (val & 15 == 15 || val & 7 == 7 || val & 11 == 11|| val & 13 == 13 || val & 14 == 14){ printf("asdjfkadscjas \n"); } ``` However this is not printing the random string as it should. It worked for 15,7,11,13 tho. If anyone knows of a better way that would be helpful. I am bad with bitwise operator. Thanks
Alternative solution: You can put all your numbers into a binary-coded lookup table: ``` int AtleastThreeBits (int a) { return (0xe880>>(a&15))&1; } ``` Each bit of the magic number represents an answer. In the constant 0xe880 bits 7,11,13,14 and 15 are set. You select the correct bit using a shift and mask it out. It's not as readable as your solution but faster..
I have a custom allocator function which uses sbrk() to obtain memory. How do I release this memory when it's no longer needed? Is there a function equivalent to free() for malloc() ? or do I have to use brk() to set the end of the data segment ?
You need to usebrkorsbrkagain to shrink. In the end the only way you have to modify the amount of memory(apart from mmap like syscalls), is to increase or decrease the heap, so you move it up withsbrkorbrkand you move it down withbrkorsbrkwith a negative increment.
Is there a possibility that strcat can ever fail? If we pass some incorrect buffer or string, then it might lead to memory corruption. But, apart from that is it possible that this function can return failure like strcat returning NULL even if destination string passed is Non-NULL? If no, why strcat has a return type specified at all? I have just mentioned strcat as an example. But, this question applies to many string and memory related (like memcpy etc) functions. I just want to know the reasoning behind some of these seemingly "always successful" functions having return types.
Returning a pointer to the target string makes it easy to use the output in this sort of (perhaps not-so-clever) way: ``` int len = strlen(strcat(firstString, secondString)); ```
In C, I want a block of statements to be executed repeatedly everytseconds. How do I do this?
This cannot be done in standard C, you need to use some platform-specific API. One popular choice is POSIX'alarm()function. This is a "pure" aynchronuous solution. It's of course possible to measure and handle time in other ways, but they're still platform-dependent. You could usesleep()(again, POSIX) to just block. If you combine that with your desired statements in a loop, that should work too.
Will the strlen() function below get called just once (with the value stored for further comparisons); or is it going to be called every time the comparison is performed? ``` for (i = 0; i < strlen(word); i++) { /* do stuff */ } ```
That's implementation-dependent. Usually, it gets called every time, but, if the compiler can see thatwordnever changes, and thatstrlenis a pure function (no side effects), it can lift the call. See:http://underhanded.xcott.com/?page_id=15for a well-known example of this being exploited. :-)
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.
Why does the following code compile? ``` #include <stdio.h> int main(void) { getchar; } ```
Because function names are aliases to function pointers to those functions, which are themselves values much like integers.. This is semantically very similar to ``` #include <stdio.h> int main(void) { 42; } ``` It is valid but pointless.