question
stringlengths
25
894
answer
stringlengths
4
863
I was reading this:http://johnsantic.com/comp/state.htmland having hard time comprehending this part: ``` void (*const state_table [MAX_STATES][MAX_EVENTS]) (void) = { { action_s1_e1, action_s1_e2 }, /* procedures for state 1 */ { action_s2_e1, action_s2_e2 }, /* procedures for state 2 */ { action_s3_e1,...
It defines 2D array of pointers functions (return void). state_table [MAX_STATES][MAX_EVENTS]means thatstate_tableis 2D array, and thevoid (*expression)(void)means thatexpressionis pointer to a function, that takes no arguments (this is the mean of(void)as argument list), and returnsvoid. The other lines just initia...
I am a beginner at C and I am trying to write a vector multiplication code. I read in an array and the scale. Then I multiply this scale with each element in the array. ``` for (i = 0 ; i < 5 ; i++) { scanf("%d", &numbers[i]); } puts("Please enter the scale:"); scanf("%d", s); puts("The scaled vector is:"); f...
Send a pointer to scanf, so that you can get the value: ``` puts ("Please enter the scale:"); scanf ("%d" , &s); ```
Is there a good C/C++ library for creating PNG files and that supports colored polygons and shapes? This library should be OS independent, since I need it for both Linux and Windows.
TheCairolibrary meets your requirements.
I create a NSData and use the function ``` - (const void *)bytes; ``` So, it return the bytes in aconst void *variable. If I read the memory manually I will find this: ``` 98 F3 00 76 84 //Then a lot of zero ``` Usestrlennot work because the00. But it will be aways the same size: 10 hexa lenght. So, to create a...
TheNSDatacontains the length. ``` const void *mybytes = [data bytes]; size_t mysize = [data length]; ```
This link explains theTCP State Machine. It lists all the state transitions based on send/receive events. I feel like it only describes the obvious ones. I'd like to know what happens when you're in a LISTEN state and you receive a DATA packet, or when you're in a ESTABLISHED state and you receive a SYN. Are there an...
This is an excellent resource for what you want: 1995 - TCP/IP Illustrated, Volume 2: The Implementation (with Gary R. Wright) - ISBN 0-201-63354-X
I'm looking for a C# integral data type that can hold 32 bit signed values on 32-bit machines and 64-bit signed values on 64-bit machines.The reason for this is a P/Invoke call to a C function that receives assize_tparameter.I know I could work with preprocessor directives to "DllImport" this function in different way...
You can use theIntPtr type: The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.
I have an embedded device with Python installed on in. Is it possible to explicitly access registers in pure Python, or should I write C extensions for my Python code?
It seems that you can't access the low level registers. I recommend just writing a short C extension code to allow Python to access the registers you need.
What attribute do I use to create a pthreads mutex that is locked by the creating thread at creation time?
It doesn't appear to be supported by the pthreads mutex interfaces. You're going to have to mutually lock it, and use some other synchronization method to keep other threads from grabbing it before you do (which is what I'm assuming you want to do here), in semi-pseudocode below: ``` pthread_mutex_lock(my_pthread_cre...
I noticed that the difference between linux and windows. strcmpi is in windows C standard libary implementation but it is not in GNU's C standard libary implementation. Is the function strcmpi in the C standard libary defined by ISO? How can I get the standard file? Thank you.
The POSIX Standard (aka, UNIX) hasstrcasecmp()but it's not part of C99 / ISO-C. Note: If you compare the above reference with e.g. the one forstrcmp()you'll note that the latter explicitly references ISO-C, while the former does not. An useful feature of the OpenGroup references. Edit:Since the locale-dependency was...
I haven't understood something about processes generated with fork(). If I try a code like this one: ``` int main(int argc, char** argv) { void* mem=malloc(100); pid_t pid=fork(); printf("%p\n",mem); } ``` Both processes print the same address. So do they point at the same area of memory in the heap? Isn...
Different processes are contained in separate virtual address spaces so those memory addresses point to different memory locations. As Karoly Horvath suggests, it is a bit more complicated due to an optimization calledcopy-on-write, which basically allows having a single copy until a distinction is needed. This is im...
``` char input[INPUT_SIZE]; /*Holding user input globaly*/ char history[50][INPUT_SIZE]; /*Storing last 0 commands*/ void addToHistory() { history[0] = input; printf("#: %s \n", history[0]); } fgets(input,INPUT_SIZE,stdin) /*Using this to get the input*/ ``` Im using the fgets to save the input, and then i w...
You cannot assign to an array, you should copy to it: ``` memcpy(history[0], input, sizeof(history[0])); ```
How can I check in C# whether a directory is shared? And is it done in C/C++ under Windows? The directory is on the same PC!
As for C#: To check wether you can access (read access at least) a network share / unc path with the current logged in user, do aIO.Directory.Exists(@"\\YourUNCShare") For C++: Check out this question There's alsothisMSDN article, usingPathFileExistswhich should do forC.
``` int a; printf("address is %u", &a); ``` Which address is this..? I mean is this a compiler generated address i.e. virtual address or the loader given physical address in the RAM..? As it prints different address every time, I guess it must be address in the RAM. Just want to make sure. Please provide any links ...
The address returned for a local variable in the user space is always a virtual address not the physical address. The variableain your case is allocated on the local storage(stack) and every time you execute your program a stack space allocated to your function, the variable is located at particular offset within thi...
I am writing a program/script that should check what services are running on a computer every hour. Is there a way to automatically launch this program every hour? I could manually launch it but that would defeat the purpose of the script. Sorry for the ambiguity of the question. I will update it as I get response...
This is more about your OS than language. You could make an app that sleeps for 60 mins then does a check (put it in a loop and you're done), but on unix systems you would be better of using cron. On Windows it's called the scheduler and has APIs to access it.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question I am facing some problem in C language to extract a valid IP(v4 and v6) from oracle DB for example. 1, if ...
``` str1[]="10.2.33.4.5-34" substr(1,11,str1); str2[]="abc-100.2.33.4.545" substr(5,14,str2) ``` The above code should be used in C.
Here's my code (created just to test fork()): ``` #include <stdio.h> #include <ctype.h> #include <limits.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int main() { int pid; pid=fork(); if (pid==0) { printf("I am the child\n"); printf("my pid=%d\n", getpid()); ...
unistd.handforkare part of thePOSIX standard. They aren't available on windows (text.exein your gcc command hints that's you're not on *nix). It looks like you're using gcc as part ofMinGW, which does provide theunistd.hheader but does not implement functions likefork.Cygwindoesprovide implementations of functions li...
I've got a Makefile that includes another makefile that sets a lot of defaults. I can't edit the included makefile and I'd like to change the value of C++FLAGS in my makefile even though it is set in the included makefile. Specifically, I'd like to remove the optimization flag from C++FLAGS whenever debug=1. I tried ...
``` C++FLAGS:=$(filter-out -O3,$(C++FLAGS)) ``` The:=assignmentimmediatelyevaluates the rvalue and this should therefore work.=on the other hand has delayed expansion semantics (i.e. theC++FLAGSwill expand whenever the lvalue gets used, which leads to recursion).
When assigning memory dynamically in C for strings, do you count the \0 end of string char? ``` char *copyInto, *copyFrom="test"; // Should copyInto = (char*)malloc(strlen(copyFrom)); // suffice? // or should this be the following? copyInto = (char*)malloc(strlen(copyFrom)+1); // assuming you want to copy the str...
Don't cast the return values ofmalloc()orcalloc()(orrealloc()for that matter) in a C program.Yes, you need to have the+1.Why bother usingcalloc()to zero out the whole string if you're just going to copy into it immediately? Seems like a waste of cycles to me.
Is it possible to do operator overloading or something similar (inline function?) in C? I know that c does not supportclass, but could I make an operator for astruct? I cannot find anything about this online, because Google will ignore '+' so if I try to google this I only get C++ results.
No, you can't do that in C. Use C++ if you want to overload operators. Youcanput function pointers inside a structure if you want a sort of C++ object-like behaviour.
In the current code base I'm looking at there's , at least, these: if(strlen(str) == 0)if(str[0] != 0)if(!*str) And similar variants for it being empty/not empty . The first one reads better, but might waste time (which might nor might not matter). And I suppose one could make a#define STR_EMPTY(str) (*(str) == 0)ma...
No. I've seen all three. Personally, I use ``` if (!str[0]) ``` Using strlen is a waste of processor time and not safe unless you can guarantee the string is terminated.
How can I check in C# whether a directory is shared? And is it done in C/C++ under Windows? The directory is on the same PC!
As for C#: To check wether you can access (read access at least) a network share / unc path with the current logged in user, do aIO.Directory.Exists(@"\\YourUNCShare") For C++: Check out this question There's alsothisMSDN article, usingPathFileExistswhich should do forC.
``` int a; printf("address is %u", &a); ``` Which address is this..? I mean is this a compiler generated address i.e. virtual address or the loader given physical address in the RAM..? As it prints different address every time, I guess it must be address in the RAM. Just want to make sure. Please provide any links ...
The address returned for a local variable in the user space is always a virtual address not the physical address. The variableain your case is allocated on the local storage(stack) and every time you execute your program a stack space allocated to your function, the variable is located at particular offset within thi...
I am writing a program/script that should check what services are running on a computer every hour. Is there a way to automatically launch this program every hour? I could manually launch it but that would defeat the purpose of the script. Sorry for the ambiguity of the question. I will update it as I get response...
This is more about your OS than language. You could make an app that sleeps for 60 mins then does a check (put it in a loop and you're done), but on unix systems you would be better of using cron. On Windows it's called the scheduler and has APIs to access it.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question I am facing some problem in C language to extract a valid IP(v4 and v6) from oracle DB for example. 1, if ...
``` str1[]="10.2.33.4.5-34" substr(1,11,str1); str2[]="abc-100.2.33.4.545" substr(5,14,str2) ``` The above code should be used in C.
Here's my code (created just to test fork()): ``` #include <stdio.h> #include <ctype.h> #include <limits.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int main() { int pid; pid=fork(); if (pid==0) { printf("I am the child\n"); printf("my pid=%d\n", getpid()); ...
unistd.handforkare part of thePOSIX standard. They aren't available on windows (text.exein your gcc command hints that's you're not on *nix). It looks like you're using gcc as part ofMinGW, which does provide theunistd.hheader but does not implement functions likefork.Cygwindoesprovide implementations of functions li...
I've got a Makefile that includes another makefile that sets a lot of defaults. I can't edit the included makefile and I'd like to change the value of C++FLAGS in my makefile even though it is set in the included makefile. Specifically, I'd like to remove the optimization flag from C++FLAGS whenever debug=1. I tried ...
``` C++FLAGS:=$(filter-out -O3,$(C++FLAGS)) ``` The:=assignmentimmediatelyevaluates the rvalue and this should therefore work.=on the other hand has delayed expansion semantics (i.e. theC++FLAGSwill expand whenever the lvalue gets used, which leads to recursion).
When assigning memory dynamically in C for strings, do you count the \0 end of string char? ``` char *copyInto, *copyFrom="test"; // Should copyInto = (char*)malloc(strlen(copyFrom)); // suffice? // or should this be the following? copyInto = (char*)malloc(strlen(copyFrom)+1); // assuming you want to copy the str...
Don't cast the return values ofmalloc()orcalloc()(orrealloc()for that matter) in a C program.Yes, you need to have the+1.Why bother usingcalloc()to zero out the whole string if you're just going to copy into it immediately? Seems like a waste of cycles to me.
Is it possible to do operator overloading or something similar (inline function?) in C? I know that c does not supportclass, but could I make an operator for astruct? I cannot find anything about this online, because Google will ignore '+' so if I try to google this I only get C++ results.
No, you can't do that in C. Use C++ if you want to overload operators. Youcanput function pointers inside a structure if you want a sort of C++ object-like behaviour.
In the current code base I'm looking at there's , at least, these: if(strlen(str) == 0)if(str[0] != 0)if(!*str) And similar variants for it being empty/not empty . The first one reads better, but might waste time (which might nor might not matter). And I suppose one could make a#define STR_EMPTY(str) (*(str) == 0)ma...
No. I've seen all three. Personally, I use ``` if (!str[0]) ``` Using strlen is a waste of processor time and not safe unless you can guarantee the string is terminated.
I am looking for an native function from the C libraries or code example to implement it: I have a string that contains byte values that I want to convert it to int value. how do I this? I tried usingatoi()andatol()but it get only0from0xbff18c08. Thanks.
Then you are likely looking forstrtoul(str, NULL, 16).
I have client-server application. The server is in C. Server have this structure: ``` int main (... ) { FILE * fp; fp = fopen("serverLog.log","w"); //init variables //bind server //listen server on port while(1) { //some code //accept //some code int check = pthread_create(&thread, NULL, handle_client,&ct...
No, it will be closed by the operating system. When your process exits (whether cleanly or forcibly) the kernel will clean up all dangling handles.
``` int t,r,c; int matrix[100][100][100]; int i,j,k=0,l=0; int te,ck=0; scanf("%d",&t); for(te=0;te<t;te++) { printf("RC"); scanf("%d %d",&r, &c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { ...
fflush(stdin)is not the way to clear your input buffer. Use: ``` void flushInputBuffer( void ) { int c; while( (c = fgetc( stdin )) != EOF && c != '\n' ); } ```
I've been browsing a lot of perl C library extensions and have noticed, especially in Date::Calc, that Z_int and Z_long and the like are the standard (vs 'int' and 'long'). I'm assuming this is some POSIX standard but Google has failed me for a while now trying to find a definition or source for this syntax. Do you k...
It's not a standard thing; I think it's justSteffen Beyer's personal notation that he uses in a number of his modules (includingDate::Calc). TheZhere is the math sense ofZto denote the set of integers;Z_intissigned int, whereasN_int(fromN, the set of natural numbers) isunsigned int. All thesetypedefs are defined inthe...
I have read about 5 different questions on the same error, but I still can't find what's the problem with my code. main.c ``` int main(int argc, char** argv) { //graph_t * g = graph_create(128); //I commented this line out to make sure graph_create was not causing this. graph_t * g; g->cap; //This line g...
You can't do that since the struct is defined in a different source file. The whole point of the typedef is to hide the data from you. There are probably functions such asgraph_capandgraph_sizethat you can call that will return the data for you. If this is your code, you should definestruct graphinside the header fil...
Here is a stripped version of my program. I don't see why I am getting segmentation fault here. ``` .... int main(int argc, const char * argv[]) { char quit = 0; char buffer[100]; ... while (quit == 0) { sprintf(buffer,"%s",get_timer_ticks(&mytimer)); // puts(buffer); ... } ``` Edit: ...
You should use ``` sprintf(buffer,"%u",get_timer_ticks(&mytimer)); ``` %sexpects string, not integer. Since some random integer is unlikely to be a valid pointer to something resembling NULL-terminated string, SEGFAULT occurs.
I have a 3D point (point_x,point_y,point_z) and I want to project it onto a 2D plane in 3D space which (the plane) is defined by a point coordinates (orig_x,orig_y,orig_z) and a unary perpendicular vector (normal_dx,normal_dy,normal_dz). How should I handle this?
Make a vector from yourorigpoint to the point of interest: v = point-orig (in each dimension); Take the dot product of that vector with the unit normal vectorn: dist = vx*nx + vy*ny + vz*nz;dist = scalar distance from point to plane along the normal Multiply the unit normal vector by the distance, and subtract tha...
I have the following files: main.c : ``` int f(void); int main(void) { f(); return 0; } ``` f.c: ``` char *f = "linker"; ``` GNUMakefile: ``` CC = gcc CFLAGS = -Wall -g all: main main: main.o f.o main.o: main.c f.o: f.c clean: rm -rf *.o main ``` When running the makefile I get no compilation ...
Because you lied to the compiler ... and it trusts you. In main.c you told the compilerfis a function (declaration / prototype), butfis, in fact, a pointer to a (unmodifiable) character array of length 7 defined in f.c (definition). Don't lie to the compiler.
``` c='q'; while(c=='q') { printf("hello"); scanf("%c",&c); } ``` Why does the loop exit without any reason on taking the input?
The loop isn't exiting without reason. Thescanfcall will read a character fromstdinand store it inc, thus changing the value ofc. When the loop condition is tested, presumablycno longer=='q'(e.g., you typed something other than "q"). If you're trying to loop until the userdoesn'ttype "q": ``` do { printf("hello"...
I need clarification for the following notation in C: I have a struct, and within that struct I have the following field: bool (* process_builtin)(struct esh_command *); I am pretty confused here.. So this is a boolean field.. What exactly isprocess_builtin? I already have a structesh_commanddefined, but I have no ...
That's not a boolean field, that's apointer to a functiontaking astruct esh_command*and returning abool; the field is calledprocess_builtin. You could also write: ``` typedef bool (* process_builtin_t)(struct esh_command *); ``` in which caseprocess_builtin_twould be a type and in which case you could write the def...
The Code window.h ``` typedef struct { WNDCLASS* wc; HWND hwnd; WNDPROC proc; } PRO_Window; PRO_Window* PRO_WindowCreate(int width, int height, const char* title); ``` window.cI don't think this is important though... ``` PRO_Window* PRO_WindowCreate(int width, int height, const char* title) { /* code...
The error with Boarland-C compiler seems to be because of the declaration ofwcafter thewnd->proc = NULL;. Try to move declaration above initialization statement...
I have written client-server application in C. I run the server in linux. I need to do simple logs of what server do. I print it to the screen. Please how can I copy output of the screen also to the file. Thx
You can use theteecommand as: ``` ./server_program | tee server.log ```
All of the code can be found herehttps://github.com/cole-christensen/airC It seems painfully obvious, but it doesn't work.#include <math.h>is there and yet M_PI isn't recognized ``` airC.c: In function ‘x_curved’: airC.c:94:33: error: ‘M_PI’ undeclared (first use in this function) ``` System Information ``` gcc ve...
M_PIis not standard C. You have to define_GNU_SOURCEto enable it on Linux. OS X is derived from BSD, so the rules are probably different there.
If the input array is - 1,4,3,8,6,5,7 the output should be - 4 8 6 1 3 5 7 I have one solution with insertion sort kind of thing. ``` void sortarrayinorder(int arr[],int size) { int i,j,tem,k; for(i=1;i<size;i++) { for(j=0;j<i;j++) { if((arr[j]%2)!=0 && (arr[i]%2)==0) { ...
You can do this inO(n)with a two-pass approach, so long as you're allowed to allocate a separate output buffer. On the first pass, detect and copy all even numbers. On the second pass, detect and copy all odd numbers.
I am programming c on linux and I have a big integer array, how to filter it, say, find values that fit some condition, e.g. value > 1789 && value < 2031. what's the efficient way to do this, do I need to sort this array first? I've read the answers and thank you all, but I need to do such filtering operation many ti...
If the only thing you want to do with the array is to get the values that match this criteria, it would be faster just to iterate over the array and check each value for the condition (O(n)vs.O(nlogn)). If however, you are going to perform multiple operations on this array, than it's better to sort it.
Here is a small piece of code, the parent process write pipe and child read pipe, everything works fine before I add 'wait()' in parent process. I think it should be no difference, but it just stucks when I input. I'm quite new to system programming. Anyone can help with this? ``` int main() { char* msg = mallo...
You forgot to closefd[1]after thedup2call in the parent. Also, you need to write some character that will causescanfto realize it has read the end of the string. Closing stdout after callingputswould be one way.
i want to make the server aware of completion of data transfer to the client and wait to see whether client is making any new request or not (at same port). like conversation:CLIENT: hi //here i would like to tell the server that the client has sent the data and waiting for response and later again it can send to ...
There are three ways of telling that the client is done. The client sends a special message that means "I'm done, close my connection.", whereby the server closes the connection.The client simply closes the connection, and the server has to handle it when it detects it.For protocols that are of the type request-respo...
I want to write the integer 1 into the first byte and 0x35 to the second byte of a file descriptor using write (http://linux.about.com/library/cmd/blcmdl2_write.htm) but I get the following warning when I try the following: ``` write(fd, 1, 1); write(fd, 0x35, 1); source.c:29: warning: passing argument 2 of ‘write’...
You need to pass an address, so you'll need a variable of some form or other. If all you need is a single char: ``` char c = 1; write(fd, &c, 1); c = 0x35; write(fd, &c, 1); ``` Or use an array (this is generally more common): ``` char data[2] = { 0x01, 0x35 }; write(fd, data, 2); ```
I'm creating a client-server application. I want to do some logging. Server is in C. Now I'm print messages to the terminal. So I'll probably just copy that to sprintf and add timestamp. How can I do that timestamp? It should probably include date, hours, minutes, seconds.
``` #include <time.h> void timestamp() { time_t ltime; /* calendar time */ ltime=time(NULL); /* get current cal time */ printf("%s",asctime( localtime(&ltime) ) ); } ``` On my PC, it just prints ``` Wed Mar 07 12:27:29 2012 ``` Check out the whole range of time related functions herehttps://pubs.opengro...
I want to allocate dynamic an array of chars. So i ve the above code ``` void initialize(char **document_table, int size){ int x, i, j, M; printf("how many words every line: "); scanf("%d", &M); document_table = malloc(sizeof(char) * size); for(x = 0; x < size; x ++) { document_table[x]...
The declarationdocument_table = malloc(sizeof(char) * size);should havesizeof(char*), since a 2D array is an array of pointers to 1D arrays.
When I include c files, I start to get undefined references to other functions. Then, I have to start including the c files that contain the functions. How do I get around this? The undefined references are referenced in the c files that I include, but since I am not actually including those files, I get undefined ref...
Generally one includes ".h" files, not ".c" files. If you call a function declared in a .h file, it is not sufficient to compile the starting C file to get a complete program -- you also need to link in the object files associated with the code that implements the declared functions. These might be in a library, in w...
I am trying to determine the purpose of checking for a pointer being greater than 0: ``` void someFunction(int *src) { int val = *src++; if( val > 0 ) { // Do something? } } ``` If the data type is pointer, wouldn't the value of the pointer always be a memory address? Does doing pointer arithmetic do...
That's not checking if a pointer is greater than zero; it's checking if the pointed-to value is greater than zero, and simultaneously advancing the pointer by one. Here's some equivalent code that might help you understand: ``` void someFunction(int *src) { int val = *src; // Dereferencing the pointer src++; ...
Is there a way to programmatically determine the type(/name) of the underlying file system? The file system in this case can be a parallel file system like lustre/pvfs. So I need to query this name, and not the name of the underlying file system like ext3. Thank you.
What is thef_typefield from thestatfs()function giving you?
so far , I have been using in my programsregcompto use regular expressions on regular strings. Now, I need to find particular byte patterns in non-ASCII binary streams: it is my understanding thatregcompcannot work in this context. Practically, I would like something that lets me define - let's say - a 3-byte patter...
If you need a regex library that works on UTF-8, you should usePhillip Hazel’s excellentPCRE library.
Could help about making that code pure C. ``` struct edge { char key; char values[5]; }; edge* a = new edge[9]; ```
``` typedef struct { char key; char values[5]; } edge ; edge *a = malloc(9 * sizeof(edge)) ; ``` This should do it
In theK&R book, it shows the following printf statement in the pointers chapter: ``` printf((argc > 1) ? "%s " : "%s", *++argv); ``` I don't understand this line - why are there two %s in here? Thanks!
That's equivalent to: ``` if ( argc > 1 ) printf("%s ", *++argv); else printf("%s", *++argv); ``` That's the ternary conditional operator: ``` (condition) ? (subexpression1) : (subexpression2) ``` The expression evaluates tosubexpression1ifconditionistrueandsubexpression2otherwise.
What format string inprintforiomanipoperator in iostream should I use to print the float in the following format: 125.0 => 125125.1 => 125.1125.12312 => 125.121.12345 => 1.121234.1235 => 1234.12 In short, print at most 2 digits after the point, but remove all trailing zeros. I tried%.2fbut doesn't work because it p...
There's no way to specify that. You can specify an exact number of digits after the decimal place (so that it adds zeros if needed), or a maximum number of significant digits, but not a maximum number of digits after the decimal place. NOTE: Xeo answered this first in a comment.
I am using some third party library for sending SMS via EMI protocol. It's written in C and using winsock library. The initialization function is returning this error (Socket error 1411). The function is returning the error on this line: ``` sock = tcp_init( hostname, port); if( sock == SOCKET_ERROR) return -1; ``` ...
Also you can seeSystem Error Codesin MSDN. It says ``` ERROR_CLASS_DOES_NOT_EXIST 1411 (0x583) Class does not exist. ``` Anyway, what you need is WSAGetLastError() or justGetLastErrorfunctions.
I am trying to use Eclipse with an existing codebase. This code has the Makefile buried several directories deep from the root of the project sources. If I tell eclipse this buried directory is the root of the project, everything builds, but nothing indexes, since Eclipse does not know where the sources are. If I tel...
I would try to changebuild directoryof your project. In project properties:C/C++ Build->Builder Settings->Build directory.
I ve to create a pi approximation based on Archimedes equation. I ve to do so with for mode and recursive mode. In for mode i ve create sth like the above: ``` double Pi_approximation(double r, double L){ int i; double fin; double y; for(i=1; i<4; i++){ y =sqrt(2*((r*r) - r*(sqrt(4*((r*r) - ...
It's hard to be sure what is happening, but I will take a guess anyway! Most likely the value you pass to one of thesqrt()calls is negative. When this happens,y(and henceL) will beNaN. The output then will be compiler dependent. For example on my compiler the output is: ``` -1.#IND00 ```
I can't imagine an architecture would design an access to its smallest data type in multiple instructions, but maybe there is some problem with pipelining that I am not considering?
Whether aboolobject is read and written in a single operation isnot guaranteedby the C++ standard, because that would put constraints on the underlying hardware, which C and C++ try to minimize. However, note that in multi-threading scenarios the question whether reading/writing a data type isatomicis only one half o...
Where can i find information on writing a vga driver? The target platform is pic24 and i'm using c. I sorted out the timing, but the implementation on how to display the data is a questionmark for me.
Back in the early 90's the definitive reference wasRichard Ferraro's Programmer's Guide to the EGA, VGA, and Super VGA Cards. The book has very detailed information regarding the card registers, with it you could program even non-standard display modes such as ModeX (320-240x256-4pages) and its derivatives. (there's ...
What format string inprintforiomanipoperator in iostream should I use to print the float in the following format: 125.0 => 125125.1 => 125.1125.12312 => 125.121.12345 => 1.121234.1235 => 1234.12 In short, print at most 2 digits after the point, but remove all trailing zeros. I tried%.2fbut doesn't work because it p...
There's no way to specify that. You can specify an exact number of digits after the decimal place (so that it adds zeros if needed), or a maximum number of significant digits, but not a maximum number of digits after the decimal place. NOTE: Xeo answered this first in a comment.
I am using some third party library for sending SMS via EMI protocol. It's written in C and using winsock library. The initialization function is returning this error (Socket error 1411). The function is returning the error on this line: ``` sock = tcp_init( hostname, port); if( sock == SOCKET_ERROR) return -1; ``` ...
Also you can seeSystem Error Codesin MSDN. It says ``` ERROR_CLASS_DOES_NOT_EXIST 1411 (0x583) Class does not exist. ``` Anyway, what you need is WSAGetLastError() or justGetLastErrorfunctions.
I am trying to use Eclipse with an existing codebase. This code has the Makefile buried several directories deep from the root of the project sources. If I tell eclipse this buried directory is the root of the project, everything builds, but nothing indexes, since Eclipse does not know where the sources are. If I tel...
I would try to changebuild directoryof your project. In project properties:C/C++ Build->Builder Settings->Build directory.
I ve to create a pi approximation based on Archimedes equation. I ve to do so with for mode and recursive mode. In for mode i ve create sth like the above: ``` double Pi_approximation(double r, double L){ int i; double fin; double y; for(i=1; i<4; i++){ y =sqrt(2*((r*r) - r*(sqrt(4*((r*r) - ...
It's hard to be sure what is happening, but I will take a guess anyway! Most likely the value you pass to one of thesqrt()calls is negative. When this happens,y(and henceL) will beNaN. The output then will be compiler dependent. For example on my compiler the output is: ``` -1.#IND00 ```
I can't imagine an architecture would design an access to its smallest data type in multiple instructions, but maybe there is some problem with pipelining that I am not considering?
Whether aboolobject is read and written in a single operation isnot guaranteedby the C++ standard, because that would put constraints on the underlying hardware, which C and C++ try to minimize. However, note that in multi-threading scenarios the question whether reading/writing a data type isatomicis only one half o...
Where can i find information on writing a vga driver? The target platform is pic24 and i'm using c. I sorted out the timing, but the implementation on how to display the data is a questionmark for me.
Back in the early 90's the definitive reference wasRichard Ferraro's Programmer's Guide to the EGA, VGA, and Super VGA Cards. The book has very detailed information regarding the card registers, with it you could program even non-standard display modes such as ModeX (320-240x256-4pages) and its derivatives. (there's ...
if I make a system call, say struct hostent * gethostbyaddr (const char *addr, int len, int family ); and it returns astruct*, do i need to copy the struct to somewhere I "own" instead of using the pointer directly?
The documentation ofgethostbyaddrreads(see Notes section): The functions gethostbyname() and gethostbyaddr() may return pointers to static data, which may be overwritten by later calls. Copying the struct hostent does not suffice, since it contains pointers; a deep copy is required. It means that you need to c...
I got a memcpy function that look strange on how it was used. I pasted it below. Can someone please help explain it. I do not know why the (void *). buffer is buffer in struct BLK. Thanks. ``` memcpy( (void *) (BLK->buffer + left), (void *) input, fill ...
There is no need for the cast, assuminginputandBLK->bufferare already pointer types (which they really should be). I can think of two reasons why they're there: The author was paranoid.The author was making it clear that he/she understands that the specific pointer type is going into a "generic" function.
This question already has answers here:Closed11 years ago. Possible Duplicate:Working of fork() in linux gcc ``` #include <stdio.h> void main () { printf ("ciao"); fork (); } ``` I have some ideas about C optimization but I'm not sure. Hope you know the answer.
The code will probably print"ciao"twice as standard output is buffered IO so the internal buffer for standard output will be replicated in the child process and both buffers flushed when each process, the parent and child, exits. It is unrelated to optimization.
My appliction all of a sudden, stops working. and i executed following comand, ``` #ps -elf | grep aeroServ ``` and Got the following output, ``` #0 S binunun 5634 2300 0 80 0 - 7781 futex_ 15:41 pts/0 00:00:04 ``` What i could able to sense is that, application is not running, but i do not understand ...
That's theWCHANcolumn of thepsoutput. As the man page says: nwchanWCHANaddress of the kernel function where the process is sleeping (use wchan if you want the kernel function name). Running tasks will display a dash ('-') in this column. So your process is blocked on afutex_*call in kernel (these calls are related ...
I have a Code example here. ``` struct node { int data; struct node *link; }; static struct node *first = NULL; ``` It would be great if someone could throw some light on my below questions about the usage of the word static. What does the keyword static do in the above code?what is the dif...
It creates a static pointer to anodeand initializez it toNULL. The variable definition can have multiple meanings: ``` static struct node *first = NULL; ``` If defined outside of a method, it givesfirstinternal linkage. It can only be used inside the defining module. But you can also find that line inside a method...
Which parameters decide the size of data type for a processor? Is it the data bus which decides this? Or is it the Instruction Set Architecture?
The maximum width or the maximum amounts of bits a processor can deal with at the same time at a given time is specific to the particular processor you're using and would be decided by the width of it's data bus and also the width of all the data lines inside the CPU. Essentially a CPU can operate on a certain amount...
I want to use previously malloc'ed array with a C getline function: ``` ssize_t getline(char **restrict, size_t *restrict, FILE *restrict) ``` The following code gives me EXC_BAD_ACCESS (code=1, address=0x400) : ``` FILE *in; if ((in=fopen(inpath, "r+w"))==NULL) exit(1); char * buf = (char *) malloc (BUFSIZ); // BU...
What you are doing now essentially tellsgetlinethere's a pointer to the address1024and you really want it to dereference it. Pass a real address as the second argument, don't cast anintand hope for the best. ``` size_t size = BUFSIZ; getline(&buf, &size, in); ```
Does anyone know of a good reference that lists which calls are interruptable? I was assuming pretty much all system calls were previously, but looking at the man pages for filesystem calls likeopenorrename, the list of errors doesn't includeEINTR.
The updated signal(7) man pages has the anwser. The one I was using from RHEL 5.5 did not. Link below. http://www.kernel.org/doc/man-pages/online/pages/man7/signal.7.html Thanks to Damon for the quick anwser!
I would like to perform the following ``` static Type2 MyData; MyData.Base.Data = (0b0000000000010100); ``` as a static initialization. For example ``` static Type2 MyData = (typecast)(0b0000000000010100); ``` What would I typecast this with? Here are the typedefs for Type1 and Type2 ``` typedef union { UINT...
Similar tothis question, tryType2 t = { .Base.Data = 0x18 };If your goal is to set the bitfields inType1you should probably call them out directly; seehere.
``` char a; char b; char c; a = b + c; a = (char)((int)b+(int)c); ``` In the first line it's implict conversion fromchartoint. In the second line it's explicit. Is there a difference in the binary file generated by compiler? Please consider this question from embedded systems perspective.
With my compiler it produces the exact same assembly twice: ``` 4: 0f b6 55 ff movzbl -0x1(%rbp),%edx 8: 0f b6 45 fe movzbl -0x2(%rbp),%eax c: 01 d0 add %edx,%eax e: 88 45 fd mov %al,-0x3(%rbp) 11: 0f b6 55 ff movzbl -0x1(%rbp),%edx 15: 0f...
``` char str1[20] = "Something"; char *str2 = "Random"; strcat(str1, str2[1]); ``` It gives the error pointer from integer without a cast why is str2[1] treated as an integer? so what should I do if I want to strcat individual elements in a string Thanks!
Because an element from achararrayisachar, which is an integral type. If you want a pointer to the second element, trystr2 + 1or&str2[1].
I'm porting an app i've been working on from Linux to Mac and i'm having trouble with one specific line: ``` system(gnome-terminal -x sh -c \"/home/mrmartin/NetBeansProjects/Consumer/dist/Debug/GNU-Linux-x86/consumer\""); ``` Obviously this is because gnome-terminal is gnome linux only but i can't seem to find the M...
You can useopen, e.g. ``` system("open -a Terminal.app"); ``` or ``` system("open -a Terminal.app /path/to/script"); ```
I have the memory location of a struct stored as an integer. How can I retrieve the struct stored at that location and make a pointer to the object at that location? ``` Structure object; int memLocation = &object; Structure objectCopy = (objectAtLocation) memLocation; Structure *objectPointer = (pointerToLocation) ...
Usingints instead of pointers is very bad form, going back even to the first edition of K&R. So what you're doing is bad. But assuming you have no choice... ifObjectis aStructure, then&objectis aStructure *. So the proper un-cast is basically your line 3: ``` Structure *objectPointer = (Structure *) memLocation; ...
When calling the functioncudaMemcpyToSymbol, I get Invalid value error (cudaErrorInvalidValue). The code where the error occurs is something like this. ``` __constant__ int c_queryLength; //Length of query sequence in chunks of 4 ............... if((cuda_err = cudaMemcpyToSymbol(c_queryLength,&queryLengthInChunks, ...
You need to check whethersize_tis the same size asinton your system. Ifsize_tis 8 bytes andintis only 4 bytes then the call will fail - you can't just copy an 8 byte variable to a 4 byte CUDA device constant.
i'l learning opencv with c++ and so i'm trying to use new c++ interface. but a lot of code i found on internet is based on old c interface. for example i fond a lot of algorithm based on ``` IplImage, cvCvtPixToPlane, cvThreshold ``` and i have to translate them in ``` cv::Mat, cv::threshold, .. ``` inhere(i thin...
Try OpenCV manuals, It seems they are the best way to find equivalent functions. Version 2.1 :http://www.comp.nus.edu.sg/~cs4243/doc/opencv.pdf All C,C++ and python API is available as single pdf, so you can just search for function names to find equivalent in C or C++ Version 2.3 :https://shimcv.googlecode.com/fil...
I tried the below program . INPUT-: i want help Desired OUTPUT-:Words=3 Characters=9 But the actual output deviates from the desired. Can someone tell what is my mistake . include ``` void main() { int countch=0; int countwd=1; printf("Enter your sentence in lowercase: "); char ch='a'; while(ch!='\r') ...
Be advised:getchar()returnsint, notchar. This is one of the most common pitfalls for beginning C programmers, it seems. Also, you should check for the special valueEOFand stop the program if it occurs; this is the typical and "clean" way of doing programs that read input and will make the program automatically handle...
I have searched through a lot of folders, but found definition only (in stdio.h) - not the realization.
It's in the source code for the C library: http://opensource.apple.com/source/Libc/Libc-763.12/stdio/getline-fbsd.c
I have a string which contains a hexadecimal value: ``` "29E94B25" ``` I want to convert this hexadecimal string into an unsigned long using a base of 10. e.g. I want to create an unsigned long with a value of: ``` 703154981 ``` How can I do this type conversion?
You can read this string into an unsigned long withstrtoul: ``` unsigned long n = strtoul("29E94B25", NULL, 16); ``` You can then print it in base-10 withprintf. There's no such thing as anunsigned longwith a base other than 2.
I am usingthisimplementation of the Mersenne twister for a diamond-square terrain generator I am writing. The point of using a separate implementation rather than the built in rand() is that I want the same seed to generate the same map every time. Diamond-square requires a random error to be added on to every pixel, ...
If you need more random numbers, just keep callingmt_randomas many times as you want.
When I do this: ``` main(){ char* output[255]; output[0] = '\0'; } ``` I get a segfault atoutput[0] = '\0'. What am I doing wrong?
The problem is probably somewhere else, this part of code shouldn't segfault. Maybe you try to print it somewhere? However I'm not sure whether it does what you want. You declared array of char pointers: ``` char* output[255]; ``` And write char there: ``` output[0] = '\0'; ``` You probably wanted to declare arra...
I am using postgres 9.0 database , where In my C program I connect the database only once and using fork I generate processes , where all my child program shares the connection Most of the time it works correctly , In some cases child A gets the query error of child B , and It also gets the query time out issues and...
It's not a good idea for threads to share a single database connection because you'll run into the exact issue that you described in your question: one thread can get the output of another thread's request. Instead, you'll want each thread to connect separately. If you have a lot of threads, you might want to consid...
I know the default value for norm_type used when calling the function is 4, but what does this correspond to? The options are NORM_INF, NORM_L1 and NORM_L2. Which of these is 4? And while I'm at it, what are the values for the rest of them? I can't find #defines for these anywhere.
These are defined inmodules/core/include/opencv2/core/core.hpp, as anenum: ``` enum { NORM_INF=1, NORM_L1=2, NORM_L2=4, NORM_TYPE_MASK=7, NORM_RELATIVE=8, NORM_MINMAX=32}; ``` So default is L2 norm (euclidean). Also, theOpenCV docssay that the default isNORM_L2.
I have a GtkImage that I am manipulating with a GdkPixbuf. When I change it, I need to redraw it to make the changes take effect. Right now I am doing this by hiding and then showing the image. What would be the proper way of doing this?
gtk_widget_queue_draw()function invalidates the widget area and forces redrawing.
I am new to socket progamming and I am trying to implement a stripped down FTP like program. It uses two TCP connections, one as a control connection and other as a data connection. The problem is that I do not know how to use the sever to connect to the client's N+1 port using its port 20. Please referhere, to fund ...
To create the active mode data connection, you: Find the local address of the control connection withgetsockname();modify this address by changing the port number to 20;create another socket withsocket();bind the new socket to the port 20 address created withbind();connect the socket to the client's address/port with...
I've got two header files, each requiring a type defined in the other. When I try to compile, I get an error regarding an unknown type name. (If I provide only struct declarations and not definitions, I get an incomplete-types error.) What's a solution that will let me share these structs properly? Right now, my code...
You should forward-declare thestruct mytypeAinstead of includingheaderA.h: Inside headerB.h: ``` struct mytypeA; // <<<--- Forward declaration void foo(struct mytypeA* myA); ``` This works because you are not using the actualmytypeA, only a pointer to it. You cannot pull the same trick withheaderA, becausemytypeAi...
I understand that compilers convert c source code to assembly and then to machine code. I searched through every compiler setting I could find, and their website but I can't get it to generate assembly. Also, the website states that Dev-C++ uses AT&T assembly, can I also convert from that to Intel?
Dev-C++ seems to use GCC. You can try this option:gcc -S -masm=intelas answered in this question:How do you use gcc to generate assembly code in Intel syntax? I do not know how to set command line options on Dev-C++ but guides can be easily found.
I have a C program in which two scanf() are done. I need to write a shellscript that will run the program and give it the arguments too. The problem is that all I could come up with is how to pipeline an argument into the program as a command line arguments which is not what I need. Any help appreciated.
This should work ``` echo "some input" | yourprog ``` e.g. echo "1 1 + p" | dc
I need to write a program in BSD sockets which behaves like a file transfer protocol for transferring file contents. It has to use two TCP connections between client and server. If not code, please provide any other reference material such as flowchart or algorithm for the implementation.
Try going through the FTP documentation availablehere.
Is there a difference betweenint *(a[10])andint *a[10]? I guess they are the same but, want to get confirmed, as the bracket is confusing me.
No, there isn't a difference between those two. The reason that they're the same is because[]has higher precedence than*, so the brackets are essentially redundant. They're both a declaration for an array of 10intpointers. Thereishowever a difference between the following: int *a[10];int (*b)[10]; In this case,ais ...
I am a bit confused about the followingif_evenfunction. How is the return type FLAGS? This seems strange - isn't an enum just a list of multiple integers to be used like#define's ? ``` enum flag_o_e {EVEN, ODD}; enum flag_o_e test1; typedef enum flag_o_e FLAGS; FLAGS if_even(int n); main() { int x; FLAGS test2;...
Actually, an enum is a new type. It is not just some alias for int. (It can be converted to and from int, though.)
Here is a sample run of this program, assuming that the executable file is called match and hit. This run illustrates a situation where the human player wins the game. User input is bolded. /home/userXYZ/ECE15/Lab3> match_and_hitWelcome to the MATCH and HIT gameThe computer has selected a 4-digit number.Try to deduc...
Assuming your terminal supports ANSI escape sequences, you can use this: ``` #define ANSI_UNDERLINED_PRE "\033[4m" #define ANSI_UNDERLINED_POST "\033[0m" printf(ANSI_UNDERLINED_PRE "underlined" ANSI_UNDERLINED_POST "\n"); ```
I was compiling/linking my program ``` i386-gcc -o output.lnx func.opc mainc.opc ``` and I kept getting that error. I honestly have no idea what this means. Any clue? thanks,
This is usually a symptom of having too much code or data in the program. The relocation at offset 7 in .text segment (code) has been compiled with a fixed size (2 or 4), but the data/instruction it is referring to is more than 64k or 2G away. Other than that, I can't tell you how to fix it without actually seeing t...
I am working on a project that requires implementation of a fork() in unix. I read freeBSD and openBSD source code but it is really hard to understand. Can someone please Explain the returning twice concept? I understand that one return is pid of a child, and that gets returned to parent and other one is zero and it g...
When you callfork, it returns "twice" in that the fork spawns two processes, which each return. So, if you're implementingfork, you have to create a second process without ending the first. Then the return-twice behavior will happen naturally: each of the two distinct processes will continue execution, only differing...