question
stringlengths
25
894
answer
stringlengths
4
863
I have a program that is running under MinTTY (cygwin's shell) and calls toGetConsoleMode/SetConsoleModefail._getchechos to the console as well. This is a native win32 app without bindings to the cygwin environment, so any cygwin functions are out. How do I turn off the echo so that I can input a password?
I essentially emulated the following viapopen: ``` save_state=$(stty -g) /bin/echo -n "Account: " read acct /bin/echo -n "Password: " stty -echo read password # this won't echo stty "$save_state" echo "" echo account = $acct and password = $password Read more at http://www.askdavetaylor.com/how_to_read_password_wit...
In the following code: ``` char *p = "Linux"; ``` Is the memory for "Linux" on the stack or the read only segment of the program? Refer to question 9 in the article12 Interesting C Interview Questions and Answers. Thanks.
The implementation is free to store it wherever it wants. It's a constant, so it can be in read-only memory, but it is not required to be. My instructor for C programming always says its on the stack, hence the doubt. He probably means the pointer. Consider: ``` char *p = "Linux"; p = "Rules"; ``` In the second li...
I use this malloc style all the time ``` int *rc = 0; rc = malloc(sizeof(*rc)); ``` However, it doesn't seg fault even though when I callsizeof(*rc)I assume thatrc==0, and I am dereferencing aNULLpointer.
You are not really dereferencing anything. The argument ofsizeofis not evaluated, unless it is a VLA. It is explicitly allowed by the language to put whatever "garbage" you want as the argument ofsizeof. The language guarantees that it will not evaluate anything, just perform compile-time analysis of the type of the e...
I am programing for a while but for this i couldn't find an answer yet . lets say i want to run on a loop when i change the names of the variables. lets say i have : ``` int ran1; int ran2; int ran3; ``` now i want to run a for loop that put numbers to them : ``` for(int k=0;k<3;k++) ran%k=k; // this is wrong ,b...
Make it an array! Using different names differentiated by a number is a bad practice: ``` int ran[3]; for (int k = 0; k < 3; k++) { ran[k % 3] = k; } ``` Now, instead of usingran1, orran2, you would useran[1]orran[2]. Arrays in C are quite confusing, and they are distinct from pointers.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. In C, I have a simple server/client...
The kernel will put packets into socket'sreceive bufferexpecting the application to read them. When that buffer fills up the kernel starts dropping new datagrams.
How to generate the same effect for random number generation in GNU SGL like the following: ``` int ind = rand() % 2 ``` i.e. generating either 0 or 1 exactly.
YOu can try this example:- ``` #include <stdio.h> #include <gsl/gsl_rng.h> int main (void) { const gsl_rng_type * T; gsl_rng * r; int i, n = 10; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < n; i++) { double u = gsl_rng_uniform (r); ...
``` #include<stdio.h> #include<string.h> int main() { char buffer[32]; char c; int i; printf("input: "); fgets(buffer, 32, stdin); printf("items filled: %d\n", sscanf("%c%d\n", &c, &i)); printf("%c%d\n", c, i); return 0; } ``` When typing a character followed by a number "f7", im expecting "f...
Actualsscanf()signature is this : ``` int sscanf(const char *str, const char *format, ...); ``` check your signature ofsscanf()you have used wrong signature It should be ``` sscanf(buffer,"%c%d\n", &c, &i); ```
The following C code will draw a rectangle. I know how to draw the ellipse, but how can i draw an ellipse into this rectangle? ``` #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); rectangle(100,100,200,200); getch(); closegraph(); return 0;...
Asuming you're using theellipsefunctionfromgraphics.h, you could do the following: ``` int left = 100; int right = 200; int top = 100; int bottom = 200; rectangle(left, top, right, bottom); int x = (left + right) / 2; int y = (top + bottom) / 2; int start = 0; int end = 360; int xrad = (right - left) /...
please let me know how a pointer ( in C / C++ programming language ) can reference to a segment in hard disk, a storage of say upto 1 GB. In more details i am going to write the signature of a function which will take a pointer as argument and that should point to a segment in hard disk, which can hold upto 1 GB spac...
You can look intommap. This allows to map files into your main memory.
i have this line of code: ``` base_num = (arr[j]/base)%256; ``` This line runs in a loop and the operations "/" and "%" take a lot of resources and time to perform. I would like to change this line and apply bit operations in order to maximize the program performance. How can i do that? Thanks.
If base is the nth power of two, you can replace division by it with a bitshift of n to the right. Then, since taking the mod 256 of an integer is equivalent to taking its last 8 bits, you can AND it with 0xFF. Alternately, you can reverse the operations if you AND it with 256*base and then bitshift n to the right. ...
I am trying to implement the htoi(s) [Dennis Ritchie chapter2 exercise 2-3 Q] which converts a string of hexadecimal digits, into its equivalent integer, can anyone help me out in the logic of this program, i dont need the code, i just need the logic for implementing it. I am not able to get the correct logic
Let's take a step back: How would you implement a function that accepts a single hex digit and returns it's decimal equivalent? In other words, how would you write this function: ``` unsigned int hextodec(char c) { ... your code here } ``` Hint: for decimal digits what happens when you calculatec -'0'? Once y...
``` #include <stdio.h> int main(int argc, char * argv[]) { int *ip; printf("%d\n", *ip); ip=NULL; if (1) { int i=300; printf("Inside If Block \n"); ip=&i; printf("*ip=%d----------\n", *ip); } //printf("i=%d\n", i); /* Now this wil...
The local variableiis out of scope, so cannot be accessed, but by chance its memory location on the stack, stored inip, has not been overwritten. You absolutely cannot rely on this behaviour, but in practice you'll find it holds true on many platforms.
Well, I've a weird problem withprintf(). It's outputting garbage on the screen. It's kind of connected with memory, I guess. Have a look: ``` char string1[] = "SAMPLE STRING"; char string2[20]; // Some garbage in it /* Let's clear this madness*/ int i = 0; for (i; i < 20; i++) string2[i] = ' '; // Space, why not? ...
Because C strings need to be NUL terminated. This means the last char of your string must be'\0'. This is howprintf(and all other C string functions) know when a string is finished.
I am coding an application in C. One of the screens has a cursor. The cursor needs to keep blinking. I have a infinite while loop that keeps refreshing the screen. To get the effect of blinking, at every fifth iteration of thiswhileloop, the cursor needs to alternate between appear and disappear. I need to somehow ke...
Simply have astaticvariable inside the function. ``` void drawCursor() { static int counter; if ((counter++ % 5) == 0) { // toggle the cursor state } } ```
want to add hue filter in iPhone app I want to write a code to add Hue Image Effect with different parameter value of Hue value by modifying the pixel value of Image. How can I do this. Overall I want to add Hue Image Filter by manipulating each Pixel value of Image. But waht the actual value for Pixel in adding Hu...
You need to use CoreImage for that, specifically a CIFilter. There are plenty of examples online, but there's one in the apple developer website that matches exactly what you want: Go tohereand check the section "Creating a CIFilter Object and Setting Values", there it shows how to create a hue filter for a given ima...
I am facing a problem with understanding the use of macro function calls from within a printf() statement. I have the code below : ``` #include<stdio.h> #define f(g,h) g##h main() { printf("%d",f(100,10)); } ``` This code outputs "10010" as the answer. I have learned that macro function call simply copy pastes...
The preprocessor concatenation operator##is donebeforethe macro is replaced. It can only be used in macro bodies.
I am looking for a thread-safe C/C++ queue implementation that is optimized for the push operation. I don't mind if the pop operation blocks but I would like to never be blocking on the push side. Let me explain why. I am planning on writing a profiler for a C# application and I will have multiple threads pushing m...
You can useboost.lockfree. It's in boost sandbox svn and planned to be released with boost for version 1.53 or 1.54 depending on whether or not boost.atomic get released in time. For the moment boost.lockfree depends on std::atomic and not boost.atomic, so you need a c+11 compiler to use it.
I am trying to create a function that fills multiple arrays with data. The problem is, I get a segmentation fault whenever I try to put in more than 2 numbers. It works fine when I don't use a double pointer. ``` #include <stdio.h> #include <stdlib.h> int readInput(int **array); int main() { int *array; re...
``` scanf("%d",array[i]); ``` Since array is anint**,array[i]is anint*(ie index 0 is the pointer to the array you just allocated, the rest is random unallocated memory) (*array)[i]is probably more like what you're looking for.
During compilation of a call to the following function: ``` char* process_array_of_strings(const char** strings); ``` GCC complains when achar**is passed as argument: ``` note: expected ‘const char **’ but argument is of type ‘char **’ ``` While the function does not alter the characters (hence the const) it does ...
Make the conversion explicit with a cast and the compiler will be happy: ``` process_array_of_strings((const char**) foo); ``` In these cases you have to explicitly say that you know what you're doing.
What doessignedmean in C? I have this table to show: This sayssigned char128to+127.128is also a positive integer, so how can this be something like+128to+127? Or do128and+127have different meanings? I am referring to the book ApressBeginning C.
A signed integer can represent negative numbers; unsigned cannot. Signed integers have undefined behavior if they overflow, while unsigned integers wrap around using modulo. Note that that table is incorrect. First off, it's missing the-signs (such as -128 to +127). Second, the standard does not guarantee that those...
I have problems to jump to an label. My Code: ``` asm{ keypress: ... cmp ax,0000 jz keypress } ``` Borland says: Undefined Label "keypress"
Try moving the label to outside of the asm block (i.e., just above the "asm{" line). This is per thislinkand thislink. Also note that evidently you may not be able to jump to a forward label (perhere), but that's of course not your problem in this example.
I am trying to create a function that fills multiple arrays with data. The problem is, I get a segmentation fault whenever I try to put in more than 2 numbers. It works fine when I don't use a double pointer. ``` #include <stdio.h> #include <stdlib.h> int readInput(int **array); int main() { int *array; re...
``` scanf("%d",array[i]); ``` Since array is anint**,array[i]is anint*(ie index 0 is the pointer to the array you just allocated, the rest is random unallocated memory) (*array)[i]is probably more like what you're looking for.
What is the standard way to get the current time in seconds (since the epoch) in a kernel module? I have seen techniques involving getting xtime which are very long-winded and involve while-loops and locks. There must be a better way. [This is not a duplicate. I have looked through previous questions on SO. The answ...
You can usegetnstimeofdayfor that. ``` /* getnstimeofday - Returns the time of day in a timespec */ void getnstimeofday(struct timespec *ts) ``` wherestruct timespecis: ``` struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; ``` And yes, you'll need#include <linux/t...
I am taking part in a line following robot competition where we use a camera in order to follow line. My algorithm is: ``` mean filter --> Gaussian filter --> find centroid --> kalman filter --> do pid for steering --> do pid for speed of back motor ``` and the robot performs 98% perfectly. My issue is that after ...
Probably setting up the buffers before image processing can work. Assume of three buffers (image pages saved continuously from camera)... page1, page2, page3. Use page1 to process the image... Then get an average image by comparing both page2 and page3, and put this resulting image on page1... then repeated the image ...
``` while (fscanf(ifp, " %d %d kl. %d %s - %s %d - %d %d\n", &round, &date, &clock, teeam, &goals, &attendance) ``` I should probably know this, but the second %d should import a date to my variable, like 20.20.2012 but instead i only get the first 20 and not rest of it. thank you :)
Internally, the string is read as long as it represents a valid integer (so it stops when '.' is encountered). How would you represent the date as one integer? You could have 3 variables and read them like this: ``` fscanf(ifp, "%d.%d.%d", &day, &month, &year); ``` By the way, 20/20 is a strange date :-)
``` #include <stdio.h> int main () { char *ptr = "stackoverflow" } ``` Is there any way to find the length of stackoverflow pointed by ptr, as sizeof ptr always gives 4
Usestrlento find the length of (number of characters in) a string ``` const char *ptr = "stackoverflow"; size_t length = strlen(ptr); ``` Another minor point, note thatptris a string literal (a pointer to const memory which cannot be modified). Its better practice to declare it as const to show this.
``` #include <stdio.h> #include <time.h> int main () { time_t time_raw_format; struct tm * ptr_time; char *buff; time ( &time_raw_format); ptr_time = localtime ( &time_raw_format ); } ``` How to copy this to a*buff, return type ofptr_timeisstruct tm*,my actual goal is to copy system date and time to ...
If you are looking for how to put a human readable time in a string, here is a solution: ``` #include <time.h> char *buff = asctime(ptr_time); ``` The memory forbuffis statically allocated byctimeandasctime.
I am making an online judge. This my school project. I am taking a.cfile from the user. I am able to compile the.cfile with command prompt. But I don't know how to run this file. I need to run this file, take input from a text file and save output in a text file. The compilation code was: ``` gcc main.c -o HelloWorl...
I need to run this file, take input from a text file and save output in a text file. Assuming you're on Linux, this should work: ``` ./HelloWorld < input.txt > output.txt ```
Say you have a program like this ``` #include <stdio.h> int main (void) { char **foo; foo = malloc (100); foo[0] = "cat"; foo[1] = "dog"; foo[2] = "bird"; return 0; } ``` How could you iterate the array, for example printing all the elements, without hard coding the upper bound?
Either you have a bound defined somewhere or you have a marker in your array which indicates end of the array (this marker would have to be excluded from possible values an array element can have).
I have a while loop that scans in an input set of integers. It scans and prints all of the numbers with "..." at the end and skips to the next line. However, the script does not: execute past the while loop and print TEST. For example, I enter: 3 44 62 1 It prints: 3... 44... 62... 1... When it should print: 3...
scanf("%d", &n) != 1is wrong. It should bescanf("%d", &n) == 1.You're expecting the loop to end just because you hit enter? As written, your program will only stop if scanf fails to read a number due to reaching the end of the input file. If you're on Unix, you can signal EOF from the terminal by hitting Ctrl-D. If yo...
I would like to perform this calculation wihout the bitwise operator. ``` unsigned result = (1u << 5); ``` The result will be 32. I know that's converting the binary1to100000but I would like to perform the same thingwithoutbitwise operations.
Since you know that 25is 32, you could just use: ``` unsigned int result = 1u * 32u; // or just 32u if it's always '1u *'. ``` Otherwise, if you just want to use the bitshift value, there are two ways. The first is a loop: ``` unsigned result = 1u; for (size_t i = 0; i < 5; result *= 2u, i++); ``` or a non-loop ve...
I am using valgrind to find memory leaks on my program however it is taking a long time and its loading. When I run the program without valgrind it takes second, what is the problem and what should I look for in the code.
There is no problem as far as I can see unless you can verify an infinite loop or some other run-time error ... Valgrind basically acts like a virtual machine or virtual execution environment running the program, watching all variables, memory allocations, etc., etc. and therefore will run quite a bit slower than nati...
I'm trying to open a file usingopen()but I'm having a problem with the path. It seems like if the path starts with a forward-slash/, it wont find the file, for example if path was/index.htmlthen it wont open, if it wasindex.htmlthen it works fine. Is there any way to fix this? I don't want to parse the path because t...
If the path starts with a slash/(abackslashlooks like\) the path is absolute and starts at the root of the file system. If it doesn't start with a slash, it is a relative path. It is unclear what you want to do but it seems you might need to remove leading slashes if you want the path to be relative.
as you know, when using getch() in windows, the applications waits for you until you press a key, how can i read a key without freezing the program , example : ``` void main(){ char c; while(1){ printf("hello\n"); if (c=getch()) { . . . } } ``` thank you.
You can usekbhit()to check if a key is pressed: ``` #include <stdio.h> #include <conio.h> /* getch() and kbhit() */ int main() { char c; for(;;){ printf("hello\n"); if(kbhit()){ c = getch(); printf("%c\n", c); } } return 0; } ``` More info here:http:/...
Objective-C is a superset of ANSI C. In GNU C,you can nest one function in another function... like this ... ``` float E(float x) { float F(float y) //objective-C compiler says expected ; at end of declaration { return x + y; } return F(3) + F(4); } ``` Is it possible to do this in Objective-...
You can't, but you can easily get the same behavior with block ``` int outer(int i) { int (^inner)(int) = ^(int x) { return x * 3; }; return inner(i); } ```
I want to know is there a way to apply Exclusive-OR (for two operands it is called XOR) operator to multiple predicates? For example suppose thatp,qandrare three predicates (in other words Boolean variables). I want to write anifcondition like this: ``` if ((p || q || r) && !(p && q && r)) ``` i.e. I want the condi...
Here's one way to do it: ``` if ((!!p + !!q + !!r) % 3) ``` But that's probably too clever for its own good. Edit: ``` if (((p ? 1 : 0) + (q ? 1 : 0) + (r ? 1 : 0)) % 3 != 0) // C#-compatible version ```
I'm stuck with my code for 20 minutes. What's wrong with this simple C code? ``` void function (char & reference_to_something) {} ``` error: ``` expected ';' , ',' or ')' before '&' token ```
C does not have references; C++ does.
I am making a program which transfers a file over a network using UDP sockets.I have already implemented protocols dealing with missing/duplicated packets and my program runs fine with text files. But for pdf files, the program is not transferring the file correctly. I am using fread() to read the file and i am using ...
Sure you can... If your file-transfer-stuff can transfer characters regardless of their contents. As you state, you can transfer text-files. Then you could just try to first encode your pdf into a helper format with e.g. uuencode my.pdf somename>my.uue
I have the following code: ``` typedef struct Y {int X;} X; enum E {X}; ``` which generates a error: error: 'X' redeclared as different kind of symbol As I know, C has implicitly defined namespaces for structure, union, and enum tags and also for their members. So, I'm not sure why doesE::Xcollide with typedef str...
C does not have a separate namespace forenummembers. When you writeenum {X}, that creates a global constantX(which can clash with other global names such astypedef'd tags).
Is there a way to open a full screen window withSFMLon a 2nd monitor?
I'm afraid the answer is no. Here's a quote from a different part of that site: SFML doesn't explicitely manage multiple monitors. As a consequence, you won't be able to choose which monitor a window appears on, and you won't be able to create more than one fullscreen window. This should be improved in a future versi...
The functionfopen(FILE *fp)in XCode it's not working, I put the text file in the root directory, but not work, it's weird because, executing from terminal works fine, but executing from IDE not. The sintax that I use it's this: ``` FILE *fp=fopen("name.txt", "r"); if(fp==NULL) { printf("the text file can't be op...
well what's the working directory when run via xcode?by default IIRC it isnt set and that might be the difference between IDE and terminal. -- set the working dir: go to: product > scheme > edit scheme... there go to:options tab and choose a working directory
When I include mysql.h in my source file, I get all sorts of syntax errors. I'm using the cygwin gcc compiler and MysQL Windows Connector 6.0.2. I added an image of my IDE. What can I do to fix this?Click here for larger image
You need to includewinsockright before mysql.
I have a array of structs. lets call itstructsarray And i have a array of ints where the ints are index's of the stuct. Lets call itindexarray I would like to sortindexarraybut i want to compare the sorting with anintinstructsarray Any way that can be done with that setup?
You have a comparison function such as this: ``` int my_compare(const void *a, const void *b) { int index1 = *((const int *) a); int indexb = *((const int *) b); return structsarray[index1].field - structsarray[index2].field; } ``` The arguments are pointer to the values in the array you are sorting. I ...
I'm just a beginner for C programming. Can I ask a simple question ? What's the difference between(int) sizeof(void *)andint? ex) ``` #define ptrint int #define PTRINT ((int) sizeof(void *)) ```
The first case acts as an alias for int so you can use ptrint instead of int. The second case is the size of a pointer in bytes. So for instance on a 32 bit system it will return 4. ``` ptrint a = 8; ptrint b = a; int sizeofptr = PTRINT; ```
If I keep incrementing aCvariable, does it saturate or wrap around?
For signed integer types, it'sundefinedas to what happens. For unsigned integer types, it will wrap around (i.e. back to 0).
I am stuck on the same code for quit some time now. I am trying to fill a char array with characters i read from a text file (ascii). But for some reason when i printf the char array it only displays the letter H. Code: ``` void append(char c) { //int len = strlen(cStr); cStr[iCounter] = c; cStr[iCounter + 1] ...
You print one character with%cuse string specifier%sinstead: ``` printf("char c:%c char array%s\n",c,cStr); ``` Note:iCounteris not actually incremented: ``` cStr[iCounter++] = c; cStr[iCounter] = '\0'; ```
I have a question regarding to reset array in c, I define a array like this: ``` static int hello[5][6] = {{1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6}}; ``` then how to reset all the element on each row and line as 0?
``` memset (hello, 0, sizeof(hello)); ```
What do i need to to do to print the contents of a memory provided that it can have null characters in between. suppose i have an address 0X123.i want to print some 100 characters before this address in the memory and there can be some NULL characters in between and i want to print those NULL characters too.
Use unformatted output: ``` cout.write(address, count); ``` Or for C: ``` fwrite(address, 1, count, stdout); ```
The following code ``` u_int32 *data_out data_out = malloc(4 * sizeof(uint32_t)); //connection_fd is a socket n = write(connection_fd, data_out[0], strlen(data_out[0])); ``` produces the following error: Array.c:261: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast /usr/include/str...
Why you are using strlen to write int?Maybe use: ``` n = write(connection_fd, &(data_out[0]), sizeof(uint32_t)); ```
The functionfopen(FILE *fp)in XCode it's not working, I put the text file in the root directory, but not work, it's weird because, executing from terminal works fine, but executing from IDE not. The sintax that I use it's this: ``` FILE *fp=fopen("name.txt", "r"); if(fp==NULL) { printf("the text file can't be op...
well what's the working directory when run via xcode?by default IIRC it isnt set and that might be the difference between IDE and terminal. -- set the working dir: go to: product > scheme > edit scheme... there go to:options tab and choose a working directory
When I include mysql.h in my source file, I get all sorts of syntax errors. I'm using the cygwin gcc compiler and MysQL Windows Connector 6.0.2. I added an image of my IDE. What can I do to fix this?Click here for larger image
You need to includewinsockright before mysql.
I have a array of structs. lets call itstructsarray And i have a array of ints where the ints are index's of the stuct. Lets call itindexarray I would like to sortindexarraybut i want to compare the sorting with anintinstructsarray Any way that can be done with that setup?
You have a comparison function such as this: ``` int my_compare(const void *a, const void *b) { int index1 = *((const int *) a); int indexb = *((const int *) b); return structsarray[index1].field - structsarray[index2].field; } ``` The arguments are pointer to the values in the array you are sorting. I ...
I'm just a beginner for C programming. Can I ask a simple question ? What's the difference between(int) sizeof(void *)andint? ex) ``` #define ptrint int #define PTRINT ((int) sizeof(void *)) ```
The first case acts as an alias for int so you can use ptrint instead of int. The second case is the size of a pointer in bytes. So for instance on a 32 bit system it will return 4. ``` ptrint a = 8; ptrint b = a; int sizeofptr = PTRINT; ```
If I keep incrementing aCvariable, does it saturate or wrap around?
For signed integer types, it'sundefinedas to what happens. For unsigned integer types, it will wrap around (i.e. back to 0).
I am stuck on the same code for quit some time now. I am trying to fill a char array with characters i read from a text file (ascii). But for some reason when i printf the char array it only displays the letter H. Code: ``` void append(char c) { //int len = strlen(cStr); cStr[iCounter] = c; cStr[iCounter + 1] ...
You print one character with%cuse string specifier%sinstead: ``` printf("char c:%c char array%s\n",c,cStr); ``` Note:iCounteris not actually incremented: ``` cStr[iCounter++] = c; cStr[iCounter] = '\0'; ```
I have a question regarding to reset array in c, I define a array like this: ``` static int hello[5][6] = {{1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6}}; ``` then how to reset all the element on each row and line as 0?
``` memset (hello, 0, sizeof(hello)); ```
What do i need to to do to print the contents of a memory provided that it can have null characters in between. suppose i have an address 0X123.i want to print some 100 characters before this address in the memory and there can be some NULL characters in between and i want to print those NULL characters too.
Use unformatted output: ``` cout.write(address, count); ``` Or for C: ``` fwrite(address, 1, count, stdout); ```
The functionfopen(FILE *fp)in XCode it's not working, I put the text file in the root directory, but not work, it's weird because, executing from terminal works fine, but executing from IDE not. The sintax that I use it's this: ``` FILE *fp=fopen("name.txt", "r"); if(fp==NULL) { printf("the text file can't be op...
well what's the working directory when run via xcode?by default IIRC it isnt set and that might be the difference between IDE and terminal. -- set the working dir: go to: product > scheme > edit scheme... there go to:options tab and choose a working directory
When I include mysql.h in my source file, I get all sorts of syntax errors. I'm using the cygwin gcc compiler and MysQL Windows Connector 6.0.2. I added an image of my IDE. What can I do to fix this?Click here for larger image
You need to includewinsockright before mysql.
I have a array of structs. lets call itstructsarray And i have a array of ints where the ints are index's of the stuct. Lets call itindexarray I would like to sortindexarraybut i want to compare the sorting with anintinstructsarray Any way that can be done with that setup?
You have a comparison function such as this: ``` int my_compare(const void *a, const void *b) { int index1 = *((const int *) a); int indexb = *((const int *) b); return structsarray[index1].field - structsarray[index2].field; } ``` The arguments are pointer to the values in the array you are sorting. I ...
I'm just a beginner for C programming. Can I ask a simple question ? What's the difference between(int) sizeof(void *)andint? ex) ``` #define ptrint int #define PTRINT ((int) sizeof(void *)) ```
The first case acts as an alias for int so you can use ptrint instead of int. The second case is the size of a pointer in bytes. So for instance on a 32 bit system it will return 4. ``` ptrint a = 8; ptrint b = a; int sizeofptr = PTRINT; ```
If I keep incrementing aCvariable, does it saturate or wrap around?
For signed integer types, it'sundefinedas to what happens. For unsigned integer types, it will wrap around (i.e. back to 0).
I am stuck on the same code for quit some time now. I am trying to fill a char array with characters i read from a text file (ascii). But for some reason when i printf the char array it only displays the letter H. Code: ``` void append(char c) { //int len = strlen(cStr); cStr[iCounter] = c; cStr[iCounter + 1] ...
You print one character with%cuse string specifier%sinstead: ``` printf("char c:%c char array%s\n",c,cStr); ``` Note:iCounteris not actually incremented: ``` cStr[iCounter++] = c; cStr[iCounter] = '\0'; ```
I have a question regarding to reset array in c, I define a array like this: ``` static int hello[5][6] = {{1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6},1,2,3,4,5,6}}; ``` then how to reset all the element on each row and line as 0?
``` memset (hello, 0, sizeof(hello)); ```
What do i need to to do to print the contents of a memory provided that it can have null characters in between. suppose i have an address 0X123.i want to print some 100 characters before this address in the memory and there can be some NULL characters in between and i want to print those NULL characters too.
Use unformatted output: ``` cout.write(address, count); ``` Or for C: ``` fwrite(address, 1, count, stdout); ```
The following code ``` u_int32 *data_out data_out = malloc(4 * sizeof(uint32_t)); //connection_fd is a socket n = write(connection_fd, data_out[0], strlen(data_out[0])); ``` produces the following error: Array.c:261: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast /usr/include/str...
Why you are using strlen to write int?Maybe use: ``` n = write(connection_fd, &(data_out[0]), sizeof(uint32_t)); ```
I am wondering if there is any way to store the results of my program into a text file. I know you can just do something like ./a.out > output.txt but for my program, after I type ./a.out I am prompted again for TIME: where I put in the amount of time, and then upon hitting enter the algorithm is performed and the re...
So redirect the input as well: ./a.out < input.txt > output.txt Whereinput.txtcontains the amount of time.
Take this simple program ``` #include <stdio.h> #include <string.h> #include <errno.h> int main (void) { printf ("ERROR %d %s\n", ETIMEDOUT, strerror (ETIMEDOUT)); return 0; } ``` If you compile it with Cygwin gcc it runs fine ``` $ gcc a.c $ ./a ERROR 116 Connection timed out ``` If you compile it with MinG...
ETIMEDOUTseems to be aPOSIXextension to the ISO C standard errno.h. Cygwin has better support for POSIX than MinGW. A bug report aboutETIMEDOUTfor mingw32 was opened and closed in2007. One option is to use the GNU Portability Library (Gnulib). It provides a POSIX-likeerrno.handstrerror()/strerror_override().
Title pretty much says everything. would like to print (NOT in decimal), but in unsigned char value (HEX). example ``` unsigned char data[6] = {70,AF,80,1A, 01,7E}; NSLog(@"?",data); //need this output : 70 AF 80 1A 01 7E ``` Any idea? Thanks in advance.
There is no format specifier for anchararray. One option would be to create anNSDataobject from the array and then log theNSDataobject. ``` NSData *dataData = [NSData dataWithBytes:data length:sizeof(data)]; NSLog(@"data = %@", dataData); ```
What am I missing? If I want to increment a counter in a separate function, why does it give me a segmentation fault? ``` int point(int *cow); int main() { int *cow = 0; point(cow); return(0); } int point(int *cow) { (*cow)++; return(0); } ```
Dereferencing a null pointer is undefined behavior in C. Maybe you wanted to do this instead: ``` int a = 0; int *cow = &a; point(cow); ``` Note that the temporary pointercowis not necessary and you can directly pass&atopointfunction.
This question already has answers here:Closed10 years ago. Possible Duplicate:Recommended way to initialize srand? I have the following problem when using srand() in c. I call srand(time(NULL))in a loop, but the loopfinishes before 1sec and every time I call the rand() I get the same value. How can I solve this?
Why are you callingsrandin a loop? Just call it once at the start of your program and then callrandany number of times.
I already read this post but the answer didn't satisfied meCheck if Array is sorted in Log(N). Imagine I have a serious big array over 1,000,000doublenumbers (positive and/or negative) and I want to know if the array is "sorted" trying to avoid the max numbers of comparisons because comparing doubles and floats take ...
That depends on your requirements. If you can say that if 100 random samples out of 1.000.000 is enough the assume it's sorted - then so it is. But to be absolutely sure, you will always have to go through every single entry. Only you can answer this question since only you know how certain you need to be about it bei...
Given input like: ``` 6 2 1 2 3 4 5 6 4 3 3 4 5 6 ``` Where first number in first line is number of variables in line, second one is number of lines. How it is possible to get only firstn/2values, wherenis number of values in a line and skip to the next line?
If the input length doesn't vary (For example, 6 numbers like your example), you can read your desired input using: ``` scanf("%d %d %d", ...); ``` then, dispose the rest of the input: ``` while ((ch = getchar()) != '\n' && ch != EOF); ``` If the input lengthdoesvary, you'll have to read it into a buffer. Then you...
I'm getting an error on my source file for the mysql functions Im using. I setup my inclusion path and the libraries. The error is, for example:undefined reference to _mysql_initwhen I callmysql_init. Whats interesting is, I can click on the function and it will go directly to themysql.hfunction declaration
Assuming your project builds well: You might like to let Eclipse rebuild its symbol index. To do so: Right-click the project and selectIndex->Rebuild (see also:eclipse C project shows errors (Symbol could not be resolved) but it compiles)
When is it appropriate to include a type conversion in a symbolic constant/macro, like this:#define MIN_BUF_SIZE ((size_t) 256)Is it a good way to make it behave more like a real variable, with type checking?When is it appropriate to use theLorU(orLL) suffixes:#define NBULLETS 8U #define SEEK_TO 150L
You need to do it any time the default type isn't appropriate. That's it.
http://en.wikipedia.org/wiki/Radix_treeSo instead of a function i used an integer value instead for isLeaf. But how many elements should an array of edges have? How many children max for each node?
That depends on your radix. The maximum number of children of a node is the number of possible unique values of the chosen discriminator; if you use a character for the discriminator, then the maximum number of children will be the number of valid characters. You can implement this data-structure with a radix of two,...
``` *pSpiTxBuf++ = CC2520_INS_SFLUSHRX; // get rid of this packet *pSpiTxBuf-- = CC2520_INS_SFLUSHRX; // double flush [CC2520 Bug#1] ``` Can anyone explain to me what the above two lines are attempting to do?pSpiTxBufis auint8_t *
This is equivalent to: ``` pSpiTxBuf[0] = CC2520_INS_SFLUSHRX; // get rid of this packet pSpiTxBuf[1] = CC2520_INS_SFLUSHRX; // double flush [CC2520 Bug#1] ``` (which would probably have been a clearer way to write the code in the first place). i.e. it just sets two adjacent register values to CC2520_INS_SFLUSHRX.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
Run: gcc cow.c -o app Then type: ./app This should work.
I'm looking to DRY out the following C code: ``` if (i < SIZE_OF_V) { if (V[i]) K = V[d]; else K = V[d] = (expensive complicated call); } else { K = (expensive complicated call); } ``` Any advice? A local macro would work, but I'd prefer a more modern alternative.
You can simply do ``` if (i < SIZE_OF_V && V[i]) { K = V[d]; } else { K = (expensive complicated call); if (i < SIZE_OF_V) V[d] = K; } ``` You can also put yourexpensive complicated callin an external function and callit from two places inside yourifconditions: ``` int myExpensiveAndComplicated...
As we know, array name can't be assigned, sentence like: ``` char * array[], * point; array = point; /* wrong */ array++; /* wrong */ ``` But inmain(int argc, char * argv[]),argv++is ok and works well. What do i missing?
In your examplesarrayis a true array, and thus a non-modifiable l-value. In main, since it's declared in the parameter list,argvis actually achar **, i.e. a pointer which is modifiable. It all boils down to the fact thatchar *array[]means different things, depending on the context.
In the course of development of some application we came to a need of possibly getting a complete core dump without completely stopping execution of a program completely. Granted there are conditions that generate core dump where continuation may not be safely possible but we are not talking about memory corruption, ...
See this Google library, it might help:http://code.google.com/p/google-coredumper/ The coredumper library can be compiled into applications to create core dumps of the running program -- without terminating.
I have this function ``` int does_exist_in_array(char team[], struct team *teams) { int i; for(i = 0; i < MAX_TEAMS_AMOUNT; i++) { if(!strcmp(team, teams[i].name)) { return 1; } } return 0; } ``` It crashes when i run the application. Anyone know what is wrong? Do i use it...
This can happen for a number of reasons: Either argument is NULL or otherwise an invalid pointerThe string pointed by either argument is not 0-terminatedThere are fewer thanMAX_TEAMS_AMOUNTteamelements
How to read from text file only numbers in C. Except spaces, symbols, enters and letters. That's how i am reading text: ``` unsigned char symb, symb1; FileIn = fopen("InCode.txt","rt"); while (!feof(FileIn)) { symb=getc(FileIn); symb1=symb; printf("%c",symb1); } ``` This is how it sh...
Try this : ``` char symb ; unsigned char symb1; FILE *FileIn; FileIn = fopen("InCode.txt","rt"); // Haven't checked fopen failure while ((symb=getc(FileIn))!=EOF) { symb1= (unsigned char) symb; if(symb1 >= '0' && symb1 <='9') ...
What does it meanif(!fork())? I'm a little bit confused about it, I dont know when Im in parent and child process: ``` if(!fork()) { // is it child or parent process? }else{ // is it child or parent process? } ```
From thefork(2)manpage: Return ValueOn success, the PID of the child process is returned in the parent, and0is returned in the child. On failure,-1is returned in the parent, no child process is created, anderrnois set appropriately. Sincefork()returns 0 to the child, theifclause tests if it's a child: ``` if (!fork...
the following code should call a command withexcvefor some reason i doesn't print the contents of the current directory, but still the program returns"ok" ``` 1 #include <stdio.h> 2 #include <unistd.h> 3 int main () 4 { char *argv[]={"ls",NULL};· 5 char *env[]={"PATH=/usr/local/sbin/:/usr/local/bin:/usr/sbi...
Sinceexecvedoes not return on success, it's obvious that the call is failing somehow. It returns -1 on error, which would be treated as true (non-zero). That's why it's saying okay. The most likely reason is that you haven't specified the full path to the executable, which is a requirement forexecve. Alternatively, i...
I'm writing a network related program in linux. the program is in kernel space and not user space. All I need in this program is a regular expression library that supports all gnu regex library features plus non-greedy repeat. Is there any such library that has those features and also I can compile and use it in ker...
I would recommendTRE. Be aware that it has a number of bugs in its POSIX BRE support (just misparsing/misinterpreting the meaning of certain characters as BRE), but the POSIX ERE support is very good, and it has most (all?) GNU extensions as well as non-greedy matching support. Only other thing I would warn you about ...
I have three ints. Fx:20121121 I want to convert them into a single int20121121 Can this be done? I have tried messing around withatoi()without results.
Well, to answer directly the question that you asked, you would do it like this: ``` int combined = year*10000 + month*100 + day; ``` But your approach is quite possibly not the best solution to your actual problem.
I am having a two static librarya.libandb.lib(of C language) which is generated using VC6 (Visual studio 6.0) . I want to merge these two libs into one static libc.lib. How to do this in CLI mode? I have seen themerging of *nix static libs. I want to do the samething with VC6 static libs in CLI mode.
LIB.EXE /OUT:c.lib a.lib b.lib LIB.EXE is available in < VC6_InstalledFolder >/VC98/BIN. And this LIB.EXE is available in all versions of visual studio.
I am porting some C# code (classes mostly) to C. I have analysed the code and the port is definitely possible. One thing I am not sure of though, is how to handle (i.e. implement) raising events in C. I am in a Linux environment, and I expect the binary to run on Linux only. I heard that GLib supports events, but don...
The closes thing to C# events implemented by GLib are theGObject signals. Useg_signal_connectto connect your callback to an existing signal, andg_signal_emitto emit a registered signal. Seethe documentationfor details. As you are coming from a C# background, you might also consider usingVala, a programming language ...
Where can I find an serial C/C++ implementation of the k-nearest neighbour algorithm?Do you know of any library that has this?I have found openCV but the implementation is already parallel.I want to start from a serial implementation and parallelize it with pthreads openMP and MPI. Thanks,Alex
How about ANN?http://www.cs.umd.edu/~mount/ANN/. I have once used the kdtree implementation, but there are other options. Quoting from the website: "ANN is a library written in C++, which supports data structures and algorithms for both exact and approximate nearest neighbor searching in arbitrarily high dimensions."...
I've got two projects in solution, library and executable. First I build library but then when I start build another project it cleans library even when library files is in different folder and should not anyhow conflict with it. How to say to not remove library by building my executable?
If your executable depends on your library, the library will be automatically cleaned when cleaning or regenerating the executable. It will not be cleaned if only generating the executable (not regenerating), which will only compile modifications since the last build. If your executable does not depend on your librar...
The following code is fromThe Practice of Programming: ``` int scmp(const void *p1, const void *p2) { char *v1, *v2; v1 = *(char **) p1; v2 = *(char **) p2; return strcmp(v1, v2); } ``` I don't understand why using the expression*(char **) p1. Can we use(char *)p1instead? What is the difference betwe...
No. The(char **)is a type cast, and the unary*which precedes the cast dereferences the pointer. If you simply takev1 = (char *) p1, thenv1will be set equal top1, when what you want is forv1to be equal to thechar*to whichp1points.
In C one can write (disregarding any checks on purpose) ``` const int bytes = 10; FILE* fp = fopen("file.bin","rb"); char* buffer = malloc(bytes); int n = fread( buffer, sizeof(char), bytes, fp ); ... ``` andnwill contain the actual number of bytes read which could be smaller than 10 (bytes). how do you do the equi...
Call thegcountmember function directly after your call toread. ``` pf.read(&v[0],bytes); int n = pf.gcount(); ```
So I'm trying to study the assembly code of a simple C program using the "Product> Generate Output> Assembly File" option in Xcode 4.5. No matter how I try to trigger it, the option is still greyed out. Any advice for what's necessary to generate the assembly file? Even this simple loop statement isn't giving me the ...
Make certain your "main.m" file isselected(highlighted) in the list of files on the left side of your project window. Then Xcode will know that this is the file you want to generate output on and the Generate Output -> Assembly option will be enabled.
I have a problem where I want to create a variable that looks like this, ``` INCDIRS = -I dir0 -I dir1 -Idir2 -I dir3 ... -I dirN ``` wheredir1, ... , dirNare the names of all the subdirectories some base directory,base_dir. How would I go about building up this variable? Originally, I thought I could do the follo...
You have two errors in yourINCDIRSassignment. One is in thefindcommand. It should befind -type d -print(or justfind -type d; the-printis superfluous here). The other error the use of$x. You need to escape the$with another$: ``` INCDIRS = $(shell for x in `find base_dir -type d -print`; do echo -I $$x; done;) ```
I have this function ``` int does_exist_in_array(char team[], struct team *teams) { int i; for(i = 0; i < MAX_TEAMS_AMOUNT; i++) { if(!strcmp(team, teams[i].name)) { return 1; } } return 0; } ``` It crashes when i run the application. Anyone know what is wrong? Do i use it...
This can happen for a number of reasons: Either argument is NULL or otherwise an invalid pointerThe string pointed by either argument is not 0-terminatedThere are fewer thanMAX_TEAMS_AMOUNTteamelements
How to read from text file only numbers in C. Except spaces, symbols, enters and letters. That's how i am reading text: ``` unsigned char symb, symb1; FileIn = fopen("InCode.txt","rt"); while (!feof(FileIn)) { symb=getc(FileIn); symb1=symb; printf("%c",symb1); } ``` This is how it sh...
Try this : ``` char symb ; unsigned char symb1; FILE *FileIn; FileIn = fopen("InCode.txt","rt"); // Haven't checked fopen failure while ((symb=getc(FileIn))!=EOF) { symb1= (unsigned char) symb; if(symb1 >= '0' && symb1 <='9') ...
What does it meanif(!fork())? I'm a little bit confused about it, I dont know when Im in parent and child process: ``` if(!fork()) { // is it child or parent process? }else{ // is it child or parent process? } ```
From thefork(2)manpage: Return ValueOn success, the PID of the child process is returned in the parent, and0is returned in the child. On failure,-1is returned in the parent, no child process is created, anderrnois set appropriately. Sincefork()returns 0 to the child, theifclause tests if it's a child: ``` if (!fork...
the following code should call a command withexcvefor some reason i doesn't print the contents of the current directory, but still the program returns"ok" ``` 1 #include <stdio.h> 2 #include <unistd.h> 3 int main () 4 { char *argv[]={"ls",NULL};· 5 char *env[]={"PATH=/usr/local/sbin/:/usr/local/bin:/usr/sbi...
Sinceexecvedoes not return on success, it's obvious that the call is failing somehow. It returns -1 on error, which would be treated as true (non-zero). That's why it's saying okay. The most likely reason is that you haven't specified the full path to the executable, which is a requirement forexecve. Alternatively, i...
I'm writing a network related program in linux. the program is in kernel space and not user space. All I need in this program is a regular expression library that supports all gnu regex library features plus non-greedy repeat. Is there any such library that has those features and also I can compile and use it in ker...
I would recommendTRE. Be aware that it has a number of bugs in its POSIX BRE support (just misparsing/misinterpreting the meaning of certain characters as BRE), but the POSIX ERE support is very good, and it has most (all?) GNU extensions as well as non-greedy matching support. Only other thing I would warn you about ...