question
stringlengths
25
894
answer
stringlengths
4
863
While writing a simple server-client application, this question came in my mind. When someone tries to write to a broken pipe, a SIGPIPE would be generated. Let's say I handle the signal in my code. Now what error does the write call returns - EPIPE or EINTR ( as it was interrupted by a signal). I tried with a sample program and I seem to be getting EPIPE always. Is this a guaranteed behavior or it could be any of the two error values?
POSIX says that EPIPE should be returned and SIGPIPE sent: For write()s or pwrite()s to pipes or FIFOs not open for reading by any process, or with only one end open.For write()s to sockets that are no longer connected or shut down for writing. You can have a look at the POSIX standardhere
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago. Take look at the code that follows. ``` "Hello " "World!"; "The number is ", 37; int x=23; char *y="232"; x,x+2,x*3; atoi(y) - x; ``` It is a perfectly valid fragment of C(99) source. But! All that expressions return to nowhere! How can one trace or even use all this anonymous values? Where are they stored and what is their purpose?
These values go nowhere. You can not retrieve them. In fact, most are optimized out by the compiler. That entire fragment can be simplified to atoi("232") because function calls usually can't be optimized out.
I am reading a binary file. and when it reaches the end. it seems it is terminated by feof() function. is it because there is no EOF character for binary files? if so how can i solve it. currently my code is using a while loop ``` while (!feof(f)) ``` when it reaches the end of file at position 5526900. it doesn't stop. it just keeps trying to read, and i am stuck at the loop. can anyone tell me why and how to solve it. Thanks
You should not use feof() to loop on - instead, use the return value of fread() - loop until it returns zero. This is easy to see if you consider reading an empty file - feof() returns the EOF status AFTER a read operation, so it will always try to read bogus data if used as a loop control. I don't know why so many people think feof() (and the eof() member of C++ streams) can predict if the next read operation will succeed, but believe me, they can't.
InPHPI can do it as simple as : ``` file_get_contents('http://stackoverflow.com/questions/ask'); ``` What's the shortest code to do the same inC? UPDATE When I compile the sample with curl, got errors like this: ``` unresolved external symbol __imp__curl_easy_cleanup referenced in function _main ```
Uselibcurl, refer to theirexample C snippets ``` #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se"); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); } return 0; } ```
I'm using multithreading in my application with _beginthread and right now to wait until all threads are done I have global bools that get set to true as each thread completes so I'm in a while loop until then. There must be a cleaner way of doing this? Thanks
You can useWaitForMultipleObjectsto wait for the threads to finish in primary thread.
I'm trying to read binary data in a C program with read() but EOF test doesn't work. Instead it keeps running forever reading the last bit of the file. ``` #include <stdio.h> #include <fcntl.h> int main() { // writing binary numbers to a file int fd = open("afile", O_WRONLY | O_CREAT, 0644); int i; for (i = 0; i < 10; i++) { write(fd, &i, sizeof(int)); } close(fd); //trying to read them until EOF fd = open("afile", O_RDONLY, 0); while (read(fd, &i, sizeof(int)) != EOF) { printf("%d", i); } close(fd); } ```
readreturns the number of characters it read. When it reaches the end of the file, it won't be able to read any more (at all) and it'll return 0, not EOF.
There are many times that I get compile errors when I usechar*instead ofconst char*. So, I am not sure the actual difference, the syntax and the compile mechanism.
If you're after the difference between the two, just think of them as: char*is a pointer that points to a location containing a value of type char that can also be changed. The pointer's value can be changed, i.e. the pointer can be modified to point to different locations.const char*is a pointer, whose value can be also changed, that points to a location containing a value of type char thatcannotbe changed.
I want to define a macro which includes another header file like so: ``` #define MY_MACRO (text) #include "__FILE__##_inline.inl" ``` So that when the preprocessor parses file person.h, MY_MACRO(blahblah) expands to #include "person.h.inline.inl" any hints on how to do this ?
It's not possible to use#defineto construct other preprocessor directives, unless you run the preprocessor twice. But in your case even running the preprocessor twice won't help because the#includemust be a single string of the form"..."or<...>.
This is a question for experienced C/C++ developpers. I have zero knowledge of compiling C programs with "make", and need to modify an existing application, ie. change its "config" and "makefile" files. The .h files that the application needs are not located in a single-level directory, but rather, they are spread in multiple sub-directories. In order for cc to find all the required include files, can I just add a single "-I" switch to point cc to the top-level directory and expect it to search all sub-dirs recursively, or must I add several "-I" switches to list all the sub-dirs explicitely, eg. -I/usr/src/myapp/includes/1 -I/usr/src/myapp/includes/2, etc.? Thank you.
This question appears to be about the C compiler driver, rather than make. Assuming you are using GCC, then you need to list each directory you want searched: ``` gcc -I/foo -I/foo/bar myprog.c ```
Maybe this has been asked before, but I couldn't find it. My question is simple: Does it make sense to write an application in higher level languages (Java, C#, Python) and time/performance-critical functions in C? Or at this point unless you do very low level OS/game/sensor programming it is all the same to have a full, say, Java application?
It makes sense if you a) notice a performance issue, AND b) use performance measurements to locate where the problem occurs, AND c) can't achieve the desired performance by modifying the existing code. If any of these items don't apply, then it's probably premature optimization.
I am writing a program that repeatedly does an operation till Ctrl+C is hit by the user in the Linux terminal. I am programming in C. Any ideas how i can implement this. I have tested my program by using "for" loops with a condition but now i want to make it run as long as Ctrl+C is hit by the user and interrupted. What I was thinking was of writing a do while loop like the following do{ /Computation/ } while(Ctrl+C is not hit) But i dont know how to check for the Ctrl+C input from the user. Any suggestions will be appreciated. Thanks
A signal trap will do the trick more cleanly than spudd86's suggestion. This example can be improved significantly, though. ``` #include <signal.h> /* ... */ int execute; void trap(int signal){ execute = 0; } int main() { /* ... */ signal(SIGINT, &trap); execute = 1; while(execute){ /* ... */ } signal(SIGINT, SIG_DFL); /* ... */ } ```
Is there any way to detect if I am connected to a VPN using standard windows APIs in C? Basically I have a client that has to sync with a server but only if the VPN is connected. This could be a standard windows VPN client or a Citrix. Is RAS helpful here? thank you, code is appreciated. EDIT: to make it clearer. This is a client that will run on our customer's computer and they set the VPN and server however they want. So I wanted to know if windows keeps a setting somewhere that I can read via an API or registry or WMI or whatever that can tell me VPN: no or yes and if yes the info.
With the VPN I suspect you able to access resources that don't exists otherwise. So you could PING test a server on the VPN network. ICMP is the protocol for ping. Here is some examples:http://www.alhem.net/project/ex10/index.html
Can I write simply ``` for (int i = 0; ... ``` instead of ``` int i; for (i = 0; ... ``` in C or C++? (And will variableibe accessible inside the loop only?)
It's valid in C++. It was not legal in the original version of C.But was adopted as part of C in C99 (when some C++ features were sort of back ported to C)Using gcc ``` gcc -std=c99 <file>.c ``` The variable is valid inside the for statement and the statement that is looped over. If this is a block statement then it is valid for the whole of the block. ``` for(int loop = 0; loop < 10; ++loop) { // loop valid in here aswell } // loop NOT valid here. ```
when i try ``` char bla[32] = "foobar"; int i; putchar(bla[i]); ``` withstrlen(bla) < i < 32,bla[i]is always\0. but isn't this in fact undefined behaviour, and should be avoided?
In section 6.7.8 of the C99 Standard, paragraph 21 states: If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration. And paragraph 10 states that static arithmetic types (which would include char) are initialized to zero. Based on that, you should expect the rest of the array to be initialized to zero when using a string literal as the initializer.
In c++, setw function is used to set the number of characters to be used as the field width for the next insertion operation. Is there any function in C, I mean, in standard c library, which does the same thing?
printf ("%5d", 42); Will print 42 using 5 spaces. Read the man pages of printf to understand how character padding, overflow and other nuances work. EDIT: Some examples - ``` int x = 4000; printf ("1234567890\n"); printf ("%05d\n", x); printf ("%d\n", x); printf ("%5d\n", x); printf ("%2d\n", x); ``` Gives the output ``` 1234567890 04000 4000 4000 4000 ``` Notice that the%2dwas too small to handle the number passed to it, yet still printed the entire value.
``` char *a=NULL; char *s=NULL; a=(char *)calloc(1,(sizeof(char))); s=(char *)calloc(1,(sizeof(char))); a="DATA"; memcpy(s,a,(strlen(a))); printf("%s",s); ``` Can you plz tell me why its printing DATA½½½½½½½½■ε■????How to print only DATA?? Thanks
Strings in C are terminated by a zero character value (nul). strlen returns the number of characters before the zero. So you are not copying the zero. printf keeps going, printing whatever is in the memory after s until it hits a zero. You also are only creating a buffer of size 1, so you are writing data over whatever is after s, and you leak the memory calloc'd to a before you set a to be a literal. Allocate the memory for s after finding the length of the string, allocating one more byte to include the nul terminator, then copy a into s. You don't need to allocate anything for a as the C runtime looks after storing the literal "DATA".
I have made strcat() function myself but after adding the string it is printing an extra ascii symbol. Please tell why? ``` #include<stdio.h> #include<conio.h> #include<string.h> void xstrcat(char string1[],char string2[]); void main(void) { char x[100]; char string1[40],string2[40]; printf("Enter a string:"); gets(string1); puts("Enter another string:"); gets(string2); xstrcat(string1,string2); printf("%s",string1); getch(); } void xstrcat(char string1[],char string2[]) { int i,x,y; x=strlen(string1); y=strlen(string2); for(i=0;i<y;i++) { string1[i+x]=string2[i]; }//for ends } ```
Yourxstrcat()function isn't placing a null terminator character at the end of the resulting string. One possible fix might be to put the following just before thexstrcat()function returns: ``` string1[x+y] = '\0'; ```
I have the following ``` size_t i = 0; uint32_t k = 0; printf("i [ %lu ] k [ %u ]\n", i, k); ``` I get the following warning when compiling: ``` format ‘%lu’ expects type ‘long unsigned int’, but argument has type ‘uint32_t’ ``` When I ran this using splint I got the following: ``` Format argument 1 to printf (%u) expects unsigned int gets size_t: k ``` Many thanks for any advice,
Try ``` #include <inttypes.h> ... printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k); ``` Thezrepresents an integer of length same assize_t, and thePRIu32macro,defined in the C99 headerinttypes.h, represents an unsigned 32-bit integer.
I want to make a program that forces it's user to input text but doesn't allow him to erase any of it, what's a simple way of doing it in C? The only thing I've got is(c = getchar()) != EOF && c != '\b'which doesn't work. Any ideas?
POSIX - unix version ``` #include <sys/types.h> #include <termios.h> #include <stdio.h> #include <string.h> int main() { int fd=fileno(stdin); struct termios oldtio,newtio; tcgetattr(fd,&oldtio); /* save current settings */ memcpy(&newtio, &oldtio, sizeof(oldtio)); newtio.c_lflag = ICANON; newtio.c_cc[VERASE] = 0; /* turn off del */ tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); /* process user input here */ tcsetattr(fd,TCSANOW,&oldtio); /* restore setting */ return 0; } ```
I have aFILE *, returned by a call tofopen(). I need to get a file descriptor from it, to make calls likefsync(fd)on it. What's the function to get a file descriptor from a file pointer?
The proper function isint fileno(FILE *stream). It can be found in<stdio.h>, and is a POSIX standard but not standard C.
I was browsing some code and I came across this macro definition ``` #define D(x) do { } while (0) ``` And its used in the code like this, ``` D(("couldn't identify user %s", user)); ``` I ran the code, and that particular line doesn't do anything. So, why would some one define a macro like that? In case you're wondering, that macro is defined in the _pam_macros.h header file.
Most likelyDis for debugging, and there's an#ifdefelsewhere that makes it do something more useful if debugging is enabled, like output the message or log it to a file. Thedo/whileloop is to make it require a semi-colon at the end, so the user can call it asD(...);instead of justD(...)(seethis post)
I've made a small application in C with Netbeans. I've ran the application in Netbeans and it created an exe. I used that exe and it worked fine on my comp but when I move it to other comp it says: "This application failed to start because cygwin1.dll was not found. Re-installing the application may fix this problem." How can i create the exe so that it runs anywhere?
The problem is you're using Cygwin GCC to compile your code. Cygwin provides a unix-like environment if you're not doing anything Unix-y you can recomplie-mno-cygwin- seeCan you statically compile a cygwin application?if you are using Unix calls you'll need to distribute cygwin1.dll along with your appor you can recompile with a different compiler, e.g. a GCC that targets mingw32 not cygwin, or one of the free (as-in-beer) Microsoft compilers from the platform SDK or Visual Studio Express downloads.
Which version of ANSI C standard does Turbo C 3.0 follow wholly or partly? C89 or C90 ?
Turbo C++ 3.0 was released in 1991, which means that in its C compilation it probably supports K&R C and C89 (C90 was essentially identical). It won't support C95 well, because that version of the standard wasn't available.
i am trying to create a function likestrlen()in string.h It's giving me the errorcan not convert char* to char ``` #include<stdio.h> #include<conio.h> int xstrlen(char string); void main(void) { char string[40]; puts("Enter string:"); gets(string); printf(" %s is the length of %d", string, xstrlen(string)); } int xstrlen(char string[]) { int i; for (i=0; ; i++) { if (string[i] == '\0') break; }// for ends return i; } ```
Your prototype: ``` int xstrlen(char string); ``` Does not match the function definition: ``` int xstrlen(char string[]) { ... } ``` Change the prototype to: ``` int xstrlen(char string[]); ```
I need to create GdkPixBuf collection. I try to save pixbufs in GList - mw->disp_list: ``` GtkTreeIter iter; int i = 0; for (i; i < g_list_length(list) - 1; ++i) { char* file = image_list_get_current_file_path( list ); mw->p1 = gdk_pixbuf_new_from_file(file,NULL); mw->p1 = scale_pix(mw->p1,128); mw->disp_list = g_list_append (mw->disp_list, mw->p1); if (!mw->img_list->current->next ) image_list_get_first(mw->img_list); else image_list_get_next(mw->img_list); } ``` Where p1 - it's GtkPixBuf*. But when i try to use mw->disp_list in another function i see that it is NULL. What's wrong? Thank you.
At the moment I see just one problem, and it is about the loop that should be: ``` for (i = 0; i < g_list_length(list); ++i) ``` The problem could be the -1: if list contains 1 element, you do not loop at all, since 1-1 = 0 and0 < 0is false.
I see there are many version of autoconf and automake available in my ubuntu linux. If I want create a new project from scratch, what's best choice, latest versions or older versions?
Go with the latest version. It's only developers who are rebuilding the configure system that need to useautoconfandautomake(and thus need to have the newer version installed), which likely just means "you"; it won't affect users who are just building your project using your distributed configure files.
I have just noticed about a librarySFIOfor a safe and fast IO processing in C. But it is not very up to date. The last version of library is released in20052012and I couldn't assess that if the claimed benefits of SFIO over STDIO are still valid with comparison to the recent releases of standard IO library. Also Would it be reasonable to use this library in a production code?
I would prefer using standard stuffs instead of relying on a lib that is not maintained or developed anymore. Do tests however to know if your code really benefits from its usage. If it is not hard, develop your code with switches definible at compile time to usesfioor the standard approach, so that you can switch to one or another according to needs and if you noticesfiois giving problems.
I need to generate values according to time of the day, is there a neat way to accomplish that ? from 9-12 value should be between x - y from 6-9 value should be between a - b is there any other way than getting timeinfo struct and extracting hour out of it?
You should take a look atboost::posix_time. ``` using namespace boost::posix_time; using namespace boost::gregorian; ptime now = second_clock::local_time(); // You can compare now with other ptime values ptime nine_o_clock = day_clock::local_day() + hours(9); ptime twelve_o_clock = day_clock::local_day() + hours(12); if ((now >= nine_o_clock) && (now < twelve_o_clock)) { // Do what you want. } ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago. ``` #include<stdio.h> main() { int a[]={0,2,4,6,8}; int *ptr; ptr=a; printf("%d", *((char*)ptr+4)); } ``` *((char*)ptr+4))What is the purpose of this?
It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case whereintoccupies 4 bytes, it'll look at the first byte of the secondintin the array. Thatcharwill be promoted to anint, passed toprintf, and printed out.
I'm writing a little pong clone with ncurses and C. I need to find a way to set the keyboard repeat delay to make it easier for a player to move the paddle, otherwise they are stuck hitting the down key and waiting about 50 milliseconds until the key begins to repeat. I've checked the ncurses man pages and documentation, and I can't seem to find any reference to changing keyboard repeat delays, also the program kbdrate is not suitable for my use, because it would be a bit strange for a game to ask to be run as root. Thanks, Emmanuel
How about capturing the keydown and the repeatedly checking to see if the key is up yet?
Microsoft's docs say: Specifies that the corresponding point in lpPoints is a control point or ending point for a Bèzier curve. PT_BEZIERTO values always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bèzier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending (if hard-coded) point. http://msdn.microsoft.com/en-us/library/dd144908%28v=VS.85%29.aspx does this mean it returns cubic or quadratic curves? Thanks
It's a cubic with shared endpoints. p[0], p[1], p[2], p[3] make up the first segment; p[3], p[4], p[5], and p[6] make up the second segment. And so forth.
What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h: Part 1Part 2Part 3
I'd like the compiler to output a file containing the pointers to all global variables in the source code it is compiling, and also the sizes of them. Is this possible? Is there a way to do it in any c compiler?
Something like a map file? That will show where the globals and statics are allocated, but not what they point at. Most compilers (linkers) will output one automatically or with a simple statement. Just search for map file in your documentation.
gcc 4.4.4 c89 I am using the code below. However, I keep getting the same number: ``` size_t i = 0; for(i = 0; i < 3; i++) { /* Initialize random number */ srand((unsigned int)time(NULL)); /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ``` I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times. Many thanks,
You're seedinginsidethe loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time. You need to move your seed functionoutsidethe loop: ``` /* Initialize random number */ srand((unsigned int)time(NULL)); for(i = 0; i < 3; i++) { /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ```
I have made strcat() function myself but after adding the string it is printing an extra ascii symbol. Please tell why? ``` #include<stdio.h> #include<conio.h> #include<string.h> void xstrcat(char string1[],char string2[]); void main(void) { char x[100]; char string1[40],string2[40]; printf("Enter a string:"); gets(string1); puts("Enter another string:"); gets(string2); xstrcat(string1,string2); printf("%s",string1); getch(); } void xstrcat(char string1[],char string2[]) { int i,x,y; x=strlen(string1); y=strlen(string2); for(i=0;i<y;i++) { string1[i+x]=string2[i]; }//for ends } ```
Yourxstrcat()function isn't placing a null terminator character at the end of the resulting string. One possible fix might be to put the following just before thexstrcat()function returns: ``` string1[x+y] = '\0'; ```
I have the following ``` size_t i = 0; uint32_t k = 0; printf("i [ %lu ] k [ %u ]\n", i, k); ``` I get the following warning when compiling: ``` format ‘%lu’ expects type ‘long unsigned int’, but argument has type ‘uint32_t’ ``` When I ran this using splint I got the following: ``` Format argument 1 to printf (%u) expects unsigned int gets size_t: k ``` Many thanks for any advice,
Try ``` #include <inttypes.h> ... printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k); ``` Thezrepresents an integer of length same assize_t, and thePRIu32macro,defined in the C99 headerinttypes.h, represents an unsigned 32-bit integer.
I want to make a program that forces it's user to input text but doesn't allow him to erase any of it, what's a simple way of doing it in C? The only thing I've got is(c = getchar()) != EOF && c != '\b'which doesn't work. Any ideas?
POSIX - unix version ``` #include <sys/types.h> #include <termios.h> #include <stdio.h> #include <string.h> int main() { int fd=fileno(stdin); struct termios oldtio,newtio; tcgetattr(fd,&oldtio); /* save current settings */ memcpy(&newtio, &oldtio, sizeof(oldtio)); newtio.c_lflag = ICANON; newtio.c_cc[VERASE] = 0; /* turn off del */ tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); /* process user input here */ tcsetattr(fd,TCSANOW,&oldtio); /* restore setting */ return 0; } ```
I have aFILE *, returned by a call tofopen(). I need to get a file descriptor from it, to make calls likefsync(fd)on it. What's the function to get a file descriptor from a file pointer?
The proper function isint fileno(FILE *stream). It can be found in<stdio.h>, and is a POSIX standard but not standard C.
I was browsing some code and I came across this macro definition ``` #define D(x) do { } while (0) ``` And its used in the code like this, ``` D(("couldn't identify user %s", user)); ``` I ran the code, and that particular line doesn't do anything. So, why would some one define a macro like that? In case you're wondering, that macro is defined in the _pam_macros.h header file.
Most likelyDis for debugging, and there's an#ifdefelsewhere that makes it do something more useful if debugging is enabled, like output the message or log it to a file. Thedo/whileloop is to make it require a semi-colon at the end, so the user can call it asD(...);instead of justD(...)(seethis post)
I've made a small application in C with Netbeans. I've ran the application in Netbeans and it created an exe. I used that exe and it worked fine on my comp but when I move it to other comp it says: "This application failed to start because cygwin1.dll was not found. Re-installing the application may fix this problem." How can i create the exe so that it runs anywhere?
The problem is you're using Cygwin GCC to compile your code. Cygwin provides a unix-like environment if you're not doing anything Unix-y you can recomplie-mno-cygwin- seeCan you statically compile a cygwin application?if you are using Unix calls you'll need to distribute cygwin1.dll along with your appor you can recompile with a different compiler, e.g. a GCC that targets mingw32 not cygwin, or one of the free (as-in-beer) Microsoft compilers from the platform SDK or Visual Studio Express downloads.
Which version of ANSI C standard does Turbo C 3.0 follow wholly or partly? C89 or C90 ?
Turbo C++ 3.0 was released in 1991, which means that in its C compilation it probably supports K&R C and C89 (C90 was essentially identical). It won't support C95 well, because that version of the standard wasn't available.
i am trying to create a function likestrlen()in string.h It's giving me the errorcan not convert char* to char ``` #include<stdio.h> #include<conio.h> int xstrlen(char string); void main(void) { char string[40]; puts("Enter string:"); gets(string); printf(" %s is the length of %d", string, xstrlen(string)); } int xstrlen(char string[]) { int i; for (i=0; ; i++) { if (string[i] == '\0') break; }// for ends return i; } ```
Your prototype: ``` int xstrlen(char string); ``` Does not match the function definition: ``` int xstrlen(char string[]) { ... } ``` Change the prototype to: ``` int xstrlen(char string[]); ```
I need to create GdkPixBuf collection. I try to save pixbufs in GList - mw->disp_list: ``` GtkTreeIter iter; int i = 0; for (i; i < g_list_length(list) - 1; ++i) { char* file = image_list_get_current_file_path( list ); mw->p1 = gdk_pixbuf_new_from_file(file,NULL); mw->p1 = scale_pix(mw->p1,128); mw->disp_list = g_list_append (mw->disp_list, mw->p1); if (!mw->img_list->current->next ) image_list_get_first(mw->img_list); else image_list_get_next(mw->img_list); } ``` Where p1 - it's GtkPixBuf*. But when i try to use mw->disp_list in another function i see that it is NULL. What's wrong? Thank you.
At the moment I see just one problem, and it is about the loop that should be: ``` for (i = 0; i < g_list_length(list); ++i) ``` The problem could be the -1: if list contains 1 element, you do not loop at all, since 1-1 = 0 and0 < 0is false.
I see there are many version of autoconf and automake available in my ubuntu linux. If I want create a new project from scratch, what's best choice, latest versions or older versions?
Go with the latest version. It's only developers who are rebuilding the configure system that need to useautoconfandautomake(and thus need to have the newer version installed), which likely just means "you"; it won't affect users who are just building your project using your distributed configure files.
I have just noticed about a librarySFIOfor a safe and fast IO processing in C. But it is not very up to date. The last version of library is released in20052012and I couldn't assess that if the claimed benefits of SFIO over STDIO are still valid with comparison to the recent releases of standard IO library. Also Would it be reasonable to use this library in a production code?
I would prefer using standard stuffs instead of relying on a lib that is not maintained or developed anymore. Do tests however to know if your code really benefits from its usage. If it is not hard, develop your code with switches definible at compile time to usesfioor the standard approach, so that you can switch to one or another according to needs and if you noticesfiois giving problems.
I need to generate values according to time of the day, is there a neat way to accomplish that ? from 9-12 value should be between x - y from 6-9 value should be between a - b is there any other way than getting timeinfo struct and extracting hour out of it?
You should take a look atboost::posix_time. ``` using namespace boost::posix_time; using namespace boost::gregorian; ptime now = second_clock::local_time(); // You can compare now with other ptime values ptime nine_o_clock = day_clock::local_day() + hours(9); ptime twelve_o_clock = day_clock::local_day() + hours(12); if ((now >= nine_o_clock) && (now < twelve_o_clock)) { // Do what you want. } ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago. ``` #include<stdio.h> main() { int a[]={0,2,4,6,8}; int *ptr; ptr=a; printf("%d", *((char*)ptr+4)); } ``` *((char*)ptr+4))What is the purpose of this?
It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case whereintoccupies 4 bytes, it'll look at the first byte of the secondintin the array. Thatcharwill be promoted to anint, passed toprintf, and printed out.
I'm writing a little pong clone with ncurses and C. I need to find a way to set the keyboard repeat delay to make it easier for a player to move the paddle, otherwise they are stuck hitting the down key and waiting about 50 milliseconds until the key begins to repeat. I've checked the ncurses man pages and documentation, and I can't seem to find any reference to changing keyboard repeat delays, also the program kbdrate is not suitable for my use, because it would be a bit strange for a game to ask to be run as root. Thanks, Emmanuel
How about capturing the keydown and the repeatedly checking to see if the key is up yet?
Microsoft's docs say: Specifies that the corresponding point in lpPoints is a control point or ending point for a Bèzier curve. PT_BEZIERTO values always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bèzier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending (if hard-coded) point. http://msdn.microsoft.com/en-us/library/dd144908%28v=VS.85%29.aspx does this mean it returns cubic or quadratic curves? Thanks
It's a cubic with shared endpoints. p[0], p[1], p[2], p[3] make up the first segment; p[3], p[4], p[5], and p[6] make up the second segment. And so forth.
What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h: Part 1Part 2Part 3
I'd like the compiler to output a file containing the pointers to all global variables in the source code it is compiling, and also the sizes of them. Is this possible? Is there a way to do it in any c compiler?
Something like a map file? That will show where the globals and statics are allocated, but not what they point at. Most compilers (linkers) will output one automatically or with a simple statement. Just search for map file in your documentation.
i am trying to create a function likestrlen()in string.h It's giving me the errorcan not convert char* to char ``` #include<stdio.h> #include<conio.h> int xstrlen(char string); void main(void) { char string[40]; puts("Enter string:"); gets(string); printf(" %s is the length of %d", string, xstrlen(string)); } int xstrlen(char string[]) { int i; for (i=0; ; i++) { if (string[i] == '\0') break; }// for ends return i; } ```
Your prototype: ``` int xstrlen(char string); ``` Does not match the function definition: ``` int xstrlen(char string[]) { ... } ``` Change the prototype to: ``` int xstrlen(char string[]); ```
I need to create GdkPixBuf collection. I try to save pixbufs in GList - mw->disp_list: ``` GtkTreeIter iter; int i = 0; for (i; i < g_list_length(list) - 1; ++i) { char* file = image_list_get_current_file_path( list ); mw->p1 = gdk_pixbuf_new_from_file(file,NULL); mw->p1 = scale_pix(mw->p1,128); mw->disp_list = g_list_append (mw->disp_list, mw->p1); if (!mw->img_list->current->next ) image_list_get_first(mw->img_list); else image_list_get_next(mw->img_list); } ``` Where p1 - it's GtkPixBuf*. But when i try to use mw->disp_list in another function i see that it is NULL. What's wrong? Thank you.
At the moment I see just one problem, and it is about the loop that should be: ``` for (i = 0; i < g_list_length(list); ++i) ``` The problem could be the -1: if list contains 1 element, you do not loop at all, since 1-1 = 0 and0 < 0is false.
I see there are many version of autoconf and automake available in my ubuntu linux. If I want create a new project from scratch, what's best choice, latest versions or older versions?
Go with the latest version. It's only developers who are rebuilding the configure system that need to useautoconfandautomake(and thus need to have the newer version installed), which likely just means "you"; it won't affect users who are just building your project using your distributed configure files.
I have just noticed about a librarySFIOfor a safe and fast IO processing in C. But it is not very up to date. The last version of library is released in20052012and I couldn't assess that if the claimed benefits of SFIO over STDIO are still valid with comparison to the recent releases of standard IO library. Also Would it be reasonable to use this library in a production code?
I would prefer using standard stuffs instead of relying on a lib that is not maintained or developed anymore. Do tests however to know if your code really benefits from its usage. If it is not hard, develop your code with switches definible at compile time to usesfioor the standard approach, so that you can switch to one or another according to needs and if you noticesfiois giving problems.
I need to generate values according to time of the day, is there a neat way to accomplish that ? from 9-12 value should be between x - y from 6-9 value should be between a - b is there any other way than getting timeinfo struct and extracting hour out of it?
You should take a look atboost::posix_time. ``` using namespace boost::posix_time; using namespace boost::gregorian; ptime now = second_clock::local_time(); // You can compare now with other ptime values ptime nine_o_clock = day_clock::local_day() + hours(9); ptime twelve_o_clock = day_clock::local_day() + hours(12); if ((now >= nine_o_clock) && (now < twelve_o_clock)) { // Do what you want. } ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed13 years ago. ``` #include<stdio.h> main() { int a[]={0,2,4,6,8}; int *ptr; ptr=a; printf("%d", *((char*)ptr+4)); } ``` *((char*)ptr+4))What is the purpose of this?
It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case whereintoccupies 4 bytes, it'll look at the first byte of the secondintin the array. Thatcharwill be promoted to anint, passed toprintf, and printed out.
I'm writing a little pong clone with ncurses and C. I need to find a way to set the keyboard repeat delay to make it easier for a player to move the paddle, otherwise they are stuck hitting the down key and waiting about 50 milliseconds until the key begins to repeat. I've checked the ncurses man pages and documentation, and I can't seem to find any reference to changing keyboard repeat delays, also the program kbdrate is not suitable for my use, because it would be a bit strange for a game to ask to be run as root. Thanks, Emmanuel
How about capturing the keydown and the repeatedly checking to see if the key is up yet?
Microsoft's docs say: Specifies that the corresponding point in lpPoints is a control point or ending point for a Bèzier curve. PT_BEZIERTO values always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bèzier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending (if hard-coded) point. http://msdn.microsoft.com/en-us/library/dd144908%28v=VS.85%29.aspx does this mean it returns cubic or quadratic curves? Thanks
It's a cubic with shared endpoints. p[0], p[1], p[2], p[3] make up the first segment; p[3], p[4], p[5], and p[6] make up the second segment. And so forth.
What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h: Part 1Part 2Part 3
I'd like the compiler to output a file containing the pointers to all global variables in the source code it is compiling, and also the sizes of them. Is this possible? Is there a way to do it in any c compiler?
Something like a map file? That will show where the globals and statics are allocated, but not what they point at. Most compilers (linkers) will output one automatically or with a simple statement. Just search for map file in your documentation.
gcc 4.4.4 c89 I am using the code below. However, I keep getting the same number: ``` size_t i = 0; for(i = 0; i < 3; i++) { /* Initialize random number */ srand((unsigned int)time(NULL)); /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ``` I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times. Many thanks,
You're seedinginsidethe loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time. You need to move your seed functionoutsidethe loop: ``` /* Initialize random number */ srand((unsigned int)time(NULL)); for(i = 0; i < 3; i++) { /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ```
I am writing a client using libsoup APIs. I have done the following. ``` session = soup_session_sync_new(); msg = soup_message_new("GET","http://www.google.com"); status = soup_session_send_message(session,msg);` ``` However now i am getting the following error code in status. I print the reason phrase and it says thestatus= 4 , msg->reason_phrase = Cannot connect to destination How do i resolve this issue?
The problem was i use a proxy server to connect to internet. Hence i needed to set the session object property of SOUP_SESSION_PROXY_URI with the proxy-sever:port value. It works fine now. Time to test POST method now.
People usevoid main() /*empty parens ()*/ I have been taught to writevoid main(void) Any ideas what the difference is?
I'm not sure what the standards are nowadays, but in traditional ANSI C, using empty parentheses indicates that the function can takeanynumber of arguments. Declaring avoidparameter on the other hand indicates that the functiononly takes zero arguments. In this case (and many others), it really doesn't matter too much. If you want to be strict though, it's probably best to define thevoidparameter. Of course, themainfunction can also be defined asint main(int argc, const char* argv[])- which is perfectly valid, but often unnecessary if you don't care about arguments.
Is there any standardized structure of C source and header files? I'm thinking about something like this (example for C source file): // static variables // public variables // static methods // public methods
This is a totally subjective question. However, here's what I do approximately. Header: ``` // extern defines, constants and enums // public types // extern methods ``` There are no extern variables :-) Compilation unit: ``` // includes // definitions for extern constants // static function prototypes // everything else ``` I tend to group things that are related together, so I don't rigidly put all of the static variables or defines in oner place, but near where they are going to be used.
which of these two is better? ``` void SetBit(int *flag, int bit) { *flag |= 1 << bit; } ``` Or ``` int SetBit(int flag, int bit) { flag |= 1 << bit; return flag; } ```
I like the second one because it doesn't have any side effects. If you want to modifyflag, you can simply assign the result to itself: ``` flag = SetBit(flag, 4); ```
My funciton takes a number input from the user and recursively sums the number 'n' to one.Inputting a 5 would sum 1/5 + 1/4 + 1/3+ 1/2 + 1/1. ``` #include<stdio.h> #include<conio.h> //to float recursion(float num,float sum); void main(void) { float num=5,sum=0; //input num printf("%d",recursion(num,sum)); getch(); } float recursion(float num,float sum) { // int sum=0; every time u run it the sum is assigned 0 if( num==1) return 1; else { sum=sum+(1/num); num--; recursion(num,sum); } return sum; }//recursion function ends ``` The problem is, that it is giving 0. Can anyone help, please?
You should return the result of the recursive call: ``` return recursion(num,sum); ``` instead ofreturn sum.
I currently have inline functions calling another inline function (a simple 4 lines biggetAbs()function). However, I discovered by looking to the assembler code that the "big" inline functions are well inlined, but the compiler use abljump to call thegetAbs()function. Is it not possible to inline a function in another inline function? By the way, this is embedded code, we are not using the standard libraries. Edit : The compiler is WindRiver, and I already checked that inlining would be beneficial (4 instructions instead of +-40).
Depending on what compiler you are using you may be able to encourage the compiler to be less reluctant to inline, e.g. with gcc you can use__attribute__ ((always_inline)), with Intel ICC you can useicc -inline-level=1 -inline-forceinline, and with Apple's gcc you can usegcc -obey-inline.
i use gconf/gconf-client.h in ,y C application, but i don't know, is gconf on users machine. How can i check gconf/gconf-client.h and gconf there or not? Thank you
If the code compiles then probably its already installed. Otherwise you can download the package and install it. If you use thepkg-config --cflags gconf-2.0and compile, gcc will give corresponding error if the package doesnt exist in the PKG_CONFIG_PATH.
If I want to explode a string by parts in PHP into an array, I have the nifty explode() function where I just do the following ``` $mystring = "HI:THERE:HOW"; $stringarray = explode(":", $mystring); ``` And I get ``` $stringarray = ( [0] = "HI" [1] = "THERE" [2] = "HOW" ); ``` Is there a similar function in Objective C that explodes a string into an array? Thanks for any help!
``` NSArray *stringArray = [myString componentsSeparatedByString:@":"]; ```
I create my VBO like this: ``` glGenBuffersARB(1,&polyvbo); glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo); glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * tempvct.size(),&tempvct[0],GL_DYNAMIC_COPY); ``` Then to update it I just do the same thing: ``` glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo); glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * tempvct.size(),&tempvct[0],GL_DYNAMIC_COPY); ``` (needless to say, the data in tempvct changes) I'm just wondering if the above produces a memory leak. do I need to delete the vbo and recreate it, or will it automatically delete the old and update? Thanks
It doesn't cause a memory leak because the buffer is not reallocated. But why not useglBufferSubData()? it will probably be much faster and does basically the same thing.
I get a segfault from this line of code: ``` int fatblob[1820][286][5]; ``` Why is that?
Because your stack segment is smaller then1820*285*5ints. It's usually in a neighborhood of 1MB.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. i have question on this topic i think that answer is incorrect look Swap bits in a number in C 1110 1011 it is equal 235 but i get 3051 why?
The value3051in decimal is101111101011in binary. If you split it up into four bit segmens like this:1011 1110 1011, you see that the lowest four bits are repeated above the eight bits that you want. The reason for that is that you haven't masked the value that should be the top four bits. So instead of something like this: ``` (c >> 4) | ((c & 0x0f) << 4) ``` or something like this: ``` ((c >> 4) | (c << 4)) & 0xff ``` you simply have this: ``` (c >> 4) | (c << 4) ```
gcc 4.4.4 c89 I have seen this in some code I am maintaining. ``` #define FALSE 0 #define TRUE (!FALSE) ``` is there any difference in writing the following: ``` #define FALSE 0 #define TRUE 1 ``` Its been used in some functions like this: ``` if(condition failed) { return FALSE; } else { return TRUE; } ``` Many thanks for any suggestions,
One difference is, in the(!FALSE)case, if you change: ``` #define FALSE 0 ``` to ``` #define FALSE 1 ``` Your program still "works", without modifying TRUE... however, it's unlikely that would be safe anyways, because I'm sure your program relies on constructs such as ``` if (funtion_that_returns_FALSE()) { } ``` Which would break if you changed the definition ofFALSE. Don't change it :)
Is it possible to decompile third-party shared libraries built for solaris into C code?
Sort of. The short answer is: not really well. The long answer is to read what REC and other "reverse" compilers do. Maybe try here REC: http://www.backerstreet.com/rec/rec.htm try Rational Rose as well: http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Rose.html They can create C. or C++. Whether you can read it is another story.
This question already has answers here:Closed13 years ago. Possible Duplicate:Garbage Collection in C++ — why? Hi, I read few articles about Garbage Collectors, and still there is one thing I just don´t understand - why use garbage collection? I will try to explain my thoughts: Garbage Collector should release dynamically allocated memory back to system in case there is no need for it, right? So, if you write program in language C, you know wheather you need some piece of memory, so if don´t, you can simply destroy it. So, why to use GC, when all you need to do is actually just be wise with memory allocation/deallocation? Or am I missing something? Thanks.
To be more productive. In other words, the programmer can focus on writing the bits that is unique for his particular problem.
If I want to explode a string by parts in PHP into an array, I have the nifty explode() function where I just do the following ``` $mystring = "HI:THERE:HOW"; $stringarray = explode(":", $mystring); ``` And I get ``` $stringarray = ( [0] = "HI" [1] = "THERE" [2] = "HOW" ); ``` Is there a similar function in Objective C that explodes a string into an array? Thanks for any help!
``` NSArray *stringArray = [myString componentsSeparatedByString:@":"]; ```
I create my VBO like this: ``` glGenBuffersARB(1,&polyvbo); glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo); glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * tempvct.size(),&tempvct[0],GL_DYNAMIC_COPY); ``` Then to update it I just do the same thing: ``` glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo); glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * tempvct.size(),&tempvct[0],GL_DYNAMIC_COPY); ``` (needless to say, the data in tempvct changes) I'm just wondering if the above produces a memory leak. do I need to delete the vbo and recreate it, or will it automatically delete the old and update? Thanks
It doesn't cause a memory leak because the buffer is not reallocated. But why not useglBufferSubData()? it will probably be much faster and does basically the same thing.
I get a segfault from this line of code: ``` int fatblob[1820][286][5]; ``` Why is that?
Because your stack segment is smaller then1820*285*5ints. It's usually in a neighborhood of 1MB.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. i have question on this topic i think that answer is incorrect look Swap bits in a number in C 1110 1011 it is equal 235 but i get 3051 why?
The value3051in decimal is101111101011in binary. If you split it up into four bit segmens like this:1011 1110 1011, you see that the lowest four bits are repeated above the eight bits that you want. The reason for that is that you haven't masked the value that should be the top four bits. So instead of something like this: ``` (c >> 4) | ((c & 0x0f) << 4) ``` or something like this: ``` ((c >> 4) | (c << 4)) & 0xff ``` you simply have this: ``` (c >> 4) | (c << 4) ```
gcc 4.4.4 c89 I have seen this in some code I am maintaining. ``` #define FALSE 0 #define TRUE (!FALSE) ``` is there any difference in writing the following: ``` #define FALSE 0 #define TRUE 1 ``` Its been used in some functions like this: ``` if(condition failed) { return FALSE; } else { return TRUE; } ``` Many thanks for any suggestions,
One difference is, in the(!FALSE)case, if you change: ``` #define FALSE 0 ``` to ``` #define FALSE 1 ``` Your program still "works", without modifying TRUE... however, it's unlikely that would be safe anyways, because I'm sure your program relies on constructs such as ``` if (funtion_that_returns_FALSE()) { } ``` Which would break if you changed the definition ofFALSE. Don't change it :)
Is it possible to decompile third-party shared libraries built for solaris into C code?
Sort of. The short answer is: not really well. The long answer is to read what REC and other "reverse" compilers do. Maybe try here REC: http://www.backerstreet.com/rec/rec.htm try Rational Rose as well: http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Rose.html They can create C. or C++. Whether you can read it is another story.
This question already has answers here:Closed13 years ago. Possible Duplicate:Garbage Collection in C++ — why? Hi, I read few articles about Garbage Collectors, and still there is one thing I just don´t understand - why use garbage collection? I will try to explain my thoughts: Garbage Collector should release dynamically allocated memory back to system in case there is no need for it, right? So, if you write program in language C, you know wheather you need some piece of memory, so if don´t, you can simply destroy it. So, why to use GC, when all you need to do is actually just be wise with memory allocation/deallocation? Or am I missing something? Thanks.
To be more productive. In other words, the programmer can focus on writing the bits that is unique for his particular problem.
For purposes of type checking I would like to define a function on the lines of ``` void myfunc(type1 a, type2 b) { ... } ``` wheretype1andtype2are both typedefed touint8_t. So far so good, but for sanity and checking purposes (think DbC) I would like to prevent the function being called with atype2value for the first parameter or atype1for the second. Sadly, C's implicit typecasting is against me here. Does anyone know of a way?
You could wrap the two types in a Struct. ``` typedef struct { uint8_t data; } type1; typedef struct { uint8_t data; } type2; ``` Edit: I don't like it because you now have to use a.data instead of a
Using inline assembler [gcc, intel, c], how to check if the carry flag is set after an operation?
sbb %eax,%eaxwill store -1 in eax if the carry flag is set, 0 if it is clear. There's no need to pre-clear eax to 0; subtracting eax from itself does that for you. This technique can be very powerful since you can use the result as a bitmask to modify the results of computations in place of using conditional jumps. You should be aware that it is only valid to test the carry flag if it was set by arithmetic performed INSIDE the inline asm block. You can't test carry of a computation that was performed in C code because there are all sorts of ways the compiler could optimize/reorder things that would clobber the carry flag.
How can I imposeGdkDrawingAreaon theGtkImagefor painting on an image, for example?
GtkDrawingAreaandGtkImageare different classes, so you must choose one of them. You can still draw onGtkImage(and on any other widget), by connecting toexpose_eventsignal. You could also use plainGtkDrawingArea- displaying image is a matter of callinggdk_draw_pixbuffunction.
I have the following code which initiate the thread. ``` int iNMHandleThread = 1; HANDLE hNMHandle = 0; hNMHandle = CreateThread( NULL, 0, NMHandle, &iNMHandleThread, 0, NULL); if ( hNMHandle == NULL) ExitProcess(iNMHandleThread); ``` My question is What will happened if I run this code while the thread already in the running state.I want to initiate the multiple independent threads of NMHandle kindly give me some hints to solve this problem.
Each time you callCreateThread, a new thread is started that is independent of any other currently-running threads. Whether your "NMHandle" function is capable of running on more than one thread at a time is up to you: for example, does it rely on any global state?
I need to get the millisecond accuracy. I take a look onthis questionbut I am working on Windows: it gives linking errors for POSIX functions. It will be very good if I can get UTC time since 1970 with milliseconds precision.
Not in ANSI C, but the Windows API provides aGetSystemTimefunction as illustrated here:https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime
I have one basic doubt. I have a process which uses a shared library. If I am allocating some memory in the library then which address space it is. (Library or Process) In my opinion it is the process address space because once the library is attached it is all in process address space. Please correct me if I am wrong. Thanks Arpit
A library doesn't have its own address space. It is mapped into and executed within some process. So you are right. Memory allocations of a shared library are done inside the process which is using it.
Is there a way to declare first and then initialize an array in C? So far I have been initializing an array like this: ``` int myArray[SIZE] = {1,2,3,4....}; ``` But I need to do something like this ``` int myArray[SIZE]; myArray = {1,2,3,4....}; ```
In C99 you can do it using a compound literal in combination withmemcpy ``` memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray); ``` (assuming that the size of the source and the size of the target is the same). In C89/90 you can emulate that by declaring an additional "source" array ``` const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */ int myArray[SIZE]; ... memcpy(myarray, SOURCE, sizeof myarray); ```
I would like to know how the contents of a file can be cleared in C. I know it can be done usingtruncate, but I can't find any source clearly describing how.
The other answers explain how to usetruncatecorrectly... but if you found yourself on a non-POSIX system that doesn't haveunistd.h, then the easiest thing to do is just open the file for writing and immediately close it: ``` #include <stdio.h> int main() { FILE *file = fopen("asdf.txt", "w"); if (!file) { perror("Could not open file"); } fclose(file); return 0; } ``` Opening a file with"w"(for write mode) "empties" the file so you can start overwriting it; immediately closing it then results in a 0-length file.
My application is rendering about 100 display lists / second. While I do expect this to be intensive for the gpu, I don't see why it brings my cpu up to 80 - 90 %. Arn't display lists stored in the graphics card and not in system memory? What would I have to do to reduce this crazy cpu usage? My objects never change so that's why im using DL's instead of VBO's. But really my main concern is cpu usage and how I could reduce it. I'm rendering ~60 (or trying to) frames per second. Thanks
If you are referring tothese, then I suspect the bottleneck is going to be CPU related. All the decoding of such files is done on the CPU. Sure, each individual command might result in several commands to your graphics card, which will execute quickly, but the CPU is stuck doing decoding duty.
This question already has answers here:Closed13 years ago. Possible Duplicate:Why there is not a comprehensive c archive network? Everyone knows that C is very small language, it has just language primitives and almost no standard library (no data structures or algorithms). Therefore I have a question, how do I find good C libraries for data structures, algorithms and perhaps system programming? For example, if I need a hash-table, how do I find a good implementation? Or for example, if I need to work with graphs, what do I do? So far I have been writing everything myself. But my hash table implementation is nowhere good enough. It's very basic. What do advanced C programmers do with this problem? Do they really write all the libraries again themselves? Thanks, Boda Cydo.
GLib.
Using Glib Testing framework, I would like to know if I can reuse a pointer queued to be freed with g_test_queue_free? Here's a code sample of what I'm trying to do: ``` static void some_test() { gchar* tmp; tmp = func_returning_gchar_ptr (...params...); g_assert(tmp); g_test_queue_free(tmp); tmp = func_returning_gchar_ptr (...params...); g_assert(tmp); g_test_queue_free(tmp); ... } ```
Yes that should be fine
Which is the global variable which holds all the environmental variables for getenv() ? In what glibc file is this var filled with env vars ? I believe it to be **environ but when I set an env var in bash it only ouputs the SSH_AGENT_PID env var. Why is SSH_AGENT_PID set and why is it the only one that is set ? ``` DOCUMENT_ROOT='/foopath/'; export DOCUMENT_ROOT ``` ``` int main(void) { extern char **environ; printf("%s\n", *environ); // outputs: SSH_AGENT_PID=2822 } ```
char **environisNULL-terminated array of strings, so you should try: ``` extern char **environ; char **p; for (p = environ; *p; p++) { printf ("%s\n", *p); } ``` In other words,environ[0]is pointer to first env variable,environ[1]to second etc. Last element inenvironarray isNULL.
In c lets say we have 2 files 1.h ``` #include<2.h> blah blah ``` and we have 2.h ``` #include<1.h> code ``` How is this resolved??
Typically you protect your include file with an ifndef/define that corresponds to the file name. This doesn't prevent the file from being included again, but it does prevent the contents (inside the ifndef) from being used and triggering the recursive includes again. ``` #ifndef HEADER_1_h #define HEADER_1_h #include "2.h" /// rest of 1.h #endif #ifndef HEADER_2_h #define HEADER_2_h #include "1.h" // rest of 2.h #endif ```
Is there someone that knows what the computational cost for this two pieces of code is? ``` while (n > 2) n = sqrt(n); while (n > 2) n = log(n); ```
The second would beO(log* n)wherelog *is theiterated logarithm. Analysing the first one yields something like this: ``` sqrt(n) = n ^ (1/2) sqrt(sqrt(n)) = n ^ (1/4) sqrt(sqrt(sqrt(n))) = n ^ (1/8) ... sqrt applied k times = n ^ (1/2^k) ``` Consider that the first algorithm executesktimes (basically, the number of times we have to applysqrtuntiln <= 2). Consider this reasoning: ``` n ^ (1/2^k) = p (p <= 2) | ^ (2^k) n = p ^ (2^k) | log log n = (2^k) log p | log log log n = log (2 ^ k) + log log p log log n = klog2 + log log p => k ~= log log n ``` So the first algorithm isO(log log n).
Is there a C function that can concatenate all the passed arguments (except the name of the executable) into achar*and return it?
Try that: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char **argv) { unsigned int i; size_t len = 0; char *_all_args, *all_args; for(i=1; i<argc; i++) { len += strlen(argv[i]); } _all_args = all_args = (char *)malloc(len+argc-1); for(i=1; i<argc; i++) { memcpy(_all_args, argv[i], strlen(argv[i])); _all_args += strlen(argv[i])+1; *(_all_args-1) = ' '; } *(_all_args-1) = 0; printf("All %d args: '%s'\n", argc, all_args); free(all_args); return 0; } ```
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed12 years ago. I need a user-mode filesystem filter (not virtual filesystem). One of such frameworks ishttp://eldos.com/cbflt/, but it has some bugs and I need an alternative.Can you please suggest similar frameworks.
There is no such thing as a user-mode FS filter. You could write aminifilter driverthat delegates the computing (of the I/O operation verdict) to a user mode componentthrough a portand reports back the result.You can check out/src/filesystem/miniFilter/scannersample in theWinDDK.
Suppose I do asystem("ps-C nautilus");how do I return the result of this function in char* ? Thank you.
You don't. Not sure what platform you're on, but have a look at thepopenfunction instead. You'll get a bidirectional pipe this way, which you can do file operations on, like reading to get a string out of it.