question
stringlengths
25
894
answer
stringlengths
4
863
That is : How can I check the drive size which is not formatted... Don't consider the formatted drives...just unformatted drive.
Programmatically in Linux: ``` #include <fcntl.h> #include <linux/fs.h> #include <sys/ioctl.h> #include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { int fd; unsigned long long numblocks=0; fd = open(argv[1], O_RDONLY); ioctl(fd, BLKGETSIZE64, &numblocks); close(fd); printf("Number of bytes: %llu, this makes %.3f GB\n", numblocks, (double)numblocks / (1024 * 1024 * 1024)); } ``` This is basically the code fromhttp://www.linuxproblem.org/art_20.html, adapted to useBLKGETSIZE64, with various warnings fixed. ``` $ gcc -o getsize getsize.c $ sudo ./getsize /dev/sda Number of bytes: 53687091200, this makes 50.000 GB ```
I've got a simple (propably) question for you. When creating own dynamic array implementation in C, is it better to allocate memory ahead(let's presume, for 10 elements) when an array is close to reach its current maximum capability, or to realloc memory every time when element count changes? I mean: for performance, elegance or whatever comes to your mind.
The usual choice is to multiple the current size by a fixed number greater than one (1.5ish is common, as is 2) which gets you amortized O(n) total allocation and copying costs. Note that there is no guarantee that you can increase the size of the array in place, so you may have to copy all the existing elements to the new location (realloc()does this automatically for you, but you still have to pay the cost).
I'm trying to write a function that'll detect if a digit is found in a number: ``` // returns 1 if source contains num, 0 otherwise int contains_num(source, num); ``` for example, contains_num(12345, 3) returns 1 and contains_num(12345, 6) returns 0. I'm not sure how to go about solving this. Probably can't use pointers, arrays and such. Any ideas? thanks.
Since this is homework, I don't want to give you the entire answer right away. Instead, I'll ask a series of questions, and let you answer in the comments, so I'll simply be guiding you to the correct answer rather than giving it to you outright. So, you have a number, and you want to break it down into individual digits. Can you think of a way of extracting one digit from the number, say, the last one? Think about what each digit represents, and how you might be able to isolate one digit from the rest of them.
What is the difference between: ``` thread_envs[i] = soap_copy(&env); ``` and ``` thread_envs[i] = soap_new(); ``` Sould we use one of them or both?
From the documentation: struct soap *soap_new() Allocates, initializes, and returns a pointer to a runtime environment struct soap *soap_copy(struct soap *soap) Allocates a new runtime environment and copies contents of the environment such that the new environment does not share any data with the original environment
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this question I am trying to exchange data between client and server using gSOAP. Actually, I succeeded to send data from client to server but not from server to client. So, could someone please explain what functions to use to pass data from server to client? Thanks for your time and replies,
The only way I know is by invoking with a function soap_call See the example of calc in gsoap package
As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?
Take a look at theC10Kpage for a great overview and comparison of I/O frameworks and strategies.
I mean i want the input to be invisible like inputing password when i log in Linux. How can I implement it both in C under linux and windows. thanx
There is no single solution that will work across platforms. For Linux you can use thegetpass() function. For windows you can try_getch().
``` #include <stdio.h> int main() { char temp[1024]; if(getchar() != 'y') { printf("no options\n"); return 1; } scanf(temp, "%s"); printf("%s", temp); } ``` I get snippet as below. I just want twice input from user. but the first input works, however the second directly skips and theprintf("%s", temp);printed unexpected characters. How can I resolve the problem.. thanx
The first parameter toscanfis the format, and the second is the buffer. You have it backwards. Tryscanf( "%s", temp );.
This question already has answers here:How is conditional initialization handled and is it a good practice?(5 answers)Closed9 years ago. How long does it take to declare a variable in C, for exampleint xorunsigned long long var? I am wondering if it would make my code any faster in something like this. ``` for (conditions) { int var = 0; // code } ``` Would it be faster to do this, or is it easier not to? ``` int var; for (conditions) { var = 0; // code } ``` Thanks for the help.
One piece of advice: stop worrying about which language constructs are microscopically faster or slower than which others, and instead focus on which ones let you express yourself best. Also, to find out where your code is spending time, use a profiler. And as others have pointed out, declarations are purely compile-time things, they don't affect execution time.
What is the result of the following line: ``` int* ptr; printf("%x, %x\n", ptr, &ptr); ``` I know thatptris an address in a memory, but what is&ptr?
&ptr would be the address for the memory location that ptr is held in. Essentially it is a pointer to a pointer.
I want to invoke a shell in C program by execve: ``` #include <stdio.h> #include <stdlib.h> #include <errno.h> main() { char* path = "/bin/sh"; int err = execve(path, &path, NULL); printf("%d\n", err); printf("%s\n", strerror(errno)); printf("%x, %x\n", path, &path); } ``` However the output is: ``` -1 Bad address 80485c0, bf816f4c ```
Because you aren't sending a NULL terminated list of arguments. You need: ``` char* path[2]; path[0] = "/bin/sh"; path[1] = NULL; int err = execve(path[0], path, NULL); ```
I compiled libxml2 with BCC 5.5 command line compiler, now I have lots of .obj files which I'd like to link into my Delphi application. Unfortunately, I get lots of "Unsatisfied forward or external declaration" errors, pointing to standard C library functions like memcpy, open, recv etc ... What should I do to compile it correctly? I'd like to avoid depending on msvcrt.dll or any other external libraries. Thanks in advance!
Depending on the version of Delphi you have, there should be a unit called crtl.dcu with which you can link. Just use the $L directive for each .obj file in a unit that also uses crtl. You may also need to "use" other various units like Windows, WinSock, etc... The point is to provide the symbols and functions to resolve during the link phase. This is the same technique used to statically link in the DataSnap TClientDataSet code used to also build midas.dll.
In MSVC++, there's a functionstrcmpifor case-insensitive C-string comparisons. When you try and use it, it goes, This POSIX function is deprecated beginning in Visual C++ 2005. Use the ISO C++ conformant _stricmp instead. What I don't see is why does ISO not want MSVC++ to use strcmpi, and why is _stricmp the preferred way, and why would they bother to rename the function, and how is a function beginning with an underscore ISO conformant. I know there must be a reason for all this, and I'm suspecting its because strcmpi is non-standard, and perhaps ISO wants non-standard extensions to begin with an _underscore?
ISO C reserves certain identifiers for future expansion (seehere), including anything that starts with "str".
What requires the most CPU: ``` int foo = 3; ``` or typecasting it to an unsigned int? ``` unsigned int foo = 3; ```
They are both represented by the same bits in memory. It's just a question of how the bits are interpreted, which depends on the range of values you want. So, neither is more intensive. As for working with the numbers, taking the example of multiply: I'm no expert but according towikipedia, in x86 there are opcodes for unsigned multiply (mul) and signed multiply (imul) which would mean that they probably take the same length of time.
I'm trying to enumerate some operators, my code line is : ``` enum operations{+=4,-,%,<,>} ``` when i'm trying to compile this line , gcc says : expected identifier before ‘+’ token So, how can I enumerate these operators. Can we use some escape characters for them ?
Your best bet is something like this: ``` enum Operations { Plus=4, Minus, Mod, LessThan, MoreThan } ```
How to inform the server if a client is interrupted, and then close the socket?
If the other end of a socket is closed, your end will be marked as readable and return0fromread- this is the "end of file" indication. If you try towriteto such a socket, you will recieve theSIGPIPEsignal, and thewritewill return error with errno set toEPIPE("Broken Pipe"). You must be prepared to handle this event, because the other end can close the socket atanytime.
I've been writing an Apache module recently. It's been interesting to work with the memory pool paradigm, but I'm clearly not doing something right. I've got a segfault, and I cannot seem to find it. My current debug cycle involves ap_rprintfs and a make script that rebuilds and reloads Apache. What kind of tools are available for working in this type of environment?
You should use GNU Debugger (gdb). Start Apache via commandgdb bin/httpdand thanr -Xinside gdb. When segfault occurs, you will be able to see where it occurred with commandbt.
I want to allocate shared memory as a 2D array using IPC. I tried the following: ``` id_shmem = shmget(ipc_key, sizeof(int)*rows*columns, IPC_CREAT|0666); matrix = (int **)shmat(id_shmem, 0, 0); ``` The problem is that whenever I try to write something into the matrix, I get a segment fault.
int** is not 2D array, it is rather an array of pointers. You should not store pointers in shared memory, as shared memory segment may be allocated at different addresses in different processes. Try to use simple, flat 1D array, which will "emulate" 2D array with some index magic, ie. ``` x,y -> y*width+x ```
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago. Rather than possibly reinventing the wheel (by "rolling my own") - I thought I'd ask in here first. Anyone knows where I can download a good C/C++ RESTful framework?. I have had a quick look on google, but there is nothing too impressive so far - maybe someone in here has written one already (that they dont mind sharing), or may know a lik to a good one (preferably, they have already used it before)
I've just seenthis, it may be what I'm looking for. Could be useful for others too
I need to set additional options for C compiler, e.g. add flag to turn all warnings ON, depending on the type of the compiler. E.g. for MSVC I should use ``` env.Append(CPPFLAGS = "/Wall") ``` but for mingw (gcc) I need to use: ``` env.Append(CCFLAGS = "-Wall") ``` How can I do this in scons way?
You could just check for the name of the compiler: ``` cc = env['CC'] if cc == 'cl': env.Append(CPPFLAGS = '/Wall') elif cc == 'gcc': env.Append(CCFLAGS = '-Wall') ```
Usingmemcpy()when source and destination overlap can lead to undefined behaviour - in those cases onlymemmove()can be used. But what if I know for sure buffers don't overlap - is there a reason to use specificallymemcpy()or specificallymemmove()? Which should I use and why?
Assuming a sane library implementor,memcpywill always be at least as fast asmemmove. However, on most platforms the difference will be minimal, and on many platformsmemcpyis just an alias formemmoveto support legacy code that (incorrectly) callsmemcpyon overlapping buffers. Bothmemcpyandmemmoveshould be written to take advantage of the fastest loads and stores available on the platform. To answer your question: you should use the one that is semantically correct. If you can guarantee that the buffers do not overlap, you should usememcpy. If you cannot guarantee that the buffers don't overlap, you should usememmove.
I am reading a file with fgetc, so each time it reads a character, the cursor positio gets changed. Is it possible to know, after each read, the "coordinates" of the cursor on the file in terms of column and line number? Thanks
You can useftell It does not give you the position in terms of row and column but gives the current position in the stream from the start.
That is : How can I check the drive size which is not formatted... Don't consider the formatted drives...just unformatted drive.
Programmatically in Linux: ``` #include <fcntl.h> #include <linux/fs.h> #include <sys/ioctl.h> #include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { int fd; unsigned long long numblocks=0; fd = open(argv[1], O_RDONLY); ioctl(fd, BLKGETSIZE64, &numblocks); close(fd); printf("Number of bytes: %llu, this makes %.3f GB\n", numblocks, (double)numblocks / (1024 * 1024 * 1024)); } ``` This is basically the code fromhttp://www.linuxproblem.org/art_20.html, adapted to useBLKGETSIZE64, with various warnings fixed. ``` $ gcc -o getsize getsize.c $ sudo ./getsize /dev/sda Number of bytes: 53687091200, this makes 50.000 GB ```
I've got a simple (propably) question for you. When creating own dynamic array implementation in C, is it better to allocate memory ahead(let's presume, for 10 elements) when an array is close to reach its current maximum capability, or to realloc memory every time when element count changes? I mean: for performance, elegance or whatever comes to your mind.
The usual choice is to multiple the current size by a fixed number greater than one (1.5ish is common, as is 2) which gets you amortized O(n) total allocation and copying costs. Note that there is no guarantee that you can increase the size of the array in place, so you may have to copy all the existing elements to the new location (realloc()does this automatically for you, but you still have to pay the cost).
I'm trying to write a function that'll detect if a digit is found in a number: ``` // returns 1 if source contains num, 0 otherwise int contains_num(source, num); ``` for example, contains_num(12345, 3) returns 1 and contains_num(12345, 6) returns 0. I'm not sure how to go about solving this. Probably can't use pointers, arrays and such. Any ideas? thanks.
Since this is homework, I don't want to give you the entire answer right away. Instead, I'll ask a series of questions, and let you answer in the comments, so I'll simply be guiding you to the correct answer rather than giving it to you outright. So, you have a number, and you want to break it down into individual digits. Can you think of a way of extracting one digit from the number, say, the last one? Think about what each digit represents, and how you might be able to isolate one digit from the rest of them.
What is the difference between: ``` thread_envs[i] = soap_copy(&env); ``` and ``` thread_envs[i] = soap_new(); ``` Sould we use one of them or both?
From the documentation: struct soap *soap_new() Allocates, initializes, and returns a pointer to a runtime environment struct soap *soap_copy(struct soap *soap) Allocates a new runtime environment and copies contents of the environment such that the new environment does not share any data with the original environment
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this question I am trying to exchange data between client and server using gSOAP. Actually, I succeeded to send data from client to server but not from server to client. So, could someone please explain what functions to use to pass data from server to client? Thanks for your time and replies,
The only way I know is by invoking with a function soap_call See the example of calc in gsoap package
As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?
Take a look at theC10Kpage for a great overview and comparison of I/O frameworks and strategies.
I mean i want the input to be invisible like inputing password when i log in Linux. How can I implement it both in C under linux and windows. thanx
There is no single solution that will work across platforms. For Linux you can use thegetpass() function. For windows you can try_getch().
``` #include <stdio.h> int main() { char temp[1024]; if(getchar() != 'y') { printf("no options\n"); return 1; } scanf(temp, "%s"); printf("%s", temp); } ``` I get snippet as below. I just want twice input from user. but the first input works, however the second directly skips and theprintf("%s", temp);printed unexpected characters. How can I resolve the problem.. thanx
The first parameter toscanfis the format, and the second is the buffer. You have it backwards. Tryscanf( "%s", temp );.
This question already has answers here:How is conditional initialization handled and is it a good practice?(5 answers)Closed9 years ago. How long does it take to declare a variable in C, for exampleint xorunsigned long long var? I am wondering if it would make my code any faster in something like this. ``` for (conditions) { int var = 0; // code } ``` Would it be faster to do this, or is it easier not to? ``` int var; for (conditions) { var = 0; // code } ``` Thanks for the help.
One piece of advice: stop worrying about which language constructs are microscopically faster or slower than which others, and instead focus on which ones let you express yourself best. Also, to find out where your code is spending time, use a profiler. And as others have pointed out, declarations are purely compile-time things, they don't affect execution time.
What is the result of the following line: ``` int* ptr; printf("%x, %x\n", ptr, &ptr); ``` I know thatptris an address in a memory, but what is&ptr?
&ptr would be the address for the memory location that ptr is held in. Essentially it is a pointer to a pointer.
I want to invoke a shell in C program by execve: ``` #include <stdio.h> #include <stdlib.h> #include <errno.h> main() { char* path = "/bin/sh"; int err = execve(path, &path, NULL); printf("%d\n", err); printf("%s\n", strerror(errno)); printf("%x, %x\n", path, &path); } ``` However the output is: ``` -1 Bad address 80485c0, bf816f4c ```
Because you aren't sending a NULL terminated list of arguments. You need: ``` char* path[2]; path[0] = "/bin/sh"; path[1] = NULL; int err = execve(path[0], path, NULL); ```
Is it required to check the return value of fclose? If we have successfully opened a file, what are the chances that it may fail to close?
When youfwriteto a file, it may not actually write anything, it may stay in a buffer (inside the FILE object). Callingfflushwould actually write it to disk.That operation may fail, for example if you just ran out of disk space, or there is some other I/O error. fcloseflushes the buffers implicitly too, so it may fail for the same reasons.
I am using gentoo and trying to compile a program to control the bits on the parallel port. It has this line near the top of it: ``` #include <asm/io.h> ``` And when I try to use gcc on it, it produces this output: port.c:4:20: error: asm/io.h: No such file or directory "locate asm/io.h" yeilds (among other things): /usr/src/linux-2.6.32-gentoo/arch/x86/include/asm/io.h So I have the header file, but it's not finding it? Why is this not working?
I am not sure if you are the author of the program or you're just trying to compile a program you got from someone, butlooks like#include <asm/io.h>should be replaced with#include <sys/io.h>. See the results ofthis google searchfor more information.
I want to do the equivalent of ``` class Foo(object): bar = 1 ``` using Python's C API. In other words, I want to create a Python class which has a static variable, using C. How can I do this?
Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above: ``` PyTypeObject type; // ...other initialisation... type.tp_dict = PyDict_New(); PyDict_SetItemString(type.tp_dict, "bar", PyInt_FromLong(1)); ```
Is there any way to get milliseconds and its fraction part from 1970 using time.h in c language?
This works on Ubuntu Linux: ``` #include <sys/time.h> ... struct timeval tv; gettimeofday(&tv, NULL); unsigned long long millisecondsSinceEpoch = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000; printf("%llu\n", millisecondsSinceEpoch); ``` At the time of this writing, the printf() above is giving me 1338850197035. You can do a sanity check at theTimestampConvert.comwebsite where you can enter the value to get back the equivalent human-readable time (albeit without millisecond precision).
Suppose I have these three functions: ``` bool A(); bool B(); bool C(); ``` How do I call one of these functions conditionally using a function pointer, and how do I declare the function pointer?
You can do the following: Suppose you have your A,B & C function as the following: ``` bool A() { ..... } bool B() { ..... } bool C() { ..... } ``` Now at some other function, say at main: ``` int main() { bool (*choice) (); // now if there is if-else statement for making "choice" to // point at a particular function then proceed as following if ( x == 1 ) choice = A; else if ( x == 2 ) choice = B; else choice = C; if(choice()) printf("Success\n"); else printf("Failure\n"); ......... ......... } ``` Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.
Is it possible to compile C code into a Visual C++ dll? I'm looking at using some C code with a .Net project and trying to determine whether this is even an option. Thanks, Becky
yes. If you want to get rid ofname manglinguse"extern "C" { /*...*/ }construct. Also, refer FAQ :How to mix C and C++
Linux gcc 4.4.1 I have this function that passes this second parameter that casts it to a different type. I am just wondering am I correct? It looks to me that it is casting the function evt_hdlr to a void * type to a long pointer type. ``` if(enable_evt_hdlr(EV_ANY, (long (*) (void *)) evt_hdlr) == -1) { .. } ``` The function evt_hdlr definition looks like this: ``` static int32_t evt_hdlr(void); ``` Many thanks for any suggestions,
You cast a function without parameters and returning an int32_t to a function-pointer with a void* parameter, returning a long. This might work, but it's more luck than skill (long and int32_t are not necessarily the same). If you can't change the type of enable_evt_hdlr or evt_hdlr, then make an in-between function: ``` static long my_evt_hdlr(void*) { return (long) evt_hdlr(); } ``` and pass this to event-handler. This way the stack will be handled as promised.
Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable: ``` typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific address by the linker */ ``` I would like to be able to take the binary generated by the C compiler/linker and parse this structure (and possibly modify it) with a Python script.
This was mentioned on SO yesterday; I haven't had a chance to check it out more thoroughly yet, but I'm meaning to. Thepycparser, a "C parser and AST generator written in Python". https://github.com/eliben/pycparser
what the difference when the number of threads is determined, as e.g.: ``` for (i*10){ ... pthread_create(&thread[i], NULL, ThreadMain[i], (void *) xxx); ... } ``` and when it is undetermined, just like this: ``` ... pthread_create(&threadID, NULL, ThreadMain, (void *) xxx); ... ``` In my case the number i can varry from 1 to 10. If e.g. I use the first method, I need to create 10times as e.g.: ``` void *ThreadMain1(void *xxx) { ... } ``` until ... ``` void *ThreadMain10(void *xxx) { ... } ``` But if I use the second method, I need to create just : ``` void *ThreadMain(void *xxx) { ... } ``` So which one is correct? Thanks for your time and replies,
If the threads are doing the same tasks, they should use the same function (with different input maybe), so one ThreadMain is the correct way.
I want to send data or packets at particular IP address using ANSI C standard so that my code will be platform independent. How is it possible in windows OS without using windows libraries like winsock etc.? Kindly give me some guidelines or hints.
i don't think it's possible to create platform independent socket code because though ANSI C is a standard, well-defined language and network communications are invariably a feature provided by the operating system and will vary from OS to OS. This means that your code will have differences between platforms. The best you could do is mitigate these differences by constructing a clever API/library to limiting the code you need to re/write when porting.
``` 8 | * 7 | * 6 | * 5 | * 4 | * * 3 |* * * * * * 2 |* * * * *** ** * * 1 |* * *** ****** **** * * +--------------------------- 012345678901234567890123456 11111111112222222 ``` how would you print numbers from the least significant digits to the most significant digits (like the numbers shown on the x-axis)? Thank you
Put the number in a temp. The next digit to print is temp % 10 Divide 10 into temp. If temp isn't 0, repeat the prior two steps.
I have a multi-threaded application which needs to display certain dates to the user. The dates are stored using UTC Unix time values. However, the date must be displayed in the time zone of the user, not the local server time or UTC. Basically, I need a function like this: ``` struct tm *usertime_r(const time_t *timer, struct tm *result, const int timezone) { <just like localtime_r, except it uses UTC+timezone as the timezone> } ``` This function must be thread safe, so I don't believe that setting theTZenvironment variable would be an option.
If you know the user's offset-from-UTC in seconds, you can just add/subtract that from thetime_tand pass the result togmtime_r. For example, Australian Eastern Daylight Time is +11, which means you'd add(11*3600)to the time value.
I'm trying to learn some graphics programming using C. What would be the best way for a beginner to start? I'd like to how to make programs that use graphics and images that can be run directly from a command line prompt, and don't rely on a windowing system like X to execute. Thanks, Mike
Look intolibsdl - Simple DirectMedia Layer. Although on Linux it can use X11 for displaying output, it can also directly use a framebuffer device. It's designed to be simple for pixel-bashing game-type programming, and supports a wide variety of platforms.
``` #ifndef NULL #define NULL NULL #endif ``` This code compiles in gcc with no warnings/errors. Can someone explain what the preprocessor is doing here?
Anywhere the compiler sees the text "NULL" it will replace it with the text "NULL". It's like doing a search-and-replace in your code for "NULL" and replacing with "NULL". Not illegal, just weird :)
I am trying to build a block where I am getting this error message pprbc_CONTENT_icverification_act.c", line 99.2: 1506-018 (S) Operand of indirection operator must be a pointer expression Can anyone please explain what this means? code below: ``` *(WORK_migration_ind_f) = *(migration_status_in_MI9_CIRCLE_INFO(WORK_source_circle_f)); ```
Yes, you put a '*' in front of something that isn't a pointer. You'd be doing yourself and everybody a favor if you posted the line of code involved.
I want to multiply two matrices but the triple loop has O(n3) complexity. Is there any algorithm in dynamic programming to multiply two matrices with O(n) complexity? ok fine we can't get best than O(n2.81) edit:but is there any solution that can even approximate the result upto some specific no. of columns and rows of matrix i mean we get the best of O(n2.81) with a complex solution but perfect results but if there is any solution for even an approximation of multiplication of matrices as we have formulas for factorial approximation etc. if there is any you know it will help me regards.
ThebestMatrix Multiplication Algorithm known so far is the"Coppersmith-Winograd algorithm"withO(n2.38)complexity but it isnotused for practical purposes. However you can always use"Strassen's algorithm"which hasO(n2.81)complexity but there is no such known algorithm for matrix multiplication with O(n) complexity.
This question already has answers here:"static const" vs "#define" vs "enum"(17 answers)Closed6 years ago. Can someone point out the advantages and disadvantages of using#defineversus constants? Most of my work is done in C and Objective-C.
As 0A0D mentioned, there are#defines,enums, andconstvariables. It's worth noting thatconst-qualified variables are not considered to be compile-time constants in C and therefore can't be used in some circumstances (e.g. when declaring the size of an array). enumconstants are compile-time constants, however. For integral values, IMO it's usually better to preferenumsoverconstvariables over#define.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help center.Closed12 years ago. What is new in the soon to be released libpng 1.4 series? The DLL is almost twice the size of 1.2.41
The many changes are listedhere, starting with the lineversion 1.4.0beta1 [April 20, 2006]
Managed to create a simple bootloader... and with VESA 2.0 I managed to change the resolution to 1024x768x32, also managed to setup a Linear Frame Buffer... Where can I find tutorials for using the frame buffer? Like lets say to display a picture before it finishes to load? So far I saw one sample on how to "draw" an ipod...called CdPod
If you have the address of the linear framebuffer all you need to do is to copy the raw image data to it's location.
In my program, I need to check the completion of a sendfile() operation in a non-blocking socket. How can that be done? After checking the documentation and searching on internet, I couldn't find out how to do it
It works very similarly tosend(): if the socket is set asO_NONBLOCKand the operation would block,sendfile()returns immediately and setserrnotoEAGAIN. In this case you have to wait a while and then try again (maybe using a function likeselect()to know when it's ready). Also keep in mind that even if it succeeds it may not write all the bytes you requested in a single function call. Always check the return value: If the transfer was successful, the number of bytes written to out_fd is returned. On error, -1 is returned, and errno is set appropriately. You can also take a look at theman page for sendfile()
I have two structure in c ``` struct data{ char *name; }; struct lst{ struct lst *next; struct table *data; }; ``` when I'm trying to assign a name like l->data->name = d->name; printf("%s",l->data->name); it gives segmentation fault. So is it because read-only memory or caused by another reason ? ok I solved the problem : ) I've done : l->data = d; d has the name already :) thanks all
Just before you do that segmentation-violation-causing instruction, insert: ``` printf( "%p\n", l); printf( "%p\n", l->data); printf( "%p\n", d); printf( "%p\n", d->name); ``` and see which one is set to NULL (or an invalid value). Your segmentation violation is almost certainly caused by an uninitialized pointer.
I have several threads which act as backup for the main one spending most of their life blocked bysem_wait(). Is it OK to keep them or is it better to spawn new threads only when they need to do actual work? Does kernel switch to threads waiting onsem_wait()and "waste" CPU cycles? Thanks.
No, blocked threads are never switched in for any common thread library and operating system (it would be an extremely badly designed one where they were). But they will still use memory, of course.
I'm about to embark on a bout of refactoring of some functions in my code. I have a nice amount of unit tests that will ensure I didn't break anything, but I'm not sure about the coverage they give me. Are there any tools that can analyze the code and see that the functionality remains the same? I plan to refactor some rather isolated code, so I don't need to check the entire program, just the areas that I'm working on. For context, the code I'm working on is in C/C++, and I work in Linux with GCC and VIM.
gcovwill give you coverage information for your unit tests. It's difficult to answer your question in an accurate manner without knowing more about the refactorings you plan to perform. An advice one might give is to proceed with small iterations instead of refactoring lots and lots of parts of your code base and then realize everything breaks. Reference:The GNU Coverage Tool - A Brief Tutorial
Is there any advantage in doing bitwise operations on word boundaries? Any CPU or memory optimization in doing so? Actual problem: I am trying to create XOR of two structure. Lets say structure-1 and structure-2 both of same size 10000 bytes. I leave first few hundreds bytes as it is and then start XOR of 1 and 2. Lets say I start with 302 to begin with. This will take 4 byte at a time and do XOR. 302, 303, 304 and 305 of both structure will be XORed. This cycle will be repeated till 10000. Now, If I start from 304, Is there any performance improvement expected?
Yes, there are at least two advantages for using proper alignment: Portability. Not all processor support non-aligned numbers. For maximum portability, you should only use fully aligned (i.e. an N-byte integer starts at an address that is a multiple of N) numbersSpeed. AFAIK, even a processor that supports non-aligned numbers is still faster with aligned numbers.
I have a structure called table, I just want to create a table, like constructor in java, but when i call this function in main, it gives segmentation fault ``` struct table *create(char *name,int number,char *s_name) { struct table *newTable; newTable->name = name; newTable->number = number; newTable->s_name = s_name; return newTable; } ```
``` struct table *newTable = malloc(sizeof(struct table)); ``` Don't forget calling free when you're done using it, as C does not have a Garbage Collector like java has.
How do I declare in C/C++ that the code that is written is to be built in either HP-UX or Solaris or AIX?
I found that, a good way to figure this king of question, is, at least with gcc, to have this makefile: ``` defs: g++ -E -dM - < /dev/null ``` then, : ``` $ make defs ``` should output all the definitions you have available. So: ``` $ make defs | grep -i AIX $ make defs | grep -i HP ``` should give you the answer. Example for Linux: ``` $ make defs | grep -i LINUX #define __linux 1 #define __linux__ 1 #define __gnu_linux__ 1 #define linux 1 ``` Once you found the define you are looking for, you type at the beginning of your code: ``` #if !(defined(HP_DEFINE) || defined(AIX_DEFINE) || defined(SOLARIS_DEFINE)) # error This file cannot be compiled for your plateform #endif ```
Is it necessary to code RTOS in C language always? Why can't that be coded in java or some other technology..?? Is that because of the absence of pointer concept in java?
Garbage collection is the big reason against Java being Real Time. JIT is another, but it could be overcome. In general though, C being effectively portable assembly gives very predicable run-time performance, and that's essential for reliable real-time execution.
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. As a web developer, is it worth me learning the programming language C? Will I ever need to use it? I am currently using PHP and Ruby on Rails.
The unending pain of getting C programs to actually work reliably will teach you a lot about why PHP is a more civilized way to write software. And yes, you'll use it eventually. Some day you'll run across a problem ill-suited to PHP or Ruby. You'll be able to fall back to C and look like a hero because you know something more than other folks.
The solutions I have found are irrelevant: someone used WebKit in a Delphi projectsomeone used it with Javathere is QtWebKit (about:blank demo app takes 44 megs).Net port of itGTK+ port I need a guide how to embed WebKit instance into a pure C/C++ application under Win32.
Brent Fulgham has put lots of work into producing a Windows Cairo port of WebKit, which doesn't rely on Apple's proprietary backend stuff (e.g. CoreGraphics, CoreFoundation, CFNetwork). I believe that is what you are after. The details aren't entirely collated in one place, but there issome information in the Trac wikiand other bits are dotted around onBrent's blog. EDIT:Link to Brent's project on sourceforge EDIT 2:News of some interesting progress from Brent's blog
On Linux systems (either 32- or 64-bit), what is the size ofpid_t,uid_t, andgid_t?
``` #include <stdio.h> #include <sys/types.h> int main() { printf("pid_t: %zu\n", sizeof(pid_t)); printf("uid_t: %zu\n", sizeof(uid_t)); printf("gid_t: %zu\n", sizeof(gid_t)); } ``` EDIT:Per popular request (and because, realistically, 99% of the people coming to this question are going to be running x86 or x86_64)... On an i686 and x86_64 (so, 32-bit and 64-bit) processor running Linux >= 3.0.0, the answer is: ``` pid_t: 4 uid_t: 4 gid_t: 4 ```
Let's say the factors for valuing a choice are the library of widgets available, the slope of the learning curve, and the degree of portability (platforms it works on). As far a language binding goes, I'm using C++. Thanks!
Pure X is quite hardcore these days, and not very portable. Basically, there are three major toolkits: GTK+ (and C++ wrapper GTKmm)QtwxWidgets which are pretty comparable, so which to choose is a matter of taste. All three run on major three operating systems, although GTK+ on Mac and Windows is little bit awkward.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question Can you please recommend any E-Book Reader which can execute a third-party software, so that anybody can create software for such device?
Well there's two I know of: TheOpenInkPotLinux distribution for e-reader devices, which works on a few e-ink readers (and should be ported to more as time goes on). You shouldn't have much trouble writing third party software for that;The iRex DR1000. Take a look atthis forum threadwhere someone has created a VMware image for doing development targetted at this e-reader.
C doesn't have any built-in Boolean types. What's the best way to use them in C?
From best to worse: Option 1 (C99 and newer) ``` #include <stdbool.h> ``` Option 2 ``` typedef enum { false, true } bool; ``` Option 3 ``` typedef int bool; enum { false, true }; ``` Option 4 ``` typedef int bool; #define true 1 #define false 0 ``` Explanation Option 1 will work only if you use C99 (or newer) and it's the "standard way" to do it. Choose this if possible.Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better. If you are undecided, go with #1!
I am writing a C project. Now I just doubt one function in the whole project may be take the most of computational complexity. If I can make sure about this, I can further improve this function with a more clear target. Or, is there any tools for this usage?? I mean to find the most "expensive" function in the whole program or project?? Any advices? Thanks!
The gprof profiler comes with theGCCcompiler suite. Theres a manual for ithere.
Hi I am working in C on Unix platform. Please tell me how to append one line before the last line in C. I have used fopen in appending mode but I cant add one line before the last line. I just want to write to the second last line in the file.
You don't need to overwrite the whole file. You just have to: open your file in "rw" mode,read your file to find the last line: store its position (ftell/ftello) in the file and its contentsgo back to the beginning of the last line (fseek/fseeko)write whatever you want before the last linewrite the last line.close your file.
I have a binary search tree created in C. The problem is I can't find a efficient way to delete all the nodes with e.g., id>5. When I traverse the tree, if I delete a node, the recursion is getting error, because the structure is not the same. Is there any way, instead of using a helping stack to keep the data before delete them from the tree?
Did you try postorder?Delete the node after its children.
How do you allocate memory that's aligned to a specific boundary in C (e.g., cache line boundary)? I'm looking for malloc/free like implementation that ideally would be as portable as possible --- at least between 32 and 64 bit architectures. Edit to add: In other words, I'm looking for something that would behave like (the now obsolete?)memalignfunction, which can be freed using free.
Here is a solution, which encapsulates the call to malloc, allocates a bigger buffer for alignment purpose, and stores the original allocated address just before the aligned buffer for a later call to free. ``` // cache line #define ALIGN 64 void *aligned_malloc(int size) { void *mem = malloc(size+ALIGN+sizeof(void*)); void **ptr = (void**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1)); ptr[-1] = mem; return ptr; } void aligned_free(void *ptr) { free(((void**)ptr)[-1]); } ```
I need to prevent application's memory pages from being swapped out of RAM on Windows. Is there a WinAPI function equivalent of POSIXmlockall()to achieve that?
Yes, VirtualLock(). There's a limit on how many pages you can lock, you can't hog RAM. Details are in theMSDN article.
I'm currently exploring interfacing C and R (using R's .Call for speed). I've only used C for trivial integer computation and text processing applications, and I've never had to worry about issues with float variables, underflow, etc. What tests can I write for functions to ensure numerical accuracy?
For a great overview of possible edge cases, see thisWikipedia article. Then for unit tests seeThe pitfalls of verifying floating-point computations.
Any idea what this means? Not sure of the language. (void *) 0x00
In C, it means a NULL pointer, i.e., a pointer that points to no relevant data. Trying to access this data raises a Segmentation Fault, at least on Unix/Linux.
There is a set of N real-time data-independent tasks. Each of the tasks processes some digital data stream. A data stream for each task comes from an input port and a resulted stream then is being directed to an output port. 1) What is computationally less intensive: tasks in form of the processes or threads?2) Does best choice depends on the number of physical CPU cores available? Thank you in advance!
Threads should have slightly less overhead since they share the same memory space within the process, however this overhead may be small enough to not impact your program. The only way to know for certain which will be better for you is to try both a measure how long each takes.
I need to work out if a massive integer (I mean 20 digits...) is prime. I'm trying to use the brute-force method, but (of course) I need to use doubles to contain the original number. However, the modulo operator (%) is an integer operator - thus it is useless to me!
That's not possible, a double only has 15 significant digits. Look for an implementation of aBigInt class.C specific is discussedhere.
I have a binary search tree created in C. The problem is I can't find a efficient way to delete all the nodes with e.g., id>5. When I traverse the tree, if I delete a node, the recursion is getting error, because the structure is not the same. Is there any way, instead of using a helping stack to keep the data before delete them from the tree?
Did you try postorder?Delete the node after its children.
How do you allocate memory that's aligned to a specific boundary in C (e.g., cache line boundary)? I'm looking for malloc/free like implementation that ideally would be as portable as possible --- at least between 32 and 64 bit architectures. Edit to add: In other words, I'm looking for something that would behave like (the now obsolete?)memalignfunction, which can be freed using free.
Here is a solution, which encapsulates the call to malloc, allocates a bigger buffer for alignment purpose, and stores the original allocated address just before the aligned buffer for a later call to free. ``` // cache line #define ALIGN 64 void *aligned_malloc(int size) { void *mem = malloc(size+ALIGN+sizeof(void*)); void **ptr = (void**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1)); ptr[-1] = mem; return ptr; } void aligned_free(void *ptr) { free(((void**)ptr)[-1]); } ```
I need to prevent application's memory pages from being swapped out of RAM on Windows. Is there a WinAPI function equivalent of POSIXmlockall()to achieve that?
Yes, VirtualLock(). There's a limit on how many pages you can lock, you can't hog RAM. Details are in theMSDN article.
I'm currently exploring interfacing C and R (using R's .Call for speed). I've only used C for trivial integer computation and text processing applications, and I've never had to worry about issues with float variables, underflow, etc. What tests can I write for functions to ensure numerical accuracy?
For a great overview of possible edge cases, see thisWikipedia article. Then for unit tests seeThe pitfalls of verifying floating-point computations.
Any idea what this means? Not sure of the language. (void *) 0x00
In C, it means a NULL pointer, i.e., a pointer that points to no relevant data. Trying to access this data raises a Segmentation Fault, at least on Unix/Linux.
There is a set of N real-time data-independent tasks. Each of the tasks processes some digital data stream. A data stream for each task comes from an input port and a resulted stream then is being directed to an output port. 1) What is computationally less intensive: tasks in form of the processes or threads?2) Does best choice depends on the number of physical CPU cores available? Thank you in advance!
Threads should have slightly less overhead since they share the same memory space within the process, however this overhead may be small enough to not impact your program. The only way to know for certain which will be better for you is to try both a measure how long each takes.
I need to work out if a massive integer (I mean 20 digits...) is prime. I'm trying to use the brute-force method, but (of course) I need to use doubles to contain the original number. However, the modulo operator (%) is an integer operator - thus it is useless to me!
That's not possible, a double only has 15 significant digits. Look for an implementation of aBigInt class.C specific is discussedhere.
I would like to calculate the no of days,hours,minutes between two different dates in iPhone(Objective C). Please provide any code sample to do the same. Thanks Sandeep
If your dates are in NSDate objects, you can use the timeIntervalSinceDate method to find the difference as an NSTimeInterval, which will give you the difference in seconds. You can then convert seconds to days, hours and minutes via a simple algorithm (this is off the top of my head and not tested): ``` minutes = seconds / 60; seconds %= 60; hours = minutes / 60; minutes %= 60; days = hours / 24; hours %= 24; ```
I'm having trouble to find a way to extract a list of all properties of a node without knowing what they're called. I'm extracting single known properties using: xmlGetProp(cur, (const xmlChar*)"nodename") But how to get a list of all properties using libxml2? Regards, marius
Simply loop through the node's properties list, ie: ``` xmlNodePtr Node = ...; for(xmlAttrPtr attr = Node->properties; NULL != attr; attr = attr->next) { ... do something with attr ... ... the name of the attribute is in attr->name ... } ```
Many C code freeing pointers calls: ``` if (p) free(p); ``` But why? I thought C standard say thefreefunction doesn't do anything given a NULL pointer. So why another explicit check?
The construct: ``` free(NULL); ``` has always been OK in C, back to the original UNIX compiler written by Dennis Ritchie. Pre-standardisation, some poor compilers might not have fielded it correctly, but these days any compiler that does not cannot legitimately call itself a compiler for the C language. Using it typically leads to clearer, more maintainable code.
Today we were discussing how long Garbage Collection breaks needs. And were wondering how long it would take to simply wipe 1 Gigabyte of memory. What would it take?
On my machine, about one second: ``` #include <stdlib.h> #include <stdio.h> const long long int NUM = 1024*1024*1024/8; int main(void) { long long int* ptr = malloc(NUM * sizeof ptr); printf("Gigabytes: %lld\n",NUM * sizeof ptr / 1024 / 1024 / 1024); for(int i=0;i<NUM;i++) { ptr[i]=1l; } } ``` I then run the following (which unwillingly measures the allocation time, too: ``` $ gcc -O3 -std=c99 mem.c -o mem $ time ./mem Gigabytes: 1 real 0m1.056s user 0m0.205s sys 0m0.845s ```
Suppose I have an array ``` unsigned char arr[]= {0,1,2,3,4,5,6,7,8,9}; ``` Is there a way to perform shift operation on them besides just copying them all into another array. We can easily do it using linked lists but I was wondering if we can use a shift operator and get work done faster. Note: The data in this question is just an example. The answer should be irrecpective of the data in the array.
If you want a circular shift of the elements: ``` std::rotate(&arr[0], &arr[1], &arr[10]); ``` ... will do the trick. You'll need to #include the algorithm header.
Does not work as expected becuase it does not set the MSB bit correct. I am using metrowerks compiler. ``` //shifting right 5 characters char * buffer; buffer=global_buffer; for(i=0;i<5;i++) //shift right for 1; { buffer[17-i]=(buffer[17-i]>>1)|(buffer[17-i-1]<<7); } ``` EDIT input buffer (just before for loop) 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x2F,0xA0,0xC6,0x9D i got after for loop 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x17,0xD0,0xE3,0xCE
You probably want "unsigned char *buffer;" This will shift zeros into the top bits rather than retaining the sign bit.
I'm looking for a nice and efficient implementation of Xiaolin Wu's anti-aliased line drawing algorithm in C, does anyone have this code they could share with me? Thanks
Wikipedia haspseudo code. Google has many examples likethis oneorthis one. And your question reminded me this nice article onantialiasing. EDIT: It's time to discoverHugo Helias's websiteif you don't know it already.
the following c statement is not passing through compiler .error being "expected expression before return". ``` int max( int a,int b) { a>b?return a:return b; } ``` and yeah ,i know i can write this for finding max as ``` return a>b?a: b; ``` which is quite okay and will run perfectly. but my question is what is exact problem with the first code.why cant we use return in ternary opoerator,although we can use function call quite easily over there? THANKS in advance!!!
The C grammar says that the things after the '?' and the ':' must be expressions - return is not an expression, it is a statement.
gcc 4.4.1 I am maintaining someone's code and I have come across something that I don't understand. ``` #define RES_API(name, func) name##_##func ``` Can anyone explain? Many thanks,
The##is a concatenation operator. UsingRES_API(name1, func1)in your code would be replaced withname1_func1. More informationhere.
If it is known that an application leaks memory (when executed), what are the various ways to locate such memory leak bugs in the source code of the application.I know of certain parsers/tools (which probably do static analysis of the code) which can be used here but are there any other ways/techniques to do that,specific to the language (C/C++)/platform?
compile Your code with -g flagDownload valgrind (if You work on Linux) an run it with --leak-check=yes option I thinkt that valgrind is the best tool for this task. For Windows: See this topic:Is there a good Valgrind substitute for Windows?
In C, I have an array of structs defined like: ``` struct D { char *a; char *b; char *c; }; static struct D a[] = { { "1a", "1b", "1c" }, { "2a", "2b", "2c" } }; ``` I would like to determine the number of elements in the array, butsizeof(a)returns an incorrect result: 48, not 2. Am I doing something wrong, or issizeofsimply unreliable here? If it matters I'm compiling withGCC4.4.
sizeofgives you the size in bytes, not the number of elements. As Alok says, to get the number of elements, divide the size in bytes of the array by the size in bytes of one element. The correct C idiom is: ``` sizeof a / sizeof a[0] ```
I'm looking to build a Morse decoder (and eventually a coder) in C. I'd like to use the audio port as input, and sample the incoming voltage on the port. How do I go about reading the voltage on a microphone audio port in Windows using C?
The simplist way is to use thewaveInfunctions provided by the Win32 API. You can readRecording and Playing Sound with the Waveform Audio Interfacefor an overview, or just dive into theAPI documentation.
I am writing a program to count the number of whitespace characters in a text file. I use "isspace" to count it. The content in the text file is "1 1 1", but the counter still 0, what's wrong of the codes? ``` #include "stdafx.h" #include "ctype.h" int _tmain(int argc, _TCHAR* argv[]) { FILE* input; char x; int space = 0; input = fopen("123.txt", "r"); while ((fscanf(input, " %c", &x)) == 1) { if (isspace(x)) space++; } printf("space : %d\n", space); return 0; } ```
scanf-family functions will automatically skip whitespace when it's present in the format string. Consider usingfgetcinstead.
How would I P/Invoke a C function which returns a union'ed struct?
You would need to use aStructLayoutof explicit and theFieldOffsetattribute. An example of usage: ``` <StructLayout(LayoutKind.Explicit, Size:=4)> _ Public Structure DWord <FieldOffset(0)> Public Value As Int32 <FieldOffset(0)> Public High As Int16 <FieldOffset(2)> Public Low As Int16 End Structure ```
What does this line mean? I havn't done C in a few years. Does it perform the operation in parens then make the int result a pointer?? ``` b[0] = *(start + pos++); ```
Apparentlystartis a pointer (or an array, which will decay to a pointer here anyway), which means that the result of the expression in()is a pointer, not anint. The*simply dereferences that pointer. The whole thing is equivalent to plainb[0] = start[pos++], but for some reason some people prefer to use the obfuscated form as in your post.
See question. Also any links to example code or example code on how to validate an xml file against multiple schemas would be helpful. EDT: Sorry forgot to mention that this is for LINUX
libxml2is portable, pure C andimplements XML Schema. It is also open-source (MIT license) and has an active developer community.
Let's say that I want to get the size in bytes or in chars for the name field from: ``` struct record { int id; TCHAR name [50]; }; ``` sizeof(record.name)does not work.
The solution for this is not so pretty as you may think: size_in_byte = sizeof(((struct record *) 0)->name) size_in_chars = _countof(((struct record *) 0)->name) If you want to use the second one on other platforms than Windows try: #define _countof(array) (sizeof(array)/sizeof(array[0]))
I have a python code computing a matrix, and I would like to use this matrix (or array, or list) from C code.I wanted to pickle the matrix from the python code, and unpickle it from c code, but I could not find documentation or example on how to do this. I found something about marshalling data, but nothing about unpickling from C. Edit : Commenters Peter H asked if I was working with numpy arrays. The answer is yes.
You might want to use something more standardized, likeJSON. You have a JSON module in Python 2.6. There are 6 different JSON modules for C. You might want to use something more C-like, like the Pythonstructmodule. It can build a C-compatible object directly, saving you from pickling and unpickling.http://docs.python.org/library/struct.html