question
stringlengths
25
894
answer
stringlengths
4
863
I wonder if it's possible to do something like: ``` call("MyFunction"); ``` and have it call a function named MyFunction not having call implement a long switch or if statement. there probly is some other way to do this, what I really want to achive is to implement the IRC protocol, which get messages, and based on those I want to call the apropiate function I'm new to C and best practices how things are done so please enlighten me!
Not without defining a table of string-to-function mappings and (probably) some kind of argument passing convention, or usingdlopen()(which counts as very advanced hackery).
I am porting a Linux code that uses<unistd.h>, specifically gethostid function, to Windows 7. I need an unique number of 32 bits that I will use in my application. How can I obtain an unique number using API from Windows 7 in the same manner that I do on Linux? Thanks.
You would normally implement this by returning the local IP address, for example by callinggetaddrinfo().
When someone statically links a .lib, will the linker copy the whole contents of lib into the final executable or just the functions used in the object files?
The whole library?-- No.Just the functions you called?-- No.Something else?-- Yes. It certainly doesn't throw in the whole library. But it doesn't necessarily include just "the functions used in the object files" either. The linker will make a recursively built list of which object modules in the library satisfy your undefined symbols. Then, it will include each of those object modules. Typically, a given object module will include more than one function, and if some of these are not called by the ones that youdocall, you will get some number of functions (and data objects) that you didn't need.
So I was wondering if there is like a centralized library management for C? likerubygemsfor C? I realized it might be a silly idea, but there are times when I wish I could have the benefits of rubygems, but for C.
Mostpackage management systemshave entries for C libraries.
``` | GOTO '*' expr ';' ``` I've never see such statements yet,anyone can bring an example?
This is so calledLabels as Valuesand represents one of the GCC extensions. As an example, I've applied this extension to give ananswertoPrinting 1 to 1000 without loop or conditionalsquestion: ``` void printMe () { int i = 1; startPrintMe: printf ("%d\n", i); void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000); goto *labelPtr; exitPrintMe: } ```
In C/CUDA, if I am passed a pointer, how can I programmatically determine whether the pointer points to memory on the CPU or the GPU? Is there a CUDA function for this purpose?
I don't know how it is with CUDA 4.0, but in 3.2 you simply cannot deduct if it is CPU or GPU pointer based solely on the address stored in it. A way around it would be to create a classCudaPtr<T>, hide a pointer there and provide basic functionality (e.g.memset,memload,memstore,memallocetc. which would in turn use CUDA stuff). Then, if you have a function which may operate on host or on device, you can easily overload it forT*andCudaPtr<T>. Update: Since the Unified Memory Addressing and new CUDA toolkit things have changed a bit. It seems you can now make such distinction at run time viacuPointerGetAttribute
I want to delete an executable after I start the process. I tried by puttingunlinkand it work fine, but I want my executable to continue running. Is using theunlinkapproach correct? Are there any issues with using this approach?
On Unix, there shouldn't be any problems unlinking the executable of a running process. When you unlink a file, the directory entry is removed, but the inode and the underlying data are not freed until all existing references to the file (i.e. hard links and open handles) are released.
What is the best way to organize matrix operations in CUDA (in terms of performance)? For example, I want to calculateC * C^(-1) * B^T + C,CandBare matrices. Should I write separate functions for multiplication, transposition and so on or write one function for the whole expression? Which way is the fastest?
I'd recommend you to use the CUBLAS library. It's normally much daster and more reliable than everything you could write on your own. In addition it's API is similar to the BLAS library which is the standard library for numerical linear algebra.
``` main() { char s[] = "abcdef", *p; for (p = &s[5]; p >= s; p--) --p*; puts(s); return 0; } ``` The compiler says there is a problem with --p* (expected an expression)?????
--p*doesn't make any sense . Probably you meant--*por--p? Your code prints`abcdewhen the underlying representation is ASCII. BTW C99 mandates the return type ofmain()to beintin a hosted environment.
I am using a mutex for the critical section. I have a design constraint that, 1) If 2 reads occur in 2 different thread, then critical section should be available for both. 2) If there is a write happening, then read on other thread should be blocked 3) If there is a read happening, then write on other thread should be blocked. I dont know to do this with Createmutex, openmutex, waitforsingleobject and releasemutex apis.
What you are looking for is aReader-Writer lock. There are some implementations of it on the internet, for examplethis one.
I'm currently using Eclipse as my main editor, and source browser for our C/C++ project. The only problem is, I have to switch to Visual C++ everytime I have to debug or trace. Is there a way to have Eclipse use the WinDbg tool to debug Windows native applications? I tried searching on the web but all the forum posts seem to trail off to nowhere around 2007/2008.
I think the answer is no. Because you will not have access to the Win Debug Symbols and libraries within the Eclipse runtime. However you could start building this as an Eclipse plugin for VS users.
I wonder if it's possible to do something like: ``` call("MyFunction"); ``` and have it call a function named MyFunction not having call implement a long switch or if statement. there probly is some other way to do this, what I really want to achive is to implement the IRC protocol, which get messages, and based on those I want to call the apropiate function I'm new to C and best practices how things are done so please enlighten me!
Not without defining a table of string-to-function mappings and (probably) some kind of argument passing convention, or usingdlopen()(which counts as very advanced hackery).
I am porting a Linux code that uses<unistd.h>, specifically gethostid function, to Windows 7. I need an unique number of 32 bits that I will use in my application. How can I obtain an unique number using API from Windows 7 in the same manner that I do on Linux? Thanks.
You would normally implement this by returning the local IP address, for example by callinggetaddrinfo().
When someone statically links a .lib, will the linker copy the whole contents of lib into the final executable or just the functions used in the object files?
The whole library?-- No.Just the functions you called?-- No.Something else?-- Yes. It certainly doesn't throw in the whole library. But it doesn't necessarily include just "the functions used in the object files" either. The linker will make a recursively built list of which object modules in the library satisfy your undefined symbols. Then, it will include each of those object modules. Typically, a given object module will include more than one function, and if some of these are not called by the ones that youdocall, you will get some number of functions (and data objects) that you didn't need.
I am using a mutex for the critical section. I have a design constraint that, 1) If 2 reads occur in 2 different thread, then critical section should be available for both. 2) If there is a write happening, then read on other thread should be blocked 3) If there is a read happening, then write on other thread should be blocked. I dont know to do this with Createmutex, openmutex, waitforsingleobject and releasemutex apis.
What you are looking for is aReader-Writer lock. There are some implementations of it on the internet, for examplethis one.
I'm currently using Eclipse as my main editor, and source browser for our C/C++ project. The only problem is, I have to switch to Visual C++ everytime I have to debug or trace. Is there a way to have Eclipse use the WinDbg tool to debug Windows native applications? I tried searching on the web but all the forum posts seem to trail off to nowhere around 2007/2008.
I think the answer is no. Because you will not have access to the Win Debug Symbols and libraries within the Eclipse runtime. However you could start building this as an Eclipse plugin for VS users.
I wonder if it's possible to do something like: ``` call("MyFunction"); ``` and have it call a function named MyFunction not having call implement a long switch or if statement. there probly is some other way to do this, what I really want to achive is to implement the IRC protocol, which get messages, and based on those I want to call the apropiate function I'm new to C and best practices how things are done so please enlighten me!
Not without defining a table of string-to-function mappings and (probably) some kind of argument passing convention, or usingdlopen()(which counts as very advanced hackery).
I am porting a Linux code that uses<unistd.h>, specifically gethostid function, to Windows 7. I need an unique number of 32 bits that I will use in my application. How can I obtain an unique number using API from Windows 7 in the same manner that I do on Linux? Thanks.
You would normally implement this by returning the local IP address, for example by callinggetaddrinfo().
When someone statically links a .lib, will the linker copy the whole contents of lib into the final executable or just the functions used in the object files?
The whole library?-- No.Just the functions you called?-- No.Something else?-- Yes. It certainly doesn't throw in the whole library. But it doesn't necessarily include just "the functions used in the object files" either. The linker will make a recursively built list of which object modules in the library satisfy your undefined symbols. Then, it will include each of those object modules. Typically, a given object module will include more than one function, and if some of these are not called by the ones that youdocall, you will get some number of functions (and data objects) that you didn't need.
So I was wondering if there is like a centralized library management for C? likerubygemsfor C? I realized it might be a silly idea, but there are times when I wish I could have the benefits of rubygems, but for C.
Mostpackage management systemshave entries for C libraries.
``` | GOTO '*' expr ';' ``` I've never see such statements yet,anyone can bring an example?
This is so calledLabels as Valuesand represents one of the GCC extensions. As an example, I've applied this extension to give ananswertoPrinting 1 to 1000 without loop or conditionalsquestion: ``` void printMe () { int i = 1; startPrintMe: printf ("%d\n", i); void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000); goto *labelPtr; exitPrintMe: } ```
It is said that stl vector is "layout-compatible with C". Where can I find the definition of "layout-compatible with C"?
This means that, as long as the vector is not empty,&vector.front()will give you a pointer to a contiguous array of objects, which could be passed to a C API that expects such an array.
This works: ``` struct LD__32 { struct LD__32 *ld; }; ``` But this doesn't: ``` struct LD_32 { struct LD_32 ld; }; ``` Why is this? I was compiling it as c++ code as pmg guessed. edited
A structure in C cannot contain a member with incomplete type. In the latter case you can't haveLD_32 ld;defined inside theLD_32definition because the structLD_32is not already defined at that point. Check outconstaintson structure in C Section 6.7.2.1/2 A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.
The title of the topic may as well be "Is size_t enough to hold an address?" I'm trying to get the offset between a struct and one of it's fields and I'm using a size_t variable to hold the offset: ``` size_t offset = (size_t)&struct.field - (size_t)&struct; ``` I know this is kind of forced, I'm just wondering if I might encounter somekind of error later on because of this. I know I could have done the same using an int, but I'm wondering if it can hold the address on a 64 bit system. What are your thoughts on this?
Use theoffsetofmacro found in<stddef.h>. Sincesize_tmust have a large enough range to store the size of the largest possible object, it is also large enough to store the offset of any member of any struct type: the offset of a member of a struct cannot be greater than the size of the struct.
I know my file pointer is at end of the line after printing this string: "xyz". How can I get it to the start of the line? (pointing to x) ``` offset = ftell(fp); fseek(fp, offset - sizeof("xyz") , SEEK_SET); ``` Above doesn't seem to work. How can I achieve that?
I would store the offset by issuing abeginning = ftell(fp)before reading/writing you "xyz". Thenfseek(fp, beginning, SEEK_SET); Would this be possible?
This question already has answers here:Closed12 years ago. Possible Duplicate:what does malloc(0) return ? Does it return zero pointer? Is the behavior standardized? How about STL allocator? I googled it, but couldn't pinpoint the answer I was looking for. EDIT: The linked question doesn't explain STL allocator. I have another relevant question. What happens if one tries to deallocate zero pointer? ``` allocator.deallocate(0, 1); ```
malloc(0)mayeitherreturn 0 or it may return a unique address (which shall not be accessed) -- the C89 and C99 Standards allow either behavior but do not mandate either one. (Bad design for a standard and I objected when I was on X3J11 but that's how it is.) BTW, this is a duplicate question:what does malloc(0) return?
Just having a tiny issue with the C open() system call regarding the filepath, on Linux (Ubuntu). If I put the absolute path ie open("/home/bob/Desktop/folder/file", O_RDONLY); it opens fine But say if I run my program on another computer that filepath would not be correct ie username may not be bob So, when I try open("./Desktop/folder/file", O_RDONLY); the file wont open, is this correct way. I know (~/) wont work but not sure why (./) wont work? Any suggestions please? Thanks,
You have to usegetenv("HOME")to get the absolute pathname to your home directory, then construct the rest (the relative part) of the pathname after that. Also note that it's very rude practice to ever use fixed filenames under the user's home directory except for hidden files/directories (ones beginning with a dot).
I recently installed VC++ 6.0 on an old machine with Windows 95. On Windows 95 there is a 3D maze screensaver made with OpenGL but the computer doesn't have a 3D video card. I would like to know how I can make 3D graphics like in the 3D maze for no 3D video cards. If you know of a good tutorial or book, I would be happy with your suggestion.
OpenGL, if no dedicated 3D hardware is available, can render the graphics on the CPU. You might have noticed that, while the screensaver is running, CPU usage gets pretty high. If you want to learn more about OpenGL, the I would recommend that you take a look athttps://stackoverflow.com/q/62540/1103747. My personal favorite is the OpenGL Superbible. But as a suggestion, if you want to learn 3D graphics and your target OS is Windows, I think that you should study something else (WPF, DirectX, XNA, etc). Obviously you will probably want to upgrade from Windows 95.
``` CASE expr_no_commas ELLIPSIS expr_no_commas ':' ``` I saw such a rule in c's syntax rule,but when I try to reproduce it: ``` int test(float i) { switch(i) { case 1.3: printf("hi"); } } ``` It fails...
OK, this involves a bit of guesswork on my part, but it would appear that you're talking about agccextension to C that allows one to specify ranges inswitchcases. The following compiles for me: ``` int test(int i) { switch(i) { case 1 ... 3: printf("hi"); } } ``` Note the...and also note that you can't switch on afloat.
I've been studying and experimenting on c language with c99 standard for almost 3 months,and everything the whole book i read only taught me how to program in DOS(console) but not in terms of GUI,I know any pro might say i should continue stick to programming in DOS so that i could learn the essence of the language without the need to focus on creating GUI,which could make learning less hassle,but i just wonder if i wanted to create GUI apps ,what thing should i learned??Don't worry i would finish learning the basic and everything before proceed to GUI,for time being i just curious about it and wanting to ask.Thank you.
First, if you're primary concern was learning to code GUI's... You may have chosen the wrong language! If you're willing to consider C++, you should look at Qt. wxWidgets is also pretty good. If you really have to stick to C, take a look at GTK+.
If your compiler actually optimizes access time of only two registers variables per function, which two variable in the following program are the best one to be made into register variables? ``` void main(void) { int i,j,k,m; do { printf("enter value"); scanf(“%d”,&i); m=0; for(k=0;k<100;k++) m=k+m; } while(i>0); } ``` Please ignore if any mistake is there...
Trick question? In a smart compiler, none of the variables are registerized.ihas its address taken, so it can't be in a register all the time.j,kandmshould be optimized away.
I've recently inherited an almost 7 year old codebase, including a library with public headers with definitions of IP-, TCP, VLAN-structs and a shitload of defines (like#define TCP_NODELAY 1). I tried to look for headers with these structs but I couldn't find anything (this is primary on linux, but also various BSD-variants). Surely there must be headers for this already? I thinknet/ethernet.hhelped with all the defines. EDIT: Found most of the structs I'm looking for:struct tcphdrinnetinet/tcp.hstruct udphdrinnetinet/udp.hstruct ipinnetinet/ip.h Does anyone have any clue about a struct with the vlan-header? (ether_vlan_header?)
Try ``` find /usr/include -type f | xargs grep TCP_NODELAY ``` whereTCP_NODELAYis the symbol you're looking for. You can look for all symbols at the same time by writing them to a file (one per line), and usinggrep -f FILE.
I'm trying to output some numbers in a log file and I want to pad a load of floats via theprintffunction to produce: ``` 058.0 020.0 038.0 -050.0 800.0 150.0 100.0 ``` Currently I'm doing this: ``` printf("% 03.1f\n", myVar); ``` ...where myVar is a float. The output from that statement looks like this: ``` 58.0 20.0 38.0 -50.0 800.0 150.0 100.0 ``` Fromwhat I've readI would expect my code to produce the output I mentioned at the top of this post, but clearly something is wrong. Can you only use one flag at a time? ..or is there something else going on here?
The width specifier is the complete width: ``` printf("%05.1f\n", myVar); // Total width 5, pad with 0, one digit after . ``` To get your expected format: ``` printf("% 06.1f\n", myVar); ```
I am doing a simple program that should count the occurrences of ternary operator ?: in C source code. And I am trying to simplify that as much as it is possible. So I've filtered from source code these things: String literals " "Character constants ' 'Trigraph sequences ??=, ??(, etc.CommentsMacros And now I am only counting the occurances of questionmarks. So my question question is: Is there any other symbol, operator or anything else what could cause problem - contain '?' ? Let's suppose that the source is syntax valid.
I think you found all places where a question-mark is introduced and therefore eliminated all possible false-positives (for the ternary op). But maybe you eliminated too much: Maybe you want to count those "?:"'s that get introduced by macros; you dont count those. Is that what you intend? If that's so, you're done.
I started some socket programming, and I ran across the function inet_ntoa . The function has the prototypechar * inet_ntoa(struct in_addr in);. So how/where will this string be allocated? Am I expected to call free on it?
Frominet_ntoa(3): The inet_ntoa() function converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation. The string is returned in astatically allocated buffer, which subsequent calls will overwrite So, no.
``` #define max(a,b) \ ({ typeof (a) _a = (a); \ typeof (b) _b = (b); \ _a > _b ? _a : _b; }) ``` Why not simply(a>b ? a : b)?
because otherwhisemax(f(1), f(2))would call one of the two functions twice: ``` f(1) > f(2) ? f(1) : f(2) ``` instead by "caching" the two values in_aand_byou have ``` ({ sometype _a = (a); sometype _b = (b); _a > _b ? _a : _b; }) ``` (and clearly as other have pointed out, there is the same problem with autoincrement/autodecrement) I don't think this is supported by Visual Studio in this way. This is a compound statement. Read heredoes msvc have analog of gcc's ({ }) I'll add that the definition of compound statement in the gcc manual given herehttp://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_4.html#SEC62shows a code VERY similar to the one of the question for max :-)
I have a 3rd party library that reads RTMP packets from a network socket, using recv() and taking the socket descriptor as an argument. I want it to read these packets from the application buffer instead (allocated in heap). Is it possible?
You may be able to usesocketpair, which creates a pair of connected (unix domain) sockets. If you are on Linux, You can stuff the socket usingvmsplice, otherwisesend()as usual.
I need to add a timeout function for getchar() in my program. What do I do so that when my program reaches the instruction getchar(), it will only wait for a certain amount of time for the user to make a keystroke and if the user does not make a keystroke within the given time limit, the program will "skip" the getchar()? The operating system does not support the conio.h library so kbhit is not an option.
This is usually achieved by usingselect()onstdin. Another solution would be usingalarm()and a dummy SIGALRM handler to interrupt thegetchar()call (only working on POSIX systems though).
What is the#errordirective in C? What is the use of it?
It's a preprocessor directive that is used (for example) when you expect one of several possible-Dsymbols to be defined, but none is. ``` #if defined(BUILD_TYPE_NORMAL) # define DEBUG(x) do {;} while (0) /* paranoid-style null code */ #elif defined(BUILD_TYPE_DEBUG) # define DEBUG(x) _debug_trace x /* e.g. DEBUG((_debug_trace args)) */ #else # error "Please specify build type in the Makefile" #endif ``` When the preprocessor hits the#errordirective, it will report the string as an error message and halt compilation; what exactly the error message looks like depends on the compiler.
run this code. you can reverse "live long and prosper" to "prosper and long live" . ``` #include <stdio.h> #include <string.h> void rev(char *l, char *r); int main(int argc, char *argv[]) { char buf[] = "live long and prosper"; char *end, *x, *y; // Reverse the whole sentence first.. for(end=buf; *end; end++); rev(buf,end-1); // Now swap each word within sentence... x = buf-1; y = buf; while(x++ < end) { if(*x == '\0' || *x == ' ') { rev(y,x-1); y = x+1; } } // Now print the final string.... printf("%s\n",buf); return(0); } // Function to reverse a string in place... void rev(char *l,char *r) { char t; while(l < r) { t = *l; *l++ = *r; *r-- = t; } } ``` I want to know, in C++ by using header, is there any good quick way to do this? thanks!
You might want to use thestd::reversefunction, provided in the<algorithm>header file.
I've just started learning C and haven't been doing any memory management up to now. Can anyone recommend a good guide/tutorial for memory management in C?
I think the biggest thing to wrap your head around is storage and lifetime of variables in memory (stack vs heap). You can check outWikiBook's treatment of this topic. I find it to be a gentler introduction to a lot of topics.
I have a quick question about using logical operators in an if statement. Currently I have an if statement that checks if x equals to 5 or 4 or 78: ``` if ((x == 5) || (x == 4) || (x == 78)) { blah } ``` And I was wondering if I could just condense all that to: ``` if (x == 5 || 4 || 78) { blah } ``` Sorry for such a basic question, I've just started learning C.
There is no shortcut, but you need to fix your equality operator. ``` if ((x == 5) || (x == 4) || (x == 78)) { ```
my file pointer is pointing to end of a line. I want to remove all contents of that line, how do I do that? I might need to move the file pointer to start of the line and then delete the contents.
You can only delete from the end of a file. To delete data from the middle of a file, you generally need to copy the subsequent data to cover up the gap (or, more easily as a rule, make a new copy of the file, skipping over the part you want to delete). If you need to do things like this very often, you'll probably want to create some sort of indexed file so you can just delete from the index -- or, of course, use a database library to handle it for you.
Does every process havestdin,stdoutandstderrassociated to it to the Keyboard and Terminal? I have a small program. I want to replace the keyboard input to a file callednew.txt. How do I go about it? ``` FILE *file1 fopen("new.txt", "r") close(0); // close the stdio dup2(file1, 0); ``` Would this work? Now mystdiois redirected to theFILE?
No, noteveryprocess. But on operating systems that give you a command-line window to type in, a program started from that command line will have stdin connected to the keyboard, and stdout and stderr both going to the terminal. If one program starts another, then often the second program's standard streams are connected to the first program in some way; for example, the first program may have an open descriptor through which it can send text and pretend that it's the "keyboard" for the second process. The details vary by operating system, of course.
Can anybody please tell me how I can get the desktop path(environment variable) using C language commands. Scenario is that I want to save a file on desktop.What I can do is just to give a fixed desktop path and a filename to save the file. But after giving this fixed path ,my code will become rigid and will not work on anyother computer having different desktop path (environment variable). My question is can I make my code generalize which can work on any windows based machine by capturing the environment variable of desktop , using C language? Regards
SHGetSpecialFolderPath(CSIDL_DESKTOP)
Can someone convert this C struct to delphi as in record? ``` typedef struct { Uint16 addr2:8; Uint16 addr1:8; Uint16 addr4:8; Uint16 addr3:8; Uint16 addr6:8; Uint16 addr5:8; }MY_ADDR; ``` I tried it out myslef. But i couldn't figure out how to deal withaddr2:8(:8) issue. ``` MY_ADDR = record addr2:8 : Uint16; addr1:8 : Uint16; addr4:8 : Uint16; addr3:8 : Uint16; addr6:8 : Uint16; addr5:8 : Uint16; end; ``` I am not sure i also need this or not? ``` pMY_ADDR = ^MY_ADDR; ```
``` MY_ADDR = record addr1 : Byte; addr2 : Byte; addr3 : Byte; addr4 : Byte; addr5 : Byte; addr6 : Byte; end; ``` You need to swap them around due to byte ordering in MS C bitfields.
I need to read an input file like this: ``` 0.142857 0.714286 0.642857 0.714286 0.285714 0.500000 0.500000 0.500000 0.785714 0.428571 0.357143 0.357143 0.714286 0.214286 0.928571 0.071429 ``` Each line corresponds to a point on a plane, with an unknown number of points input comes from standard input.. any ideas?
scanfreturns the number of parameters is receives. You can test to make sure you're getting what you're asking for. Example: ``` #include <stdio.h> // ... double f1, f2; while(scanf("%lf %lf", &f1, &f2) == 2) { // store f1 and f2 somewhere } ```
What is the point of making a function static in C?
Making a functionstatichides it from other translation units, which helps provideencapsulation. helper_file.c ``` int f1(int); /* prototype */ static int f2(int); /* prototype */ int f1(int foo) { return f2(foo); /* ok, f2 is in the same translation unit */ /* (basically same .c file) as f1 */ } int f2(int foo) { return 42 + foo; } ``` main.c: ``` int f1(int); /* prototype */ int f2(int); /* prototype */ int main(void) { f1(10); /* ok, f1 is visible to the linker */ f2(12); /* nope, f2 is not visible to the linker */ return 0; } ```
For example, can the output of 'uname -a' be used to create the COMPILED_ON macro below? ``` #include <stdio.h> #define COMPILED_ON `call uname -a and use the output as a quoted string' int main( int argc, char **argv ) { printf( COMPILED_ON ); return 0; } ```
no, but: ``` gcc -DCOMPILED_ON="$(uname -a)" ```
This question already has answers here:Closed12 years ago. Possible Duplicate:How does system() exactly work in linux? For the sake of my curiosity, I want to know that how does system() function spawn the process and its internal implemenation ? Is is using fork , exec internally ?
On my Debian box it uses clone() that itself calls sys_clone(). You can use strace to look at system calls.
I have the same shared library in three different paths in the system. Let's say the paths are PATH1, PATH2 & PATH3. Shared library name is libmylib.so Now, in PATH1 if I replace the libmylib.so with a broken soft link, it goes and searches in PATH2 for the library. But, in PATH1 if I replace libmylib.so with some other text file (or some unrelated file) which has the name libmylib.so, then application execution fails stating "not an ELF Header" I am a little confused by the behaviour? Why does it search the other paths incase of a broken soft link and fails in case of an incorrect file. I was expecting it to search other paths for incorrect file also.
It probably just try to open it. Dangling symbolic link or not present, it will returns the same error. You'd need to do test explicitly for symbolic link if you wanted to do something different. Few programs care.
Hi My VC2008 project uses the stdcall calling conventions. I have an external library that I am using which has been built with cdecl naming convention, however they didn't mention the calling convention in the function declaration of the functions. I would like to know if VC has some kind of #pragma or other keyword that would force specific calling convention for the entire header file kinda like the extern "C" trick but for calling conventions: ``` extern "C" { #include <file1.h> #include <file2.h> } ``` Anyone knows of such?
You can specify calling convention by: Do nothing and you get the default of cdecl.Specify__cdeclexplicitly (or perhaps through a macro).Elect to use cdecl throughout a translation unit by compiling with /Gd. There's no pragma or anything similiar to control calling convention.
I am looking for a name or phrase to identify two distinct parts of a function definition 1.The part that looks exactly the same as the function declaration (minus the semi-colon)2.The rest (the portion within and including the curly-braces) ``` int someFunction(int value, bool flag) // part one { ... } // part two ``` Is there an accepted way to describe these two parts?
I call them the function header and function body. A quick glance at Harbison & Steele comes up with no real names for them.
Is there a way to find out in which function/file/line set the current errno?
Not that I know of,it's just a global static int (no magic in it)(see comment below). You're supposed to check after each function that could set it when it returns an error.
How can I insert or remove a word in the middle of a text file using C on Linux?
Copy the whole file to a temporary location by adding/omitting the word to remove, replace the original source by the temporary file. There's also the possiblity to use fseek()http://www.manpagez.com/man/3/fseek/
Is this ok? ``` char buf[] = { 0, 1, 2 }; memcpy(buf, buf + 1, 2); ``` Does having a bigger datatype make any difference? I know I could use memmove(), but I'm just curious.
The effects ofmemcpyare not defined when the input and output overlap. You should usememmove.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a book, tool, software library, tutorial or other off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.Closed9 years ago.Improve this question Is there any open source C implementation for PSNR, SSIM or MSE that doesn't rely on OpenCV? Thanks.
IQAprovides a C implementation with no dependencies of the following image quality metrics: MSEPSNRSSIMMS-SSIMMS-SSIM*
How do you get a file extension (like.tiff) from a filename in C? Thanks!
``` const char *get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); if(!dot || dot == filename) return ""; return dot + 1; } printf("%s\n", get_filename_ext("test.tiff")); printf("%s\n", get_filename_ext("test.blah.tiff")); printf("%s\n", get_filename_ext("test.")); printf("%s\n", get_filename_ext("test")); printf("%s\n", get_filename_ext("...")); ```
I want to port my code from linux to windows. It is something like this: ``` void SetNonBlocking( int filehandle ) { int fhFlags; fhFlags = fcntl(filehandle,F_GETFL); if (fhFlags < 0) { perror("fcntl(F_GETFL)"); exit(1); } fhFlags |= O_NONBLOCK; if (fcntl(filehandle,F_SETFL,fhFlags) < 0) { perror("fcntl(F_SETFL)"); exit(1); } return; } ``` Now I want have same in windows. Any ideas? Actualy my filehandle is read side of pipe which is created via WinApiCreatePipemethod.
The term for non-blocking / asynchronous I/O in Windows is 'overlapped' - that's what you should be looking at. Basically, you identify a file handle as using overlapped i/o when you open it, and then pass an OVERLAPPED structure into all the read and write calls. The OVERLAPPED structure contains an event handle which can be signalled when the I/O completes.
Is it possible to implement a non-blocking client socket? I have tried using ``` sockfd = socket(AF_INET, SOCK_STREAM, 0); fcntl(sockfd, F_SETFL, O_NONBLOCK); connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)); ``` but when the application reaches theconnectstatement, it exists with the following error: ERROR connecting: Operation now in progress I need to create a completely non-blocking socket, that doesn't even wait for the TCP handshake. Is this possible using standard socket functions or do I have to go into threading?
The error you receive is normal when in non-blocking mode. It just means that the operation could not be completed immediatly. That means you need to wait on the file descriptor for the connect to be finished before you can use it. This is the way non-blocking sockets are working in C.
I am trying to port a Linux program written in C to Windows. In the original program, they defined a small function which allocates aligned memory. If they want to free it, they just callfree(). I used_aligned_malloc()to allocate but when I want to free it, I also need to use_aligned_free(). But I have to find all the calls of the functionfree()which correspond to the aligned allocations. Not all of the allocations are aligned, so I cannot simply replace all thefree()'s with_aligned_free(). My question is: is there any tool in Visual Studio which can find themalloc()/free()pairs? Any advice? I am also new to Visual Studio.
In Cmaloc()is guaranteed to return memory aligned for any purpose. I think you can replace all_aligned_malloc()calls withmalloc()ones. Just drop the alignment parameter ... ``` #define _align_malloc(size, alignment) malloc(size) /* ignore alignment */ ```
I have a program that creates pipes between two processes. One process constantly monitors the output of the other and when specific output is encountered it gives input through the other pipe with thewrite()function. The problem I am having, though is that the contents of the pipe don't go through to the other process's stdin stream until Iclose()the pipe. I want this program to infinitely loop and react every time it encounters the output it is looking for. Is there any way to send the input to the other process without closing the pipe? I have searched a bit and found that named pipes can be reopened after closing them, but I wanted to find out if there was another option since I have already written the code to use unnamed pipes and I haven't yet learned to use named pipes.
Take a look at usingfflush.
Is it possible to put the equivalent of#define VAR(in a C program) into a makefile, so that one can control which part of the program should be compiled?
Accordingly toccmanpage onlinux ``` -D name=definition The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive. In particular, the definition will be truncated by embedded newline characters. ```
I have a Rails application with a FFI binding to a custom RPC system. Unfortunately, the C code callsexit()when it is unable to connect to the RPC server, terminating the entire Rails application. Is it possible to trap calls toexit()in Ruby? I'd rather not have to change the C code.
You cannot trap a function call. However maybe you can link the C code with a dummyexit()function that will not actually exit. The cleaner solution is by far to change the C code to give it a proper library behaviour. You could also fork in ruby before doing the RPC call, a bit on the expensive side performance wise but would solve the issue too...
I've defined an opaque structure and related APIs like this: ``` typedef struct foo foo; foo *create_foo(...); delete_foo(foo *f); ``` I am not able to define the structure in my c file. Gives redefinition error. ``` typedef struct foo { int implementation; }foo; ``` I am able to use foo in c file without typedef but I want the typedef (i.e. use it directly as foo*). Is there a way?
You already have thetypedefin your header, so include that and definestruct fooin the implementation without thetypedef. foo.h: ``` typedef struct foo foo; foo *create_foo(...); delete_foo(foo *f); ``` foo.c: ``` #include <foo.h> struct foo { int implementation; }; /* etc. */ ```
In my program I have saveral pipes which are connected to stdout and stderr streams of child processes (i.e. in main process I'm reading from this streams). But when there is nothing to read from one of them my program hangs. Is there way to solve this problem not using thread. Also I want all child processes to be killed if there is nothing to read duringxmsecs. In unix select() + non_blocking read solves this two problems. But what about windows?
You can use a similar approach in windows. Using OVERLAPPED structs, you can issue asynchronous I/O against the pipes. Then use WaitForMultipleObjects on the associated event handles with a timeout (this is the select analog). Seethisfor an overview of the options.
When i do like this, it works well in my code... ``` ... for (i = 2; i <= sqrt(500000); i++) ... ``` But do like ``` for (i = 2; i < sqrt(500000) + 1; i++) ``` executes after compile, error occurs sayingSegmentation fault (core dumped). for loop bodyis: ``` for (i = 2; i <= sqrt(500000); i++) { summation[i * i] += i; for (j = i + 1; j <= 500000 / i; j++) { summation[i * j] += (i + j); } } ``` Is there any difference between the two for loops? Thanks
Your second loop run once more: 500000 is not a perfect square, soi < sqrt(500000)andi <= sqrt(500000)are always equal and the +1 ensure another iteration.
Imagine that I have two strings, one of them is a url like "/sdcard/test.avi" and the other one is"/sdcard/test.mkv". I want to write an if statement that looks whether the last four characters of string is ".avi" or not in C. How can I do this? Using strcmp or what and how?
If you have a pointer-to-char array,str, then this: ``` int len = strlen(str); const char *last_four = &str[len-4]; ``` will give you a pointer to the last four characters of the string. You can then usestrcmp(). Note that you'll need to cope with the case where(len < 4), in which case the above won't be valid.
I have a file and I want to read this file using C program using file operations. Then i want to take parameters from that file. Lets say nalu_type=x. So whenever i detect the string nalu_type in that file I want to put the value x in an array which is defined by me. please tell me how to do it. Thanks in Advance Sanket
``` # include<stdio.h> # include <conio.h> # include <string.h> void main() { int noc=0,l; FILE *fp; char *str2,ch; char*str1; clrscr(); printf("Enter the String to be matched\n"); gets(str1); l=strlen(str1); fp=fopen("A.C","r"); while(1) { ch=fgetc(fp); if(ch==EOF) break; else if(ch==' ') { fgets(str2,l+1,fp); if((strcmp(str1,str2))==NULL) noc++; } } printf("NO of occurence is: %d",noc); getch(); } ```
I have a main() function and prior to declaring main(), I declare global variables. Then inside main() 2 processes start: 1 child and 1 parent via fork(). Why can't the parent and child processes share the global variables I declared? What is a good way to handle this? Thank you.
When youfork()you're spawning a new process. Everythingat the time of the forkis copied, but after that ... nothing is shared. You have two choices at that point: Keep a pipe open between your two processes and communicate changesRe-write your code to be multi-threaded, where you can access the same data (using locks)
in c++ where are static or non-static variables stay? I mean in memory. and, When are static or non-static variables initialized? Need someone help me get my thought clear. Thank you! and what about C? same?
They can go wherever the compiler (or linker or loader) wants to put them in memory, the C and C++ standards don't mandate that level of detail. They only mandate thebehaviour. Typically, static members are initialised once, either on program startup (including at compile time so that they're simply loaded in an already-initialised state) or immediately before first use.
I want to display the binary tree as a Max Heap order. Requirement 1) Input - Binary Tree 2) Output - Max Heap / Min Heap Thanks a lot. REgards, Girija
If you are allowed to use other's work: Use std::make_heap to make a heap from a vector
I am implementing a Simple Iterative TCP client/server in C. The server is infinitely listing in a loop. Now if Ctrl+c (SIGINT) occurred at any point of time, how would I free up the resources used in server? For example, I caught the signal in my own signal handler; how would I get socket descriptors and buffers used in the program so as to free them? I new to socket programming; any suggestions would be appreciated.
Don't install a signal handler. Don't do anything. The default action forSIGINTis to terminate the process, and assuming no other processes have descriptors for your sockets, they'll all naturally be closed and cease to exist when the process terminates.
Please explain working in each case. Why both cases have same output? Case I: ``` int main (void) { int i = 5; if(i == ++i) //plz explain here How values are checked printf("Equal"); else printf("Not Equal"); return 0; } //Output: Equal; ``` Case II: ``` int main (void) { int i = 5; if(++i == i) //plz explain here How values are checked printf("Equal"); else printf("Not Equal"); return 0; } //Output: Equal; ```
Neither of those programs is valid; you are not allowed to read and update the same variable without a sequence point in between. Thus, it is undefined behavior what either of those programs will do, and so the fact that they may happen to return the same answer on your compiler and machine doesn't mean anything.
What would be a best and simple way of storing incoming message from different processes in an array in C? I was thinking to have an array MQ but also need to store message sequence numbers and process ids for each incoming message. Thanks.
It sounds like you want to have an array of structures that contain the various elements that you want to store, e.g. ``` struct MessageInfo { int message_id; pid_t incoming_pid; char message_data[MAX_MESSAGE_LEN]; }; struct MessageInfo message_queue[MAX_QUEUE_LEN]; ```
I've defined an opaque structure and related APIs like this: ``` typedef struct foo foo; foo *create_foo(...); delete_foo(foo *f); ``` I am not able to define the structure in my c file. Gives redefinition error. ``` typedef struct foo { int implementation; }foo; ``` I am able to use foo in c file without typedef but I want the typedef (i.e. use it directly as foo*). Is there a way?
You already have thetypedefin your header, so include that and definestruct fooin the implementation without thetypedef. foo.h: ``` typedef struct foo foo; foo *create_foo(...); delete_foo(foo *f); ``` foo.c: ``` #include <foo.h> struct foo { int implementation; }; /* etc. */ ```
In my program I have saveral pipes which are connected to stdout and stderr streams of child processes (i.e. in main process I'm reading from this streams). But when there is nothing to read from one of them my program hangs. Is there way to solve this problem not using thread. Also I want all child processes to be killed if there is nothing to read duringxmsecs. In unix select() + non_blocking read solves this two problems. But what about windows?
You can use a similar approach in windows. Using OVERLAPPED structs, you can issue asynchronous I/O against the pipes. Then use WaitForMultipleObjects on the associated event handles with a timeout (this is the select analog). Seethisfor an overview of the options.
When i do like this, it works well in my code... ``` ... for (i = 2; i <= sqrt(500000); i++) ... ``` But do like ``` for (i = 2; i < sqrt(500000) + 1; i++) ``` executes after compile, error occurs sayingSegmentation fault (core dumped). for loop bodyis: ``` for (i = 2; i <= sqrt(500000); i++) { summation[i * i] += i; for (j = i + 1; j <= 500000 / i; j++) { summation[i * j] += (i + j); } } ``` Is there any difference between the two for loops? Thanks
Your second loop run once more: 500000 is not a perfect square, soi < sqrt(500000)andi <= sqrt(500000)are always equal and the +1 ensure another iteration.
Imagine that I have two strings, one of them is a url like "/sdcard/test.avi" and the other one is"/sdcard/test.mkv". I want to write an if statement that looks whether the last four characters of string is ".avi" or not in C. How can I do this? Using strcmp or what and how?
If you have a pointer-to-char array,str, then this: ``` int len = strlen(str); const char *last_four = &str[len-4]; ``` will give you a pointer to the last four characters of the string. You can then usestrcmp(). Note that you'll need to cope with the case where(len < 4), in which case the above won't be valid.
I have a file and I want to read this file using C program using file operations. Then i want to take parameters from that file. Lets say nalu_type=x. So whenever i detect the string nalu_type in that file I want to put the value x in an array which is defined by me. please tell me how to do it. Thanks in Advance Sanket
``` # include<stdio.h> # include <conio.h> # include <string.h> void main() { int noc=0,l; FILE *fp; char *str2,ch; char*str1; clrscr(); printf("Enter the String to be matched\n"); gets(str1); l=strlen(str1); fp=fopen("A.C","r"); while(1) { ch=fgetc(fp); if(ch==EOF) break; else if(ch==' ') { fgets(str2,l+1,fp); if((strcmp(str1,str2))==NULL) noc++; } } printf("NO of occurence is: %d",noc); getch(); } ```
I have a main() function and prior to declaring main(), I declare global variables. Then inside main() 2 processes start: 1 child and 1 parent via fork(). Why can't the parent and child processes share the global variables I declared? What is a good way to handle this? Thank you.
When youfork()you're spawning a new process. Everythingat the time of the forkis copied, but after that ... nothing is shared. You have two choices at that point: Keep a pipe open between your two processes and communicate changesRe-write your code to be multi-threaded, where you can access the same data (using locks)
in c++ where are static or non-static variables stay? I mean in memory. and, When are static or non-static variables initialized? Need someone help me get my thought clear. Thank you! and what about C? same?
They can go wherever the compiler (or linker or loader) wants to put them in memory, the C and C++ standards don't mandate that level of detail. They only mandate thebehaviour. Typically, static members are initialised once, either on program startup (including at compile time so that they're simply loaded in an already-initialised state) or immediately before first use.
I want to display the binary tree as a Max Heap order. Requirement 1) Input - Binary Tree 2) Output - Max Heap / Min Heap Thanks a lot. REgards, Girija
If you are allowed to use other's work: Use std::make_heap to make a heap from a vector
I am implementing a Simple Iterative TCP client/server in C. The server is infinitely listing in a loop. Now if Ctrl+c (SIGINT) occurred at any point of time, how would I free up the resources used in server? For example, I caught the signal in my own signal handler; how would I get socket descriptors and buffers used in the program so as to free them? I new to socket programming; any suggestions would be appreciated.
Don't install a signal handler. Don't do anything. The default action forSIGINTis to terminate the process, and assuming no other processes have descriptors for your sockets, they'll all naturally be closed and cease to exist when the process terminates.
Please explain working in each case. Why both cases have same output? Case I: ``` int main (void) { int i = 5; if(i == ++i) //plz explain here How values are checked printf("Equal"); else printf("Not Equal"); return 0; } //Output: Equal; ``` Case II: ``` int main (void) { int i = 5; if(++i == i) //plz explain here How values are checked printf("Equal"); else printf("Not Equal"); return 0; } //Output: Equal; ```
Neither of those programs is valid; you are not allowed to read and update the same variable without a sequence point in between. Thus, it is undefined behavior what either of those programs will do, and so the fact that they may happen to return the same answer on your compiler and machine doesn't mean anything.
What would be a best and simple way of storing incoming message from different processes in an array in C? I was thinking to have an array MQ but also need to store message sequence numbers and process ids for each incoming message. Thanks.
It sounds like you want to have an array of structures that contain the various elements that you want to store, e.g. ``` struct MessageInfo { int message_id; pid_t incoming_pid; char message_data[MAX_MESSAGE_LEN]; }; struct MessageInfo message_queue[MAX_QUEUE_LEN]; ```
In Windows, the RGBTRIPLE and RGBQUAD structs are defined in reverse order. It is so counterintuitive that I imagine it must have been done deliberately. It doesn't really matter, of course, but this has bugged me enough that I feel it's worth asking. So, why? The definitions: ``` typedef struct tagRGBTRIPLE { BYTE rgbtBlue; BYTE rgbtGreen; BYTE rgbtRed; } RGBTRIPLE, *PRGBTRIPLE, NEAR *NPRGBTRIPLE, FAR *LPRGBTRIPLE; typedef struct tagRGBQUAD { BYTE rgbBlue; BYTE rgbGreen; BYTE rgbRed; BYTE rgbReserved; } RGBQUAD; ```
On a little endian machine (aka x86 and friends) the structs match the data format of a Bitmap's color data exactly.
there is an error in fopen.c how can i solve it? error in assigning argv[1], argv[2] to ft, fs. ``` int main ( int argc, char *argv[] ) { //FILE *fs, *ft ; char ch ; //ft = fopen ("d:\\out.txt", "w") ; fs = fopen( argv[1], "r" ); if ( fs == NULL ) { puts ( "Cannot open source file" ) ; exit(1) ; } //fs = fopen("d:\in_file.txt","r") ; ft = fopen( argv[2], "w" ); if ( ft == NULL ){ puts ( "Cannot open target file") ; exit(1) ; } } ```
At first, there a huge indentation problem in your code. Please solve it. [EDIT: Now it is ok] Second, what kind of error? Both fs and ft are equal to NULL? Instead of using puts to display error message, you can use perror(const char *s). This will add informations to your message knowing the stat of the errno variable.
I am working with a system whereby I can send 1 32 bit int at a time. However I need to send two numbers at a time. What is the best way to do this in standard C? I assume I will have to do some conversion to binary/hex and some masking? Any ideas would be appreciated. Thanks
You can encode two 16-bitunsignednumbers like this: ``` unsigned int out = (in1 << 16) | in2; ``` and decode them like this: ``` unsigned int in1 = out >> 16; unsigned int in2 = out & 0xFFFF; ``` All this assumes thatintis at least 32 bits, thatin1andin2are in the 0-65535 range, and that anunsigned intcan be sent across correctly (w.r.t. endianness).
``` #include <stdio.h> void findpairs(int arr[], int arr_size, int sum) { int i, temp; int hash[100] = {0}; for(i = 0; i < arr_size; i++) { temp = sum - arr[i]; if(hash[temp] == 1) { printf("Pair with given sum %d is (%d, %d) \n", sum, arr[i], temp); } hash[arr[i]] = 1; } } int main() { int A[] = {4,-4,9,2,1,6,5,11}; int sum =7; int arr_size = 8; findpairs(A, arr_size, sum); return 0; } ``` link to the same program
``` hash[arr[i]] = 1; ... hash[-4] = 1; ``` Yourhasharray has indices from 0 to 99, so you're accessing out-of-bounds data. Your next out-of-bounds access will be for the value 9, ``` temp = 7 - 9; if (hash[temp] == 1) ```
I have a DVB receiver (set-top box) similar likeDreamboxand it has MIPS cpu It hasembedded Linuxand I can connect to it withtelnet Question is how to compile simple "Hello World" application inC? Where to gettoolchain,SDK?
You should useCodescape SDK.
I have implemented TCp concurrent server and client in c using threads as well as forks. But I don't have any way to check whether there is any other standard way of implementing this. I have goggled for standard coding stuff but didnt find anything useful. Can someone pl z share some good links or code so that I can have a standard idea of implementing Concurrent servers. Thanks for help
There's no "standard idea". Your approach is going to depend on requirements, performance, scalability, and amount of time allowed for development. One thread per clientPossibly with a threadpoolMulti-threaded pipeline model, with N workersOne thread per server, using poll/selectOne thread per server, event-based with callbacksForking children, one per client connectionpre-forking children, e.g. Apache web server Etc. All of these have their uses.
This question already has answers here:Closed12 years ago. Possible Duplicates:C - determine if a number is prime Is there any way to test easily in C whether a selected number is prime or not?
The easiest way is writing a loop, like: ``` int is_prime(int num) { if (num <= 1) return 0; if (num % 2 == 0 && num > 2) return 0; for(int i = 3; i < num / 2; i+= 2) { if (num % i == 0) return 0; } return 1; } ``` You can then optimize it, iterating tofloor(sqrt(num)).
I have a file in which some text is stored. Now I want to display the text in a list box usinggtk. How can I do this? Also the values are changing dynamically. Is there a way to refresh the listbox?
This is done using model-view architecture in GTK. The view is aGtkTreeView, and you can associate it with aGtkListStore, which you can update dynamically. The tree view will refresh automatically when you update the list store. You might also want to read thisoverview of tree and list widgets in GTK.
Compiling my project on new xcode4 usingllvm 2.0compiler I get a strange error coming from standard<sqlite3.h>header. Problem is with the following line: ``` //<sqlite3.h> typedef struct sqlite3 sqlite3; ``` Error message: ``` In file included from /Projects/trunk/MyProj/Classes/StatsProvider.m:14: Elaborated type refers to a non-tag type in /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/include/sqlite3.h ``` Using GCC 4.2 project compiles with no problem How can I fix that error?
My guess: you are compiling sqlite as C++ code, whereas you should compile it as plain C code. class/struct keywords implicitly introduce a typedef in C++, but not so in C.
Can i store the unspecified type in GtkListStore? For instance, I want to store in one field - the field of int type and the field of GdkColor type ?
I think you meanunions in C C++
I have two enums. ``` enum A { A1=1, A2=2 } enum B { B1=1, B2=2 } ``` Is this valid by standard of C? ``` A a = A1; B b = a; ``` (compiled well with Clang, but I can't sure this is standard or extension behavior)
It's valid by the standard, but the C99 spec mentions that some implementations may generate a warning: An implementation may generate warnings in many situations, none of which are specified as part of this International Standard. The following are a few of the more common situations.A value is given to an object of an enumerated type other than by assignment of an enumeration constant that is a member of that type, or an enumeration variable that has the same type, or the value of a function that returns the same enumerated type (6.7.2.2).
I need to allocate 4 byte memory and the allocated memory address should be the multiple of 4. eg:400, 404,408,40c If I use any memory allocation function, I receive memory which are available and the addresses are not necessarily be in multiples of 4. So can anyone suggest to achieve this design.
In the Microsoft C/C++ compiller you can use_aligned_mallocand in Linuxposix_memalign. MSVC: ``` ptr = _aligned_malloc(4, 4); ``` Signature: ``` void * _aligned_malloc(size_t size, size_t alignment); ``` Linux: ``` posix_memalign(&ptr, 4, 4); // returns 0 if successful ``` Signature (Note order is reversed compares to MSFT): ``` int posix_memalign(void **memptr, size_t alignment, size_t size); ```
Is there a way I could get the inode number of a file which has not yet been opened. I would like to do this from inside a c function Regards, Lipika
Usestat(2)(which takes a file path), and check the st_ino field. Do note that it's possible for someone to move or remove the file between the time you callstatand whenever you manage to do anything with the information.
I compiled gcc on one of my ubuntu 10.10 hosts, and installed it in /c. I can compile c and c++ programs fine on that host but when i copy /c (which contains bin, libexec etc) to a ubuntu 10.04.2 host i get: ``` /c/libexec/gcc/i686-pc-linux-gnu/4.5.2/cc1: error while loading shared libraries: libmpc.so.2: cannot open shared object file: No such file or directory ``` when compiling a simple .c file. I've also installed and compiled gmp, mpfr and mpc from source (same versions as i did on the 10.10 host) but it's still coming up with the same error. The reason i'm not recompiling gcc on each host is because it takes too long, and prefer not to use the gcc (from the build-essential) deb that comes with ubuntu Please help
did you export your LD_LIBRARY_PATH environment variable? Looking at the error, it's not able to find libmpc.so.2. Try 'locate libmpc.so.2' and if you can find that, export LD_LIBRARY_PATH=