question
stringlengths
25
894
answer
stringlengths
4
863
Isa = getchar()equivalent toscanf("%c",&a);? Isputchar(a)equivalent toprintf("%c",a);whereais acharvariable?
Generally speaking yes they are the same. But they are not in a few nitpicky ways. The functiongetcharis typed to returnintand notchar. This is done so thatgetcharcan both all possiblecharvalues and additionally error codes. So while the following happily compiles in most compilers you are essentially truncating away an error message ``` char c = getchar(); ``` The functionscanf, though, allows you to use achartype directly and separates out the error code into the return value.
``` #include<conio.h> #include<stdio.h> #define abc 7 int main() { int abc=1; printf("%d",abc); getch(); return 0; } ``` why this program is giving compile time error
You're assigning7=1which is invalid. Since you've definedabcto be 7, the preprocessor translates the line: ``` int abc=1; ``` to: ``` int 7=1; ``` Which is a syntax error in C (mygccsayssyntax error before numeric constant).
i am using pcap sample codes to create my own sniffer. i downloaded their sample sniffer and its working on windows but not on linux. i am using gcc compiler on both machines, and i have only pcap.h included.the error is : dereferencing pointer to incomplete type.the netmask is causing the error. the netmask is the mask of the first address of the interface. ``` u_int netmask=netmask((struct sockaddr_in*)d->addresses->netmask))->sin_addr.S_un.S_addr; ``` any solutions?
The compiler indicating that it doesn't have the definition ofstruct sockaddr_inin scope, so it can't look inside such a structure. On Linux that struct is defined in this header, which you will need to include: ``` #include <netinet/in.h> ```
A simple google search for: CGRect + C or CGRect in C brings back only Apple, iPhone, and Objective-C websites. However, I remember hearing that Core Graphics was part of C at my university. Did I hear incorrectly, or is CGRect something that I can use in C, or even C++ as it's Object oriented?
CGRect is defined in Carbon, which is plain C: ``` #import <Carbon/Carbon.h> int main() { CGRect r; } ``` If you look at preprocessor output you'll notice CGRect is just a plain struct: ``` $ gcc -E test.c | grep -A 3 "struct.*CGRect" struct CGRect { CGPoint origin; CGSize size; }; typedef struct CGRect CGRect; ```
How to get he upper limit of a number in C? If I divide 3 by 2 I want the answer to be 2 (ie 1.5 rounded to 2).
If you are just interested in dividing by 2, then just take (n + 1) / 2 to keep it in integer math. For example (3 + 1) / 2 gives 2. For a larger number x, use x - 1. For example, (3 + 7) / 8 = 1, for 3 divided by 8. For the general case, you are looking for the ceiling function -- ceil. A quick Google search for "math ceil C" gave this page at the top of the results:http://www.elook.org/programming/c/ceil.html
I'm using fgets with stdin to read in some data, with the max length I read in being 25. With one of the tests I'm running on this code, there are a few hundred spaces after the data that I want - which causes the program to fail. Can someone advise me as to how to ignore all of these extra spaces when using fgets and go to the next line?
Usefgets()iteratively, then scan the string to see whether it is all spaces (and whether it ends with a newline) and ignore it if it is. Or usegetc()orgetchar()in a loop instead? ``` char buffer[26]; while (fgets(buffer, sizeof(buffer), stdin) != 0) { ...process the first 25 characters... int c; while ((c = getchar()) != EOF && c != '\n') ; } ``` That code simply ignores all characters up to the next newline. If you want to ensure that they are spaces, add a test in the (inner) loop - but you have to decide what to do if the character is not a space.
What's the difference of pData1 and pData2, which are build as follows: pData1 = (int*) calloc (i,sizeof(int));int * pData2 = (int*) calloc (i,sizeof(int));
Without any more information, it would appear the only difference is thatpData2is local to the allocation since it is declared as anint *.pData1is not declared so it would have to have a larger (global?) scope and be defined elsewhere.
Rather Trivial Question. So I tried to do this: ``` if (array[0]=="some_string") ``` wherearrayis a list of strings ``` array[0] = "some_string_1"; array[1] = "some_string_2"; array[2] = "some_string_3"; ``` but obviously it doesn't work... What do I have to do?
``` if(array[0] == 'n') ``` ""signifiesstring''signifieschar Note:'a'is acharand"a"is astring, so'a' != "a" charis a single character (actually int), so if you want to compare strings, usestrcmpinstead.
In C++ one might use namespace to keep independent groups working in the same code base from inadvertently creating functions with the same name and thus creating a conflict. My question is, before the idea of namespace comes out, how might one emulate namespace in C.
By naming things differently, e.g.: ``` void namespace_group_function(); ``` gtk+is a prime example for this conventional style: ``` GtkWidget* gtk_window_new(GtkWindowType type); ```
I need to create a simple application that doesn't work after 30 days. How can I do that ? Is there a way to use Trial program after 30 days ?
There is always a way to use a trial program after 30 days.
See this example! ``` int main( int argc, char ** argv ) { int *ptr = malloc(100 * sizeof (int)); printf("sizeof(array) is %d bytes\n", sizeof(ptr)); } ``` The printf function return only 4 bytes! What is wrong? Thanks so much!!!
Nothing is wrong. You are asking for, and getting, the size of the pointer on your platform. It is not in general possible to get the size of the memory block that a pointer points at, you must remember it yourself if you need it later.
Currently I have my private key saved in a file, private.key, and I use the following function to load it: RSA *r = PEM_read_RSAPrivateKey("private.key", NULL, NULL, NULL); This works perfectly but I'm not happy with the file-based format; I want to save my key in pure binary form (ie, no base64 or similar) in achar*variable and load/save the key from/to it. This way I have much more freedom: I'll be able to store the key directly into the applicationconst char key[] { 0x01, 0x02, ... };, send it over a network socket, etc. Unfortunately though I haven't found a way to do that. The only way to save and load a key I know of reads/saves it to a file directly.
Used2i_RSAPrivateKeyto load directly from a buffer containing binary DER format: ``` const unsigned char *p = key; RSA *r = d2i_RSAPrivateKey(NULL, &p, keylen); ```
I have a simple gateway listener which generates a log at the screen output via printf. I would like to record it so I can insert it in a mysql table. ``` printf("\nPacket received!! Decoding..."); ``` I wonder if there is any fast way to do this is C. In case there is, could I get both outputs at the same time? Thanks
I'm not aware of any function that does output buffering in C. But you can simulate one easily like: ``` char buffer[MAX_BUFFER_SIZE] = ""; // that buffers your output. char temp[SOME_SUITABLE_MAX]; ``` now everytime you are usingprintf, use asprintfas follows: ``` sprintf(temp,"\nPacket received!! Decoding..."); ``` and them append this string to the buffer ``` strcat(buffer,temp); ``` keep doing thesprintffollowed bystrcatfor every message you want to buffer and once done buffer will have the buffered output.
Is it possible to access the "errno" variable in C# when P/Invoking? This is similar to Win32 GetLastError().
I'm fairly sure that there is a way, but it probably is a bad idea. How would you guarantee that the runtime has not called some CRT function during its internal processing that has affected theerrno? For the same reason, you should not callGetLastErrordirectly either. TheDllImportAttributeprovides aSetLastErrorproperty so the runtime knows to immediately capture the last error and store it in a place that the managed code can read usingMarshal.GetLastWin32Error. I think the most robust thing you could do in this case is make a C DLL that performs both the actual C work and the capture of theerrno. (Note that just writing a wrapper around theerrnocapture would still have the concerns mentioned above.)
``` #include<stdio.h> void function(int); int main() { int x; printf("Enter x:"); scanf("%d", &x); function(x); return 0; } void function(int x) { float fx; fx=10/x; if(10 is divided by zero)// I dont know what to put here please help printf("division by zero is not allowed"); else printf("f(x) is: %.5f",fx); } ```
``` #include<stdio.h> void function(int); int main() { int x; printf("Enter x:"); scanf("%d", &x); function(x); return 0; } void function(int x) { float fx; if(x==0) // Simple! printf("division by zero is not allowed"); else fx=10/x; printf("f(x) is: %.5f",fx); } ```
I've been looking at Boost and various other C++ libraries. The vast majority of Boost is implemented in header files. My question is: under what conditions do you do a header-only implementation (like Boost) or also include a .cpp file?
If you want to use a template in another translation unit (i.e. another source file), you should (almost always) define it in the header file. (There are exceptions, like the comments below point out, but IMHO this is a good rule of thumb.) Same applies if you want to use an inline function from another translation unit. Otherwise you should put the implementation into a separate .cpp file to minimize dependencies.
Can anyone explain the difference between a fork and a thread?
A fork gives you a brand new process, which is a copy of the current process, with the same code segments. As the memory image changes (typically this is due to different behavior of the two processes) you get a separation of the memory images (Copy On Write), however the executable code remains the same. Tasks do not share memory unless they use someInter Process Communication (IPC)primitive. One process can have multiple threads, each executing in parallel within the same context of the process. Memory and other resources are shared among threads, therefore shared data must be accessed through some primitive and synchronization objects (likemutexes,condition variablesandsemaphores) that allow you to avoid data corruption.
Isa = getchar()equivalent toscanf("%c",&a);? Isputchar(a)equivalent toprintf("%c",a);whereais acharvariable?
Generally speaking yes they are the same. But they are not in a few nitpicky ways. The functiongetcharis typed to returnintand notchar. This is done so thatgetcharcan both all possiblecharvalues and additionally error codes. So while the following happily compiles in most compilers you are essentially truncating away an error message ``` char c = getchar(); ``` The functionscanf, though, allows you to use achartype directly and separates out the error code into the return value.
``` #include<conio.h> #include<stdio.h> #define abc 7 int main() { int abc=1; printf("%d",abc); getch(); return 0; } ``` why this program is giving compile time error
You're assigning7=1which is invalid. Since you've definedabcto be 7, the preprocessor translates the line: ``` int abc=1; ``` to: ``` int 7=1; ``` Which is a syntax error in C (mygccsayssyntax error before numeric constant).
i am using pcap sample codes to create my own sniffer. i downloaded their sample sniffer and its working on windows but not on linux. i am using gcc compiler on both machines, and i have only pcap.h included.the error is : dereferencing pointer to incomplete type.the netmask is causing the error. the netmask is the mask of the first address of the interface. ``` u_int netmask=netmask((struct sockaddr_in*)d->addresses->netmask))->sin_addr.S_un.S_addr; ``` any solutions?
The compiler indicating that it doesn't have the definition ofstruct sockaddr_inin scope, so it can't look inside such a structure. On Linux that struct is defined in this header, which you will need to include: ``` #include <netinet/in.h> ```
A simple google search for: CGRect + C or CGRect in C brings back only Apple, iPhone, and Objective-C websites. However, I remember hearing that Core Graphics was part of C at my university. Did I hear incorrectly, or is CGRect something that I can use in C, or even C++ as it's Object oriented?
CGRect is defined in Carbon, which is plain C: ``` #import <Carbon/Carbon.h> int main() { CGRect r; } ``` If you look at preprocessor output you'll notice CGRect is just a plain struct: ``` $ gcc -E test.c | grep -A 3 "struct.*CGRect" struct CGRect { CGPoint origin; CGSize size; }; typedef struct CGRect CGRect; ```
How to get he upper limit of a number in C? If I divide 3 by 2 I want the answer to be 2 (ie 1.5 rounded to 2).
If you are just interested in dividing by 2, then just take (n + 1) / 2 to keep it in integer math. For example (3 + 1) / 2 gives 2. For a larger number x, use x - 1. For example, (3 + 7) / 8 = 1, for 3 divided by 8. For the general case, you are looking for the ceiling function -- ceil. A quick Google search for "math ceil C" gave this page at the top of the results:http://www.elook.org/programming/c/ceil.html
I'm using fgets with stdin to read in some data, with the max length I read in being 25. With one of the tests I'm running on this code, there are a few hundred spaces after the data that I want - which causes the program to fail. Can someone advise me as to how to ignore all of these extra spaces when using fgets and go to the next line?
Usefgets()iteratively, then scan the string to see whether it is all spaces (and whether it ends with a newline) and ignore it if it is. Or usegetc()orgetchar()in a loop instead? ``` char buffer[26]; while (fgets(buffer, sizeof(buffer), stdin) != 0) { ...process the first 25 characters... int c; while ((c = getchar()) != EOF && c != '\n') ; } ``` That code simply ignores all characters up to the next newline. If you want to ensure that they are spaces, add a test in the (inner) loop - but you have to decide what to do if the character is not a space.
What's the difference of pData1 and pData2, which are build as follows: pData1 = (int*) calloc (i,sizeof(int));int * pData2 = (int*) calloc (i,sizeof(int));
Without any more information, it would appear the only difference is thatpData2is local to the allocation since it is declared as anint *.pData1is not declared so it would have to have a larger (global?) scope and be defined elsewhere.
Rather Trivial Question. So I tried to do this: ``` if (array[0]=="some_string") ``` wherearrayis a list of strings ``` array[0] = "some_string_1"; array[1] = "some_string_2"; array[2] = "some_string_3"; ``` but obviously it doesn't work... What do I have to do?
``` if(array[0] == 'n') ``` ""signifiesstring''signifieschar Note:'a'is acharand"a"is astring, so'a' != "a" charis a single character (actually int), so if you want to compare strings, usestrcmpinstead.
In C++ one might use namespace to keep independent groups working in the same code base from inadvertently creating functions with the same name and thus creating a conflict. My question is, before the idea of namespace comes out, how might one emulate namespace in C.
By naming things differently, e.g.: ``` void namespace_group_function(); ``` gtk+is a prime example for this conventional style: ``` GtkWidget* gtk_window_new(GtkWindowType type); ```
I need to create a simple application that doesn't work after 30 days. How can I do that ? Is there a way to use Trial program after 30 days ?
There is always a way to use a trial program after 30 days.
I recently encountered with this question: How to reduce this expression:s>73?61:60;. The hint given was thatInstead of using conditional operator we could use a simple comparison which will work fine. I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself. EDIT:The whole expression is this :s-=s>73?61:60
Just like the other answers: ``` s -= (s > 73) + 60; ``` This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6: Each of the operators<(less than),>(greater than),<=(less than or equal to), and>=(greater than or equal to) shall yield1if the specified relation is true and0if it is false. The result has typeint.
I am attempting to make a program in C which presents a GUI and allows the user to select from a list of applications, which to install on the computer. I can manage the gui, but I've never been taught how to actually issue command line commands. I know with bash its justapt-get install firefoxfor example, but how do I do such a thing with C? i.e. on click, the program runs 'apt-get install The other problem is I'm not familiar with the proper name for this interaction, so it is hard to search. Thanks for the help
If you use the traditional C standard lib, you can choose from: popen()- Opens a process with stdio IO streams to read/write to the processsystem()- Executes a process with same IO streams as parent or: fork()+execl()(or exec variants) which is essentially howsystem()is implemented. Try the man pages on all of these. Also, order "Advanced Programming in the UNIX Environment" by W. Richard Stevens
I'm reading a bit of C code in an OS kernel that says ``` x & ~(uint32_t)CST_IEc; ``` What does the~()mean? It's a tilde followed by parentheses!
~()is actually two things: (uint32_t)is a cast.~is a bitwise complement operator.
I have a time in the future when I want a notification to occur and need to know if::CeSetUserNotificationExexpects UTC or local time in thestStartTimefield of theCE_NOTIFICATION_TRIGGERstructure if thedwTypefield is set toCNT_TIME?
After actually testing::CeSetUserNotificationExwith both UTC and local time input, I'm in the position of answering my own question: ::CeSetUserNotificationExwants local time.
By default,printf()seems to align strings to the right. ``` printf("%10s %20s %20s\n", "col1", "col2", "col3"); /* col1 col2 col3 */ ``` I can also align text to the left like this: ``` printf("%-10s %-20s %-20s", "col1", "col2", "col3"); ``` Is there a quick way to center text? Or do I have to write a function that turns a string liketestinto(space)(space)test(space)(space)if the text width for that column is 8?
printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the width by reading it from an argument. Lets' try this (ok, not perfect) ``` void f(char *s) { printf("---%*s%*s---\n",10+strlen(s)/2,s,10-strlen(s)/2,""); } int main(int argc, char **argv) { f("uno"); f("quattro"); return 0; } ```
Why is calling a standard library function inside a signal handler discouraged?
This is explained in theGNU LibC documentation. If you call a function in the handler, make sure it is reentrant with respect to signals, or else make sure that the signal cannot interrupt a call to a related function. And just in case, here's theWikipedia pageon reentrant functions. A computer program or routine is described as reentrant if it can be safely called again before its previous invocation has been completed (i.e it can be safely executed concurrently).
i have a task to transfer text files from one pc to another using FTP , i need some directions how can it be done in ansi c as its user requirement to do it in ansi c windows palte form so windows libs may also be used .............. looking for help!
what platform do you use? On windows, have a look at the winsock library.on Unix, examine sockets library Can you use an external library? thenthis heremight come in handy.
I'm trying to write a client/server program with threads. I close the socket once the connexion is finished. The servers gets plenty of new connexions, and the socket number (file descriptor) increases very quickly: after 5 minutes running I was already at around file descriptor number 800! Is this a normal thing? Do threads share file descriptors? When I doclose(sockfd);is the number released immediatly or after a some time? PS: I used to do with fork(), and I didn't have this issue. Thanks
Frompthreads(7): POSIX.1 also requires that threads share a range of other attributes (i.e., these attributes are process-wide rather than per-thread):open file descriptors
I have console application in c. I want to convert into window application, kindly guide me so that I can make it possible.
That is a huge topic that requires a separate discussion. You may want to learn some GUI toolkit. Qt or wxWidgets will do (though they are written in C++, not C). If you're into C crossplatform development, you may take a look at GTK+. If you are planning only to write programs for Windows, you may learn Windows API. Whichever way you choose, there's a lot of docs available, but each and every way requires a lot of study and cannot be explained here.
This question can be treated as a sister question ofprevious oneposted by myself. It is very tedious that when you want to bind a link local address to an IPv6 socket, you need to set thesin6_scope_idfield of thesockaddr_in6struct. I'm wondering if someone can provide a solution following good practice.
The IPv6 link-local address is not unique on the node it's only unique for the NIC which is why you have to specify the scope-id. In other words it is perfectly valid to have multiple adapters with exactly the same IPv6 address. This means you should take in as input the scope-id or suitable text form (%eth0, %1) that you can pass togetaddrinfo(). One method is to take in a IPv6 link-local address, enumerate the interfaces and if only one matches use that, if more than one match then bail out with a list of interfaces and get the user to specify which one in full form.
Is there any way to find particular C language function's input and output parameters from a framework (apple's ARM) during the runtime or from any method with out knowing the headers. It is a framework and there are no header files for it.I decompile it with IDA Pro and it gives me the function names but not input and output parameters information. I am able to load those private functions using dlsym. Is it possible to find the parameters info in runtime (C language or Objective C) or from IDA Pro ? Regards, Raghu
Almost impossible without debug information or something, i think. If there are some structs passed, or pointers, you won't be able to guess their meaning from disassembly, anyway (it could be possible to guess a few types, such as floats, but no more)
is it possible to find out the page size of a processor using C program and malloc? and not by using sysconf() call?
If you can #include some linux kernel header, you can find the macro PAGE_SIZE in ``` <asm/page.h> ``` On cygwin (and perhaps windows' ddk) i's in ``` <w32api/ddk/winddk.h> ``` There are "dirty tricks" (very, very dirty!) to calculat the page size at runtime. All unportable and totally system-dependent. Let's have some fun! A possible trick on may systems is to create a shared memory object only 1 byte long. The system call usually rounds the size up to the system page size. Bleach! Another one, if you are running on unix-like systems and you dare to intercept the SIGSEGV signal, you could try to explore the memory by looking for valid areas and see which power of 2 they are rounded. Uhm... So, why sysctl is not good for you? Regards
``` __thread Foo foo; ``` How isfooactually resolved? Does the compiler silently replace every instance offoowith a function call? Isfoostored somewhere relative to the bottom of the stack, and the compiler stores this as "hey, for each thread, have this space near the bottom of the stack, and foo is stored as 'offset x from bottom of stack'"?
It's a little complicated (this documentexplains it in great detail), but it's basically neither. Instead the compiler puts a special .tdata section in the executable, which contains all the thread-local variables. At runtime, a new data section for each thread is created with a copy of the data in the (read-only) .tdata section, and when threads are switched at runtime, the section is also switched automatically. The end result is that __thread variables are just as fast as regular variables, and they don't take up extra stack space, either.
I have a situation where I have to print out a NUL character if there is no action in a part of my program. Take for example the code below: ``` char x = '\0'; ... printf("@%c@\n", x); ``` I want it to print this: @@ but it prints out @ @ Whats the correct way not to have the \0 character printed out a space as above?
``` if (x == 0) printf("@@\n"); else printf("@%c@\n", x); ``` It's not actually printing a space, it actually outputs the \0. It's just that whatever you're viewing the text with isdisplayingthe \0 as a space.
I'm writing a Linux kernel module, and I'd like to allocate an executable page. Plainkmalloc()returns a pointer within a non-executable page, and I get a kernel panic when executing code there. It has to work on Ubuntu Karmic x86, 2.6.31-20-generic-pae.
``` #include <linux/vmalloc.h> #include <asm/pgtype_types.h> ... char *p = __vmalloc(byte_size, GFP_KERNEL, PAGE_KERNEL_EXEC); ... if (p != NULL) vfree(p); ```
Why won't the following C code compile? It seems like it should just change the pointers' address but it throws an error. ``` int x[10]; int y[10]; y=x; ```
xandyare arrays, not pointers. In C, arrays can't change size or location; only their contents can change. You can't assign arrays directly. If you want a pointer to one of the arrays you can declare one like this. ``` int *z = x; ``` If you need to assign an array you can create a struct that contains an array.structs are assignable in C.
I have a CGI application written in C. When I POST (delete data) to the cgi app from the html form, the action is correctly executed on the server but the page does not refresh after the POST. It does flicker, but displays the non-updated page. I then have to hit the browsers refresh to see the correct updated html page (showing data has been removed). Is this the web server? Javascript? or just a browser setting? (I am using GoAhead web server, cgi app in C, javascript, html and Fire Fox.) Any help is appreciated.
It's your browser cache that is playing tricks on you. Check the HTTP headers you get whenGETting (orPOSTing) the page to see if there are anything about cache, if there is it's your webserver that is causing the cache otherwise it's the browser. Try with a different browser, or make the webserver send the page with a negative expiration date.
I was wondering if there was any resources available online that explains what happens with something, like printf of C, that explains what's going on in the very low level (BIOS/kernel calls)
Linux: printf() ---> printf() in the C library ---> write() in C library ---> write() system call in kernel. To understand the interface between user space and kernel space, you will need to have some knowledge of howsystem callswork. To understand what is going on at the lowest levels, you will need to analyze the source code in thekernel. TheLinux system call quick reference(pdf link) may be useful as it identifies where in the kernel source you might begin looking.
I create a 2D dynamic array: ``` a = (int**)calloc(n-1, sizeof(int)); for(i = 0; i < (n-1); i++) a[i] = (int*)calloc(n, sizeof(int)); ``` Then I need to change its size (add new line): ``` a = (int**)realloc(a, n); a[n] = (int*)calloc(n, sizeof(int)); ``` But when i want to print my array, ``` void Print(void){ int i, j; for(i = 0; i < (n-1); i++){ for(j = 0; j < n; j++){ printf("%d\t", arr[i][j]); } printf("\n"); } } ``` i have access violation. First line is printed... What should I do?
``` a = (int**)realloc(a, (n + 1) * sizeof(int *)); n++; ```
I'm just starting to study C. I have a program that prints a menu and let users choose what to do step by step. Now I would like to return to the main menu whenever the user enters an empty line, but how can I do that?I think I can make a function that return the program to the main menu, but when to call that function? I know it's not good to put an if-else whenever Iscanfsomething... I am used to the OO world, so this is a bit unfamiliar to me, please help :)
I'm guessing you're using a switch statement to filter your input, so just make an option for '\n', or the newline character, to output the print the menu.
I'm just wondering exactly what factors affect how quickly createthread executes, and how long it has to live to make it "worth it". CONTEXT: Where in my game's loops should I spawn threads?
The main game loop is not the place to spawn worker threads. The main game loop should be as free of clutter as possible. Worker threads should be spawned during program startup and then used as need by the main game loop. Look into thread pooling techniques.
I recently encountered with this question: How to reduce this expression:s>73?61:60;. The hint given was thatInstead of using conditional operator we could use a simple comparison which will work fine. I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself. EDIT:The whole expression is this :s-=s>73?61:60
Just like the other answers: ``` s -= (s > 73) + 60; ``` This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6: Each of the operators<(less than),>(greater than),<=(less than or equal to), and>=(greater than or equal to) shall yield1if the specified relation is true and0if it is false. The result has typeint.
I am attempting to make a program in C which presents a GUI and allows the user to select from a list of applications, which to install on the computer. I can manage the gui, but I've never been taught how to actually issue command line commands. I know with bash its justapt-get install firefoxfor example, but how do I do such a thing with C? i.e. on click, the program runs 'apt-get install The other problem is I'm not familiar with the proper name for this interaction, so it is hard to search. Thanks for the help
If you use the traditional C standard lib, you can choose from: popen()- Opens a process with stdio IO streams to read/write to the processsystem()- Executes a process with same IO streams as parent or: fork()+execl()(or exec variants) which is essentially howsystem()is implemented. Try the man pages on all of these. Also, order "Advanced Programming in the UNIX Environment" by W. Richard Stevens
I'm reading a bit of C code in an OS kernel that says ``` x & ~(uint32_t)CST_IEc; ``` What does the~()mean? It's a tilde followed by parentheses!
~()is actually two things: (uint32_t)is a cast.~is a bitwise complement operator.
I have a time in the future when I want a notification to occur and need to know if::CeSetUserNotificationExexpects UTC or local time in thestStartTimefield of theCE_NOTIFICATION_TRIGGERstructure if thedwTypefield is set toCNT_TIME?
After actually testing::CeSetUserNotificationExwith both UTC and local time input, I'm in the position of answering my own question: ::CeSetUserNotificationExwants local time.
By default,printf()seems to align strings to the right. ``` printf("%10s %20s %20s\n", "col1", "col2", "col3"); /* col1 col2 col3 */ ``` I can also align text to the left like this: ``` printf("%-10s %-20s %-20s", "col1", "col2", "col3"); ``` Is there a quick way to center text? Or do I have to write a function that turns a string liketestinto(space)(space)test(space)(space)if the text width for that column is 8?
printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the width by reading it from an argument. Lets' try this (ok, not perfect) ``` void f(char *s) { printf("---%*s%*s---\n",10+strlen(s)/2,s,10-strlen(s)/2,""); } int main(int argc, char **argv) { f("uno"); f("quattro"); return 0; } ```
Why is calling a standard library function inside a signal handler discouraged?
This is explained in theGNU LibC documentation. If you call a function in the handler, make sure it is reentrant with respect to signals, or else make sure that the signal cannot interrupt a call to a related function. And just in case, here's theWikipedia pageon reentrant functions. A computer program or routine is described as reentrant if it can be safely called again before its previous invocation has been completed (i.e it can be safely executed concurrently).
i have a task to transfer text files from one pc to another using FTP , i need some directions how can it be done in ansi c as its user requirement to do it in ansi c windows palte form so windows libs may also be used .............. looking for help!
what platform do you use? On windows, have a look at the winsock library.on Unix, examine sockets library Can you use an external library? thenthis heremight come in handy.
I'm trying to write a client/server program with threads. I close the socket once the connexion is finished. The servers gets plenty of new connexions, and the socket number (file descriptor) increases very quickly: after 5 minutes running I was already at around file descriptor number 800! Is this a normal thing? Do threads share file descriptors? When I doclose(sockfd);is the number released immediatly or after a some time? PS: I used to do with fork(), and I didn't have this issue. Thanks
Frompthreads(7): POSIX.1 also requires that threads share a range of other attributes (i.e., these attributes are process-wide rather than per-thread):open file descriptors
I have console application in c. I want to convert into window application, kindly guide me so that I can make it possible.
That is a huge topic that requires a separate discussion. You may want to learn some GUI toolkit. Qt or wxWidgets will do (though they are written in C++, not C). If you're into C crossplatform development, you may take a look at GTK+. If you are planning only to write programs for Windows, you may learn Windows API. Whichever way you choose, there's a lot of docs available, but each and every way requires a lot of study and cannot be explained here.
This question can be treated as a sister question ofprevious oneposted by myself. It is very tedious that when you want to bind a link local address to an IPv6 socket, you need to set thesin6_scope_idfield of thesockaddr_in6struct. I'm wondering if someone can provide a solution following good practice.
The IPv6 link-local address is not unique on the node it's only unique for the NIC which is why you have to specify the scope-id. In other words it is perfectly valid to have multiple adapters with exactly the same IPv6 address. This means you should take in as input the scope-id or suitable text form (%eth0, %1) that you can pass togetaddrinfo(). One method is to take in a IPv6 link-local address, enumerate the interfaces and if only one matches use that, if more than one match then bail out with a list of interfaces and get the user to specify which one in full form.
Is there any way to find particular C language function's input and output parameters from a framework (apple's ARM) during the runtime or from any method with out knowing the headers. It is a framework and there are no header files for it.I decompile it with IDA Pro and it gives me the function names but not input and output parameters information. I am able to load those private functions using dlsym. Is it possible to find the parameters info in runtime (C language or Objective C) or from IDA Pro ? Regards, Raghu
Almost impossible without debug information or something, i think. If there are some structs passed, or pointers, you won't be able to guess their meaning from disassembly, anyway (it could be possible to guess a few types, such as floats, but no more)
is it possible to find out the page size of a processor using C program and malloc? and not by using sysconf() call?
If you can #include some linux kernel header, you can find the macro PAGE_SIZE in ``` <asm/page.h> ``` On cygwin (and perhaps windows' ddk) i's in ``` <w32api/ddk/winddk.h> ``` There are "dirty tricks" (very, very dirty!) to calculat the page size at runtime. All unportable and totally system-dependent. Let's have some fun! A possible trick on may systems is to create a shared memory object only 1 byte long. The system call usually rounds the size up to the system page size. Bleach! Another one, if you are running on unix-like systems and you dare to intercept the SIGSEGV signal, you could try to explore the memory by looking for valid areas and see which power of 2 they are rounded. Uhm... So, why sysctl is not good for you? Regards
``` __thread Foo foo; ``` How isfooactually resolved? Does the compiler silently replace every instance offoowith a function call? Isfoostored somewhere relative to the bottom of the stack, and the compiler stores this as "hey, for each thread, have this space near the bottom of the stack, and foo is stored as 'offset x from bottom of stack'"?
It's a little complicated (this documentexplains it in great detail), but it's basically neither. Instead the compiler puts a special .tdata section in the executable, which contains all the thread-local variables. At runtime, a new data section for each thread is created with a copy of the data in the (read-only) .tdata section, and when threads are switched at runtime, the section is also switched automatically. The end result is that __thread variables are just as fast as regular variables, and they don't take up extra stack space, either.
I have a situation where I have to print out a NUL character if there is no action in a part of my program. Take for example the code below: ``` char x = '\0'; ... printf("@%c@\n", x); ``` I want it to print this: @@ but it prints out @ @ Whats the correct way not to have the \0 character printed out a space as above?
``` if (x == 0) printf("@@\n"); else printf("@%c@\n", x); ``` It's not actually printing a space, it actually outputs the \0. It's just that whatever you're viewing the text with isdisplayingthe \0 as a space.
I'm writing a Linux kernel module, and I'd like to allocate an executable page. Plainkmalloc()returns a pointer within a non-executable page, and I get a kernel panic when executing code there. It has to work on Ubuntu Karmic x86, 2.6.31-20-generic-pae.
``` #include <linux/vmalloc.h> #include <asm/pgtype_types.h> ... char *p = __vmalloc(byte_size, GFP_KERNEL, PAGE_KERNEL_EXEC); ... if (p != NULL) vfree(p); ```
Why won't the following C code compile? It seems like it should just change the pointers' address but it throws an error. ``` int x[10]; int y[10]; y=x; ```
xandyare arrays, not pointers. In C, arrays can't change size or location; only their contents can change. You can't assign arrays directly. If you want a pointer to one of the arrays you can declare one like this. ``` int *z = x; ``` If you need to assign an array you can create a struct that contains an array.structs are assignable in C.
I have a CGI application written in C. When I POST (delete data) to the cgi app from the html form, the action is correctly executed on the server but the page does not refresh after the POST. It does flicker, but displays the non-updated page. I then have to hit the browsers refresh to see the correct updated html page (showing data has been removed). Is this the web server? Javascript? or just a browser setting? (I am using GoAhead web server, cgi app in C, javascript, html and Fire Fox.) Any help is appreciated.
It's your browser cache that is playing tricks on you. Check the HTTP headers you get whenGETting (orPOSTing) the page to see if there are anything about cache, if there is it's your webserver that is causing the cache otherwise it's the browser. Try with a different browser, or make the webserver send the page with a negative expiration date.
I was wondering if there was any resources available online that explains what happens with something, like printf of C, that explains what's going on in the very low level (BIOS/kernel calls)
Linux: printf() ---> printf() in the C library ---> write() in C library ---> write() system call in kernel. To understand the interface between user space and kernel space, you will need to have some knowledge of howsystem callswork. To understand what is going on at the lowest levels, you will need to analyze the source code in thekernel. TheLinux system call quick reference(pdf link) may be useful as it identifies where in the kernel source you might begin looking.
I create a 2D dynamic array: ``` a = (int**)calloc(n-1, sizeof(int)); for(i = 0; i < (n-1); i++) a[i] = (int*)calloc(n, sizeof(int)); ``` Then I need to change its size (add new line): ``` a = (int**)realloc(a, n); a[n] = (int*)calloc(n, sizeof(int)); ``` But when i want to print my array, ``` void Print(void){ int i, j; for(i = 0; i < (n-1); i++){ for(j = 0; j < n; j++){ printf("%d\t", arr[i][j]); } printf("\n"); } } ``` i have access violation. First line is printed... What should I do?
``` a = (int**)realloc(a, (n + 1) * sizeof(int *)); n++; ```
I'm just starting to study C. I have a program that prints a menu and let users choose what to do step by step. Now I would like to return to the main menu whenever the user enters an empty line, but how can I do that?I think I can make a function that return the program to the main menu, but when to call that function? I know it's not good to put an if-else whenever Iscanfsomething... I am used to the OO world, so this is a bit unfamiliar to me, please help :)
I'm guessing you're using a switch statement to filter your input, so just make an option for '\n', or the newline character, to output the print the menu.
Even though it is possible to write generic code in C using void pointer(generic pointer), I find that it is quite difficult to debug the code since void pointer can take any pointer type without warning from compiler. (e.g function foo() take void pointer which is supposed to be pointer to struct, but compiler won't complain if char array is passed.) What kind of approach/strategy do you all use when using void pointer in C?
The solution is not to usevoid*unless you really, really have to. The places where a void pointer is actually required are very small: parameters to thread functions, and a handful of others places where you need to pass implementation-specific data through a generic function. In every case, the code that accepts thevoid*parameter should only acceptonedata type passed via the void pointer, and the type should be documented in comments and slavishly obeyed by all callers.
The assignment at my first year uni computing course says my program should read a barcode number, and then display the same 13 digit barcode number separated by hyphens. For example, 9300675016902 should look like 930-067501-690-1. The restrictions say I can't use the following: No arrays No strings No functions. Any directions on this? So far I have: ``` part1 = barcode/10000000000; ``` which gives me the first three digits, and this: ``` part4 = barcode%10; ``` which gives me the last digit. Thanks in advance!
Try: ``` long p1 = n/10000000000; long p2 = n%100000000000/10000; long p3 = n%10000/10; long p4 = n%10; printf("%03ld-%06ld-%03ld-%01ld\n",p1,p2,p3,p4); ```
I know you can print withprintf()andputs(). I can also see thatprintf()allows you to interpolate variables and do formatting. Isputs()merely a primitive version ofprintf(). Should it be used for every possibleprintf()without string interpolation?
putsis simpler thanprintfbut be aware that the former automatically appends a newline. If that's not what you want, you canfputsyour string to stdout or useprintf.
I want to transfer files across the network using C or C++. What topics should I look up? How can I do this?
You should start by choosing a protocol.HTTPSandSFTPare both good choices, but there are obviously others. Once you have that straight, you can look up choices for client and server libraries.
How can I display a splash screen using C or C++ in Windows? What libraries or Windows components would be applicable?
A splash screen is typically just a modeless dialog with a static picture control covering its surface, or even just a normal window that loads and blits a bitmap to its client area.CodeProjecthas an example of the latter sort. It uses MFC, but that's a thin enough wrapper over the Win32 API that rewriting it to use Win32 directly should be fairly simple.
I'm just starting to learn how network programming in C works, and I've written a small program that sends messages to and from a UNIX terminal. I'm using pthreads in my program, one of which essentially just waits onrecvfrom()to receive a message. However, I want to be able to close all threads properly if the users chooses to quit the program. The way I have it set up right now, a different thread just cancels the thread waiting on recvfrom, but I'm worried this might not be a good idea since I'm leaving sockets unclosed and I'm not freeing all the memory I allocated. Is there a way to cancel arecvfrom()call, or some way to run a certain routine upon cancelling a pthread? Thanks.
If you usepthread_killto send a signal to the thread,recvfrom()should return -1 witherrnoset toEINTR- you can then check for the "application is now exiting" condition and finish up gracefully.
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.Closed7 years ago.Improve this question Is there any good tutorial or code snippet out there on how to use OpenGL via C/C++ on the iPhone?
http://developer.apple.com/iphone/library/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html I'm pretty sure you need a bit of Objective-C to create the context and do other initialization stuff. The rest is also usable in C++.
There is a question in my programming languages textbook that is as follows: Write a C function that includes the following sequence of statements:x = 21; int x; x = 42;Run the program and explain the results. Rewrite the same code in C++ and Java and compare the results. I have written code, and played with it in all three languages but I can not even get it to compile. This includes declaring x above the three lines as well as in the calling function (as this question is obviously attempting to illustrate scoping issues) I'd like to explain the results and do the comparisons on my own, as it is an assignment question but I was wondering if anyone had any insight as to how to get this code to compile? Thanks
Note the following requires C99: ``` int x; void foo() { x = 21; int x; x = 42; } ``` Since this is homework, you'll need to provide your own explanation.
During a make, I'm seeing an error along the lines of: ``` cc1: warnings being treated as errors somefile.c:200: error: the frame size of 1032 bytes is larger than 1024 bytes ``` The line number points to the closing brace of a c function that has a signature like this: ``` void trace(SomeEnum1 p1, SomeEnum2 p2, char* format, ...) { char strBuffer[1024]; ... ``` The function prints some stuff into the buffer. Anyone know what this type of error means in general?
I'm guessing there's some large buffer in that routine that is stack-allocated; this is likely causing the stack frame of that function to exceed 1024 bytes, which seems to be some compiler-enforced limit for the architecture upon which you are building. Possible solutions would include passing a compiler flag to relax the warning, expand the upper limit of the stack size, or dynamically allocating the buffer.
This is a simple question: Is this a correct way to get an integer part from a float division? ``` int result = myFloat / anInteger; ``` this is working, but I am not sure if it is the best way. thanks for any help.
To truncate: ``` int result = (int)(myFloat / anInteger); ``` Other conversion options: ``` #include <math.h> int result = (int)ceilf(myFloat / anInteger); int result = (int)roundf(myFloat / anInteger); int result = (int)floorf(myFloat / anInteger); ```
I have the misfortune of having use conio.h in vc++ 6 for a college assignment, My problem is that my graphic setup is in the center of the screen... e.g. ``` gotoxy( getcols()/2, getrows()/2); printf("Enter something"); scanf( "%d", &something ); ``` now if someone accidentally hits enter before they enter the "something", then the cursor gets reset to the left of the screen on the next line. Iv tried flushing the keyboard and bios buffers with fflush(stdin) and getchar(), which like I expected didn't work! Any help/ideas would be appreciated, Thanks, V
Try reading the user's input one character at a time. If a leading carriage return is detected, ignore the character and run yourgotoxy( getcols()/2, (getrows()/2)+1)code again to re-place the cursor at the appropriate location (adding one row to avoid writing over the previously-output message).
``` for(i = 0; i < n; i++){ srand(time(NULL)); printf("%d ", time(NULL)); for(j = 0; j < (n-1); j++){ a[i][j] = rand(); } } ``` I try to generate random numbers, but they are the same... I trysrand(i * time(NULL)). No matter.. What should i do? Array declaration: ``` int** a; int i; printf("Enter array size: "); scanf("%d", &n); a = (int**)calloc(n, sizeof(int)); for(i = 0; i < n; i++) a[i] = (int*)calloc(n-1, sizeof(int)); ```
Callsrand()outside of the loop. You are reseeding it every iteration. srand()seeds the random number generator so you get a different sequence of random numbers depending on the input. Your loop runs very fast, so the call totime(NULL)always returns the same value. You are resetting to the same random sequence with every iteration. As a general rule, only callsrand()once in your program.
I cannot understand why this throwsundefined reference to `floor'": ``` double curr_time = (double)time(NULL); return floor(curr_time); ``` Hasn't it been casted to double, which is whatfloorreceives?
You possibly have run in to the infamous-lmproblem: Compile as: ``` gcc yourfile.c -o out -lm ``` This is CFAQ 14.3item as well.
That may be really simple but I'm unable to find a good answer. How can I make a macro representing first a certain value and then a different one? I know that's nasty but I need it to implicitly declare a variable the first time and then do nothing. This variable is required by other macros that I'm implementing. Should I leverage "argument prescan"? The thing you need to know is the fact I'm generating the code: ``` #define INC_X x++ //should be declared if needed to #define PRINT_X printf("VALUE OF X: %d\n", x) int func() { [...] INC_X; [...] INC_X; [...] PRINT_X; [...] } ```
As far as I know, this is impossible. I know of no way for the expansion of a macro to control the way another macro -- or itself -- will be expanded after. C99 introduced _Pragma so that#pragmathings can be done in macros, but there is no equivalent for#defineor#undef.
In each loop iteration,variable jis declared again and again. Then why is itsaddress remaining same? Shouldn't it be given some random address each time?Is this compiler dependent? ``` #include<stdio.h> #include<malloc.h> int main() { int i=3; while (i--) { int j; printf("%p\n", &j); } return 0; } ``` Testrun:- ``` shadyabhi@shadyabhi-desktop:~/c$ gcc test.c shadyabhi@shadyabhi-desktop:~/c$ ./a.out 0x7fffc0b8e138 0x7fffc0b8e138 0x7fffc0b8e138 shadyabhi@shadyabhi-desktop:~/c$ ```
It is memory on the stack. It is not allocated from the heap. The stack would not change in that loop.
I want to define initialized C-array in Pyrex, e.g. equivalent of: ``` unsigned char a[8] = {0,1,2,3,4,5,6,7}; ``` What will be equivalent in Pyrex? Just array is ``` cdef unsigned char a[8] ``` But how can I made it initialized with my values?
InCython, Pyrex's successor, this feature was added over a year a go to fix thisfeature request, so for example the following works in Cython now: ``` cdef double a[] = [0.5, 0.3, 0.1, 0.1] ``` However, Pyrex's development is proceeding much more slowly (which is why Cython was forked years ago by developers rarin' for faster action), so I doubt it's picked up this feature (though you can try, esp. if you're using thevery latest releaseof Pyrex, 0.9.8.6). If Pyrex isn't giving you the features you want, may I suggest switching to Cython instead? Most Pyrex code should just recompile smoothly in Cython, and you do get the extra features this way.
I have an application processing network communication with blocking calls. Each thread manages a single connection. I've added a timeout on the read and write operation by using select prior to read or write on the socket. Select is known to be inefficient when dealing with large number of sockets. But is it ok, in term of performance to use it with a single socket or are there more efficient methods to add timeout support on single sockets calls ? The benefit of select is to be portable.
Yes that's no problem, and you do want some timeout mechanisms to not leak resources from bad behaving clients etc. Note that having a large number of threads is even more inefficient than having select dealing with a large number of sockets.
Consider the following code which shows compile time error : ``` #include <stdio.h> int main(int argc, char** argv) { int x=5,y=0,z=2; int a=z?x,y?x:(y); // but z?x,y?x:y:z is not showing any error printf("%d",a); return 0; } ``` Please help me explain the reason whyz?x,y?x:y:zis not showing any error?
Why would it; it's valid and groups like this: ``` z?(x, (y?x:y)):z ``` The middle operand of the conditional expression can beanyexpression.
Please see this piece of code: ``` #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { int i = 0; FILE *fp; for(i = 0; i < 100; i++) { fp = fopen("/*what should go here??*/","w"); //I need to create files with names: file0.txt, file1.txt, file2.txt etc //i.e. file{i}.txt } } ```
``` for(i = 0; i < 100; i++) { char filename[sizeof "file100.txt"]; sprintf(filename, "file%03d.txt", i); fp = fopen(filename,"w"); } ```
I'm writing an MPI C program. I have troubles debugging it, because whenever I use fprintf, like this: fprintf(stdout, "worker: %d", worker); if the program hangs, because of some blocking MPI_Recv, I can't see any output. I'm sure the line of code is reached, because I can put a return statement after the fprintf statement, in which case the process finishes execution and the output is printed. Any ideas, on how to print (see the output) even though the process gets blocked later by Recv? I hope this makes sense.
By default,stdoutis line buffered, so you may want to end your debugging print calls with newlines: ``` fprintf(stdout, "workder: %d\n", worker); ``` If you don't want a newline, you can flush the stream yourself: ``` fprintf(stdout, "workder: %d", worker); fflush(stdout); ```
I'm trying to detect "Use after free()" bugs, otherwise known as "Dangling pointers". I know Valgrind can be used to detect "Use after free" bugs on the *nix platform, but what about windows? What if I don't have the source? Is there a better program than Valgrind for detecting all dangling pointers in a program? A free and open source would be preferred , but I'll use a commercial solution if it will get the job done.
The MSVC debug memory allocator already does this. When you get 0xfeeefeee from a pointer dereference you've dangled. With some luck that will bomb the program.
I have written the majority of my project in C++. However there are several "filters" or folders which need to be compiled as C and linked to the project. How can I configure this within VStudio? Thanks.
You can change the Language property by right-clicking on the individual files and settingConfiguration Properties > C/C++ > Advanced > CompileAs ToCompile As C (/TC). No such facility for the filter are present though.
What was the munch library (or program?) fromcfrontpackage? What is was used for?
Munch was used to scan the nm output and look for static constructors/destructors. See thecode(with comments) atSoftwarePreservation.com.
how can I set themousecursor position in an X window using a C program under Linux? thanks :) (like setcursorpos() in WIN) EDIT: I've tried this code, but doesn't work: ``` #include <curses.h> main(){ move(100, 100); refresh(); } ```
12.4 -Moving the Pointer Although movement of the pointer normallyshouldbe left to the control of the end user, sometimes it is necessary to move the pointer to a new position under program control.To move the pointer to an arbitrary point in a window, useXWarpPointer(). Example: ``` Display *dpy; Window root_window; dpy = XOpenDisplay(0); root_window = XRootWindow(dpy, 0); XSelectInput(dpy, root_window, KeyReleaseMask); XWarpPointer(dpy, None, root_window, 0, 0, 0, 0, 100, 100); XFlush(dpy); // Flushes the output buffer, therefore updates the cursor's position. Thanks to Achernar. ```
I'm doing some prototyping with OpenCV for a hobby project involving processing of real time camera data. I wonder if it is worth the effort to reimplement this in C or C++ when I have it all figured out or if no significant performance boost can be expected. The program basically chains OpenCV functions, so the main part of the work should be done in native code anyway.
You've answered your own question pretty well. Most of the expensive computations should be within the OpenCV library, and thus independent of the language you use. If you're really concerned about efficiency, you could profile your code and confirm that this is indeed the case. If need be, your custom processing functions, if any, could be coded in C/C++ and exposed in python through the method of your choice (eg: boost-python), to follow the same approach. But in my experience, python works just fine as a "composition" tool for such a use.
I want to disable CTRL+ALT+DEL in Windows XP in my ANSI-C code. Is it possible to do it?
First of all, Trapping Ctrl-Alt-Del (Secure Attention Sequence) and disabling it are two different things. Despite misconceptions of many it is possible to disable SAS. Here are 3 ways to do it: Set HKCU/Software/Microsoft/Windows/CurrentVersion/Policies/System/DisableTaskMgr = 1Replace msgina.dll with your own or write a keyboard driver.Go to the Start menu, select Run, and type "gpedit.msc" to run the Group Policy editor. Look in User Configuration | Administrative Templates | System and you'll find a section called Ctrl+Alt+Del Options - "Remove Task Manager" In order to trap SAS, you could write a GINA stub, create a keyboard driver or replace TaskMgr.exe These requirements arise mainly for embedded systems and you have control over how the WinXP image is made. Reference:MSDN Mag Sept 2002
I have a thread with return typeDWORDin C but it is then handled by aHANDLEtype pointer. What is the difference between these two types? I am asking this question specially for ANSI C. It is right thatDWORDisuinttype andHANDLEisPVOID, and C allows to cast directlyDWORDtoHANDLE. But is there any difference in these types or can I simply say they are the same? It is a question that was asked during a discussion. I want to know what the right answer is.
Win32: DWORD 32 bit unsigned longHANDLE void * (32 bit pointer) Win64 DWORD 32 bit unsigned longHANDLE void * (64 bit pointer) DO NOT just assume you can cast one to the other. It will work for Win32 and break when you port it to Win64.
This one is quite obviously a function pointer : ``` typedef int (* foobar) (int a, unsigned char *b, unsigned int c); ``` But what does this one do? ``` typedef int (foobar *) (int a, unsigned char *b, unsigned int c); ```
It produces a compiler error, at least in GCC 4.3: ``` foo.cpp:1: error: expected `)' before '*' token ```
Could somebody tell me the difference between: ``` int *p; p=(int*)malloc(10*sizeof(int)); free(p); ``` or ``` int *p; p=(int*)malloc(10*sizeof(int)); p=NULL; ```
freewill deallocate the memory thatppoints to - simply assigning it toNULLwill not (and thus you will have a memory leak). It is worth mentioning that it is good practice to assign your pointer toNULLAFTER the call tofree, as this will prevent you from accidentally trying to access the freed memory (which is still possible, but absolutely should not be done).
``` #include<stdio.h> int main() { printf("He %c llo",65); } ``` Output: HeAllo ``` #include<stdio.h> int main() { printf("He %c llo",13); } ``` Output:llo. It doesnt print He. I can understand that 65 is ascii value for A and henceAis printed in first case but whylloin second case. Thanks
ASCII 13 is carriage return, which on some systems simply moves the cursor to the beginning of the line you were just on. Further characters then wipe out the earlier text.
Are there any stdin input length limitations (in amount of input or input speed)?
No.stdinhas no limits on length or speed. If you want to get gigabytes of data viastdinyou can, and your computer will supply it as fast as it can.
How do I perform an unsigned right shift (>>> in Java) in C/C++?
In C, to get an unsigned shift, you just do a shift on an unsigned type. ``` unsigned int result = (unsigned int)valueToBeShifted >> shiftAmount; ``` Note that there is no guarantee that>>on a signed type gives you a signed shift in C -- this is implementation defined behavior. Most common implementations produce a signed shift if the type is signed, however.