question
stringlengths
25
894
answer
stringlengths
4
863
my code is : ``` #include <stdio.h> void main( int argc, char** argv) { printf("%s", argv[0]); system("pwd"); } ``` The output is: ``` [river@localhost studio]$ ./a.out /home/river/Desktop/studio ./a.out[river@localhost studio]$ ``` It seems that system("pwd") print first , then print argv[0] . why? If I ...
Theprintfcall only puts the output in a buffer. For the buffer to actually be written it needs to beflushed. Output is automatically flushed when you print a newline, so if you replace the format-string inprintfwith this:"%s\n"it should work without the call tofflush.
I have a int that has values like 1235 and 12890. I want only the 1st 2 digits from this int. How can I extract it? I thought for some time and couldn't come up with any solution.
Reduce the number until you only have two digits left: ``` while (n >= 100) n /= 10; ```
This question already has answers here:Closed11 years ago. Possible Duplicate:Floating point comparison When I run the code below I get the following output: Output : if Why does this happen? ``` #include <stdio.h> void main() { float a = 0.7; if(a<0.7) { printf("if"); } else { ...
Your program compares thedoublerepresentation of0.7(which is what the compiler produces when you write0.7in your program) with afloatrepresentation of0.7(which is what variableacontains). The two are not the same, and it just happens that thedoubleone is slightly larger. EDIT:(float)0.7can be represented compactly in...
I an new at working with IPC objects with synchronization purposes for processes and threads. Is there any special way to implement a Monitor in C? (such as semaphores, pipes, sockets, etc.) Is there a special .h file that has a specific object to use here? If not, which is the best way to implement this? Thanks in...
I'd use select, it works pretty much for everything you need:http://linux.die.net/man/2/select Beyond that, I usually use the pthread style functions for mutexes/semaphores, but it's really down to what the task at hand actually is.
Has anyone had any success with libcurl and POP3 with APOP authentication? I had success with the clear authentication but not with APOP since the library sends the USER command almost immediately after making a connection. How do I make libcurl send APOP command and stop it sending USER command?
libcurl currently doesn't support APOP. You need to dive in and make it so!
Let us say I have a function which manipulates a 2D array which receives a pointer to the 2D array from the main function as its parameter. Now, I want to modify(assume add 10 to each element) each element of the 2D array. I am interested in knowing about traversing through the 2D array with a single pointer given t...
``` int* add_10(const int *dest, const int *src, const int M, const int N) { int *idest = dest; memmove(dest, src, M * N * sizeof(int)); for(int i = 0; i < (M * N); ++i) *idest++ += 10; return dest; } ```
I'm trying to analyse some code (not written by myself) which callsreadlinkwith a positivebufsize, and then tests if the result is zero. I can't see how the result can be zero, with everything I've tried it is either -1, size of the real link or size of the soft link. Can the result be zero, and if so how?
According tospec Upon successful completion, readlink() shall return the count of bytes placed in the buffer. Otherwise, it shall return a value of -1, leave the buffer unchanged, and set errno to indicate the error Here two possible answers it is highly possible that you've found the bug in implementation (author ...
``` void start() { stuff(); //code before mainCRTStartup mainCRTStartup(); } int main() { //other code } ``` In Visual C++,it compiles fine and function "stuff()" gets called before main. How would call "stuff()" before "mainCRTStartup()"? on Mingw(OS:Windows NT)? it seems to ignore "void start()".
You could use the -e argument told(the linker) to specifystartas your entry point. I'm not sure how to feed arguments toldusing mingw; perhaps someone can edit my answer to provide that.
I m trying to assign a value to string pointer.It's compiling and running but not printing the correct answer? ``` char *x = "girl"; *x = x[3]; printf("%s\n",x); ``` Why it's not printing "lirl" ?
You cannot modify a string literal like that. It is undefined behavior. You should do this instead: ``` char x[] = "girl"; x[0] = x[3]; printf("%s\n",x); ``` This works because"girl"is now an array initializer forx[]. Which is just a short form for: ``` char x[] = {'g', 'i', 'r', 'l', '\0'}; ``` So this is allow...
I am working on my data in a C/C++ program, which is 2 dimensional. Here my value is calculated for pair-wise and here values would be same forfoo[i][j]andfoo[j][i]. Thus if I implement it by using a simple 2 dimensional array, half of my space would be wasted. So what would be best data structure to represent this l...
If you have N items then a lower triangular array without the main diagonal will have (N - 1) * N / 2 elements, or (N + 1) * N / 2 elements with the main diagonal. Without the main diagonal, (I, J) (I,J ∈ 0..N-1, I > J) ⇒ (I * (I - 1) / 2 + J). With the main diagonal, (I,J ∈ 0..N-1, I ≥ J) ⇒ ((I + 1) * I / 2 + J). (A...
My application creates a in-memory database (:memory:) using sqlite as a back end. I want my master thread to create a connection to a in-memory database and this connection to be shared by multiple threads. Is this possible? SQLite 3.7.8 is available for download right now. Isthe shared cacheda possible way to go?...
If you open the connection to your in-memory database usingserialized mode, then the connection may be shared among multiple threads. For this to work, your SQLite must be compiledthreadsafe-- this is the default. Depending on your application, you may get better performance with a large shared cache to an on-disk d...
How can I make sure that a pipe is closed when my C program is stopped by a SIGINT?
You could usesignal handlingfor that: ``` #include <signal.h> void sigHandler(int sig) { // Respond to the signal here. } int main(..) { signal(SIGINT, &sigHandler); .. } ```
I want to remove the repetition in this code: ``` printf( "%.2f: %s\n", 440.00f, "A4" ); printf( "%.2f: %s\n", 523.25f, "C5" ); printf( "%.2f: %s\n", 880.00f, "A5" ); printf( "%.2f: %s\n", 1046.50f, "C6" ); ``` My plan is to make a list of pairs and loop over it. Is it possible and a good solution, or should I ju...
Just make an array of structs: ``` struct pair { double num; char str[32]; }; struct pair pairs[10] = { {440.00f, "A4"}, {523.25f, "C5"}, /* ... */ }; /* C99. */ pairs[2] = (struct pair){880.00f, "A5"}; pairs[3] = (struct pair){ .str = "C6", .num = 1046.50f }; for (i = 0; i < sizeof(pa...
I am kind of new to c , but i cant figure out how to send this string to the function. I tried several things but it tells me it is expecting something ``` program.c: In function ‘main’: program.c:48:87: error: expected identifier or ‘(’ before ‘long’ char string1[] = "This is process %d with ID %ld and ...
I think you meant to usesprintf: ``` int length = 100; char string1[length]; if(sprintf(string1, "This is process %d with ID %ld and parent id %ld\n", i, (long)getpid(), (long)getppid())) { write(wrfd1,string1, length); } ```
sometimes we use this type of code in our c programming. ``` char *p = "Sam"; ``` Here the address of constant character string "Sam" is going to be stored in char pointer p. now herei want to ask where the Sam is going to be stored ?
The string "Sam" will usually be stored in global memory in the same region as the global constants. However, if you did this: ``` char p[] = "Sam"; ``` Then it would be on the stack instead. (as an array initializer)
I think I am not clear about when and how read/write blocks for various kind of files. (disk file, pipe, socket, FIFO) Could any one explain for both read and write scenarios of each file type? Thanks!!
For a disk-based file,readandwritemay block briefly while the requested read/write is performed. Areadat the end of a file will always return a short result, and awriteto a file on a full FS will fail -- barring various unusual circumstances,read/writeto a plain file will never block indefinitely. For pipes, sockets,...
I am using ar.h for the defining the struct. I was wondering on how I would go about getting information about a file and putting it into those specified variables in the struct. ``` struct ar_hdr { char ar_name[16]; /* name of this member */ char ar_date[12]; /* file mtime */ char ar_uid[6]; ...
You're looking forstat(2,3p).
sizeof(long) returns 8 bytes but the &along (address of a long) is 12 hex digits (48-bits) or 6 bytes. On OS X 64-bit compiled with clang. Is there a discrepancy here or is this a genuine 64-bit address space?
In effect modern systems use 64 bit for addresses but not all of these are used by the system since 2 to the 64 is an amount of memory no one will use in a near future. Under linux you can find out what your machine actually uses by doingcat /proc/cpuinfo. On my machine I have e.g address sizes : 36 bits physical, 48...
Why does this particular piece of code return false on the strstr() if I input "test"? ``` char input[100]; int main() { fgets(input, 100, stdin); printf("%s", input); if(strstr("test message", input)) { printf("strstr true"); } } ``` I thought strstr searched the first param for ins...
It's because fgets stores the newline character so when strstr does a comparison it fails. From the man page: fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored ...
I have a question about the buffering in standard library for I/O: I read "The Linux Programming Interface" chapter 13 about File I/O buffering, the author mentioned that standard library used I/O buffering for disk file and terminal. My question is that does this I/O buffering also apply to FIFO, pipe, socket and net...
Yes, if you're using theFILE *based standard I/O library. The only odd thing that might happen is if the underlying system file descriptor returns non-zero for theisattyfunction. Then stdio might 'line buffer' both input and output. This means it tends to flush when it sees a'\n'. I believe that it's required to line...
I would like to write a program that keeps asking for user input until I break out of it with ctrl+D. Here is what I have: ``` char input[100]; while(input != EOF){ printf("Give me a sentence:\n"); fgets(input, 5, stdin); printf("your sentence was: %s\n", input); } ``` I would like the fgets to ...
I think you are looking for the function feof. ``` char input[100]; while(!feof(stdin)){ printf("Give me a sentence:\n"); fgets(input, 5, stdin); printf("your sentence was: %s\n", input); } ```
Should I free up memory returned by the following two functions in the caller function? I see that it is ok with functionget_current_timebut not ok with theget_filename_ext. I see similar questionhere, but not sure that answers my question. In general what should I look for? ``` char *get_current_time(void){ stru...
Neither of these functions allocate any memory. So there's actually nothing to free. Thechar*returned byasctimeis an internal buffer. So you can't free it anyway.
I am doing an assignment, which require to develop a simple text editor using C/C++. But it is a GUI application, which may port to different platform, for example, windows, linux and mac. Please recommend a ui framework to serve the purpose. Thanks.
Qtis a cross-platform application and UI framework for developers using C++ or QML, a CSS & JavaScript like language. Quoted fromqt-project.org
I have a structure as follows: ``` struct something{ char *string_member; }; ``` now I created ``` struct something *s = malloc(sizeof(struct something)); s.string_member = malloc(5); //one way s.string_member = "some thing wrong"; // second way ``` While I free the memory pointed by s. How do I free the memor...
You mustn't free it in yoursecond wayexample, and you have no way to (portably) make the difference between case one and case two by just looking at the pointer. So don't do that, make sure you always allocate thestring_memberusingmallocor e.g.strdup. That way, you can alwaysfreeit (once). ``` s.string_member = strdu...
So here's my code ``` int find_h(int i, int j, int current[N+1][N], int goal[N+1][N]) { int sum=0; int a, b; int cp[N*3], gp[N*3]; for(a=0;a<N;a++) { for(b=0;b<N;b++) { cp[4*a+b]=current[a][b]; gp[4*a+b]=goal[a][b]; printf("b = %d\n", b); } printf("\n"); } return sum; }...
I think your loop is overwriting memory. if N = 4 then you are allocating cp[12] and gp[12]. Yet when a = 3 cp[4*a+b] and gp[4*a+b] both are [12] which is past the end of the array
I downloadedhttp://sites.google.com/site/zigmar/notepad2withluasupportsource code, opened it in VS2008 and when compiling I got Error 1 fatal error C1083: Cannot open source file: '.\scintilla\win32\ScintillaWin.cxx': No such file or directory c1xx Notepad whereas \scintilla\win32\ScintillaWin.cxx does exis...
I downloaded the sourcecode from the link you provided, however in the project the file is present, in the zip/directory tree the scintilla directory is empty.
As title stated, I'm writing function taking 2 boolean as parameters but don't know what is the best way to do! What are your suggestions?
c99 already provides thebooldata type if you are using that, you can use it directly. Else another ways are: Simple way: Use integers and treat 0 as false and 1 as true. Verbose way: Create enum with true and false names and use that. Code Sample: ``` typedef enum { FALSE = 0, TRUE = 1 }Boolean; int doS...
As we know that 4294967295 is the largest number inunsigned intif I multiply this number by itself then how to display it? I have tried: ``` long unsigned int NUMBER = 4294967295 * 4294967295; ``` but still getting 1 as answer.
You are getting an overflow. Consider the muplication in hexadecimal: ``` 0xffffffff * 0xffffffff == 0xfffffffe00000001 ^^^^^^^^ only the last 32 bits are returned ``` The solution is to use a larger type such aslong long unsigned: ``` long l...
``` void * bsearch ( const void * key, const void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) ); ``` If I pass in aconst void * base, shouldn'tbsearchalso return aconst void *result?
When you search for something, it's a valid request that you be able to modify it after you found it. It would be too restrictive if the search function didn't allow you to do that. Of course such a modificationcouldbreak a subsequent search, but that's a different matter. The parameters are const as a promise that b...
I am aware of two possible ways to define and usestructs: ``` #1 struct person { char name[32]; int age; }; struct person dmr = {"Dennis Ritchie", 70}; #2 typedef struct { char name[32]; int age; } person; person dmr = {"Dennis Ritchie", 70}; ``` The interesting property of the first way is that ...
structare compatible between C & C++ only when they arePOD-s. I tend to code something like: ``` struct person_st { char name[32]; int age; }; typedef struct person_st Person_t; ```
What is the equivalent of__declspec( naked )ingcc/g++?__declspec( naked )is actually used to declare a function without any epilogue and prologue.
On some architectures, gcc supports an attribute called "naked"; the most recentgcc docsI have give this list of architectures: ARM, AVR, MCORE, RX and SPU. Ifyou are using one of those architectures (gcc will give you a warning if you try to use it and it isn't supported), the attribute can be used like this: ``` _...
I am using thepowfunction in C and storing the return value in an integer type. see the code snippet below: ``` for (i = 0; i < 5; i++){ val = (int)pow(5, i); printf("%d, ", val); } ``` herei, andvalare integers and the output is1, 5, 24, 124, 624. I believe this is because a float 25 is treated as 24.99999....
Add0.5before casting toint. If your system supports it, you can call the C99round()function, but I prefer to avoid it for portability reasons.
I want to do the equivalent of ``` ::Infinity= 1.0/0 ``` in a ruby extension which is written in C. So far I have come up with ``` rb_const_set(rb_mKernel, rb_intern("Infinity"), rb_float_new(1.0/0)); ``` which gives me a compiler warning due to division by zero. And ``` rb_const_set(rb_mKernel, rb_intern("Infin...
I found the answer in thisquestion. ``` rb_const_set(rb_mKernel, rb_intern("Infinity"), rb_float_new(INFINITY)); ``` There are no compiler warnings for this.
character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. Suppose at some point the user types a backspace, how can you remove the character efficiently. one solution that came in my mind is that there is no need to think about one b...
What do you mean first bit?In the 2-octet value0xfade(0b1111101011011110) is the first bit a0or a1? Anyway, you can arrange to write the values in little-endian or big-endian format to have the "first bit" always written last. By examining only the last octet written you know whether to delete 1 or 2 octet.
In a#defineone can useA ## Bto concatenate preprocessor variables and defines to an identifier. ``` #define ADD_UNDERSCORE(X) X##_ /* ADD_UNDERSCORE(n) -> n_ */ ``` Is there an equivalent leftside of the #define? E.g. ``` #define A a #define B b #define A##B(X) X /* ab(n) -> n */ ```
No. In a macro definition, the first token after thedefinehas to be an identifier ((draft) ISO/IEC 9899;1999, 6.10, page 149). There is no other preprocessing of the#definedirectives which could make an identifier out of something else. In particular, the standard specifies (6.10.3): The preprocessing tokens within ...
How to convert an OpenCVcv::Matinto afloat*that can be fed intoVlfeat vl_dsift_process? I cannot understand howvl_dsift_processworks on a one-dimensional float array. The official samples only demonstrate how to use MatLab API. It seems that there are no samples about C API, and the only clue is the MEX file in the so...
float* matData = (float*)myMat.data; Make sure the matrix is not deleted/goes out of scope before finishing using the pointer to data. And make sure the matrix contain floats.
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.Closed11 years ago. Is C standard library function(ex.p...
it depends on how you link your program. you can go both ways. On VS, you can specify either/MT(static) or/MD(dynamic). On gcc, you can specify-static-libgccflag to link your program against the static library. Refer tohttp://gcc.gnu.org/onlinedocs/gcc/Link-Options.htmlfor more info on gcc flags andhttp://msdn.micros...
Do you know some open-source very tiny SQL server implementation possibly in 1 *.c (or several) file without external dependencies ? Implementation should be very basic - support of most simple forms of select/insert/delete/update... No DDL is needed (albeit it would be good to have). Only basic 1 user at-a-timer oper...
The obvious choice isSQLite. You can add "-DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION" to avoid external dependencies.
Im really new to C and just got Codeblocks to compile/run any code that I write and I can't make it run this block of code. ``` #include <stdio.h> int main() { printf("\nHello, world!\n"); return 0; } ``` If someone could list out how to make it do something it would really be appreciated (Maybe its just m...
Select File->New->Project from the menu From the "New from template" window, select "Console application" Run through the wizard and give your project a title. (Select defaults if you don't know what to set) From the workspace manager (shift+F2), expand the dropdown through your project,the sources folder, and sele...
Can alphanumeric values be stored in an int data type or do we need a char to store it?
Alphanumeric values are not values. They are numbers like everything else, but they follow a specified mappingnumer -> character. For example character 'A' is65according to ASCII encoding. The only difference is how you treat them: if you treat them as numbers then you print out them as numbers, otherwise you print t...
I wrote a program in windows that will play binary audio sent to it over stdin, I called it aplay(like the linux program). I then wrote a seperate program as follows ``` FILE * f = popen("aplay.exe", "wb"); FILE * song = fopen("C:/Users/Ray/Dropbox/DJ Automica 2/Debug/raymonster 5.wav", "rb"); while(1) { byte buf...
If you include the header files ``` #include <fcntl.h> #include <io.h> ``` you can switch modes with ``` _setmode(_fileno(stdin), _O_BINARY); ```
I want to know how to get the IP address of a client who connects to a socket on a server using accept. How would I do this? getpeername returns a wrong IP address, and I can't seem to find another way to do it. On the server, after accept returns, I'm doing this: ``` char buf[INET_ADDRSTRLEN]; struct s...
The 2nd parameter of accept has this information.
So i wrote this in C, so sscanf scans in s but then discards it, then scans in d and stores it. So if the input is "Hello 007", Hello is scanned but discarded and 007 is stored in d. ``` static void cmd_test(const char *s) { int d = maxdepth; sscanf(s, "%*s%d", &d); } ``` So, my question is how can I do the ...
``` #include <string> #include <sstream> static void cmd_test(const char *s) { std::istringstream iss(s); std::string dummy; int d = maxdepth; iss >> dummy >> d; } ```
I'm using clang's libraries to write a program that will take the parsed code and put it into a structure. is there any up to date information about clang's libraries? reference and tutorial would be nice.
Have a look at thedocand atutand atut more. Edit: Anewer tutorial. Should only be 5 days old. You might want to have a look at theclang Internals Manualand thecfe-devmailing list.
What's the best way to fill a variable with an unknown (at compile time) number of ones? For example, let's say: ``` int n = 5; int b = fillwithones(5); ``` now b contains 11111 (in binary). I can't just hard code int b = 31 because n is not known ahead of time (in my application). I could do something like this:...
You can use left shift and then subtract 1: ``` unsigned int b = (1U << n) - 1U; // Broken down into steps // 1 = 00000001b // 1 << 5 = 00100000b // (1 << 5) - 1 = 00011111b ``` The reason this works is1 shifted left n timesis the same as2n, as each sole bit position represents a power of 2.
If there someone who worked with Amazon S3 API in C? I can't manage to sign my REST request proper. Can someone share his successful experience in that?
I've never tried it, but a quick Google turned upthe libs3 C library API for Amazon S3. That might make things easier, so you don't have to deal with raw HTTP requests viacurl.
I need to define an iterator structure and method in C (for a BST), so far I realise that the iterator struct must have a pointer to a current node, and possibly a parent node. Is there anything else I should have in there, or that would be good to have? Thanks
Do the BST elements have a pointer to their own parent node? If not, you'll need a stack of parent node pointers.
I thought it's possible to concatenate strings (char arrays) in C on the fly. ``` char* str1= "hello" " " "world"; ``` But when I try the following I'll receive an error message (Too few arguments to function fopen). why? ``` fopen(*argv ".comp", "r"); ``` I want to concat the argument with an char[] constant - wi...
You can only concatenate string literals at compile time. Because compiler has no idea what*argvis going to be.
I have a small console application, that asks for a values to count with (scanf function). But I wanna call this program with arguments -> so I haven't to fill it manually. My program looks like this: ``` ./a.out Give me 3 values: ``` And I have to write "3 78 63". But I want this (run the program with arguments):...
You need to parse theargvarray passed to the program: ``` int main(int argc, char **argv) { if (argc > 1) { for (int i = 1; i < argc; i++) { char *arg = argv[i]; // do something } } else { // ask for arguments via stdin } } ```
I looked through the available C-api for notes and couldn't find any API which will give me a list or views in the (notes)database which I've opened. I am coding in C. Has anyone faced similar problem and knows the solution? (Any api/documentation I might have over looked?) I have already seen the question @How to ...
NSFDbGetModifiedNoteTablecan be used. ``` STATUS LNPUBLIC NSFDbGetModifiedNoteTable( DBHANDLE hDB, WORD NoteClassMask, TIMEDATE Since, TIMEDATE far *retUntil, HANDLE far *rethTable); ``` TIMEDATESince should be set to the "beginning of time" andNoteClassMaskshould beNOTE_CLASS_VIEW More info can be foundhere
If I search for counting the number of threads an application has, all the answers involve external programs liketop. I want to count the threads within the application itself. I can't add code at the point of thread creation because it happens inside an immutable library. I can't read/proc. It's a C/pthreads progr...
If you can't read/procyou are a bit in trouble, unless your program communicate with another program which reads/proc If you don't want to read/procbecause of portability concerns, you might use a library which abstracts that a bit, likelibprocdoes
What does a statement such as this mean ? ``` int x = ( { int a; scanf( "%d", &a ); a ; } ) ; ``` It compiles and runs equivalent to : ``` int x; scanf( "%d", &x ); ``` It seems to be like some kind of anonymous function call or something, but I'm not sure. I have not come across statements like({})before, and I ...
It is anStatement Expression.It as an compiler extension supported by GCC and it is not Standard C++,hence it is non portable.If you compile your code with the-pedanticflag it will tell you so. Thisanswer of mine talks about it in detail.
i want to create a simple state machine using C but all the events in the respective states are executed using perl scripts.so is there any way to link these perl and C scripts so that when i go to a particular state in a state machine it should execute the particular function(event) defined in the perl script..how to...
If your aim is to improve the speed of an existing module by extracting out some of the heavy lifting to C functions, then try using the Perl XS interface to write (some of) a module in C. Seehttp://perldoc.perl.org/perlxs.htmlfor more information.
I have been learning to use the ncurses library and I have come across getstr(). I was wondering how you would erase the text from getstr() on the terminal after the value has already been stored in a variable? I have tried to find the answer on google but no luck! Basically I want it so when the user presses enter t...
As far as I know, ncurses has two functions,gotoxy()andgetxy(), which let you jump to every position of the screen and tell you where you are located right know. Jump to the front of the previous line and callclrtobot()to erase everything after the cursor. Edit: Since you said that clearing the entire window is an ...
I've been reading this site long enough to know not to hide that this is a homework assignment. But I am trying to write a code that can generate all possible combinations of a string of only 0's and 1's. If the length of the string is n^2, then there will be n 1's and the rest will be 0's. The length is always a p...
pseudocode: ``` myfun(pos,length, ones) if (length==0) pos='\0' #print, collect, whatever... return if (length>ones) pos='0' myfun(pos+1,length-1, ones) pos='1' myfun(pos+1, length-1, ones-1) task(n) #allocate n^2 buffer myfun(buffer, n*n, n) ```
I'm performing matrix inversion using Householder transformations acting on an augmented matrix. Currently I can only perform accurate inversions for matrix dimensions up to 4x4. After this A*A^-1 != I precisely and I think it's due to back substitution. Is there a better way to go about this?
It turns out that the 'Householder reflection with back-substitution' method is viable. When verifying that a row has zeros in the proper locations to be part of a matrix in row-echelon form, it is important to compare both the real and imaginary components of a matrix entry to zero, rather than their magnitude.
Hi here is my problem i am able to input values for my matrix as such ``` for(i=0;i<n;i++) { for(j=0;j<n;j++){ scanf("%d",&a[i][j]); ``` how ever this is very tedious for matrices of a large order and i cant get the matrix to work with pointers and the rand function ``` for(i=0;i<n;i++) { for(j=0;j<n;j++){ ...
Apparentlyais an array ofint(you are using"%d"to input values withscanf). The expression you use generatesdoubles(ranging from-1to1) that when converted tointresult in0. I guess that's what you see ina. Makeaan array ofdoubles.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
You might want to trycflow: The cflow utility shall analyze a collection of object files or assembler, C-language, lex, or yacc source files, and attempt to build a graph, written to standard output, charting the external references. It should print a callgraph and mark the recursive functions.
How do I determine if a character is a forward slash ('/ ')? I'm looking for something along the lines of: ``` if (isupper(varToTest)) {//do something} ``` but for the life of me I can't find it.
``` if (varToTest == '/') { //do something} ```
How do I determine if a character is a forward slash ('/ ')? I'm looking for something along the lines of: ``` if (isupper(varToTest)) {//do something} ``` but for the life of me I can't find it.
``` if (varToTest == '/') { //do something} ```
I got an error message of Segmentation fault (core dump) when I try to run this code. Note: This is a really long program (almost 600 lines) so I only posted the ones that I 'think' is related. Let me know if more needed? Thanks in advance :) ``` #define CONSTANT 4 int main() { pthread_t tid[CONSTANT]; int i, ch...
If you're going to cast a constant tovoid *and pass it in as your context parameter, you need to do the complementary operation on the other end: ``` int num = (intptr_t)param; ``` Should do it for you. Your current program has an extra dereference, which ends up doing something like this: ``` int num = *(int *)4;...
In a declaration such asint i, v[5], j;, how will the variables be allocated? Is the compiler allowed to change their order?
Yes, the compiler can do whatever it wants, as long as the meaning of the program stays the same. These variables might be optimized out of existence, stored only in a register, reused for other purposes, reordered for alignment requirments. (note that a compiler cannot reorder variables within a struct)
I have a C code which successfully runs under ubuntu, but when I am trying to run it on a red hat PC it is giving a "Segmentation fault (core dumped)" error. I have narrowed down the error to be from the following statement: ``` long int encryption[800000][2]; ``` this declaration is causing the code to crash. What...
Change it to ``` static long int encryption[800000][2]; ``` Or make it global, or usemalloc. Or useulimit -s.
Here is a sqlite library problem (using C) After binding parameters of a prepared statement, how can I print the SQL with the bound parameters for debugging? I google it and only find a function to print the original prepare statement.
You can't access the prepared statement after thebind(). For debug-purposes, you can sprintf the values into the sql-string and give that toprepare()thus omitting the bind-calls. What is your original sql string and what are your bind-calls?
i'm writing in C (gcc) and I have a function read_serial_device() that will be called as thread. I'm using the pthread library. Thing is in main() i call this fn and I know i don't need to wait for it to exit. so I can instantiate it in DETACHABLE state. however in other parts of the code (from another thread actuall...
Whether the thread is detached or not is a property of thethread, not the thread function... so nothing is stopping you from creating threads with different attributes that use the same thread function. The same goes for stack sizes, signal masks, and anything else you can set outside the thread function itself befor...
``` #include <stdio.h> #define N 1024 int main(){ int i, j; int a[N][N]; int b[N][N]; for (i=0;i<N;i++){ a[i][i]=i; b[i][i]=i; } for (i=0;i<N;i++) for(j=0;j<N;j++) { printf("%d", a[i][j]); printf("%d", b[i][j]); } return 0; } ``` This program is a reason of segmenta...
You are overflowing the stack.2 * 1024 * 1024 * sizeof(int)is a lot for most systems. The simplest solution would be to make the arraysstatic. ``` static int a[N][N]; static int b[N][N]; ``` Other methods: Make the arrays global (this is essentially the same as the above)Usemallocin a loop and of course remember t...
Referring to this construct, posting a full example would be a little too big: ``` __thread char* buf; buf = malloc(1000); ``` Valgrind says the bytes are "definitely" lost. Shouldn't they just be "still reachable"?
Because the allocated memory is not thread-local. It's shared by all of the threads. The variable is, on the other hand, thread local so once it's out of scope that allocated memory will be definitely lost (if there are no copies of that pointer elsewhere.. and obviously there aren't because valgrind reports definite...
My eth1 : IP adrress is something like a:b:c:d What i get in server that is router given address (public ip): e:f:g:h is there any way to find the local ip address of the system inCand must beudp
If your client is behind a NAT:ing firewall or router, then no, there's no way for the server to directly see the client's LAN IP address. Often, such addresses are "LAN only" (non-routable) e.g. 192.168.x.y or 10.x.y.z. If using your own custom protocol, then you can of course embed the information in a datagram and...
When I wish to check if a value is0in C, how is it idiomatically done? if (!num)if (num == 0)
While this is a matter of taste, I find it pretty much depends on intention. If the value is to be used as a boolean,!is alright. If the value is counting something the equality makes more sense. ``` if (!isVisible) {...} if (isVisible == 0) {...} // Intention not as clear as line above. if (numberOfItems == 0) {......
Here is a sqlite library problem (using C) After binding parameters of a prepared statement, how can I print the SQL with the bound parameters for debugging? I google it and only find a function to print the original prepare statement.
You can't access the prepared statement after thebind(). For debug-purposes, you can sprintf the values into the sql-string and give that toprepare()thus omitting the bind-calls. What is your original sql string and what are your bind-calls?
i'm writing in C (gcc) and I have a function read_serial_device() that will be called as thread. I'm using the pthread library. Thing is in main() i call this fn and I know i don't need to wait for it to exit. so I can instantiate it in DETACHABLE state. however in other parts of the code (from another thread actuall...
Whether the thread is detached or not is a property of thethread, not the thread function... so nothing is stopping you from creating threads with different attributes that use the same thread function. The same goes for stack sizes, signal masks, and anything else you can set outside the thread function itself befor...
``` #include <stdio.h> #define N 1024 int main(){ int i, j; int a[N][N]; int b[N][N]; for (i=0;i<N;i++){ a[i][i]=i; b[i][i]=i; } for (i=0;i<N;i++) for(j=0;j<N;j++) { printf("%d", a[i][j]); printf("%d", b[i][j]); } return 0; } ``` This program is a reason of segmenta...
You are overflowing the stack.2 * 1024 * 1024 * sizeof(int)is a lot for most systems. The simplest solution would be to make the arraysstatic. ``` static int a[N][N]; static int b[N][N]; ``` Other methods: Make the arrays global (this is essentially the same as the above)Usemallocin a loop and of course remember t...
Referring to this construct, posting a full example would be a little too big: ``` __thread char* buf; buf = malloc(1000); ``` Valgrind says the bytes are "definitely" lost. Shouldn't they just be "still reachable"?
Because the allocated memory is not thread-local. It's shared by all of the threads. The variable is, on the other hand, thread local so once it's out of scope that allocated memory will be definitely lost (if there are no copies of that pointer elsewhere.. and obviously there aren't because valgrind reports definite...
My eth1 : IP adrress is something like a:b:c:d What i get in server that is router given address (public ip): e:f:g:h is there any way to find the local ip address of the system inCand must beudp
If your client is behind a NAT:ing firewall or router, then no, there's no way for the server to directly see the client's LAN IP address. Often, such addresses are "LAN only" (non-routable) e.g. 192.168.x.y or 10.x.y.z. If using your own custom protocol, then you can of course embed the information in a datagram and...
When I wish to check if a value is0in C, how is it idiomatically done? if (!num)if (num == 0)
While this is a matter of taste, I find it pretty much depends on intention. If the value is to be used as a boolean,!is alright. If the value is counting something the equality makes more sense. ``` if (!isVisible) {...} if (isVisible == 0) {...} // Intention not as clear as line above. if (numberOfItems == 0) {......
Extened question fromIn multi thread application how can i redirect stderr & stdout in separate file as per thread? see some how i want to keep all printf and error/warning message produced in each thread in different log-file. ``` FILE * freopen ( const char * filename, const char * mode, FILE * stream ); ``` freo...
Since all resources are shared in a threaded application, including files, changingstdinorstdoutin one thread changes them for all threads. If you want to change it in just a single thread then useforkto create a new process instead.
I have a cross platform project where the client gets the code, but doesn't want to resolve any dependencies. The requirements are best solved with a relational database, so it seems I need to copy the source of an embeddable relational database into my program and compile the library directly into the executable or a...
SQLite They have “amalgamation” source distribution which is one C source file, which can be included into a project and used right away.
Can i go to the line of error , while compiling aC or C++project ? Usually by executingmake, and parse the error string , and go to the specific file , and the line with errors. Is there already an usable plugin ?
Yeah this is already buit into vim. After typing:maketype:cwindowto bring up the error list. You can then navigate to the errors using this window.
I got a code snippet in which there is a ``` printf("%.*s\n") ``` what does the%.*smean?
You can use an asterisk (*) to pass the width specifier/precision toprintf(), rather than hard coding it into the format string, i.e. ``` void f(const char *str, int str_len) { printf("%.*s\n", str_len, str); } ```
What is the benefit of having 2 sections - .data and .bss for process scope variables. Why not just have one? I know what each section is used for. I am using gcc.
.bss consumes "memory" but not space within the executable file. Its sole purpose is to hold zero-initialized data (as you know). .data (and related sections such as rodata) do actually consume space within the executable file, and usually holds strings, integers, and perhaps even entire objects. There is a lot of z...
I have a problem assigning an array like: ``` int a[]; int b[] = {1,2,3}; &a = &b; ``` I know I could use pointers but I want to try it that way...
You can't assign arrays in C. You can copy them with thememcpy()function, declared in<string.h>: ``` int a[3]; int b[] = {1,2,3}; memcpy(&a, &b, sizeof a); ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. So I've seen it everywhere in apps/...
Create aUILabelto display the score, and use anNSTimerto update theUILabel'stextproperty. Apple doesn't ship a class that will do it all for you.
I have not coded in c in a while, and I never was very good with pointers. i have this beginning for main. ``` int main(int argc, char *argv[]) ``` I need to be able to make a copy of the *argv[] in a global scope to allow multiple threads to access it, Is there a fast/easy way to do this?
You don't need tocopytheargvarray (given tomain). You only need to transmit the pointer to it to your threads. This is quite easy (by passing it thru arguments, or by having some global variable containing it).
consider a function like ``` char* strcpy (char* destination, const char* source); ``` The given value at (address) source is const because the author of the function wants to show that the value of source will not be changed by strcpy. The pointer itself is not changed by strcpy to. Why not to write ``` char* strc...
The pointer itself is passed by value, so there's no point.
I have an attributed string that I want to draw bottom-aligned into a rectangular path, using Core Text. Is there a way to get CTFrameSetter / CTFrame to do this, or do I need to do it manually? The manual way being: Figure out the height of the frame using CTFramesetterSuggestFrameSizeWithConstraintsAdjust the heigh...
You'll have to do it manually. ``` CGRect boundingBox = CTFontGetBoundingBox(font); //Get the position on the y axis float midHeight = self.frame.size.height / 2; midHeight -= boundingBox.size.height / 2; CGPathAddRect(path, NULL, CGRectMake(0, midHeight, self.frame.size.width, boundingBox.size.height)); ``` Refer...
I see this line in C: ``` #define log(format, args...) snprintf(buffer + strlen(buffer), 1023 - strlen(buffer), format, ##args); ``` What does the double pound / hash mean before the last param insnprintf()?
In standard C, the "##" is for concatenating tokens together within a macro. Here, this macro is not in standard C, but in "Gnu C", the dialect implemented byGCC. The "##" is used to remove the comma if the extra arguments (inargs) turn out to be empty. Seethe GCC manual.
(I have just answered this question after searching for a while, so I am asking and answering this question here for it to be here when it's needed. There are similar, but not quite the same, questions.)
Cast it toint. This can be consumed by astringstreamor otherwise converted forstringuse. Wherecolourwas astruct SDL_ColorcontainingUint8(a defined alias foruint8_t) members, the solution was ``` stringstream ss << "[colour=" << (int)colour.r << ", " << (int)colour.g << ", " << (int)colour.b << "; light=" << light <<...
I've been learning about C recently, and I've encountered something which I can't seem to find a good answer to. In my code I might have: ``` struct randomStruct a; struct secondStruct array[5]; struct structyStruct q = { 17, "Hey yo", {123,123}}; ``` But in memory, they might be stored as: ``` q, a, array ``` Wh...
What you are seeing happens because ofthe direction of the stack growth. The standard says nothing whatsoever about addresses of automatic variables. Thus it's not required that a relation between variables' addresses exists.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed8 years ago. ``` int main(void) { int i = 0; i = ++i % 3; return 0; } ``` I compile it like this: ``` $ gcc -Wall main.c -o main main.c: In function ‘main’: main.c:4: warning...
Because you are modifying the value ofitwice without an interveningsequence point. It'sundefined behavior.
I have a C application running on Linux and it processes thousands of messages...but not whe I run the application after a couple minutes it brings up the following error: sh: error while loading shared libraries: libc.so.6: cannot open shared object file: Error 24 The application is doing about 30 messages per seco...
Errno 24 means: "Too many open files". After some thoughts I think the application opens a file, which is not allowed by the system anymore. The application can not handle this situation correctly, and crashes with a segmentation fault. Are the return values from the "open" system call checked correctly everywhere?
I want to turn off the buffering for the stdout for getting the exact result for the following code ``` while(1) { printf("."); sleep(1); } ``` The code printf bunch of '.' only when buffer gets filled.
You can use thesetvbuf function: ``` setvbuf(stdout, NULL, _IONBF, 0); ``` Here're some other links to the function. POSIXC/C++
I have manyjoinablethreads that at some point need to all stop. The threads are pthread, but are created through RTAI's user-space interface (never mind the RTAI though). For each thread I have a variable that I can set to tell them to quit. So what I do is: set that variable for each thread so that they stopWait at...
Killing a thread doesn't change whether you should join it or not. If the thread hasn't been detached, then you need to join it, or you will leak resources in the system.
i have a piece of code in C .But i am not able to understand its output ``` #include<stdio.h> main() { char a1[20]; char a2[30]; char a3[40]; scanf("%s",&a1); gets(a2); fgets(a3,sizeof(a3),stdin); printf("%d,%d,%d\n",strlen(a1),strlen(a2),strlen(a3)); } ``` When i enter my input like ``` amit singh ``` output c...
input is"amit\nsingh\n"thescanfconsumes "amit" (and writes that intoa1)thegetsconsumes "\n" (and writes empty string toa2)thefgetsconsumes "singh\n" (which it writes toa3) The output is correct. Do notEVERusegets! http://pubs.opengroup.org/onlinepubs/9699919799/functions/fscanf.htmlhttp://pubs.opengroup.org/onlinep...
I am writing a program that gets a filepath-name from the command-line and then proceeds to open the file. My question is: Is it possible to create a string, the moment the user gives the input, that would be exactly the size needed for the filepath to fit into it? If not, what would be the ideal size for the non-dyna...
Per the C standard the FILENAME_MAX macro (defined in stdio.h) specifies either the maximum or recommended length of file names (quote:222) If the implementation imposes no practical limit on the length of file name strings, the value of FILENAME_MAX should instead be the recommended size of an array intended to hold ...
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed10 years ago.Improve this question I currently need to resolve an issue with duplicated logic on web-based monitoring ...
The answer iscompletely dependent on your problem domain. Java has libraries available for reading XML, JSON and a host of other protocols. You need to be asking questions like: How much data will I be producing?Does the data need to be human-readable?Is storage size an issue?Is the time to read / write the data an...
I want to change the background texture of a Gobject clutter actor whenever it is highlighted. Is there any way i can replace the texture during runtime ?
you can use theclutter_texture_set_*family of functions, like: clutter_texture_set_from_fileclutter_texture_set_from_rgb_dataclutter_texture_set_area_from_rgb_data all documented here:http://developer.gnome.org/clutter/stable/ClutterTexture.html
I am dumping a class in Windbg (bydt) and for aboolmember I see the valuefffffffffffffff8(bin: ...1111111111111111000).It is a valid value (including padding) or not? PS: i'm investigating a dump that may be a memory corruption so .. can't be sure.PS2: my bool is in class between apointerand asize_t. Compiled as rele...
It's not a validboolvalue --boolshould only show up as0or1. Since you're seeing 0xf8, the memory is either not initialized or overwritten. (Note that for some reason, WinDbg will only read a single byte and then sign-extend it to 64-bits.)
This question already has answers here:Closed11 years ago. Possible Duplicate:post and pre increment in cUndefined Behavior and Sequence Points here i want to know why this output comes?? Any one Can Explain me All in proper manner ``` #include<stdio.h> int main() { int a=5; printf("%d %d %d",a++,a++,++a);...
It's undefined - side effects are only guarantied to be completed atsequence points.
I am doing some matrix multiplication in C and I am trying to compile my progam however it fails to compile for the reason: No such file or directory cblas.h This is the command I am using to compile: ``` gcc -o BLAS BLAS.c ``` Can anybody please help me? I am compiling this program on a server. I'm not sure if th...
You need to add a-I directoryoption wheredirectoryis the place where thecblas.hfile is located on your system. This gives: ``` gcc -o BLAS -I directory_of_cblas_header BLAS.c ```
I have a problem assigning an array like: ``` int a[]; int b[] = {1,2,3}; &a = &b; ``` I know I could use pointers but I want to try it that way...
You can't assign arrays in C. You can copy them with thememcpy()function, declared in<string.h>: ``` int a[3]; int b[] = {1,2,3}; memcpy(&a, &b, sizeof a); ```