question
stringlengths
25
894
answer
stringlengths
4
863
I want to get to the children task (process) list of a process, here is the code: ``` void myFunc() { struct task_struct* current_task; struct task_struct* child_task; struct list_head children_list; current_task = current; children_list = current_task->children; child_task = list_entry(&children_list,struct task_struct,tasks); printk("KERN_INFO I am parent: %d, my child is: %d \n", current_task->pid,child_task->pid); } ``` The current pid is right, but the child pid is not correct. What am I doing wrong?
``` child_task = list_entry(&children_list,struct task_struct,children); ``` Note, the last parameter to the list_entry should bechildren btw: if you are not very familiar with list_entry, following article is a good source:http://isis.poly.edu/kulesh/stuff/src/klist/
In my programfprintf()returns -1, which indicates an error. How can I find out what actual error was?
``` #include <errno.h> #include <string.h> ... rc = fprintf(...) if (rc < 0) printf("errno=%d, err_msg=\"%s\"\n", errno,strerror(errno)) ```
I am using PC lint in my project. My project is compatible to build in both windows and linux. So i have used windows header(visualstudio) files and linux header files(gcc) in my project. I am running pclint entirely for all the file. Its giving error message ``` Unable to open include file *.h ``` I dont want to suppress this error in std.lnt file and i dont want to add ``` -elint errorcode ``` before the include statement. Please suggest me is there any way to suppress particualar headerfiles in std.lnt file.
I am assuming that you don't really get message ``` Unable to open include file *.h ``` but are really getting message ``` Unable to open include file fred.h ``` for some file fred.h. If I am correct, then add these two lines to std.lnt: ``` -efile(322,fred.h) -efile(7,fred.h) ```
I have a version number returned as a string which looks something like "6.4.12.9", four numbers, each separated by a "." What I would like to do is to parse the string into 4 distinct integers. Giving me ``` int1 = 6 int2 = 4 int3 = 12 int4 = 9 ``` I'd normally use a regex for this but that option isn't available to me using C.
You can use sscanf ``` int a,b,c,d; const char *version = "1.6.3.1"; if(sscanf(version,"%d.%d.%d.%d",&a,&b,&c,&d) != 4) { //error parsing } else { //ok, use the integers a,b,c,d } ```
Is there any way to create a user defined signals in Linux? My signal (signal number) should not match any of the existing signal numbers. In other words, i want to create my own unique signal, which will be registered and caught by my handler. Is it possible? If yes, how? Thanks in advance.
SIGRTMINthroughSIGRTMAX(these are not normally constants but macros which expand to functions evaluated at runtime) are available for whatever use you like, as areSIGUSR1andSIGUSR2. The former have additional realtime queueing support; the latter don't. Simply choose one to use.
I am new to makefiles and I am a bit stuck. I have two c source files called trade.c and report.c . They both depend on a file called acc.h. The acc.h file is composed of two other header files, users.h and resellers.h. I am wondering how you write the dependency of the two header files to the acc.h file. I have so far... ``` OBJECTS = trade.c report.c CC = gcc trading: $(OBJECTS) $(CC) $(OBJECTS) -o trading trade.o: trade.c accts.h $(CC) -c trade.c report.o: report.c accts.h $(CC) -c report.c ``` Any help is greatly appreciated.
You have no other choice than to add all the header files in the dependency list for the object file, as follows. ``` trade.o: trade.c accts.h users.h resellers.h $(CC) -c trade.c ```
I'd like to call some C functions from a Visual Basic 6 program which take anIUnknown*. Assuming that I know that some control in my VB6 application is an ActiveX control, can I get the underlyingIUnknown*out of that (maybe by casting?) to pass it to the C function?
AllCOM interfaces derive fromIUnknown, you can just use theIUnknownmethods on any valid interface pointer. If you need an additional reference to the same component, but don't care about which interface then use theQueryInterfacemethod forIUknown.
I need to combine phrases together as a sentence and pass that as words. I have a yacc rule which states: ``` words : words WORD { if($1 == NULL) { $$ = $2; } else { printf("\t$1 = %s\n",$1); printf("\t$2 = %s\n",$2); strBuffer[0]='\0'; strcat((char *)strBuffer,$1); $$ = strcat((char *)strBuffer,$2); printf("\t$$ = %s\n\n",$$); } } ``` char strBuffer[200] is a sufficiently large global array. But when I run the parser, I get: ``` $1 = The G $2 = nats and $$ = nats and ``` What should I do so that both $1 & $2 make it into $$?
Try: ``` sprintf($$, "%s%s", $1, $2); ```
This code doesn't compile: ``` const int x = 123; const int y = x; ``` It complains that "initializer element is not constant" for the y= line. Basically I want to have two const values, one defined in terms of the other. Is there a way to do this in C or do I have to use type-unsafe #defines or just write out the values literally as magic numbers?
When assigning const type you can only assign literals i.e.: 1, 2, 'a', 'b', etc. not variables like int x, float y, const int z, etc. Variables, despite the fact that your variable is really not variable (as it cannot change) is not acceptable. Instead you have to do: ``` const int x = 123; const int y = 123; ``` or ``` #define x 123 const int y = 123; ``` The second one works, because the compiler will strip everywhere there is x and replace it with a literal before it is compiled.
Why 2[a] can be compiled if only declare int a[3] in C. ``` 1 #include <stdio.h> 2 3 int main(int argc, char **argv) 4 { 5 int a[3] = {1, 2, 3}; 6 printf("a[2] is: %d\n", a[2]); 7 printf("2[a] is: %d\n", 2[a]); 8 9 return 0; 10 } ``` And the output both 3, how to explain it?
Becausea[2]is just syntactic sugar for*(a+2), which is the same as*(2+a)or2[a].
What I have to put as second parameter in this function? I need to understand the meaning ofint (*fn)(const char *, const struct stat *ptr, int flag). ``` int ftw(const char *path, int (*fn)(const char *, const struct stat *ptr, int flag), int depth); ``` Thank you!!
``` int (*fn)(const char *, const struct stat *ptr, int flag) ``` is a pointer to a function that returns anintand takes aconst char*, aconst struct stat *, and anint. If you had this function: ``` int func (const char *s, const struct stat *ptr, int flag) { return 0; } ``` You could passfuncas that argument.
Hi I'm trying to make a security feature for my C Project, so that if someone steals it, it becomes useless. It works as following: The main function only runs if the comparison of my macbook's Serial to an encrypted one is 1. The Problem is that I cannot get the system info in the program. When I do: ``` int main () { i=0; if (strcmp(system("system_profiler SPHardwareDataType | grep \"Serial Number\""), "Serial Number (system): W80314GJATP")); { bla bla bla } else {for(i=0;i<100;i++) {printf("Unauthorized Computer"); } return 1; } ``` It only prints info to stdout. Is there a way to do that comparison? Best Regards
Not an answer to your question, but keep in mind that these tricks are never really secure. See for examplethis post at lifehacker(this is about OS X, but it doesn't really matter).
Very quick question. I want to copy & paste textual data into the source code from the separate file usingincludedirective. Is it legal? ``` struct Record; // collection of data fields Record rec = { #include "some_big_record.txt" }; int numbers[] = { #include "some_long_sequence_of_numbers.txt" }; ``` It works on my box (GCC), but is it portable?
This is portable: ``` Record rec = { #include "some_big_record.txt" }; ```
How to detect at compile time if I'm using gcc or icc? (I was quite puzzled to find out that icc defines__GNUC__-- and even__GNUC_MINOR__and__GNUC_PATCHLEVEL__! why?)
We use ``` #ifdef __INTEL_COMPILER ``` to spliticcoff, assuminggccas a default.
I want to say ``` a[current] = value ``` rather than saying ``` a.append(value) ``` because I want to show that the current value is value. The former listing shows this better. I come from C, so I am a bit confused with python lists. In C I preallocate space, so a[current] would exist and contain junk before I assign it value. Can I do something similar in Python?
You can do something like ``` [0] * 10 ``` which will result in ``` [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ``` But your approach will probably not be very "pythonic". If switching to Python, you should also think about thinking in python. ;-)
I want to call a C function from C#. C function is inside a dll. The function I want to call is declared as follows: ``` int raxml_main(int argc, char*[] argv); ``` The problem is I am new to C# and I don not know how to convertstring[] argstochar*[] argv. Is it possible? Any idea?
try using below: ``` public static extern int raxml_main(int count, string[] argv); ``` You need to decorate with appropriateDllImport. Sometimesstringhas to be declared asStringBuilderbut I doubt it is necessary here sinceyouare sending the string.
In C (or a language based on C), one can happily use this statement: ``` #include "hello.h"; ``` And voila, every function and variable inhello.his automagically usable. But what does it actually do? I looked through compiler docs and tutorials and spent some time searching online, but the only impression I could form about the magical#includecommand is that it "copy pastes" the contents ofhello.hinstead of that line. There's gotta be more than that.
Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the;, though. Your specific example is covered by the spec, section6.10.2 Source file inclusion, paragraph 3: A preprocessing directive of the form# include"q-char-sequence"new-linecauses the replacement of that directive by the entire contents of the source file identified by the specified sequence between the"delimiters.
In my programfprintf()returns -1, which indicates an error. How can I find out what actual error was?
``` #include <errno.h> #include <string.h> ... rc = fprintf(...) if (rc < 0) printf("errno=%d, err_msg=\"%s\"\n", errno,strerror(errno)) ```
This question already has answers here:Closed12 years ago. Possible Duplicate:Parsing XML in Pure C Which is the best XML Library for C? Features I am looking out for are 1) Good Support in the form of tutorials and active mailing list. 2) Easy to develop. 3)Portabilityfor Windows, Linux, Mac. 4) I need to do parsing, validating and writing of simple XML Files.
Libxml2should do the trick.
hello everyone i try to debug a program, which have been installed by makefile. it have a binary file of OpenDPI_demo.o and a shell shellscript OpenDPI_demo. when i gdb OpenDPI_demo.o,i have a problem. i can't run it. the error is: ``` Starting program: /home/lx/ntop/test/opendpi/src/examples/OpenDPI_demo/OpenDPI_demo.o /bin/bash: /home/lx/ntop/test/opendpi/src/examples/OpenDPI_demo/OpenDPI_demo.o:can't execute the binary file. ``` please tell me why. actually i can run the program by ./OpenDPI_demo. thank you.
Based on the extension, the file isan object file. It is used by the linker (alongside other object files) to produce an executable. It's the real executable the one you want to run/debug.
im trying to fix this while loop but keep running into errors. Basically lets pretend I have 4 turtles, for every turtle that I sell I get a coin. Once I get to 0 I want to print how many coins I have. The error im getting is this, error parentheses around assignment used as truth value make: *** [cents] Error 1 Here is the code: ``` while (turtles > 0) { turtles = turtles - 1; coin++; if (turtles = 0) printf("Now you have %d coins\n", coin); } ```
Be glad that your compiler gave you that error. You areassigning0 toturtlesin your if condition: ``` if (turtles = 0) ``` I suppose you are trying to test if it is equal to 0. Then it should be two equals==for equality instead. ``` if (turtles == 0) ```
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.Closed12 years ago. In which place C saves file's offset?
When using standard C I/O, aFILEpointer contains most of the information needed to deal with the file, including its "position indicator." As you read or write through the file, its position (seek) indicator gets updated. See thedefinition of theFILEtype.
Is there any way of having 3d graphics in PSL1GHT? If so, please explain how to set up PSL1GHT to work with 3d graphics. I don't know much about programming in general, so please be specific. Thanks in advance, cheeseisedible.
Short answer: Yes Long answer: PSL1GHT supports libgmc and especially openGL via PSGL. Currently there is no easy howto on this topic on the net. But you can just try to google for psl1ght +opengl to see some demos about the base possibilities. I would suggest you start the classic way with "hello world" before running into the 3D-topics
I need a method in C that the random number between decimal 65-90 [a-z] and decimal 97-122 [A-Z] returns. If I call the method the method must be a different number give back what he has previously given How can I do this in C ?
``` #include <stdlib.h> char rand_az_AZ() { char val = rand() % 52; if (val < 26) { val += 'a'; } else { val -= 26; val += 'A'; } return val; } ```
i create here some space of malloc and with that a 2 dynamic array. it have colorbuffer[0 to 256][0 to 4]. and i read a bmp file out and put the colors into. now i want to change the color settings but this isnt working like colorbuffer[0][0] = "255" now the first color the red value should be 255 but then my programm shuts down.also like colorbuffer[233][2] = "23" the color 233 the value of green should be now 23. and i also cant print it out like printf("Color senitive %d", colorbuffer[0][1]); SOME PASSAGES OUT OF THE SOURCE->http://pastebin.com/fRD5w1XC Hope you can help me would be awesome thank you edit // Done the fail was the & on read and write to &colorbuffer ! thank you stackoverflow !
Change ``` fread(&colorbuffer[i] //With & ``` into ``` fread(colorbuffer[i] //No & ``` The current program is overwriting your colorbuffer table, and causing all kinds of trouble afterwards because of it.
I was working with C++ for a long time and now I am on a C project.I am in the process of converting a C++ program to C. I am having difficulty with the constants used in the program.In the C++ code we have constants defined like ``` static const int X = 5 + 3; static const int Y = (X + 10) * 5 static const int Z = ((Y + 8) + 0xfff) & ~0xfff ``` In C, these definitions throw error. When I use #defines instead of the constants like ``` #define X (5+3); #define Y (((X) + 10) * 5) #define Z ((((Y) + 8) + 0xfff) & ~0xfff) ``` the C compiler complains about the definitions of "Y" and "Z". Could anyone please help me to find a solution for this.
You need to remove the semi-colon from the #define X line ``` #define X (5+3) #define Y (((X) + 10) * 5) #define Z ((((Y) + 8) + 0xfff) & ~0xfff) ```
``` mov r8, FlushCounts[r14] ``` Can some one explain me what the FlushCounts[r14] is used for ? Does this mean r14 = &FlushCounts and r8 = FlushCounts ? Why is it done like this ?
This means copy 64 bits from addressFlushCount + r14to r8. Offset inr14register is in bytes.
Are there any reference guides or tutorials for writing a MIPS assembler?
If you are looking to actually write an assembler you need to know the format of the executable of the platform you are writing for (ex.ELF), then you need to use theMIPS instruction setas a reference to determine the correct machine code for your .TEXT section. Good luck!
I need a method in C that the random number between decimal 65-90 [a-z] and decimal 97-122 [A-Z] returns. If I call the method the method must be a different number give back what he has previously given How can I do this in C ?
``` #include <stdlib.h> char rand_az_AZ() { char val = rand() % 52; if (val < 26) { val += 'a'; } else { val -= 26; val += 'A'; } return val; } ```
i create here some space of malloc and with that a 2 dynamic array. it have colorbuffer[0 to 256][0 to 4]. and i read a bmp file out and put the colors into. now i want to change the color settings but this isnt working like colorbuffer[0][0] = "255" now the first color the red value should be 255 but then my programm shuts down.also like colorbuffer[233][2] = "23" the color 233 the value of green should be now 23. and i also cant print it out like printf("Color senitive %d", colorbuffer[0][1]); SOME PASSAGES OUT OF THE SOURCE->http://pastebin.com/fRD5w1XC Hope you can help me would be awesome thank you edit // Done the fail was the & on read and write to &colorbuffer ! thank you stackoverflow !
Change ``` fread(&colorbuffer[i] //With & ``` into ``` fread(colorbuffer[i] //No & ``` The current program is overwriting your colorbuffer table, and causing all kinds of trouble afterwards because of it.
I was working with C++ for a long time and now I am on a C project.I am in the process of converting a C++ program to C. I am having difficulty with the constants used in the program.In the C++ code we have constants defined like ``` static const int X = 5 + 3; static const int Y = (X + 10) * 5 static const int Z = ((Y + 8) + 0xfff) & ~0xfff ``` In C, these definitions throw error. When I use #defines instead of the constants like ``` #define X (5+3); #define Y (((X) + 10) * 5) #define Z ((((Y) + 8) + 0xfff) & ~0xfff) ``` the C compiler complains about the definitions of "Y" and "Z". Could anyone please help me to find a solution for this.
You need to remove the semi-colon from the #define X line ``` #define X (5+3) #define Y (((X) + 10) * 5) #define Z ((((Y) + 8) + 0xfff) & ~0xfff) ```
``` mov r8, FlushCounts[r14] ``` Can some one explain me what the FlushCounts[r14] is used for ? Does this mean r14 = &FlushCounts and r8 = FlushCounts ? Why is it done like this ?
This means copy 64 bits from addressFlushCount + r14to r8. Offset inr14register is in bytes.
Are there any reference guides or tutorials for writing a MIPS assembler?
If you are looking to actually write an assembler you need to know the format of the executable of the platform you are writing for (ex.ELF), then you need to use theMIPS instruction setas a reference to determine the correct machine code for your .TEXT section. Good luck!
I have a thread whose job is to send messages to UDP peers. the threads sends the messages iff one of the following apply: 1) a certain time has passed since the last time it sent a message (like a timeout). 2) an update boolean flag in a shared struct has been raised by other thread. i want to be able to wait for these conditions to happen so i would know when to send the message. the simplest way i can do it is by making a loop that repeats until one of the conditions satisfy. i'm afraid it is busy waiting and will consume a lot of CPU time for nothing. I don;t want to use sleep() either. i don't mind for a C++ solution as long as it's easy to understand and implement since i'm not very familiar with C++. Thanks !
For windows, use an event (CreateEvent) rather than a bool, thenWaitForSingleObjecton it.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question I know there are EventMachine and Twist, they are pretty good! but is there any networking framework based on C ?
If I haven't misread your question, I believelibeventshould fit the bill.
When a user program is interrupted with ^C, is the default signal handler run in user mode or in kernel mode? If in kernel mode, which kernel subsystem invokes the default signal handler? I could not find any reference in docs and manpages of sigaction. I was asked this question in an interview.
User-level code always runs in user mode. Including the signal handlers if they have been set by that process (or its environment - C library setup routines for instance). If there is no user-mode signal handler registered for given signal, and it is not ignored (or not ignorable/trappable as SIGKILL and SIGSTOP), the actions related to that signal (termination, core dump, suspend, resume) can be carried out entirely kernel side. The signal delivery is mostly handled by the process scheduler subsystem in the kernel.
How do you write anNaNfloating-point literal in C?
In C99's<math.h> 7.12 Mathematics <math.h> ``` [#5] The macro NAN is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN. | ```
``` #include <stdio.h> int main() { unsigned char data[1]; FILE *f = fopen("bill.jpg", "rb"); while (!feof(f)) { if (fread(data, 1, 1, f) > 0) { printf("0x%02x\n", data[0]); } } fclose(f); } ``` Is this the right? I am worried because if I view the file using hexdump, I get completely different output.
That should correctly print the first byte of the file in hex. Check the documentation for the Hexdump utility used, or tell us which platform is being used. Some dump utilities display the bytes in reverse order on each line to make little-endian reading somewhat more intuitive—once you understand what it is doing.
Yesterday I programmed a small piece code in C++ which contains a loop and an array. In the program I need to reset the array every time the loop starts over. However, if I use ``` memset(sum,sizeof(sum),0); ``` Then the array won't be reset to all 0. For this program I used: ``` for (i=0;i<sizeof(sum)/sizeof(int);i++) sum[i]=0; ``` instead. However, I think a loop is not as clear as a function, and it requires an additional variable, not to mention this is a million times uncool than the wizardry of memset() function. Could you guys enlighten me on this?
You're actually writing the size of sum into the 0 first bytes. You should be doingmemset(sum,0,sizeof(sum))instead. (In other words, the arguments aretarget,dataandlengthand you provided data and length in the wrong order.)
When a parent process creates a child process withfork(), according to me, the child process is in aRunningstate whereas the parent process is in aReadystate, i.e. waiting for the child to end. Am I right?
No, the fork creates a copy of the parent. Then you generally tests for the return value of fork which says 0 = I am the child, other: I'm the parent and the child has the return value as PID If the parent has to wait for the child to end, you need to use the wait function. Edit: seehttp://linux.die.net/man/2/forkandhttp://linux.die.net/man/2/waitfor the fork() in C.
I am not trying to optimize anything, so please don't tell me, that premature optimization is root of all evil. I am trying to solve a problem and I can't find the third solution. The problem goes like this: ``` if (x) y = a; else y = b; ``` xcan only be 0 or 1. How to write this conditionwithout a jump? One solution, with a data structure, is: ``` int temp[2] = {b, a}; y = temp[x]; ``` Another arithmetic solution is: ``` y = x * a + (1 - x) * b; ``` There is supposed to be a third one, a logical solution. Do you know how it looks like? Please give a solution in C.
``` y = a ^ ((x - 1U) & (a ^ b)); ``` This uses bitwise x-or
If I usegetHostByName()I only get "127.0.0.1", because it is written on /etc/host, but this is not useful to me. However, with the following java code I actually get what I want: ``` NetworkInterface.getByName(("eth0")).getInetAddresses().nextElement().getHostAddress() ``` I think that there is a way to get the same ip address also from C?
Check outgetifaddrs.
Here I have some Perl code: ``` sub clustering { ($brapa,$gee) = @_; $g=0; while ($g<$brapa) { if (($Y1XY[$g]-$Y2XY[$g])<=0) { push(@Y1new,$g+$gee);} else { push(@Y2new,$g+$gee);} $g++; } $sizeY1new = $#Y1new+1; $sizeY2new = $#Y2new+1; } ``` The problem is that I have try to write it in C like this: ``` int clustering (int brapa, int gee){ int g; g=0; while (g<brapa) { if ((jarakY1-jarakY2)<=0) { /*stuck at here*/ } else { } } return 0; } ``` How can I call data/results from jarakY1 and jarakY2? Then, how do I write it perfectly in C? Please help me.
Perl has built in data types and functions which aren't provided in C. It is the case for push. You'll have to write your own stack, list or variable length array handling yourself depending on how you use the result.
I am new in opencv. I am trying to make an application to transform an image to an "old picture" effect. can anybody help me with the algorithm? or is there any sample code for this? I am using C language...
Image transformations, including converting to sepia ("old picture" style), can be accomplished usingmatrix operations. EDIT: A different transformation called "grain effect" can be accomplished by drawing on each frame: White specs of dust at random locations about the x- and y- axis,A white bar that spans the whole height of the frame at a random x-axis location, and;A circular flicker spanning out from the center of the frame of a random intensity. Thisis a good tutorial for a flash-based version. Just translate what's done there into C.
I'm trying to capture the fields in a table but I need to get that data even if the table is empty. sqlite3_table_column_metadataisn't an option (it wasnt compiled into my version of SQLite3). Is there is a trick to obtain that info?
``` PRAGMA table_info(table_name); ``` returns a list of column names heres a link: http://www.sqlite.org/pragma.html#pragma_table_info
Is there a way to have Makefiles run automatically (then pause at the end) when doubleclicked in Windows Explorer?
Makefiles themselves are not meant to be executable, but there is a way to automate the making of programs by using a batch file (for Windows) or a shell script (for Unix). Place the following in a notepad text file and rename it to a .bat extension file (like makeprogram.bat): makepause This .bat file is executable, and if placed in the same folder as a makefile will compile according to said makefile using the make command.
I'm trying to compile a C program (myProgram.c) that includes a custom .h file that is in a specified directory. How can I add the directory to gcc so that I can build myProgram.c anytime using just a command likegcc myProgram(with no flags and what not)
You can do this by altering theC_INCLUDE_PATHenvironment variable, e.g. ``` C_INCLUDE_PATH=~/include export C_INCLUDE_PATH ``` You can add that to your.bashrcor.bash_profileor whatever to always have the environment variable set properly.Here's a reference on how you can do the same for libraries and C++.
I have been struggling to figure out the fscanf formatting. I just want to read in a file of words delimited by spaces. And I want to discard any strings that contain non-alphabetic characters. ``` char temp_text[100]; while(fscanf(fcorpus, "%101[a-zA-Z]s", temp_text) == 1) { printf("%s\n", temp_text); } ``` I've tried the above code both with and without the 's'. I read in another stackoverflow thread that the s when used like that will be interpreted as a literal 's' and not as a string. Either way - when I include the s and when I do not include the s - I can only get the first word from the file I am reading through to print out.
The%[scan specifier does not skip leading spaces. Either add a space before it or at the end in place of yours. Also you have your 100 and 101 backwards and thus a serious buffer overflow bug.
I am not trying to optimize anything, so please don't tell me, that premature optimization is root of all evil. I am trying to solve a problem and I can't find the third solution. The problem goes like this: ``` if (x) y = a; else y = b; ``` xcan only be 0 or 1. How to write this conditionwithout a jump? One solution, with a data structure, is: ``` int temp[2] = {b, a}; y = temp[x]; ``` Another arithmetic solution is: ``` y = x * a + (1 - x) * b; ``` There is supposed to be a third one, a logical solution. Do you know how it looks like? Please give a solution in C.
``` y = a ^ ((x - 1U) & (a ^ b)); ``` This uses bitwise x-or
If I usegetHostByName()I only get "127.0.0.1", because it is written on /etc/host, but this is not useful to me. However, with the following java code I actually get what I want: ``` NetworkInterface.getByName(("eth0")).getInetAddresses().nextElement().getHostAddress() ``` I think that there is a way to get the same ip address also from C?
Check outgetifaddrs.
Here I have some Perl code: ``` sub clustering { ($brapa,$gee) = @_; $g=0; while ($g<$brapa) { if (($Y1XY[$g]-$Y2XY[$g])<=0) { push(@Y1new,$g+$gee);} else { push(@Y2new,$g+$gee);} $g++; } $sizeY1new = $#Y1new+1; $sizeY2new = $#Y2new+1; } ``` The problem is that I have try to write it in C like this: ``` int clustering (int brapa, int gee){ int g; g=0; while (g<brapa) { if ((jarakY1-jarakY2)<=0) { /*stuck at here*/ } else { } } return 0; } ``` How can I call data/results from jarakY1 and jarakY2? Then, how do I write it perfectly in C? Please help me.
Perl has built in data types and functions which aren't provided in C. It is the case for push. You'll have to write your own stack, list or variable length array handling yourself depending on how you use the result.
I am new in opencv. I am trying to make an application to transform an image to an "old picture" effect. can anybody help me with the algorithm? or is there any sample code for this? I am using C language...
Image transformations, including converting to sepia ("old picture" style), can be accomplished usingmatrix operations. EDIT: A different transformation called "grain effect" can be accomplished by drawing on each frame: White specs of dust at random locations about the x- and y- axis,A white bar that spans the whole height of the frame at a random x-axis location, and;A circular flicker spanning out from the center of the frame of a random intensity. Thisis a good tutorial for a flash-based version. Just translate what's done there into C.
I'm trying to capture the fields in a table but I need to get that data even if the table is empty. sqlite3_table_column_metadataisn't an option (it wasnt compiled into my version of SQLite3). Is there is a trick to obtain that info?
``` PRAGMA table_info(table_name); ``` returns a list of column names heres a link: http://www.sqlite.org/pragma.html#pragma_table_info
Is there a way to have Makefiles run automatically (then pause at the end) when doubleclicked in Windows Explorer?
Makefiles themselves are not meant to be executable, but there is a way to automate the making of programs by using a batch file (for Windows) or a shell script (for Unix). Place the following in a notepad text file and rename it to a .bat extension file (like makeprogram.bat): makepause This .bat file is executable, and if placed in the same folder as a makefile will compile according to said makefile using the make command.
I'm trying to compile a C program (myProgram.c) that includes a custom .h file that is in a specified directory. How can I add the directory to gcc so that I can build myProgram.c anytime using just a command likegcc myProgram(with no flags and what not)
You can do this by altering theC_INCLUDE_PATHenvironment variable, e.g. ``` C_INCLUDE_PATH=~/include export C_INCLUDE_PATH ``` You can add that to your.bashrcor.bash_profileor whatever to always have the environment variable set properly.Here's a reference on how you can do the same for libraries and C++.
I have been struggling to figure out the fscanf formatting. I just want to read in a file of words delimited by spaces. And I want to discard any strings that contain non-alphabetic characters. ``` char temp_text[100]; while(fscanf(fcorpus, "%101[a-zA-Z]s", temp_text) == 1) { printf("%s\n", temp_text); } ``` I've tried the above code both with and without the 's'. I read in another stackoverflow thread that the s when used like that will be interpreted as a literal 's' and not as a string. Either way - when I include the s and when I do not include the s - I can only get the first word from the file I am reading through to print out.
The%[scan specifier does not skip leading spaces. Either add a space before it or at the end in place of yours. Also you have your 100 and 101 backwards and thus a serious buffer overflow bug.
I want to input words from a file which are delimited by anything that isn't a letter. Is there an easy way to do this in C similar to using the \W predefined character classes in Java? How should I approach this? Thanks.
Character classes in general and \W specifically really aren't related to Java at all. They're just part of regular expression support, which is available for many languages, including GNU C. SeeGNU C library Regular Expressions.
What does the following declaration mean? ``` unsigned char (*pArray[10][10]); ```
Declaration ``` unsigned char (*pArray[10][10]); ``` is exactly equivalent to ``` unsigned char *pArray[10][10]; ``` The parentheses are entirely redundant and have no effect at all. This is a 2D 10x10 array ofunsigned char *pointers.
I am using resources with Win32 to create a dialog containing a single tab control. The tab works fine when changing tabs but somehow dragging the window off screen ( eg. dragging it past bottom of screen then back up ) will cause the tab contents to disappear. I think it may be a problem with how I've set the clipping properties but after much fiddling I still didn't get it working exactly how I expect. I have uploaded a basic skeleton project here which has the bare minimum required to reproduce this problem and would be very grateful if someone could check it out. http://localhostr.com/file/nPTbTTQ/skeleton.rar
It is a Z-order problem, the dialog isbehindthe tab control. Change the parent of the inner dialog from hwndDlg to hwndTab. I don't want to guess why you saw the static control text at all.
I wonder what can be reason, that access to poiner to bigger structure is slower. For example. W got to structure: First: ``` typedef struct TAL { struct TAL *next; int v; int a; int b; int c; } LAL; ``` And Second: ``` typedef struct TAL { struct TAL *next; int v; } LAL; ``` And Simply explore the list ``` LAL *tmp; tmp = AL; while(tmp != 0) { tmp = tmp -> next; } ``` The execution time of smaller stucture (second) is less than first. What can be reason?
One reason could be caching effects. Whilst linked-lists display pretty badspatial localityalready, making the nodes bigger can only exacerbate the situation.
I'm trying to develop a small app like Flash Player updater. I want users to download this executable first and so I can check if user has required .net framework and other prerequisites (sql server, crystal reports etc.). Then by this app I'll download missing ones and install them. So which language I must use (c, c++, visual c++)? How is Adobe doing this and are there any open-source examples?
It seems you're looking for abootstrapper. Several solutions target the .NET framework, including the popular (and free)dotNetInstaller.
I want to declare a new integer in the heap, ``` int *intPtr = (int*) malloc(sizeof(int)); ``` How do I change the value of the space in the heap, to which*intPtrpoints to? Thanks
DereferenceintPtr: ``` *intPtr = 0; ```
I recently looked into Lua and it seems really nice. The only annoying thing is its lack of (standard) libraries. But with the JIT compiler comes along a nice FFI C interface. Coming from a java background, i tried to avoid C as much as possible, so my question: has anyone some experience with LuaJIT, especially its FFI interface, and how difficult is it to set up a library for someone with little to no knowledge in C?
Seemed really simple to me, and Mike Pall has some nice tutorials on ithere, the lua mailing list also includes some good examples, so check out the archives as well
Let's say I have sometypedef struct {int b;} some_t;and a pointerato such a struct. Then why is ``` (*a).b = 5; ``` not the same as ``` some_t c = *a; c.b = 5; ``` ?
In the second,cis acopyof*a, andc.bis a copy of(*a).b. c.b = 5modifies the copy, not the original.
I have a function as follows: ``` DWORD stats = GetFileAttributesA(path); return (stats != INVALID_FILE_ATTRIBUTES) && !(stats & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0; ``` The problem is that a SQL Connection string: "Driver={SQL Server Native Client 10.0};server=localhost;database=NorthWindDB;Trusted_Connection=yes;" somehow is valid. It returns 32 (stats is 32 when that input is given) which is the FILE_ATTRIBUTE_ARCHIVE value. I cannot filter this out because other legitimate files also return that value. How do I determine whether the value specifies a file or connection string? UPDATE: PathFileExists doesnt work either
Since all else seems to fail, here is a completely different approach: trysystem("dir \"path_to_check\"")and check its return value (works on my machine :) See alsosystem().
I have a file namedtodo.txtand I have a function that will list every line in the file: ``` void list() { FILE *todoFile; todoFile = fopen("./todo.txt", "r"); char line[4096]; int len; if (todoFile != NULL) { while (fgets(line, sizeof line, todoFile)) { len = strlen(line); if (len && (line[len - 1] != '\n')) { printf("%s", line); } printf("%s", line); fclose(todoFile); } } else { printf("ERROR"); } } ``` todo.txtcontents is: ``` * foo! * hello * FP! ``` but when I use thelist()function only the first line is printed: ``` * foo! ``` Any ideas?
You can't callfgets()on a closed file.
``` #include <stdio.h> int main() { int i = 0; char stuffing[44]; for(i = 0; i <= 40; i+=4) { *(int *)&stuffing[i] = 0x4004f8; } puts(stuffing); } ``` The above terminates as soon as it gets to0x00, how to output all stuff instuffing?
You want to usefwritefor outputting arbitrary binary data: ``` fwrite(stuffing, 1, sizeof(stuffing), stdout); ``` Theputsfunction writes a C string and C strings are terminated by'\0'(AKA 0x00). UPDATE: In comments elsewhere you say that you want "ASCII characters to be read bygets". First of all,don't everusegets, never, don't even mention its name. Secondly, if you just want ASCII characters then why go to all the trouble of stuffing the raw bytes into acharbuffer when you could just do this: ``` printf("%d\n%d\n%d\n%d\n", 0x4004f8, 0x4004f8, 0x4004f8, 0x4004f8); ``` or something similarly straight forward?
This function aims to get the start address of the stack: ``` unsigned long find_start(void){ __asm__("movq %rsp, %eax"); } ``` When I compile it,getting an error: ``` Error: suffix or operands invalid for `movq' ```
movqis an instruction that expects 64-bit operands.rspis a 64-bit register, whileeaxis a 32-bit register. Perhaps tryrax?
I am using BorlandC and Windows 7. When I compile the file, I am getting these errors: ``` Error Assign.C : Unable to open include file 'stdio.h' Error Assign.C : Unable to open include file 'conio.h' Error Assign.C : Unable to open include file 'dos.h' Error Assign.C : Unable to open include file 'stdlib.h' ``` What am I doing wrong?
check the bcc32.cfg file (should be in the same directory as bcc32.exe) It should contain: -ID:\BorlandC\Include Assuming that the include files can be found in D:\BorlandC\Include
That is,Bhas agetsthat asks for input,Ahas aputsthat outputs something. BothAandBare C programs. How can I use the output of program A as input for B in bash? What I tried is./A |./Band./B |./A, but neither works. UPDATE How does stuff in stdout of A goes to stdin of B for./A|./B?
Here is an example to get you started: ``` /* a.c */ #include <stdio.h> int main() { puts("This is a string"); return 0; } ``` Compile this as "a.out". Here is the program that will catch the string from a.out: ``` /* b.c */ #include <stdio.h> int main() { char line[1024]; fgets(line,1023,stdin); printf("b.c: %s",line); return 0; } ``` Compile this as "b.out". Now run them together: ``` ./a.out | ./b.out ``` The main principle for pipes to work is that you write to stdout and read stdin. Let me know if you need more help.
What exactly is the difference between the two?
fprintfdoes formatted output. That is, it reads and interprets a format string that you supply and writes to the output stream the results. fputssimply writes the string you supply it to the indicated output stream. fputs()doesn't have to parse the input string to figure out that all you want to do is print a string.fprintf()allows you to format at the time of outputting.
I need to define some path to files with macros. How can I use the $HOME environment variable? I can't find it on the GNU manual, and this doesn't work: ``` #define LOGMMBOXMAN "$HOME/mmbox/LOGmmboxman" ```
No it shouldn't and you probably don't want constant-defined settings like that in any case. If you did that and it worked as you're intending to use it, your home directory would be built in as whatever$HOMEis for whoever's doing the building. The executable then depends on that specific home directory existing. If that's OK, just#defineyour own home. I suspect it isn't though, so you need to deduce it at runtime. For run-time deduction what you want isthis, such that: ``` const char* home_dir = getenv("HOME"); ``` If there is no$HOMEdefined, you getNULLreturned so be sure to test for this. You can then build your string based on that. You'll need#include <stdlib.h>.
I want to write regular expression library in C/C++. What is the good starting point , any books or articles. I know there are may libraries are available , but I want to write my own version.
A good starting point is to use existing implementations and criticize them. Pay attention to data structures and design decisions you don't like.Avoid them when you write your version.
What this does is converts the argument./a.out -b 101into a decimal 5 though what I am trying to do is only covert the 101 into a binary number if I give it the argument-b ``` #include <stdio.h> void main(int argc, char *argv[]) { if ((argc == 3) && (argv[2] == "-b") ) //here lies the problem { int n = 0; char *c_pt = argv[2]; printf("argv[1]: %s\n", argv[1]); while (*c_pt) { if (*c_pt < '0' || *c_pt > '1') { break; } n = n * 2 + *c_pt - '0'; c_pt++; } printf("%d\n", n); } } ```
In C you need to callstrcmp(3)to compare strings.
I have a function that takes in two strings, and I want to, let's say compare the 2nd letter of each string to the other. How do I fix this statement: ``` if (strncmp(str1 + 1, str2 + 1) != 0) { ... ``` I get an error stating that passing the argument makes a pointer from an integer without a cast.
``` if (str1[1] == str2[1]) { /* Do something */ } ```
How do I conver an RGB component (0-255) to a floating point number in which 255 would be 1.0f and 0 would be 0.0f?
What's wrong with dividing? ``` unsigned char red = 45; float percentage = red/255.0f; ```
my C program has type definition of a stack like this : ``` typedef struct { char T[MaxEl+1][MAX_CHAR]; address TOP; boolean alive;//ignore this } Stack; ``` and create a function: ``` void expandP(Stack stack[],int i,char input[]) {//variable stack is array of Stack .. Stack temp; CreateEmpty(&temp); .. copyStack(&temp,stack[i]); } void CreateEmpty(Stack *S) { Top(*S) = Nil; isAlive(*S) = false; } void copyStack(Stack* out,Stack in) { } ``` it gives error segmentation fault when running and no warning when compile
MakeStack ina pointer ``` void copyStack(Stack* out, const Stack *in) { ``` And then call it like so: ``` copyStack(&temp,&stack[i]); ```
I am running a code that mimics demand paging system here are some of the parameters: ``` Page size = 4096 bits Processor = 32 bits Number of page frames = (variable) ``` I run my code with a fifo or random page replacement algorithm with number of page frames set to 100. My disk read/ write ends at 63. Then when I changed the Processor size to 32 bits - this boundary moves to 16. The latter case, I understand. If the page frame count is more than the possible page table entries, (2^4) there is no need for evictions. But I don't understandwhy in the former case, where the page table entries go up to 2^20, the disk read/write stops at 63 with both page replacement algorithms. What is this mystery 63 number? Any idea where this may be coming from? Thank you.
The reference string had only 63 pages -- now that I have gotten some sleep...
I'm using VS 2010 Pro. First, C doesn't have a bool type? I just have to use int with 0/1. Seems odd as most languages consider boolean a standard type. Also I have Visual Studio 2010 Pro but doesn't have a "C Project". I just created an Empty C++ Project. The file names end with .c The problem with this is the keywords are messed up (shows bool as highlighted/valid in the editor, but compiler doesn't like it). I went to repair/add components and they have C#, F#, C++, Visual Basic; but no C?
Newest C standard (C99) has bool type indeed. Just includestdbool.hand you can use it. Unfortunately MSVC does not haver proper support for C at all. Only partial C89.
I want to make my program to print something, then wait for a few seconds and then print something else in the same line. I've tried to write it as: ``` printf ("bla bla bla"); sleep (2); printf ("yada yada yada\n"); ``` but in the output I get to wait for 2 seconds and then I get the whole line printed as one. When I tried to put the output in different lines it did print with a pause. How do I make it to print with a pause in the same line? *Working on Linux
``` printf ("bla bla bla"); fflush(stdout); sleep (2); printf ("yada yada yada\n"); ``` fflush forces the stdout internal buffer to be flushed to the screen.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed11 years ago. Does anyone know some good easy to learn openCV c/c++ tutorial you can recommend? I tried Google, but I wasn't very satisfied with results.
OpenCV has recently provided alist of books they recommend. Other interesting materials: There's a great introduction to OpenCV atGady Agam's introduction to OpenCV.Noah Kuntz OpenCV tutorialsare OK. It covers image manipulation, data types, image processing, camera stuff and several other topics.There's also the officialOpenCV Tutorials, provided by the OpenCV folks themselves.Also you can find some good Opencv C++ Exampleshereto get started.
Why does this Compile: ``` int main() { {} } ``` But this does not: ``` {} int main() { } ```
First case, you're defining a block inside a function, which is allowed (it limits visibility). Second case, you're defining an anonymous block, which is not allowed (it needs to be predeceded by a function definition, otherwise, the compiler will never know when it will have to execute it)
What does the quoted footnote in the title mean? It's a footnote attached to 6.10.3p11 If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives,147)the behavior is undefined. I checked up and found A preprocessing directive consists of a sequence of preprocessing tokens that begins with a # preprocessing token that ... and I didn't find the non-terminalnon-directivematching that syntax. It can, but doesn't have to, start with a#preprocessing token. So wouldn't we have to say the following? "Despite the name, a preprocessing directive is a non-directive." Also, what is the purpose of that footnote?
Seehttp://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_250.htmIt is to clarify that ``` #define nothing(x) // Nothing /* Case 1 */ nothing ( #nonstandard ) ``` is UB.
Is there any difference betweenuintandunsigned int? I'm looking in this site, but all questions refer to C# or C++. I'd like an answer about the C language. If it is relevant, note that I'm using GCC under Linux.
uintisn't a standard type -unsigned intis.
I have musical app developed for OS X, which has following features, Play multiple tracks at a time (long audio files and short sounds)rewind, forward, pause, stop functionalitythe app also displays the waveform of the songCreate playlist I used Apple's Core Audio framework for music playback. Now I have to develop the same application for Windows. I don't have any experience of working on Windows. Any idea, Which IDE to use? It must has Audio frameworks (as close to Core Audio) Also, want some suggestions on which approach can we take so development will be easy. Thanks
You can get Visual C++ 2010 Express for free. You can either use OpenAL or DirectSound.
I have a C program which captures data, and among them it captures MAC Addresses. However, while the MAC might be for example00:0F:3A:D3, the program captures it like0:F:3A:D3. Is there a way to check the string and see if between two ":" there's one character, and if so to add a zero in front ? I'm not a good programmer, so any help is appreciated - Thanks :)
``` int main() { char *s = "0:F:3A:D3"; char o[15]; int a, b, c, d; sscanf(s, "%X:%X:%X:%X", &a, &b, &c, &d); sprintf(o, "%02X:%02X:%02X:%02X", a, b, c, d); printf(o); } ```
I malloc a 2d array. The 2d array is part of a struct and when I try malloc is I get an error that malloc has too many arguments. ``` malloc(world->representation, sizeof(int *) * mapHeight); int i; for (i = 0; i < mapHeight, i++ ) { malloc(world->representation[i], sizeof(int) * mapWidth); } ``` How should this be malloced if its part of a struct?
You are usingmallocincorrectly. The proper usage is: ``` world->representation = malloc(sizeof(int *) * mapHeight); ``` and ``` world->representation[i] = malloc(sizeof(int) * mapWidth); ```
For example, ``` struct node { struct node *left, *right; }; #define LEFT(X) (X->left) #define RIGHT(X) (X->right) ``` I would like to forbid macro call like this without changing the existing macro interface. ``` LEFT(n) = ... ``` Any idea?
Try this: ``` #define LEFT(X) ((X)->left+0) #define RIGHT(X) ((X)->right+0) ```
Does posix_memalign catch signals? I am allocating memory using posix_memalign and running timer in the background, i get a "Interrupted system call exception", from posix_memalign in the logs. Is it due to the timer signal? Or is there some other issue? Thanks in advance.
My best guess is that you're treating the return value ofposix_memalignincorrectly. This function does not return a pointer. It returns 0 on success and an error code on failure. Perhaps you're findingEINTRinerrnoafterposix_memalignreturns; this is meaningless sinceposix_memaligndoes not useerrno.
Hi How can I convert pdf to txt with qt ? if there isn't way to do this , Is there any library for c++ that convert pdf files to txt files ? thanks.My os is windows7 and my ide is visual studio 2008
Foxit sells their PDF code as a library. I use it, and it's great. http://www.foxitsoftware.com/pdf/sdk/dll/ You may know them for their very popular free Acrobat Reader alternative.
I am getting this exception with posix_memalign. Any idea as to why we get it? Thanks in advance.
Interrupted system calls are usually the result of a system call being interrupted. In other words, the process is receiving a signal while the call is executing.
Is it guaranteed that a function registered with atexit will ALWAYS be called upon normal program termination? (I encounterd a scenario in FreeBSD where a function that I register with atexit never gets called, even when the program terminates normally).
No. First, the function will not be called ifatexitreturns a non-0 value. Secondly, it won't be called if a function registered before it doesn't return normally.
Are there any tools, libraries, or frameworks to get the control flow graph of a C program, and find the worst possible path a program can take? When I read the other questions related to control flow graphs, I came across a few tools which can generate the control flow graph. Is there any way to use them to find the worst possible path?
If the graph will ever have loops in it, then no -- there isn't a foolproof way to figure this, as the question is equivalent to thehalting problem. Short version: it's impossible for a program, given an arbitrary other program, to even determine whether it will ever return. You could possibly determinepotentialinfinite loops, but the only way to be anywhere near certain is to actually run the program with an exhaustive set of inputs.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question I have a set of simple shapes (see following figure), and I want to recognize handwriting shape and figure out which shape it probably is in the set. Is there any simple algorithm to do that? Or any open source lib? BTW, my task is simple, so I don't use too complicated lib like OpenCV. Thanks, in advance!!
It's an old project, butthismay be along the lines of what you are looking for. This onerequires OpenCV, but as the commenter pointed out, it might be worth your while to learn it.
I'm wondering how you can loop over each line of a file heres the code I have so far: ``` FILE *todoFile; todoFile = fopen("./todo.txt", "r"); if (todoFile != NULL) { } else { printf("ERROR"); } ```
The idiomatic way to read a file line-by-line until it ends is ``` /* assume line is a char array */ while (fgets(line, sizeof line, handle)) { size_t len = strlen(line); if (len && (line[len - 1] != '\n')) { /* incomplete line */ } /* possibly remove trailing newline ... and */ /* deal with line */ } ```
a.cpp: ``` static const struct A { int a1; const char ** a2; } as[] = { {1,(const char *[]){"LOL",NULL}}, {2,(const char *[]){"LOL","LOL2",NULL}} }; const char ** getA(int a) { int i = 0; for(;i< sizeof(as)/sizeof(struct A);i++){ if (as[i].a1 == a) return as[i].a2; } } ``` Is there a context or scope problem in returningconst char **from a static const struct initialized statically?
There's certainly no scope problem. Scope pertains to variables, not to values. (There is a problem with missing{in your code, though.)
Are there any tools, libraries, or frameworks to get the control flow graph of a C program, and find the worst possible path a program can take? When I read the other questions related to control flow graphs, I came across a few tools which can generate the control flow graph. Is there any way to use them to find the worst possible path?
If the graph will ever have loops in it, then no -- there isn't a foolproof way to figure this, as the question is equivalent to thehalting problem. Short version: it's impossible for a program, given an arbitrary other program, to even determine whether it will ever return. You could possibly determinepotentialinfinite loops, but the only way to be anywhere near certain is to actually run the program with an exhaustive set of inputs.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question I have a set of simple shapes (see following figure), and I want to recognize handwriting shape and figure out which shape it probably is in the set. Is there any simple algorithm to do that? Or any open source lib? BTW, my task is simple, so I don't use too complicated lib like OpenCV. Thanks, in advance!!
It's an old project, butthismay be along the lines of what you are looking for. This onerequires OpenCV, but as the commenter pointed out, it might be worth your while to learn it.
I'm wondering how you can loop over each line of a file heres the code I have so far: ``` FILE *todoFile; todoFile = fopen("./todo.txt", "r"); if (todoFile != NULL) { } else { printf("ERROR"); } ```
The idiomatic way to read a file line-by-line until it ends is ``` /* assume line is a char array */ while (fgets(line, sizeof line, handle)) { size_t len = strlen(line); if (len && (line[len - 1] != '\n')) { /* incomplete line */ } /* possibly remove trailing newline ... and */ /* deal with line */ } ```
a.cpp: ``` static const struct A { int a1; const char ** a2; } as[] = { {1,(const char *[]){"LOL",NULL}}, {2,(const char *[]){"LOL","LOL2",NULL}} }; const char ** getA(int a) { int i = 0; for(;i< sizeof(as)/sizeof(struct A);i++){ if (as[i].a1 == a) return as[i].a2; } } ``` Is there a context or scope problem in returningconst char **from a static const struct initialized statically?
There's certainly no scope problem. Scope pertains to variables, not to values. (There is a problem with missing{in your code, though.)