question
stringlengths
25
894
answer
stringlengths
4
863
I need to make an application with GUI built on gtk, that checks socekets for incoming messages and displays statistics as they are gathered without any imput from user. How can this be organised?
I'd know how to do it using PyGtk and PyGObject but I never did something like it in C. However, I have a suggestion to you: try theg_io_add_watchfunctionfrom GLib (which is base for GObject as well). It worked well in Python for me (and were much more practical to use BTW) and the Python version is just a wrapper for the original C function. Since GTK+ is based in GObject and GObject uses GLib extensively, you already have this function available in your development environment and it should work well with GTK+.
I had written a small thread program when i compiled cc filename.c, i got some statements during compilation, but when i compiled using -lpthread (cc filename.c -lpthread) it got executed what is this -lpthread why is it required? can anyone explain this in detail. it would be of great help.
Thepthread_create()function that you use in your program is not a basic C function, and requires that you use a library. This is why you have to use this command switch-lpthread. This gcc command tells him to look for a library namedlibpthreadsomewhere on your disk, and use it to provide the thread creation mechanisms. I suggest you read this to get familiar with the "library" concept:http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html
Almost every c/c++ open source project I see ships with it aconfigurefile. But in our own c/c++ project I haven't seen this file so far, when is it needed?
I think you are speaking about configure script which is used, whenautotoolsare used to build the project. The main purpose of theconfigurefile is to generateMakefilesappropriate to your system configuration and to check various preconditions (installed libs, for example).
I have a code which suppose to read an integer from a file. But its actually reading as an character. Suggest me some modification where I can read the integers into an array. ``` fptr =fopen("path","r"); while(1) { c=getc(fptr); putchar(c); if (c==EOF) exit(1); } ``` Thanks in advance Amit
``` #include <stdio.h> int main(int argc, char **argv ) { int value; FILE *fp = fopen ( "d:\\abc.txt", "r"); while ( fscanf(fp, "%d", &value) == 1 ) { printf ( "%d\n", value ); } fclose ( fp ); } ```
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. Is there a way to avoid writing to file, and keep a table in main memory?, using C/C++ and SQL Server 2008?
If you mean whether there is an in-memory version of the SQL Server, like TimesTen for Oracle the answer is no. If you mean a 'little' database that you can add to your App see MS SQL Compact Server. If you mean using memory mapped files instead of a database, see here:http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile(VS.100).aspx Otherwise, please be more specific in your question! hth Mario
I already did the hard part of adding a system call to the linux kernel. I need to return the following array:unsigned int counts[4]I can reference the array as curr->counts, but I don't think there is a return value for that, and I think it is bad to give a pointer into kernel space?Instead I'm thinking the best way is to return void and pass by parameter. Is that the way to go?
See the kernel routinecopy_to_user (). Design the system call interface to pass a parameter which is a pointer where to return the data. You are trying to do something like theread()orgettimeofday()system calls, right? Those all return more than 32-bit results by usingcopy_to_user().
I have a hex value stored in a two byte array: ``` unsigned char hex[2] = {0x02, 0x00}; ``` How can I convert this to a decimal value?
You can use (bitwise operation) int b = (hex[0] << 8) | hex[1]; or (simple math) int b = (hex[0] * 0x100) + hex[1];
This question already has answers here:Why can't we initialize members inside a structure?(6 answers)Closed7 years ago. Can you have a structure in C that has elements of that same structure? My first attempt at implementing a binary search tree in C is the following: ``` #include <stdio.h> struct binary_tree_node { int value; struct binary_tree_node *left = null; struct binary_tree_node *right = null; }; main() { struct binary_tree_node t; t.value = 12; struct binary_tree_node y; y.value = 44; t.left = &y; } ``` I can't figure out what's wrong with this code, any help would be appreciated. I realize there are other questions on binary search implementations in C, but I'm trying to figure this out from scratch with my own code (and some guidance of course). Thanks!
Remove the= nullin your struct declaration. You can declare the self-reference, but you cannot set it.
How can I draw a shadow like the one you'd get withCGContextSetShadowWithColorbut manually? I basically need to draw the path and then somehow blur it, so what I'm really asking is how to blur a shape drawn with CG so it looks like a shadow. I need to draw it manually. Please don't ask "Why not just use the function?".
One option if you are on the Mac is to useCore Imagewhich provides a several blur filters. Another more difficult option would be to draw into your own buffer and then run your ownGaussian Bluron it.
How does 1.000(base2) x 2^-1 + (-0.111(base2) x 2^-1) = .001(base2) x 2^-1? To add binary numbers don't you simply just add? I'm not seeing how the addition works..
I'm not sure what you mean when you ask "don't you simply just add?", but the math is correct. It is basically in base-2 scientific notation. ``` 1.000(base2) x 2^-1 = 0.100(base2) -0.111(base2) x 2^-1 = -0.0111(base2) 0.100 + (-0.0111) = 0.0001 0.0001 = 0.001(base2) x 2^-1 ```
I am using eclipse CDT on xubuntu. It works perfectly. The only problem is that the background colour of the pop up box that appears when you put the mouse over a variable for instance will have a background colour of black. Sometimes some of the text in this box will be black as well. I then have to select all text inside the box to read what is in there. For the life of me I cannot figure out where to change that background black colour... Does anybody here know perhaps please.
Go toWindow>Preferencesand then openC/C++>Editorand play withSource hover background. Don't forget to uncheck theSystem Defaultbox to be able to change the colour.
In C to parallelize a loop withschedule(static)would mean that the chunk size is quickly computed asceil(loops/threads). For my project I have to iterrate through 9 different chunk sizes, one of which is "default". This is how I did it: I wrote a perl loop that compiles my program with-DCHUNKSIZE=$cand in theompcode I specifyschedule(static, CHUNKSIZE). Question: what can I do for default? Chunk size of 0 doesn't work :( Thanks! P.S. I was hoping to avoid having#ifdef ... #else ... #endifsince I have very many loops that are parallelized
I agree with ejd. As to how to handle it, why not: ``` #ifdef CHUNKSIZE #pragma omp parallel for schedule(mode, CHUNKSIZE) #else #pragma omp parallel for schedule(mode) #endif for ( ; ; ) /* ... */ ``` and then not pass-DCHUNKSIZEfor the default.
I am having difficulty defining the return type in the method signature properly. The problem islist* GetPrimeNumbers() ``` struct dynamicArray{ int val; struct dynamicArray * next; }; typedef struct dynamicArray list; int PrimeFactor() { int sum = 0; list * primeNumbers; primeNumbers = GetPrimeNumbers(); return sum; } list* GetPrimeNumbers() { int max = 100; list * current, * head; head = NULL; for(int i = 2; i < max; i++) { //..implmenetation } return current; } ``` I have tried several return types, but nothing has worked. I am a beginner level C programmer. What needs to be there?
Either you need a header file with thetypedefand prototype forGetPrimeNumbers, or you need to swap the functionsGetPrimeNumbersandPrimeFactorin the file. The way you presented the code,GetPrimeNumbershas no declaration in place whenPrimeFactoris compiled.
I need to print characters part of ASCII extended, namely something like: ``` char p = 219; // a rectangle printf("%c\n", p); ``` However, in the shell it does not show the proper character .. what can i do to see the rectangle? Thank you
Use libiconv to convert the CP-1252 or ISO-8859-1 or whatever 8-bit character set you are converting from to UTF-8; something like this: ``` #include <iconv.h> iconv_t cd = iconv_open("utf-8", "cp-1252"); iconv(cd, &inbuf, sizeof(inbuf), &outbuf, sizeof(outbuf)); // <- psuedocode, change to meet your needs ```
Sample code snippet ``` const const const int x = 10; int main() {} ``` gets compiled in C but not in C++. Why does it get compiled in C? I thought this would fail in C as well. Never mind. Which part of the C++ Standard forbids the use of duplicateconstand which part of the C standard allows this?
C99 §6.7.3/4: If the same qualifier appears more than once in the samespecifier-qualifier-list, either directly or via one or moretypedefs, the behavior is the same as if it appeared only once. Yes, that is valid C99, and your discovery is correct.
Apple's non-standard language extension, "blocks" (like closures) isn't supported by the parser in Netbeans 7. I'm a bit unsure as to why this is, since I thought the parser just relied on the compiler. Is it possible to get Netbeans to recognize the block syntax in any way? Xcode 4: Netbeans 7:
Most syntax highlighters do not depend on the compiler in that they do not use compiler outputs. In the general case, most have some type of logic or rule that does the syntax highlighting at runtime.Otherwise you would have to wait to compile the program to have highlighting.
i'm practicing c and looking to use visual studio. but can I write console C programs and debug it step by step? (i use debug for understading algorithms step by step) thank you.
Yes, you can. Start off with the c++ version (if you are using Express), it supports c as well. Visual Studio has a very good debugger and will allow you to step through your code.
How can I make it so my window never gets any smaller than x,y? Which WINAPI function can do this? Thanks
You reply toWM_GETMINMAXINFOand fill in the structure with your limits.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a book, tool, software library, tutorial or other off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.Closed9 years ago.Improve this question I'm trying to find the fundamental frequency of a recorded sound using FFT in C. Would anyone know a open source implementation in C that I can modify and use? Thanks!
FFTWis probably what you are looking for.
I want to find the size of file on disk on linux OS . I know command to do so: du -s -h Is there any way to find it using c/c++ code ?
Yes, use thestat(2)system call: ``` #include <sys/stat.h> ... struct stat statbuf; if (stat("file.dat", &statbuf) == -1) { /* check the value of errno */ } printf("%9jd", (intmax_t) statbuf.st_size); ```
I got problem. Seriously i need help. I directory SavedGames i got 5 folders aabblolgraaffdzzzz And here simply code in C to read what folders are in "SavedGames" and simly put in on screen. ``` #include <stddef.h> #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <windows.h> int main (void) { DIR *dp; struct dirent *ep; char *array[4]; int i = 0; dp = opendir ("SavedGames/"); while (ep = readdir (dp)) { array[i++] = ep->d_name; } closedir (dp); puts(array[0]); puts(array[1]); puts(array[2]); puts(array[3]); system("pause"); return 0; } ``` It returns zzzz, zzzz, zzzz, zzzz, zzzz. It seems this is simply error, but i spend on it 2 hour!! :( Thanks
You have forgotten to allocate memory space while storing the directories. ``` array[i] = (char*) malloc(strlen(ep->d_name) + 1); strcpy(array[i], ep->d_name); i++; ```
I am reading a file of integers. I want to save integers from each line to a new array. For this I want to detect a new line of a file. If anybody knows this please help. The file to be read is as follows ``` 1 2 4 5 6 7 3 2 5 8 3 9 7 6 2 ```
Why not usefgets()to get one line at a time from the file? You can then usesscanf()instead offscanf()to extract the integers.
I'm looking for a GIS/Geometric algorithm: I have 1000 points randomly distributed in a large area(such as a city), How can I find out all the small areas which have more than 15 points? Like this picture below: Each point has its own latitude and longitude coordinates. The small area less than 200m x 200m.
You should take a look at RTREE structures. Seehttp://en.wikipedia.org/wiki/R-tree You've such algorithms implemented e.g. in the SQlite3 engine. Seehttp://www.sqlite.org/rtree.html Our Open Source version already includes the RTREE extension for Delphi 6 up to XE,compiled by default since rev. 1.8.
What is the most optimized way of retrieving key and values from a stringI havechar *stringRow="thisIsKey1=ThisIsValue1&thisIsKey2=ThisIsValue2"I have above string from which I need to extractchar *keyandchar *valueWhich will go in loop until we extract all the key value pairs from the string. Key and value pairs are divided by&character there can bennumber of key and values in the string. Also, keys and values are of different lengths. How to do this using simpleC? Any example would help. ***UPDATE:I think better way of doing it usingsscanfparsing. can some one tell me how to parse this string usingsscanfformating.
First go with Noufals comment. Otherwise I assume a strtok with "=&" as delimter set should work. And then iterate over the array and build the value pairs. Be aware though that this does not handle the delimiters included in the key or value values. You need to escape or transcode these.
I have a code which suppose to read an integer from a file. But its actually reading as an character. Suggest me some modification where I can read the integers into an array. ``` fptr =fopen("path","r"); while(1) { c=getc(fptr); putchar(c); if (c==EOF) exit(1); } ``` Thanks in advance Amit
``` #include <stdio.h> int main(int argc, char **argv ) { int value; FILE *fp = fopen ( "d:\\abc.txt", "r"); while ( fscanf(fp, "%d", &value) == 1 ) { printf ( "%d\n", value ); } fclose ( fp ); } ```
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. Is there a way to avoid writing to file, and keep a table in main memory?, using C/C++ and SQL Server 2008?
If you mean whether there is an in-memory version of the SQL Server, like TimesTen for Oracle the answer is no. If you mean a 'little' database that you can add to your App see MS SQL Compact Server. If you mean using memory mapped files instead of a database, see here:http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile(VS.100).aspx Otherwise, please be more specific in your question! hth Mario
I already did the hard part of adding a system call to the linux kernel. I need to return the following array:unsigned int counts[4]I can reference the array as curr->counts, but I don't think there is a return value for that, and I think it is bad to give a pointer into kernel space?Instead I'm thinking the best way is to return void and pass by parameter. Is that the way to go?
See the kernel routinecopy_to_user (). Design the system call interface to pass a parameter which is a pointer where to return the data. You are trying to do something like theread()orgettimeofday()system calls, right? Those all return more than 32-bit results by usingcopy_to_user().
I have a hex value stored in a two byte array: ``` unsigned char hex[2] = {0x02, 0x00}; ``` How can I convert this to a decimal value?
You can use (bitwise operation) int b = (hex[0] << 8) | hex[1]; or (simple math) int b = (hex[0] * 0x100) + hex[1];
I have an array of strings defined like this: ``` char** arrNames; ``` Now I want to dynamically allocate a size to it. I have a function that receives the new size and the array above. It goes like this: ``` char** AddName(char** arrNames, int nNameCount) { char** arrTemp; arrTemp = new char[nNameCount]; ... // And later I change the pointer of arrNames to arrTemp } ``` Now this obviously doesn't work. So what should I be doing instead? Thanks in advance.
If you want nNameCount strings, you need to allocate an array of arrays of chars (i.e an array of strings): ``` char** AddName(char** arrNames, int nNameCount) { char** arrTemp = new char *[nNameCount]; for (int i = 0; i < nNameCount; ++i) arrTemp[i] = new char[STRING_SIZE]; ... } ``` After this you can access each string with arrTemp[index]. Note that you still need to initialize each string.
If I have the following: ``` /** * @brief (x,y,z) points for block */ int x, y, z; ``` It will only generate that documentation for x, is it possible in doxygen to get it to comment all x, y and z with one comment? EDIT Following the suggestions of envu I now have the following (based offhttp://www.doxygen.nl/manual/grouping.html#memgroup) ``` //@{ /** some documentation here */ int x, y, z; //@} ``` or ``` //@{ /** * @brief some documentation here */ int x, y, z; //@} ``` However both of these still only document x. Trying it with different forms I have yet to get the same documentation string to span multiple variables
Been banging my head on this one for a while. Turns out you have to setDISTRIBUTE_GROUP_DOC = YESin the configuration.
I encountered a piece of assembly code in a C program I was trying to run in FreeBSD 64-bit. ``` void *curbrk; __asm__ __volatile__( "movl .curbrk, %%eax;" "movl %%eax, %0" : "=r" (curbrk) :: "%eax" ); ``` I get an error like "mov missing suffix or operand".(The above code follows AT&T syntax) What determines the syntax i should use for the code - The compiler (gcc follows AT&T syntax) or the processor (I'm working on an Intel Processor). Is the problem due to the fact that the code is in AT&T syntax or is there anything else I'm missing?
If you have a 64-bit GCC, the above code will not complete unless you use the -m32 switch to output 32-bit object code, because the 64-bit pointer value will not fit into the 32-bit EAX register. Either use -m32 to generate 32-bit output, or use rax inplace of eax and change the movl's to mov (without 'l')
I am trying to use_findfirst()Windows API in C to match file name using wildcards. If I am passing????????.txtthen I am expecting it will match all the files in a directory with 8 characters only, but it matches more than that. Is there any thing wrong with this usage?
I would guess that it is matching on the short name. On windows all files have a long name and a DOS 8.3 short name. Therefore "????????.txt" is effectively the same as "*.txt". Also on a pedantic note, _findfirst() is not part of the Windows API. Is it part of the Microsoft C run-time library.
There is one var named "users" in one process and the process fork some child processes, I want know how could these child processes access the "users" variable ? BTW:The variable will be modified by parent process in runtime
You want to use shared memory. You will needto opena file, usethisto set the length (probably sizeof(*var)),mmapit. Do this before the fork. After you are finishedunmap it,close the file, andunlinkthe shared file. ``` void *mem; int shm_fd; shm_fd = shm_open("file", O_CREAT | O_RDWR, 0644); ftruncate(shm_fd, sizeof(int)); mem = mmap(0, sizeof(int), PROT_WRITE | PROT_READ, MAP_SHARED, shm_fd, 0); /* fork it, use it */ munmap(mem, sizeof(int)); close(shm_fd); shm_unlink("file"); ```
I have this piece of code in one of my file: ``` switch ([sender tag]){ ... case 100: UIView *v1 = [UIView alloc] initWithFrame blabllabla... [v1 bla bla bla... break; ... ``` Looks pretty standard huh? But it gives me this error: ``` "Use of undeclared v1" ``` Then i put an "NSLog()" or "if" statement, like this: ``` case 100: NSLog(@"why need a nslog here?"); ``` or ``` case 100: if(1==1) { ... ``` Then it works. Anyone know why is that? Is it my code or objective-c rules?
You cannot declare variables whose scope is limited to acasewithout using a C block. Change it to: ``` case 100: { UIView *v1 = [UIView alloc] initWithFrame blabllabla... [v1 bla bla bla... break; } ``` and it should work.
I have a check in my program to see if the user supplies the right amount of command line arguments. If they do not, I print a usage message and then exit the program. However I'm not sure if I should exit with EXIT_SUCCESS or EXIT_FAILURE - it appears that they both have some merit in terms of their english meaning. Is there an important distinction? What should I do?
I personally useEXIT_FAILURE, since it's not a normal usage of your program.
This question already has answers here:Closed12 years ago. Possible Duplicate:Undefined Behavior and Sequence Points What is the outcome of the following code: ``` #include <stdio.h> int main() { int a = 3; a= (a = 2) + (a = 3); printf("%d", a); } ``` Why do I get 6 as the output on gcc? Why not 5?
You're both writing and reading variableabetween sequence points, so the result is formallyundefined behavior. Looking at the assembly code generated by your particular compiler will make it clear why you get a particular result, but the standard makes no guarantees at all.
I'm writing a program that takes a single command line argument. This argument needs to be in the range [0, INT_MAX]. What is the best way to take argv[1] and convert it into an int, while ensuring that it will be a valid integer?
argv[1]is the first commandline arg andstrtoul()converts to an unsigned integer Also argc is the number of arguments, so check it is at least 2 (argc counts the program name) before callingargv[1] Strictly strtoul() is c++ but most c compilers support it in their standard library, it takes a 'c' style char * string
is there a try-catch statement in C? or an external library someone made? would be very useful if not, is there a way one can determine if a variable is an array?
is there a try-catch statement in C? or an external library someone made? would be very useful On Windows there is SEH, but you really shouldn't use that for general application usage. Without something like C++ destructors it's impossible to write truly exception safe code. if not, is there a way one can determine if a variable is an array? Yes. You keep track of it yourself.
On my Linux box it shows up as^A,CTRL-Awhen ivithe file. While writing a C program, how should i reference it? How can i find out a numeric value of it?
Control characters are 0x40 less than their character.Ais65, so^Ais1.
After havingdownloadeda Linux Man Page Viewer, I am not seeing the actual man page when hovering over a function. Should i enable it somehow? Is where a menu item i should be using? Please advise
Looks like it requiresCDT5.0.1 and depending on the version of Eclipse you have installed it may not be included. What Eclipse package do you have installed?
Coming from Java environment, I feel I got spoiled a lot when it comes to documentation. In C, using Eclipse, mouseoverputchar()shows: ``` __CRT_INLINE int __cdecl __MINGW_NOTHROW putchar(int __c) { return (--stdout->_cnt >= 0) ? (int) (unsigned char) (*stdout->_ptr++ = (char)__c) : _flsbuf (__c, stdout);} ``` While all this is terrific, I was wondering if any IDE includes more information about the specifics of what a given function does, ie, "prints a character to the output device"? Something similar tothisas part of an IDE would be awesome. Is there a way to get this level of detailed as part of Eclipse or any other IDE? The question, obviously is not aboutputchar(), but rather is about a general approach to documentation using C programming language.
NetBeans will show you the man page inline:http://netbeans.org/kb/docs/cnd/navigating-editing.html
i wrote amemoizedcode for computing factorial of a number in C . But on giving the input asn=3it gives the output as6! = 134513904.Can someone please explain what is going wrong? ``` int fact(int n) { int temp; static int lookup_table[100]; if(lookup_table[n]) return lookup_table[n]; else if(n == 0 ) { lookup_table[0]= 1; return 1; } else { temp = n * fact(n-1); lookup_table[n] = temp; return temp; } } ```
One problem could be that you don't ever initialize your table, so it is filled with whatever happens to be in memory. Edit: Ah, it seems I'm wrong and that the behavior is well defined: If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant. Source
The readln reads until the end of line (enter pressed) with spaces and everything, I would like something like that but for ansi c (not c++ and need to be for linux and windows) I know that I can make a function that reads every char until the enter pressed but If there is anything cooler it would be great =D Thanks!
Fromherethere is fgets that does this.
I would like to store 4 char (4 bytes) into an unsigned int.
You need to shift the bits of each char over, then OR combine them into the int: ``` unsigned int final = 0; final |= ( data[0] << 24 ); final |= ( data[1] << 16 ); final |= ( data[2] << 8 ); final |= ( data[3] ); ``` That uses an array of chars, but it's the same principle no matter how the data is coming in. (I think I got the shifts right)
how to count number of occurrences of 1 in a 8 bit string. such as 10110001. bit string is taken from user. like 10110001 what type of array should be used to store this bit string in c?
Short and simple. Usestd::bitset(C++) ``` #include <iostream> #include <bitset> int main() { std::bitset<8> mybitstring; std::cin >> mybitstring; std::cout << mybitstring.count(); // returns the number of set bits } ``` Online Test at Ideone
I'm new at C and a bit at this site. We were asked to balance symbols using stacks in C. I have a function push and pop which adds and deletes the symbols to be balanced, respectively. Whenever the string contains a {, (, [ or < symbol it pushes the single char to the stack. Else, it pops it. If at the end of the whole process, the stack is empty, it means the string entered is balanced. ``` if(string[i] == '(' || string[i] == '{' || string[i] == '[' || string[i] == '<') push(string[i], s); else pop(s); ``` However, when I view it, the terminal prints numbers instead of the pushed symbols. Here is my view function: ``` int i; for(i = 0; i < (s->tos + 1); i++) printf("%d ", s->arr[i]); ```
You want to tell printf to print a character not a decimal ie. ``` printf("%c ", s->arr[i]); ```
I did a basic helloWorld system call example that had no parameters and was just: ``` int main() { syscall(__NR_helloWorld); return 0; } ``` But now I am trying to figure out how to pass actual arguments to the system call (ie. along). What is the format exactly, I tried: ``` int main() { long input = 1; long result = syscall(__NR_someSysCall, long input, long); return 0; } ``` Where it takes alongand returns along, but it is not compiling correctly; what is the correct syntax?
Remove the type names. It's just a function call. Example: ``` #include <sys/syscall.h> #include <unistd.h> int main( int argc, char* argv[] ) { char str[] = "boo\n"; syscall( __NR_write, STDOUT_FILENO, str, sizeof(str) - 1 ); return 0; } ```
The matrix X is: ``` aa bb cc dd ee ff gg hh ii ``` and can be indexed as X[0][1] my question is how to represent a string matrix in C? I know char ***matrix, but I don't know the details
A string is represented in C as an array of chars, so actually this is a three-dimensional matrix: ``` char string_matrix[ROWS][COLUMNS][STRING_LENGTH] ``` or ``` char*** string_matrix ```
Possible Duplicate:What is a “translation unit” in C++ Possible duplicate:What is a "translation unit" in C++ x.h : ``` void f(); ``` x.c : ``` void f(){} ``` main.c : ``` #include"x.h" int main(){ f(); } ``` then I use: gcc -o a.out main.c why it say f is a undefined symbol?
That's a linker error. You need to compilemain.candx.cat the same time, or compile them separatelywithout linkingand link the resulting object files. For example: ``` gcc -o x.o -c x.c gcc -o main.o -c main.c gcc -o myexecutable main.o x.o ```
Is there anywhere I can find side-by-side examples of dead simple C and x86 programs? The examples I've found so far on the Internet seem to jump straight from "here's Hello World in x86" to "write your own operating system!" I'm having trouble internalizing what has to happen when you do things like call a function.
I would recommend a look at GCC's intermediate assembly output, for example call ``` gcc -S a.c ``` then look at a.s Most of the time, smaller and easier to understand assembly is generated by optimizing, so you would rather use ``` gcc -O -S a.c ```
I created a socket using: socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP). According tothis, if I send simple packet several times (multiply send() and/or sendto()), I can get ECONNREFUSED. ICMP should tell that previous packet didn't arrive and ECONNREFUSED should appear. But it fails, errno doesn't report about any errors, and send() always returns number of bytes sent. UDP protocol actually shouldn't tell that packet was sent. But ICMP can give advice as I understand. So, the question is - why does it fail to receive ECONNREFUSED? Everything is done using Winsock.
There could be two reasons for this. The target machine does not (for some reason) send theICMPbackThe target machinesdoessend theICMPback butwinsockdoesn't correctly interpret it (I know that certain older Unixes did this) In short, your best bet to find out would be using a sniffer. Try wireshark and see if you get an ICMP back.
I'm going through K&R and 3-2 looks like it would be easy to get into a buffer overflow Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s. Use a switch If I replace the byte '\n' with '\' and 'n', the size of s could potentially be quite a bit bigger than the source string. I could just write this program and ignore the overflow but I would rather not. I'm having issue wrapping my head around how to handle this? I'm thinking having a fixed buffer size, perhaps something out of limit.h, and flushing the buffer to stdio when it gets full?
I believe the entire point of the exercise is to teach you that when you're dealing with something like this you either need to: Shoot too high (make a buffer double the size of the original)Take extra time (an extra pass) and pre-compute the required size of the buffer.
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. I just had a quick question for all devs out there, what does+=mean?
``` a += b; ``` is equivalent to ``` a = a + b; ``` Likewise, you have-=,*=,/=,%=,<<=,>>=,&=,|=and^=. But<=and>=mean "less or equal than" and "greater or equal than" respectively. This linkshould provide you with a comprehensive list of C operators.
I am trying to overwrite an element (of unknown size) "copyHere" with newElement, but I am having problems. I set copyHere to the chunk of the elementArr of which I want to overwrite: ``` void *copyHere = ((char *)elementArray + (i * elementSize)); copyHere = memcpy(copyHere, *newElement, elementSize); ``` I am getting an error, "invalid use of void expression". How am I misusing the void * or memcpy? From my understanding, I feed in memcpy a destination block of memory and a source block of memory and the size of the source that I want to copy. I have done this. And for void *copyHere, I have traversed through the elementArray (of unknown type, but known size elementSize) to find the block of memory I want to overwrite. Any clues?
Remove the*beforenewElement. You cannot (and do not need to) dereference avoidpointer to pass it tomemcpy.
I have a file reader, it read a text file (csv) line by line...the method work fine..I use a string tokenizer for each ';' character... I need to break the first while loop when a line start with the character 'a'.... How I can do that ?? ``` while(fgets(buffer, 1024, file) != NULL) { if (cnt>0) { char *ch; ch = strtok(buffer, ";"); while (ch != NULL) { printf("%s\n", ch); ch = strtok(NULL, ";"); } } } ``` Thanks Maxime
Try this: ``` if(buffer[0] == 'a') break; ```
I have a multithreaded C code, I want to make a global variable to be thread-private. That is each thread has it's own copy of it...what is the best way of doing so?
What you want is calledTLS. TLS is declared just like any other global (static) variable, but syntax is implementation dependent. For example: ``` // Visual C/C++ and Intel C/C++ on Windows __declspec(thread) int number; // GCC and Intel C/C++ on Linux __thread int number; ``` Boost and TBB have their own portable TLS, but it is C++, not C.
How can I write afor/whileloop inside a#definedirective in C?
You're probably looking for\to continue a macro definition across several lines: ``` #define LOOP(start, end) \ for (int i = (start); i < (end); i++) { \ printf("%d\n", i); \ } ```
Say the structure for the file I want to read looks like this: ``` typedef struct { char length; char* text; } name; typedef struct { long n_names; name* names; } file; ``` In the file there is first the number of names, followed by the list of names with dynamic lengths. So I need to allocate memory for thenamesarray, but before I can do that I first need to know the lengths of all the names. How can I work this out?
1) You could use a dynamically growing data structure (e.g., a list) and add the names you find on the go. If for some reason you don't want that, you could 2) Run through the whole file twice and determine the respective size on the first run, thereafter allocate memory you need, and finally get strings out. Note that in the example above, though, sizeof(struct name) is fixed as text is only a pointer to some other location.
Can you advice some network connection example made with glib/gio libraries. There is quite a goodreference manual, but no full example even for basic things. It will be used for simple sending and receiving files as a part of program.
How about like this? There is similar question atFetch a file from web: in GTK using C ``` #include <gio/gio.h> int main() { const gchar *uri = "https://stackoverflow.com/questions/5758770/"; GFile *in; GFile *out; GError *error = NULL; gboolean ret; g_type_init(); in = g_file_new_for_uri(uri); out = g_file_new_for_path("/tmp/a"); ret = g_file_copy(in, out, G_FILE_COPY_OVERWRITE, NULL, NULL, NULL, &error); if (!ret) g_message("%s", error->message); return 0; } ```
I am using the JNI between Java and C code to pass a byte[] array from Java to C. In C, the parameter is a jbyteArray, like follows: ``` jint Java_com_my_example_Class_getResult(jbyteArray ary, JNIEnv* env, jobject thiz); ``` Now, once I receive 'ary' as a jbyteArray, I would like to cast it to a structure, like this one: ``` struct st { int first; int second; }; ``` What is the best and safest way to do this? Should I try to convert the jbyteArray to a char array and then cast as normal, or is there a safer JNI related method for doing this?
callGetByteArrayElementsto get a pointer-to-byte, and case that to your struct. Then don't forget to make the corresponding release call.
How can I do an atomic operation on a shared memory?I have something similar to this: ``` __shared__ int a[10]; //set a if(tid<5) a[2]++; ``` Therefore 5 threads are incrementinga. How can I do this?I know that in this way I am serializing the execution of 5 threads, but how does this effect the warp? would all the threads in the warp be serialized or just the first 5?
Replacea[2]++with ``` atomicAdd( a + 2, 1 ); ``` if you can make a unsigned, you might prefer to useatomicInc()instead, but either one is going to kill performance.
Suppose my program is: ``` typedef int MYINT; int main() { MYINT x = 5; ........ do_something() ........ /* I wanna test whether MYINT is defined or not */ /* I can't use: ifdef (MYINT), since MYINT is not a macro */ ........ return 0; } ``` Actually, I encountered this problem while I was using a cross-compiler for vxworks. The cross-compiler header file included: typedef int INT. But, my stack's header file used: ``` #ifndef INT #define int INT ``` Can you please suggest how to test typedefs, whether they are defined previously or not? Thanks in advance.
I don't think you can. typedefis just atypename aliasfor the compiler.
``` #include <cstdio> int main() { int i; printf("%d", scanf("%d", &i)); } ``` Whatever number i input, i get the output: ``` 1 ``` Why is it so?
On success, thescanffunction returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read,EOFis returned. Try this as well: printf("%d",scanf("%d%d",&i,&i));
i need my client app to be able to sendto() and recvfrom() through the same port using UDP. I have discovered i can only bind one socket to the port and it's better to do it when using recvfrom(), otherwise things mess up. I want to be able to still send UDP packets through that port but binding it to a different socket is a problem as i mentioned above. What can i do ? thanks.
This should work fine. One socket bound to a port where you use recvfrom() and sendto() on the same socket. See thisexamplefrom MSDN that shows recvfrom() in isolation - right around the recvfrom() you should be able to sendto() using that same socket.
How can I compile my C source files without needing to put amainfunction within them? I get an error for the.cfiles that have no main function and don't want to have to add the main function just for compilation.
On GCC, the-cswitch is what you want. -cmeans "compile, don't link", and you get aname.ooutput file.
The matrix X is: ``` aa bb cc dd ee ff gg hh ii ``` and can be indexed as X[0][1] my question is how to represent a string matrix in C? I know char ***matrix, but I don't know the details
A string is represented in C as an array of chars, so actually this is a three-dimensional matrix: ``` char string_matrix[ROWS][COLUMNS][STRING_LENGTH] ``` or ``` char*** string_matrix ```
Possible Duplicate:What is a “translation unit” in C++ Possible duplicate:What is a "translation unit" in C++ x.h : ``` void f(); ``` x.c : ``` void f(){} ``` main.c : ``` #include"x.h" int main(){ f(); } ``` then I use: gcc -o a.out main.c why it say f is a undefined symbol?
That's a linker error. You need to compilemain.candx.cat the same time, or compile them separatelywithout linkingand link the resulting object files. For example: ``` gcc -o x.o -c x.c gcc -o main.o -c main.c gcc -o myexecutable main.o x.o ```
Is there anywhere I can find side-by-side examples of dead simple C and x86 programs? The examples I've found so far on the Internet seem to jump straight from "here's Hello World in x86" to "write your own operating system!" I'm having trouble internalizing what has to happen when you do things like call a function.
I would recommend a look at GCC's intermediate assembly output, for example call ``` gcc -S a.c ``` then look at a.s Most of the time, smaller and easier to understand assembly is generated by optimizing, so you would rather use ``` gcc -O -S a.c ```
I created a socket using: socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP). According tothis, if I send simple packet several times (multiply send() and/or sendto()), I can get ECONNREFUSED. ICMP should tell that previous packet didn't arrive and ECONNREFUSED should appear. But it fails, errno doesn't report about any errors, and send() always returns number of bytes sent. UDP protocol actually shouldn't tell that packet was sent. But ICMP can give advice as I understand. So, the question is - why does it fail to receive ECONNREFUSED? Everything is done using Winsock.
There could be two reasons for this. The target machine does not (for some reason) send theICMPbackThe target machinesdoessend theICMPback butwinsockdoesn't correctly interpret it (I know that certain older Unixes did this) In short, your best bet to find out would be using a sniffer. Try wireshark and see if you get an ICMP back.
I'm going through K&R and 3-2 looks like it would be easy to get into a buffer overflow Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s. Use a switch If I replace the byte '\n' with '\' and 'n', the size of s could potentially be quite a bit bigger than the source string. I could just write this program and ignore the overflow but I would rather not. I'm having issue wrapping my head around how to handle this? I'm thinking having a fixed buffer size, perhaps something out of limit.h, and flushing the buffer to stdio when it gets full?
I believe the entire point of the exercise is to teach you that when you're dealing with something like this you either need to: Shoot too high (make a buffer double the size of the original)Take extra time (an extra pass) and pre-compute the required size of the buffer.
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. I just had a quick question for all devs out there, what does+=mean?
``` a += b; ``` is equivalent to ``` a = a + b; ``` Likewise, you have-=,*=,/=,%=,<<=,>>=,&=,|=and^=. But<=and>=mean "less or equal than" and "greater or equal than" respectively. This linkshould provide you with a comprehensive list of C operators.
I am trying to overwrite an element (of unknown size) "copyHere" with newElement, but I am having problems. I set copyHere to the chunk of the elementArr of which I want to overwrite: ``` void *copyHere = ((char *)elementArray + (i * elementSize)); copyHere = memcpy(copyHere, *newElement, elementSize); ``` I am getting an error, "invalid use of void expression". How am I misusing the void * or memcpy? From my understanding, I feed in memcpy a destination block of memory and a source block of memory and the size of the source that I want to copy. I have done this. And for void *copyHere, I have traversed through the elementArray (of unknown type, but known size elementSize) to find the block of memory I want to overwrite. Any clues?
Remove the*beforenewElement. You cannot (and do not need to) dereference avoidpointer to pass it tomemcpy.
I have a file reader, it read a text file (csv) line by line...the method work fine..I use a string tokenizer for each ';' character... I need to break the first while loop when a line start with the character 'a'.... How I can do that ?? ``` while(fgets(buffer, 1024, file) != NULL) { if (cnt>0) { char *ch; ch = strtok(buffer, ";"); while (ch != NULL) { printf("%s\n", ch); ch = strtok(NULL, ";"); } } } ``` Thanks Maxime
Try this: ``` if(buffer[0] == 'a') break; ```
I have a multithreaded C code, I want to make a global variable to be thread-private. That is each thread has it's own copy of it...what is the best way of doing so?
What you want is calledTLS. TLS is declared just like any other global (static) variable, but syntax is implementation dependent. For example: ``` // Visual C/C++ and Intel C/C++ on Windows __declspec(thread) int number; // GCC and Intel C/C++ on Linux __thread int number; ``` Boost and TBB have their own portable TLS, but it is C++, not C.
How can I write afor/whileloop inside a#definedirective in C?
You're probably looking for\to continue a macro definition across several lines: ``` #define LOOP(start, end) \ for (int i = (start); i < (end); i++) { \ printf("%d\n", i); \ } ```
Say the structure for the file I want to read looks like this: ``` typedef struct { char length; char* text; } name; typedef struct { long n_names; name* names; } file; ``` In the file there is first the number of names, followed by the list of names with dynamic lengths. So I need to allocate memory for thenamesarray, but before I can do that I first need to know the lengths of all the names. How can I work this out?
1) You could use a dynamically growing data structure (e.g., a list) and add the names you find on the go. If for some reason you don't want that, you could 2) Run through the whole file twice and determine the respective size on the first run, thereafter allocate memory you need, and finally get strings out. Note that in the example above, though, sizeof(struct name) is fixed as text is only a pointer to some other location.
Can you advice some network connection example made with glib/gio libraries. There is quite a goodreference manual, but no full example even for basic things. It will be used for simple sending and receiving files as a part of program.
How about like this? There is similar question atFetch a file from web: in GTK using C ``` #include <gio/gio.h> int main() { const gchar *uri = "https://stackoverflow.com/questions/5758770/"; GFile *in; GFile *out; GError *error = NULL; gboolean ret; g_type_init(); in = g_file_new_for_uri(uri); out = g_file_new_for_path("/tmp/a"); ret = g_file_copy(in, out, G_FILE_COPY_OVERWRITE, NULL, NULL, NULL, &error); if (!ret) g_message("%s", error->message); return 0; } ```
I am using the JNI between Java and C code to pass a byte[] array from Java to C. In C, the parameter is a jbyteArray, like follows: ``` jint Java_com_my_example_Class_getResult(jbyteArray ary, JNIEnv* env, jobject thiz); ``` Now, once I receive 'ary' as a jbyteArray, I would like to cast it to a structure, like this one: ``` struct st { int first; int second; }; ``` What is the best and safest way to do this? Should I try to convert the jbyteArray to a char array and then cast as normal, or is there a safer JNI related method for doing this?
callGetByteArrayElementsto get a pointer-to-byte, and case that to your struct. Then don't forget to make the corresponding release call.
How can I do an atomic operation on a shared memory?I have something similar to this: ``` __shared__ int a[10]; //set a if(tid<5) a[2]++; ``` Therefore 5 threads are incrementinga. How can I do this?I know that in this way I am serializing the execution of 5 threads, but how does this effect the warp? would all the threads in the warp be serialized or just the first 5?
Replacea[2]++with ``` atomicAdd( a + 2, 1 ); ``` if you can make a unsigned, you might prefer to useatomicInc()instead, but either one is going to kill performance.
Suppose my program is: ``` typedef int MYINT; int main() { MYINT x = 5; ........ do_something() ........ /* I wanna test whether MYINT is defined or not */ /* I can't use: ifdef (MYINT), since MYINT is not a macro */ ........ return 0; } ``` Actually, I encountered this problem while I was using a cross-compiler for vxworks. The cross-compiler header file included: typedef int INT. But, my stack's header file used: ``` #ifndef INT #define int INT ``` Can you please suggest how to test typedefs, whether they are defined previously or not? Thanks in advance.
I don't think you can. typedefis just atypename aliasfor the compiler.
``` #include <cstdio> int main() { int i; printf("%d", scanf("%d", &i)); } ``` Whatever number i input, i get the output: ``` 1 ``` Why is it so?
On success, thescanffunction returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read,EOFis returned. Try this as well: printf("%d",scanf("%d%d",&i,&i));
OK, I have read about CreateFile, ReadFile and WriteFile and I know how to use these. But I could not find any tutorial or guide with an example to use them properly. How do I handle files? I want to learn about: Read strings from file.Write strings to file. How does one do that?
Here is an example: http://www.gamedev.net/page/resources/_/reference/programming/platform-specific/windows/file-io-in-visual-c-r707
I'm programming in objective-c so I can use C as well. I have an array of bytes: (eg) ``` Byte byteArray[] = {0,0}; ``` And I need to compared to another array which is hard coded. So I'm looking to do something like: ``` if (byteArray == {0,1}) { //do something } ``` But there is the error "Expected Expression" on the curly braces. Is it not possible to have an inline C array?
``` byte toTest[2] = {0, 1}; if(memcmp(byteArray, toTest, sizeof(toTest)) == 0) { ... } ``` Or the easier way: ``` if(byteArray[0] == 0 && byteArray[1] == 1) { ... } ```
All I want is to go from 'a' to 0110 0001
if you writeint i = 'a';you get you want since all numbers physically are base 2. But if it's needed to get a string with ones and zeros then here is an example ``` /* itoa example */ #include <stdio.h> #include <stdlib.h> int main () { int i = 'a'; char buffer [33]; //the variable you will store i's new value (binary value) in _itoa_s(i,buffer,2); printf ("binary: %s\n",buffer); return 0; } ```
I was asked this question in an interview. You are writing a PCI driver and you want to export the hardware-related information to the /proc filesystem. The interesting thing is that I searched the driver code and I couldn't find any call related to /proc filesystem though actually the information is exported. Is it done automatically? What is the mechanism? Can anyone please explain?
Creating entries in the /proc pseudo-filesystem is explained inLinux Device Drivers [3rd ed], chapter 4. Nowadays you probably want to consider usingsysfsinstead; it's covered in LDD3 chapter 14.
I have a simple question for a Comp Sci class I'm taking where my task is to convert a function into MIPS assembly language. I believe I have a correct answer but I want to verify it. This is the C function ``` int strlen(char *s) { int len; len=0; while(*s != '\0') { len++; s++; } return len; } ``` Thanks! ``` strlen: add $v0, $zero, $zero # len = 0 loop: # do{ lbu $t0, 0($a0) # tmp0 = load *s addi $a0, $a0, 1 # s++ addi $v0, $v0, 1 # len++ bne $t0, $zero, loop # }while(tmp0 != 0) s_end: addi $v0, $v0, -1 # undo counting of the terminating 0 j $ra ```
Yeah, you have a correct asm version, and I like the fact that you do as much work as possible before testing the value of t0 to give as much time as possible for loading from memory.
Last week I released the Linux and windows version of an application. And after the release we realized that the symbols were not stripped off, and my manager thinks (and I disagree) that it might allow the user to understand our algorithm. Anyway, now, I will have to clean-up the symbols and re-release the application. My question, What is the best way to strip symbols in Linux?What is the best way to strip symbols in Windows?
With Visual C++ (and other Microsoft compilers) on Windows, symbols aren't part of the binaries. Instead, they are stored in separate files called "Program Database" files (.pdb files). Just don't provide the .pdb files. With the GNU toolchain you would usestripto remove symbols from the binaries.
What does it mean to say that a function (e.g. modular multiplication,sine) is implemented in hardware as opposed to software?
Implemented in hardware means the electrical circuit (through logical gates and so) can perform the operation. For example, in the ALU the processor is physically able to add one byte to another. Implemented in software are operations that usually are very complex combinations of basic implemented in hardware functions.
AFAIK, neither C99 nor C++ standards are aware of shared libraries. Why is that? EDIT: What is a good practice of writing shared libs without duplicating Linux/Windows versions? Thanks.
Because a shared library is a feature of the OS. Nothing to do with any particular language.
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.
I want output to the command line (so far, in the gdb command line within XCode) to overwrite the same line. The code I'm using to print the output right now takes some things from an Objective-C method and eventually does this: ``` unsigned char _output = ...; printf("Output:%c\r",_output); fflush(stdout); ``` It prints the correct output, but on successive lines instead of overwriting. What could the problem be?
The GDB console in Xcode is not a full-featured terminal emulation. It's intended to support interaction with GDB, and that's it. How control characters are handled is going to depend on the terminal emulator you use. What happens when you run the tool from the commandline directly using Terminal.app? What about xTerm? rxvt?
I'm a new in both C and Python. These days, I'm learning to embed Python in C. As I am calling Python functions from C, I'd like to know, how can we pass a C structure to Python? thanks alot in advance!
The cleanest thing to do is probably tocreate a new typeand implementtp_getattr, either returning the appropriate member of the struct or raising an exception depending on the argument passed.
I have adoxygengeneratedhtmlfiles. I would like to know the mappings between the originalC/Javafile to itshtmlcounterpart. I was able to do it with some dirty tweaking of file.text in latex folder. Any other approach?
You can use theGENERATE_TAGFILEfeature to let doxygen create a so-calledtag file. That's just an XML file which contains the mappings. I didn't find a formal description of the XML dialect, but it seems easy enough. Here's one for libstdc++:http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/libstdc++.tag
I am new to OpenGL and I have been doing some tutorials utilizing GLUT. GLUT seems to be quite clunky and "old-fashioned" (if you know what I mean :D) so I am asking if there are a bit more straightforward and easier (perhaps more intuitive) libraries to substitute GLUT functionality?
Sounds likeGLFWis what you are looking for. It is pretty simple library but much more intuitive than GLUT. It has basic support for keyboard, mouse and joystick inputs too. It is also a pretty small library so it does have small overhead too. Typically GLFW adds only 20-30kb overhead if linked statically. Portability is excellent too, platform support includes all major desktop platforms (Windows, Mac OS X, Unix like system with X Window System such as FreeBSD and Linux).
I want to read a string through keyboard to avoid buffer overflow. When i usedfgets(text,30,stdin), it reads but it also reads '\n' character. But i don't want to read '\n' character.
``` char s[30]; scanf("%30[^\n]", s); ``` a little explain: %30[^\n] 30which means read at most 30 chars,[^\n]which means read any char except '\n'.