question
stringlengths
25
894
answer
stringlengths
4
863
Hay All Can we get the hard-disk number using php or C Is there possible or not ? This is not a problem just configuring.
If you're using linux just read the file, /etc/fstab I'm looking around for a windows equivalent.
This is some C code from the Make Controller firmware. I'm familiar with what void pointers are, but I've never seen syntax like the first line of this function. What precisely is being accomplished by that? ``` void MakeStarterTask(void* parameters) { (void)parameters; Run(); TaskDelete(NULL); } ```
It "uses"parametersso the compiler won't emit a warning about an unused parameter, but the expression does itself nothing. Any expression can be cast tovoid, which discards the result. (Keep in mind that the expression is still evaluated;to make an expression completely ignored is trickier.)
According toCREATE VIRTUAL TABLEsyntax,IF NOT EXISTSclause isnot available. How should I handle the case when the virtual table already exists without usingDROP TABLE IF EXISTS? I want to use rtree and fts module.
You can use ``` select DISTINCT tbl_name from sqlite_master where tbl_name = ? ``` Then bind the virtual table name to your statement and call sqlite3_step(). If you get SQLITE_ROW back, then your table exists. To be certain that it is a virtual table, check therootpagecolumn for '0'.
GCC'sbacktrace_symbols()only resolves dynamic symbols, since handling all types of symbols issomething GCC maintainers do not want to get into. How would I go about extracting non-dynamic symbols obtained from GCC'sbacktrace()function myself?
Check out whataddr2linedoes using bfd. That is one approach I have used successfully. More specifically,backtracefiltgets you basically all the way there, you just need to adapt it to take the addresses from backtrace instead of parsing a file.
This program is based on the program in K&R in the input/output section ``` #include <stdio.h> main(){ double sum, v; sum = 0; while (scanf("%1f",&v)==1) printf("\t%.2f\n",sum+=v); return 0; } ``` It compiles ok. But when trying to run, from any input the output is "-NAN", presumably NOT A NUMBER. I have n...
The format code is wrong in scanf. It should be%lf(with lower case L), not%1f. ``` while (scanf("%lf",&v)==1) ``` This is because%lfscans for a double, and%fscans for a float. For details, seescanf format codes.
I have a sorted array ( in ascending order) and I want to find the subscript of a number in the array which is the the next highest number to a given number. For example,if I have 67 as a given number and if I have an array x=(23,36,45,62,79,103,109), then how do I get the subscript 5 from x (to get 79 which is...
Is this homework? You can do it pretty easily with a recursive call, splitting the array in half each time.
Hay All Can we get the hard-disk number using php or C Is there possible or not ? This is not a problem just configuring.
If you're using linux just read the file, /etc/fstab I'm looking around for a windows equivalent.
This is some C code from the Make Controller firmware. I'm familiar with what void pointers are, but I've never seen syntax like the first line of this function. What precisely is being accomplished by that? ``` void MakeStarterTask(void* parameters) { (void)parameters; Run(); TaskDelete(NULL); } ```
It "uses"parametersso the compiler won't emit a warning about an unused parameter, but the expression does itself nothing. Any expression can be cast tovoid, which discards the result. (Keep in mind that the expression is still evaluated;to make an expression completely ignored is trickier.)
According toCREATE VIRTUAL TABLEsyntax,IF NOT EXISTSclause isnot available. How should I handle the case when the virtual table already exists without usingDROP TABLE IF EXISTS? I want to use rtree and fts module.
You can use ``` select DISTINCT tbl_name from sqlite_master where tbl_name = ? ``` Then bind the virtual table name to your statement and call sqlite3_step(). If you get SQLITE_ROW back, then your table exists. To be certain that it is a virtual table, check therootpagecolumn for '0'.
GCC'sbacktrace_symbols()only resolves dynamic symbols, since handling all types of symbols issomething GCC maintainers do not want to get into. How would I go about extracting non-dynamic symbols obtained from GCC'sbacktrace()function myself?
Check out whataddr2linedoes using bfd. That is one approach I have used successfully. More specifically,backtracefiltgets you basically all the way there, you just need to adapt it to take the addresses from backtrace instead of parsing a file.
This program is based on the program in K&R in the input/output section ``` #include <stdio.h> main(){ double sum, v; sum = 0; while (scanf("%1f",&v)==1) printf("\t%.2f\n",sum+=v); return 0; } ``` It compiles ok. But when trying to run, from any input the output is "-NAN", presumably NOT A NUMBER. I have n...
The format code is wrong in scanf. It should be%lf(with lower case L), not%1f. ``` while (scanf("%lf",&v)==1) ``` This is because%lfscans for a double, and%fscans for a float. For details, seescanf format codes.
How would I convert an NSDate to a NSString, formatted with strftime specifiers?
you could use strftime. ``` NSDate *date = [NSDate date]; time_t time = [date timeIntervalSince1970]; struct tm timeStruct; localtime_r(&time, &timeStruct); char buffer[80]; strftime(buffer, 80, "%d.%m.%Y %H:%M:%S", &timeStruct); NSString *dateStr = [NSString stringWithCString:buffer encoding:NSASCIIStringEncoding]; ...
May I know how I can a write a character string into a 2D character array? I need to read every character in the string and put it into a 2D array. For example: char string[10]; I want to write all the characters in the string into a 2D array. That means, when I read array[0][0], I should get the first character....
First, make surearray[0]is big enough to hold your string. Second, usememcpyorstrncpyto copy the bytes ofstringintoarray[0]. If you need to process and address each character individually, you can start by doing what memcpy does, but in a for loop: ``` #define NUM_ARRAYS 2 #define LENGTH 4 char *string = "GOODMORN"...
How do addresses get generated in arrays in C, say how does a [x][y] get to a particular value, i know its not that big a question but just about to actually start coding.
Well it is done depending on your data type of whose array you have considered. Say for an Integer array, each value holds 4 bytes, thus a row X long will take 4X bytes. Thus a 2-D matrix of X*Y will be of 4*X*Y Bytes. Any address say Arry[X][Y] would be calculated as : (Base Address of Arry) + (X * No. of colu...
I need to allocate a varibale size for SYMBOLs, typedef int SYMBOL I did in following way SYMBOL test[nc], herencis an integer. But this gives me following warning: ISO C90 forbids variable-size array How could i do it without getting warning? Thanks, Thetna
Theallocalibrary function was intended for that before variable-sized arrays were introduced. It all has to do with incrementing the stack pointer. For the declaration of a typical constant-size array, the stack pointer is incremented with a constant that is known at compile-time. When a variable-size array is declar...
Is it equivalent to a unsigned integer ?I'm able to use unsigned unknown_type_var = 3332934; and print it successfully. This value is greater than a integer variable right ?
unsigned is totally equivalent to unsigned int, just like long is equivalent to long int, etc.
I have a script that generates 2 code files (For example, src1.c, src2.c) according to another code file (say origin.h).I use a makefile to build them.Now, I want the script to be executed when src1.c OR src2.c is older that origin.h. What is the best way to do that? Thanks.
Make src1.c and src2.c jointly dependent on origin.h: ``` src1.c src2.c : origin.h build-sources ```
I am working on a basic graph implementation(Adj List based) in C so that I can re-use the basic structure to solve all graph related problems. To map a graph I draw on a paper,I want the best and easiest way. Talking of the way I take the input rather then how should I go about implementing it! :) Should I make an...
Best is to go for input of an edge list, that is triplets of, Source, Destination, Cost This routine can be used to fill Adj List and Adj Matrix. With the latter, you would need to properly initialize the Matrix though and setup a convention to determine non existent edges.
Refering tohttp://www.devx.com/tips/Tip/13291, it says that I can usememcpywith the size to copy determined bysizeof(), however, isn't the array pointing to a pointer? Other than iterating through the array, how can I usememcpyto deep copy an array? Thanks!
In the linked exampleint weekly_hours[5][5];allocates space for 25 integers. There is no further indirection, so you can safely use memcpy to duplicate it's values.
I have to write a code such that, it may create child process via Createprocess API. Parent process in the process tree has to allocate the memory common to the total process tree, so that child process can access it. Malloc, globalalloc does allocate memory within the scope for the process. However I could not exten...
The way to share memory across processes under Windows is throughmemory-mapped files. Don't be thrown off by the word "file"; there doesn't have to be a file under the memory (other than the swap file).
Hey all yesterday i have given my GATE exam and in this exam there was a question: What does the following fragment of C-program print? ``` char c [] = "GATE2011"; char *p =c; printf ( "%s", p+p [3] − p [1]) ; ``` options: ``` (A) GATE2011 (B) E2011 (C) 2011 (D) 011 ``` Answer is 'C'. when i tried the code on my ...
That's pointer arithmetic: ``` char c [] = "GATE2011"; // indices: 01234567 char *p =c; ``` p[1]isAcharacter code,p[3]isEcharacter code, their difference (Ecode minusAcode) is 4, that difference is then added toppointer and you've got the address of2011substring passed intoprintf().
How do I find what library files I need to include for the implementation of a particular c header if there is not library with the same name?
I'd Google for the name of the header or the functions within it. If you're on a Debian-based system you could also trydpkg -S <full header path>to tell you what package provided the header, then see what other files (in/usr/lib) that same package provides.
If I am writing to a socket file descriptor using write() bytes by bytes, Is every byte now a packet?will the socket add TCP/IP header to every byte?Or does it have a buffer mechanism (I personally doubt so since I don't have explicitly flush). For example: ``` write(fd, 'a', 1); write(fd, 'b', 1); write(fd, 'c', 1...
No, not every byte will become a packet. Some may be coalesced due to Nagle's Algorithm and other things. There will be one TCP header per packet, not per byte. That said, you should avoid calling write/send byte by byte because each one is a system call, which is expensive (on the local machine, not in terms of ho...
Can anybody tell me how to implement a program to check a string contains all unique chars ?
If you are talking about an ASCII string: Create an int array [0-255], one for each character index, initialised to zero.Loop through each character in the string and increment the respective array position for that characterIf the array position already contains a 1, then that character has already been encountered....
I'd like to create aPyThreadStatesince there doesn't appear to be one for the current thread. How do I get the current PyInterpreterState to pass toPyThreadState_New(...), or is that something that I should only do if I'm embedding an interpreter (and thus have created it), rather than calling into a library from pyt...
I guess that you might are doing multi-threads programming. Recently, I'm having the similar problems. Hope the following codes may help you. ``` //in main thread PyThreadState * mainThreadState = NULL; Py_Initialize(); PyEval_InitThreads(); mainThreadState = PyThreadState_Get(); PyEval_ReleaseLock(); ``` ``` //in ...
I recently had to type in a small C test program and, in the process, I made a spelling mistake in the main function by accidentally usingvooidinstead ofvoid. And yet it still worked. Reducing it down to its smallest complete version, I ended up with: ``` int main (vooid) { return 42; } ``` This doesindeedcomp...
It's simply using the "old-style" function-declaration syntax; you're implicitly declaring anintparameter calledvooid.
``` struct queens_arg { int board[64]; int focus_idx; }; struct queens_arg *args; (*args).focus_idx = 0; ``` The code is as the following. I get a seg fault (debugged) to occur on settingfocus_idx = 0. Why is this happening? How can I fix it? Thanks!
The problem is that you're creating a pointer to astruct queens_arg, but you're not initializing it to point anywhere. Consequently, when you write ``` (*args).focus_idx = 0; ``` You're following a garbage pointer, causing the segfault at runtime. To fix this, make sure that you set up the pointer to point somewhe...
Given matrix productC = A*B, is thereN^2way to estimate max value in C? Or rather what is a good way to do so?
How about this: For each row inAand each column inB, find the vector-norm squared (i.e. sum of squares).O(n^2)For each combination of row fromAand column fromB, multiply the corresponding vector-norm squareds.O(n^2)Find the maximum of these.O(n^2) The square-root of this will be an upper-bound formax(abs(C)). Why? ...
I've got around 12,000 lines of badly styled C code, e.g. ``` initholeend=(mm_footer *) (end-sizeof(mm_footer)); initholeend->magic=MM_MAGIC; initholestart->used+=amount; ``` What I'd like to do is automatically adding spaces around all binary operands and assigments: ``` initholeend = (mm_footer *) (end - sizeof(m...
astyleisn't bad.
Is it equivalent to a unsigned integer ?I'm able to use unsigned unknown_type_var = 3332934; and print it successfully. This value is greater than a integer variable right ?
unsigned is totally equivalent to unsigned int, just like long is equivalent to long int, etc.
I have a script that generates 2 code files (For example, src1.c, src2.c) according to another code file (say origin.h).I use a makefile to build them.Now, I want the script to be executed when src1.c OR src2.c is older that origin.h. What is the best way to do that? Thanks.
Make src1.c and src2.c jointly dependent on origin.h: ``` src1.c src2.c : origin.h build-sources ```
I am working on a basic graph implementation(Adj List based) in C so that I can re-use the basic structure to solve all graph related problems. To map a graph I draw on a paper,I want the best and easiest way. Talking of the way I take the input rather then how should I go about implementing it! :) Should I make an...
Best is to go for input of an edge list, that is triplets of, Source, Destination, Cost This routine can be used to fill Adj List and Adj Matrix. With the latter, you would need to properly initialize the Matrix though and setup a convention to determine non existent edges.
Refering tohttp://www.devx.com/tips/Tip/13291, it says that I can usememcpywith the size to copy determined bysizeof(), however, isn't the array pointing to a pointer? Other than iterating through the array, how can I usememcpyto deep copy an array? Thanks!
In the linked exampleint weekly_hours[5][5];allocates space for 25 integers. There is no further indirection, so you can safely use memcpy to duplicate it's values.
I have to write a code such that, it may create child process via Createprocess API. Parent process in the process tree has to allocate the memory common to the total process tree, so that child process can access it. Malloc, globalalloc does allocate memory within the scope for the process. However I could not exten...
The way to share memory across processes under Windows is throughmemory-mapped files. Don't be thrown off by the word "file"; there doesn't have to be a file under the memory (other than the swap file).
Hey all yesterday i have given my GATE exam and in this exam there was a question: What does the following fragment of C-program print? ``` char c [] = "GATE2011"; char *p =c; printf ( "%s", p+p [3] − p [1]) ; ``` options: ``` (A) GATE2011 (B) E2011 (C) 2011 (D) 011 ``` Answer is 'C'. when i tried the code on my ...
That's pointer arithmetic: ``` char c [] = "GATE2011"; // indices: 01234567 char *p =c; ``` p[1]isAcharacter code,p[3]isEcharacter code, their difference (Ecode minusAcode) is 4, that difference is then added toppointer and you've got the address of2011substring passed intoprintf().
How do I find what library files I need to include for the implementation of a particular c header if there is not library with the same name?
I'd Google for the name of the header or the functions within it. If you're on a Debian-based system you could also trydpkg -S <full header path>to tell you what package provided the header, then see what other files (in/usr/lib) that same package provides.
If I am writing to a socket file descriptor using write() bytes by bytes, Is every byte now a packet?will the socket add TCP/IP header to every byte?Or does it have a buffer mechanism (I personally doubt so since I don't have explicitly flush). For example: ``` write(fd, 'a', 1); write(fd, 'b', 1); write(fd, 'c', 1...
No, not every byte will become a packet. Some may be coalesced due to Nagle's Algorithm and other things. There will be one TCP header per packet, not per byte. That said, you should avoid calling write/send byte by byte because each one is a system call, which is expensive (on the local machine, not in terms of ho...
Can anybody tell me how to implement a program to check a string contains all unique chars ?
If you are talking about an ASCII string: Create an int array [0-255], one for each character index, initialised to zero.Loop through each character in the string and increment the respective array position for that characterIf the array position already contains a 1, then that character has already been encountered....
I'd like to create aPyThreadStatesince there doesn't appear to be one for the current thread. How do I get the current PyInterpreterState to pass toPyThreadState_New(...), or is that something that I should only do if I'm embedding an interpreter (and thus have created it), rather than calling into a library from pyt...
I guess that you might are doing multi-threads programming. Recently, I'm having the similar problems. Hope the following codes may help you. ``` //in main thread PyThreadState * mainThreadState = NULL; Py_Initialize(); PyEval_InitThreads(); mainThreadState = PyThreadState_Get(); PyEval_ReleaseLock(); ``` ``` //in ...
I recently had to type in a small C test program and, in the process, I made a spelling mistake in the main function by accidentally usingvooidinstead ofvoid. And yet it still worked. Reducing it down to its smallest complete version, I ended up with: ``` int main (vooid) { return 42; } ``` This doesindeedcomp...
It's simply using the "old-style" function-declaration syntax; you're implicitly declaring anintparameter calledvooid.
``` struct queens_arg { int board[64]; int focus_idx; }; struct queens_arg *args; (*args).focus_idx = 0; ``` The code is as the following. I get a seg fault (debugged) to occur on settingfocus_idx = 0. Why is this happening? How can I fix it? Thanks!
The problem is that you're creating a pointer to astruct queens_arg, but you're not initializing it to point anywhere. Consequently, when you write ``` (*args).focus_idx = 0; ``` You're following a garbage pointer, causing the segfault at runtime. To fix this, make sure that you set up the pointer to point somewhe...
Given matrix productC = A*B, is thereN^2way to estimate max value in C? Or rather what is a good way to do so?
How about this: For each row inAand each column inB, find the vector-norm squared (i.e. sum of squares).O(n^2)For each combination of row fromAand column fromB, multiply the corresponding vector-norm squareds.O(n^2)Find the maximum of these.O(n^2) The square-root of this will be an upper-bound formax(abs(C)). Why? ...
I've got around 12,000 lines of badly styled C code, e.g. ``` initholeend=(mm_footer *) (end-sizeof(mm_footer)); initholeend->magic=MM_MAGIC; initholestart->used+=amount; ``` What I'd like to do is automatically adding spaces around all binary operands and assigments: ``` initholeend = (mm_footer *) (end - sizeof(m...
astyleisn't bad.
I have a python program that calls into a c++ library, which wishes to release all the python locks so that other python threads can run. UsingPyEval_SaveThreadandPyEval_ReleaseThreadI get errors that the thread state is NULL: ``` Fatal Python error: PyEval_SaveThread: NULL tstate ``` However, the lower-level funct...
Answer:no, it is never meant to beNULL(if it is, it's a fatal error). Turned out this was because I was linking against two different versions of python, one via boost_python, and the other directly. Top Tip: uselddorotool -Lto check your library dependencies when funny stuff happens ;)
I have a project which uses the windows API on windows, and pthreads on every other platform. How do I have my makefile add-pthreadto my CFLAGS if I'm NOT targetting for windows? For compiling, I use [gcc (mingw and native), clang, icc], and for targets I have [GNU/Linux, BSD, Darwin, Windows].
Assuming that you have mingw installed and are using GNUmake: ``` OPERATING_SYSTEM:= $(shell uname | sed 's/-.*//') ifneq ($(OPERATING_SYSTEM),MINGW32_NT) CFLAGS+= -pthread LDFLAGS+= -pthread endif ```
I'm creating an iPhone app that needs the location of .wav which is located in the sandbox. I do this with the following: ``` recordFilePath = (CFStringRef)[NSTemporaryDirectory() stringByAppendingPathComponent: @"recordedFile.wav"]; ``` How can I convert recordFilePath to a string that can then be passed into a C f...
That will depend on what type your c function expects to get - you can write a c function that accepts NSString* object as parameter. If you want to convert yourNSStringtochar*then you can use one of the following functions: ``` – cStringUsingEncoding: – getCString:maxLength:encoding: – UTF8String ```
without using multiplication or division operators. You can use only add/substract operators.
A pointless problem, but solvable with the properties of logarithms: ``` pow(a,b) = exp( b * log(a) ) = exp( exp(log(b) + log(log(a)) ) ``` Take care to insure that your exponential and logarithm functions are using the same base. Yes, I know how to use a sliderule. Learning that trick will change your p...
Is it possible to only use C syntax in a .mm file?
There's nothing wrong with writing .mm file that works in terms of plain old functions, strings and arrays, rather than the additions made by objective-c and c++. However, there are a few cases where valid C isn't valid C++ (or Objective-C++) which you'll want to consider (http://www.parashift.com/c++-faq-lite/big-pi...
How would I connect to char* strings to each other. For example: ``` char* a="Heli"; char* b="copter"; ``` How would I connect them to one char c which should be equal to "Helicopter" ?
strncat Or usestrings.
I'm just working on a new porject an I'm working actually with simple coordinates: ``` if (locationOnJoystick.x > joystickArea.frame.size || locationOnJoystick.y > joystickArea.frame.size) { ``` But while running the code I get an ERROR: error: invalid operands to binary > (have 'CGFloat' and 'CGSize') Can anyone ...
locationOnJoystick.xis aCGFloat, whilejoystickArea.frame.sizeis aCGSize. They're different types, you cannot compare them. I guess you should comparelocationOnJoystick.xwith the width of yourjoystickArea.frame.size(and the same with y and height): ``` if (locationOnJoystick.x > joystickArea.frame.size.width || locat...
This question already has answers here:Closed12 years ago. Possible Duplicate:Best algorithm to test if a linked list has a cycle ``` p=head; q=head->next; while(p!=NULL && q!=NULL) { if(p==q) { //Loop detected! exit(0); } p=p->next; q=(q->next)?(q->next->next):q->next; --how this line works ?? } ```
First of all, if there is no loop in the list, the conditionp==qwill never be true, asqis always "ahead" ofp. Then, the distance betweenpandqis increased by one at each iteration. So if there's a loop, the conditionp==qwill be true as soon as the distance is a whole multiple of the loop length. The line in question ...
stack is increasing or decreasing using C program ?
Right, in C usually variables in function scope are realized by means of a stack. But this model is not imposed by the C standard, a compiler could realize this any way it pleases. The word "stack" isn't even mentioned in the standard, and even less if it is in- or decreasing. You should never try to work with assumpt...
I'm studying data structures and linked lists, but I'm not getting the concept of how to make a copy of a linked list. Can someone explain this, possibly using pseudocode or C code?
The logic for duplicating a linked list is recursive and based on the following observations: The clone of the empty list is the empty list.The clone of a list with first node x and remaining nodes xs is a copy of x prepended to a clone of xs. If you encode the linked list in C++, this can be very clean: ``` struct...
``` int search( struct node **front, int val) { struct node *cur; cur=*front; while(cur!=NULL) { cur=cur->next; } return cur!=NULL; } ```
This will always run to the end of the list, then return0, so no. You need to compare withvalsomewhere. Also, passingfrontas astruct node **is not necessary, since you're never assigning*front. Pass it as aconst struct node *instead. Your code is equivalent to ``` int search(struct node **front, int val) { retu...
Here is a c program.I am getting a strange output. When num1=10 and num2=20-> ``` #include<stdio.h> void main() { int num1=10,num2=20; clrscr(); if(num1,num2) { printf("TRUE"); } else { printf("FALSE"); } getch(); } ``` Output: TRUE when num1=0 and num2=220 Output: TRUE But when num1=0 and num2=0: Output:...
You're using thecomma operator. That operator first evaluates its first operand, then drops the result on the floor and proceeds to evaluate and return its second operand. That's why your program only printsFALSEifnum2evaluates tofalsein a boolean context (like e.g.0,0.0orNULL).
How do i look for a substr in string pointed by u_char* as all C functions take a char* as argument?
Assuming thatu_charis a typedef forunsigned char, then the normal trick is to use the standard functions and apply casts. That is very ungainly, though, so you might instead use macros that apply the casts automatically. ``` #define STRSTR(haystack, needle) \ ((u_char *)strstr((char *)haystack, (cha...
What is the shortest way to check if a string contains the character "-" or it contains only numbers? Edit:And how would I do it in C without std::string? Which one is better?
std::stringhas a member function,find, which can be used to search for a character or substring. It returnsstd::string::nposif the search character or substring is not found. One straightforward way to test whether a string contains only digits is to use thefind_first_not_ofmember function with the search list"01234...
I am trying to access items in an array of structs and print the structs fields as follows ``` printList(Album *a, int numOfStructs) { int i; int j; for(i = 0; i < numOfStructs; i++) { printf("number%d\n:", i+1); printf("%s", a[i]->field2); printf("%s", a[i]->field2); ...
ais of typeAlbum*which means thata[i]is of typeAlbum(it is theith element in the array ofAlbumobject pointed to bya). The left operand of->must be a pointer; the.operator is used if it is not a pointer.
When one uses free() in C, does freeing one pointer, free the contained pointers? e.g. If a pointer points to an array of structures that each hold another array of Strings and some other fields. Will freeing the pointer to the array of structs ripple down and free all the data or will these other pointers be broken,...
Thefreefunction knows nothing of the data contained within the block being freed. If you have pointers to other data in that block, you must free thembeforeyou free the block. If you don't free them at all you will have a memory leak. If you free them afterwards, you could have heap corruption.
This question already has answers here:Closed12 years ago. Possible Duplicate:Enter Password in C Ask user to enter Password without showing the input characters on console?
You need to set the console to "no echo" mode. This depends on your particular OS. Here is an example of doing it for linux:http://www.cplusplus.com/forum/beginner/1988/page4.html#msg14522
I have a buffer that is text read from a file. I loop over it like so to count the lines: ``` while(fgets(buf, 1024, fp) != NULL){ for(counter = strtok(buf,"\n"); counter; counter=strtok(0,"\n")){ threads++; } } printf("NUMBER OF THREADS: %i", threads); ``` and ...
userewind(fp);orfseek(fp, 0, SEEK_SET); fseekis considered better practice since it returns a status code.
Is it possible to return two variables in C? I would like to return a pointer as well as a string so that I can use both outside of the function. Is this done with an array? if so, what type of array would it be? Void?
No, you can only return one object. You can, however, return a struct type object and you can put your "multiple returns" into the struct: ``` typedef struct return_type { void* pointer_; // You should, of course, use whatever the appropriate types char* string_; // are for the objects that you are trying t...
How does one malloc an array of structs correctly if each struct contains an array of strings which vary in size? So each struct might have a different size and would make it impossible to realloc(numberOfStructs * sizeof(structName)) after malloc(initialSize * sizeof(structName) How does one allocate memory for ...
If your structure has a char *, it takes up the size of one pointer. If it has a char[200], it takes up two hundred bytes.
Slightly oxymoronic title! Bonus points for Xcode answer but it's a gdb question. If I have a standard, statically sized array gdb will print all its elements [and Xcode will let me browse through it] but if I have azero length array, it won't, because it doesn't know. Obviously I can print the array indexes one by o...
http://www.chemie.fu-berlin.de/chemnet/use/info/gdb/gdb_9.html#SEC54 Discusses "Artificial arrays" It is often useful to print out several successive objects of the same type in memory;...
I would like to represent a structure containing 250 M states(1 bit each) somehow into as less memory as possible (100 k maximum). The operations on it are set/get. I cold not say that it's dense or sparse, it may vary. The language I want to use is C. I looked at other threads here to find something suitable also. ...
If you know your data might be sparse, then you could userun-length encoding. But otherwise, there's no way you can compress it.
In the .NET compiler (csc.exe) I can use the option/target:exeto compile into an exe that will keep the console open so that I can see somestderror `stdout`` output. However I cannot achieve this same functionality using the C/C++ compiler (cl.exe). My program usesWinMainwhich means it's an entire UI application. Tha...
the flag you need to create a console application is/subsystem:console, check out the MSDN documentationabout it. and it is actually a flag for the linker stage: ``` link /out:foo.exe /subsystem:console a.obj b.obj ``` you can however tell the compiler to use certain flags when invoking the linker: ``` cl /flags /l...
Libcurl defaults to stdout when handling a server's response. We can override it withCURLOPT_WRITEFUNCTIONandCURLOPT_WRITEDATA. From the manual I got that I could set theCURLOPT_WRITEFUNCTIONtoNULLand then pass aFILE *toCURLOPT_WRITEDATA. If I just want to not use it what would be the most efficient way to go about it...
Write to/dev/nullor a similar black hole. Note that the existence and location of such special file(s) is OS dependent - Unixen have /dev/null, Windows has \Device\Null, etc.
I'm a Java dev, and for some reason I'm studying C at the moment. The thing is I'm having some trouble reading function definitions. Could you give me a hint with this one for instance: ``` void (*signal(int sig, void(*func)(int)))(int) ``` Thanks guys!
You should learn theright-to-left rule. This page contains good examples. signalis a function taking as arguments: an integera pointer to function takingintand returning nothing and returning a pointer to a funcction takingintand returning nothing.
How are arrays scoped in C? When do they ever get destroyed? (Note, also talk about if they can be passed even in p_threads)
They're scoped just like normal variables: ``` // in a function int arrayA[300]; { float arrayB[100]; // arrayA and arrayB available here } // arrayB out of scope, inaccessible. // arrayA still available. ``` If you were to pass the array to a function, it would be valid as long as the array was still in sco...
Is there a difference (in terms of execution time) between implementing a function in Python and implementing it in C and then calling it from Python? If so, why?
Python (at least the "standard" CPython implementation) never actually compiles to native machine code; it compiles to bytecode which is then interpreted. So a C function which is in fact compiled to machine code will run faster; the question is whether it will make a relevant difference. So what's the actual problem ...
``` char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ ```
amessageis of typechar[16]. It is an array. The elements of the array contain the sixteen characters from the string literal. pmessageis of typechar*. It is a pointer. It points to a (non-modifiable) array containing the sixteen characters from the string literal. (You should avoid using achar*to point to a stri...
I want to write C Code which converts first string into integer then integer into hexadecimal. ex: I have Ip iddress as "172.24.18.240" now first find out first dot from it and take the number before it that is "172" convert it into integer then convert it inti hexadecimal and it should do the same for all like 24,18,...
``` #include <stdio.h> // testing int main(int argc, char** argv) // testing { char* ipString = argc > 1? argv[1] : "172.24.18.240"; // testing char* ip = ipString; unsigned int hex; for( int i = 0; i < 4; i++ ){ unsigned int n = 0; for( char c; (c = *ip) >= '0' && c <= '9'; ip++ ) ...
I am trying to do a jump table inClike this ``` cmp eax, dword 3 ;max number ja invalid ;default jmp [eax*4+jumptable] ;jump to handler invalid: retn jumptable: dd handle0, handle1, handle2, handle3 handle0: .... ``` and so forth ...
jumptableis an array of pointers. Don't try to scale the offset, just index which pointer you want to reference. ``` void dohandler(int a, int b, void (*jumptable[4]) (int x)) if (a >= 0 && a < 4) jumptable[a](b); } ```
I've a C code where I fetch headers for all mails in the inbox via imap issuing UID FETCH 1:* (FLAGS BODY[HEADER]) command. Due to special authentication requirements I cannot use a standard imap library like vmime or libetpan. I need to parse the mail header values in accordance with RFC 822. Do we have some library/...
Mimetic works great ! it also takes care of non-standard mail headers.
I am using this resource to help me out with Function Pointers:hereBut in this code (written below), compilation on gcc says: ``` line 15: warning: dereferencing 'void*' pointer line15:error:called object *foo is not a function ``` The code is here: ``` #include<stdio.h> #include<stdlib.h> #include<pthread.h> void...
Your pointer is the wrong type. You need to use: ``` void (*foo)(void *) = print_mess; ``` It looks weird, but that's a function pointer definition. You can also typedef it: ``` typedef void (*vp_func)(void *); vp_func foo = print_mess; ```
Hi I am trying to create a counter that will just count the number of times the system call vfork() has been called in fork.c in the Linux kernel source. I'am following how total_forks is implemented. Total_forks is defined in sched.h. But I can't find where it is initialized to zero.
I'm guessing you are talking about the Linux kernel, and the variabledeclaredinsched.handdefinedhere. It's a global variable (defined at file scope and notstatic) - these are implicitly initialized to zero. Try this in you own code: ``` #include <stdio.h> int var; int main( int argc, char* argv[] ) { printf( "v...
Right now I have a function connected toSIGARLMthat goes off after 1 second and will re-alarm itself to go off in another second everytime. There's a test in the logic of theSIGALRMfunction I wrote to see if a certain timeout has been reached and when it does I need it to kill a function that's running. Does anybody k...
One approach that might be worth looking into is usingselectto pollstdinand see if any data is ready.selectlets you wait for some period of time on a file descriptor, controlling when you can be interrupted and by what, and seems like it's perfect here. You could just sit in a loop waiting for up to a second, then fa...
I'm having issues with the GCC linker, specifically using the-lmflag since I'm using some functions from math.h. I get the following errors: main.c:(.text+0x8e5): undefined reference to `floor'main.c:(.text+0x901): undefined reference to `ceil' Here's the relevant portion of my makefile: ``` myprogram: main.o ...
Furthermore, library specifications have to come after the objects referencing them (cf.Linker flags in wrong place).
In the following: ``` struct adt { void * A; }; int new_adt(const void * const A) { struct adt * r = malloc(sizeof(struct adt)); r->A = A; } ``` I get: warning: assignment discards qualifiers from pointer target type I know I can use ``` memcpy(&(r->A), &A, sizeof(void *)); ``` to workaround it, but I...
By using const void * const I pretend to say that no changes will be made to the input. Youhave notpretendedto say that no changes will be made to the input, you have explicitly told the compiler that you haveguaranteedthat no changes will be made to the input. YouMUST NOTdo what you are doing.
For example take 123 and put it into an array where that is a[3] = {1, 2, 3}? Without converting it to a string and iterating over it.
You can get the decimal digits of a number by using integer division and modulo. ``` //Pseudo code int[MAX_SIZE] result; int index = 0; while (workingNumber > 0) { digit = workingNumber % 10; result[index] = digit; workingNumber = workingNumber / 10; //Must be integer division index++; } ```...
I have a static method in a cpp file (not in class) . I want to use it globally without redeclaring it as extern . In that case is it possible to use a global function pointer to this static method and use this function pointer globally ??
It is possible to do what you want, but why would you avoid using extern when it does exactly what you are trying to emulate through a much more convoluted (and unreadable) mechanism?
Is it possible to still use inet_ntoa() and not worry about Windows User Permissions? Do I need to put a try/catch block around inet_ntoa() to catch any possible problems if User Permissions prevent me from getting the IP address of an interface?
inet_ntoadoesn't raise exceptions. It returnsNULLin case of an error. It's hard to see how user permissions could come into this function since it is just an integer to string conversion.
I have a 16 bit fixed point processor and I want to do fixed point processing with it. I'm looking for the correct datatype to use for unsigned 16 bit ints.. My question is: what is the difference between auint16_tanduint_fast16_t? (These are included in thestdint.h.) Isuint_fast16_tbetter since it is faster?? Th...
uint16_tis an unsigned 16-bit integer.uint_fast16_tis the fastest available unsigned integer with at least 16 bits.
The following C program: ``` int doStuff(int afm[]); int main(){ int afm1[9] = {1,2,3,4,5,6,7,8,9}; //size=9 int afmLength = sizeof(afm1)/sizeof(int); printf("main: Length Of Array=%d\n", afmLength); //9 OK int k = doStuff(afm1); system("PAUSE"); return 0; } int doStuff(int afm[]){ ...
Because inmainyou have an array and in the function you have a pointer to that array. ``` int doStuff(int afm[]) ``` is equivalent to ``` int doStuff(int *afm) ```
``` int solutions[92][81]; void add_solution(int board[81]) { solutions[found_sltns++] = board; } ``` Code sample attached, I get error: incompatible types when assigning to type ‘int[81]’ from type ‘int’ when compiling Any clue?
You can't copy array in this manner. You have to perform a element by element copy. ``` int i; for(i=0;i<81;i++) solutions[found_sltns][i] = board[i]; found_sltns++; ```
In the .NET compiler (csc.exe) I can use the option/target:exeto compile into an exe that will keep the console open so that I can see somestderror `stdout`` output. However I cannot achieve this same functionality using the C/C++ compiler (cl.exe). My program usesWinMainwhich means it's an entire UI application. Tha...
the flag you need to create a console application is/subsystem:console, check out the MSDN documentationabout it. and it is actually a flag for the linker stage: ``` link /out:foo.exe /subsystem:console a.obj b.obj ``` you can however tell the compiler to use certain flags when invoking the linker: ``` cl /flags /l...
Libcurl defaults to stdout when handling a server's response. We can override it withCURLOPT_WRITEFUNCTIONandCURLOPT_WRITEDATA. From the manual I got that I could set theCURLOPT_WRITEFUNCTIONtoNULLand then pass aFILE *toCURLOPT_WRITEDATA. If I just want to not use it what would be the most efficient way to go about it...
Write to/dev/nullor a similar black hole. Note that the existence and location of such special file(s) is OS dependent - Unixen have /dev/null, Windows has \Device\Null, etc.
I'm a Java dev, and for some reason I'm studying C at the moment. The thing is I'm having some trouble reading function definitions. Could you give me a hint with this one for instance: ``` void (*signal(int sig, void(*func)(int)))(int) ``` Thanks guys!
You should learn theright-to-left rule. This page contains good examples. signalis a function taking as arguments: an integera pointer to function takingintand returning nothing and returning a pointer to a funcction takingintand returning nothing.
How are arrays scoped in C? When do they ever get destroyed? (Note, also talk about if they can be passed even in p_threads)
They're scoped just like normal variables: ``` // in a function int arrayA[300]; { float arrayB[100]; // arrayA and arrayB available here } // arrayB out of scope, inaccessible. // arrayA still available. ``` If you were to pass the array to a function, it would be valid as long as the array was still in sco...
Is there a difference (in terms of execution time) between implementing a function in Python and implementing it in C and then calling it from Python? If so, why?
Python (at least the "standard" CPython implementation) never actually compiles to native machine code; it compiles to bytecode which is then interpreted. So a C function which is in fact compiled to machine code will run faster; the question is whether it will make a relevant difference. So what's the actual problem ...
``` char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ ```
amessageis of typechar[16]. It is an array. The elements of the array contain the sixteen characters from the string literal. pmessageis of typechar*. It is a pointer. It points to a (non-modifiable) array containing the sixteen characters from the string literal. (You should avoid using achar*to point to a stri...
I want to write C Code which converts first string into integer then integer into hexadecimal. ex: I have Ip iddress as "172.24.18.240" now first find out first dot from it and take the number before it that is "172" convert it into integer then convert it inti hexadecimal and it should do the same for all like 24,18,...
``` #include <stdio.h> // testing int main(int argc, char** argv) // testing { char* ipString = argc > 1? argv[1] : "172.24.18.240"; // testing char* ip = ipString; unsigned int hex; for( int i = 0; i < 4; i++ ){ unsigned int n = 0; for( char c; (c = *ip) >= '0' && c <= '9'; ip++ ) ...
I am trying to do a jump table inClike this ``` cmp eax, dword 3 ;max number ja invalid ;default jmp [eax*4+jumptable] ;jump to handler invalid: retn jumptable: dd handle0, handle1, handle2, handle3 handle0: .... ``` and so forth ...
jumptableis an array of pointers. Don't try to scale the offset, just index which pointer you want to reference. ``` void dohandler(int a, int b, void (*jumptable[4]) (int x)) if (a >= 0 && a < 4) jumptable[a](b); } ```
I've a C code where I fetch headers for all mails in the inbox via imap issuing UID FETCH 1:* (FLAGS BODY[HEADER]) command. Due to special authentication requirements I cannot use a standard imap library like vmime or libetpan. I need to parse the mail header values in accordance with RFC 822. Do we have some library/...
Mimetic works great ! it also takes care of non-standard mail headers.
I am using this resource to help me out with Function Pointers:hereBut in this code (written below), compilation on gcc says: ``` line 15: warning: dereferencing 'void*' pointer line15:error:called object *foo is not a function ``` The code is here: ``` #include<stdio.h> #include<stdlib.h> #include<pthread.h> void...
Your pointer is the wrong type. You need to use: ``` void (*foo)(void *) = print_mess; ``` It looks weird, but that's a function pointer definition. You can also typedef it: ``` typedef void (*vp_func)(void *); vp_func foo = print_mess; ```
Hi I am trying to create a counter that will just count the number of times the system call vfork() has been called in fork.c in the Linux kernel source. I'am following how total_forks is implemented. Total_forks is defined in sched.h. But I can't find where it is initialized to zero.
I'm guessing you are talking about the Linux kernel, and the variabledeclaredinsched.handdefinedhere. It's a global variable (defined at file scope and notstatic) - these are implicitly initialized to zero. Try this in you own code: ``` #include <stdio.h> int var; int main( int argc, char* argv[] ) { printf( "v...
Right now I have a function connected toSIGARLMthat goes off after 1 second and will re-alarm itself to go off in another second everytime. There's a test in the logic of theSIGALRMfunction I wrote to see if a certain timeout has been reached and when it does I need it to kill a function that's running. Does anybody k...
One approach that might be worth looking into is usingselectto pollstdinand see if any data is ready.selectlets you wait for some period of time on a file descriptor, controlling when you can be interrupted and by what, and seems like it's perfect here. You could just sit in a loop waiting for up to a second, then fa...
I'm having issues with the GCC linker, specifically using the-lmflag since I'm using some functions from math.h. I get the following errors: main.c:(.text+0x8e5): undefined reference to `floor'main.c:(.text+0x901): undefined reference to `ceil' Here's the relevant portion of my makefile: ``` myprogram: main.o ...
Furthermore, library specifications have to come after the objects referencing them (cf.Linker flags in wrong place).
In the following: ``` struct adt { void * A; }; int new_adt(const void * const A) { struct adt * r = malloc(sizeof(struct adt)); r->A = A; } ``` I get: warning: assignment discards qualifiers from pointer target type I know I can use ``` memcpy(&(r->A), &A, sizeof(void *)); ``` to workaround it, but I...
By using const void * const I pretend to say that no changes will be made to the input. Youhave notpretendedto say that no changes will be made to the input, you have explicitly told the compiler that you haveguaranteedthat no changes will be made to the input. YouMUST NOTdo what you are doing.
For example take 123 and put it into an array where that is a[3] = {1, 2, 3}? Without converting it to a string and iterating over it.
You can get the decimal digits of a number by using integer division and modulo. ``` //Pseudo code int[MAX_SIZE] result; int index = 0; while (workingNumber > 0) { digit = workingNumber % 10; result[index] = digit; workingNumber = workingNumber / 10; //Must be integer division index++; } ```...