question
stringlengths
25
894
answer
stringlengths
4
863
I always get either malloc() error. Here is the code: ``` char *data = malloc(200); add_data(data, tableO, line); void add_data(char *data, struct ARP_entryO *tableO, int line) { int i=0; while (i < line) { strcat(data, tableO[i].IPaddr); strcat(data, " "); strcat(data, tableO[i].MACaddr); str...
It's because you dont reset the string to empty string. The malloc function just allocates some memory, you are concatenating strings, but with some "garbage". Sometimes you can receive empty string, sometimes not. The solution is to store empty string there before your loop: ``` data[0] = '\0'; //or data[0] = 0; or...
I need to pass two args to a shell script, here is the code: ``` #include <stdio.h> #include <stdlib.h> void main() { char *script; int lines = 1; sprintf(script, "/...path.../line.sh %d %d", lines, lines); system(script); } ``` The script works well, ive tried. But I always get Segmentation fault. The question is...
You are writing to the memory location pointed to byscriptwhich hasn't been allocated any memory. Try something like: ``` #include <stdio.h> #include <stdlib.h> void main() { char script[100]; // Allocate as much as you need here for your string, not int lines = 1; // necessarily 100 sprintf(script,...
AFAIK, after upgrading toMinGW 4.4.* some time ago all of my literally written strings (like"i'm the string") are treated as of the typestd::string. Is there any command line option to make MinGW treat them asconst char*as it was before?
Strings are per defaultchar */char[]in C / C++, only if you explicit say its astd::stringyou'll get those. Example: ``` std::cout << "first:\t" << typeid("aa").name() << std::endl; std::cout << "second:\t" << typeid(std::string("a")).name() << std::endl; ``` Output: ``` first: A3_c second: Ss ``` Result: first:...
Can anyone tell me how to verify the Password-based P12 file using openssl? Logic or sample code will be much helpful.
You can find a code sample that :- opens a pkcs#12 file with password- extracts the private key and certificates in the openssl source code at : ``` ./demos/pkcs12/pkread.c ```
I have read the following statement. The status argument given to _exit() defines the termination status of the process, which is available to the parent of this process when it calls wait().A process is always successfully terminated by _exit() (i.e.,_exit() never returns). Question If _exitdoesn't return, h...
When the child terminates, the kernel keeps some information about it. Among this information is the return code. Meanwhile, the parent hasn't terminated. By callingwaitorwaitpidit simply asks the kernel "Hey, you know that child of mine? What's his status?".
So, i am assuming that i will need to use sockets(i am a newbie to C). The program will be for Windows(in pure C). And i shall be using these examples http://cs.baylor.edu/~donahoo/practical/CSockets/winsock.html My question is, instead of the client program connecting via TCP, i want the server to accept connectio...
The simplest option that is supported by most web servers is CGI -Common Gateway Interface. Microsoft, of cource, has their own way of running web apps -ISAPI.
I want to know the method of converting an integer into char/string and vice-versa also. I have already used sprintf(&charvar,"%d",&intvar) but it produces wrong output, possibly garbage. i have also heard atoi() in gcc has bugs.Reference:GCC atoi bug What is the other method to convert string/char back to int ? A...
If you want to send an integer to another machine you can send it as binary data, just by sending theintvardirectly to the stream, you don't have to convert it to a char first. That will only introduce problems with knowing the length of the data as different values generate different lengths of strings.
Hi all, As per definition of Threaded binary tree given below A binary tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node, and all left child pointers that would normally be null point to the inorder predecessor of the node. But in above diag...
Look at C, what is it's predecessor? Successor? The order is ``` B then C then D ``` So B is C's predecessor, D is C successor. Where does C's left pointer point? B, that's the predecessor, seems good to me. Likewise, as expected, C's right pointer points to D. Seems like statement, diagram and logic all agree. W...
Hi I am working with a matrix of 448*448 elements of real(signed) data and wanted to display it as grayscale image in C as i did in MATLAB usingimagesc. Can anyone tell me which is the fastest and easiest library or code to display the grayscale image from the matrix in C? Thanks.
Also look atopenCVlibs. These libs are quite good. It has both c and C++ interface.
I need to discover all network neighbors in Linux(they are running Linux too) and I need to get theirs IP addresses(3rd layer). Any ideas how to do that? Btw, I need to do that inC, not inshell Many thanks in advance!
What you should do is, have the neighbours run a daemon which responds (with a unicast response to the sender) to UDP multicasts. Then send a UDP multicast with a TTL of 1 (so it will not be routed) and listen to see who responds. You will only receive responses from the neighbours which are running the agent. Anoth...
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. If you have an object1 and a pointe...
No. Suppose you have several pointers pointing to OBJECT2 ``` (POINTER1) ------------\ (POINTER2) -------------\ (POINTER3) --------------> (OBJECT2) ..... -------------/ (POINTERN) ------------/ ``` When you "go up", to which pointer should you go?
I need to pass two args to a shell script, here is the code: ``` #include <stdio.h> #include <stdlib.h> void main() { char *script; int lines = 1; sprintf(script, "/...path.../line.sh %d %d", lines, lines); system(script); } ``` The script works well, ive tried. But I always get Segmentation fault. The question is...
You are writing to the memory location pointed to byscriptwhich hasn't been allocated any memory. Try something like: ``` #include <stdio.h> #include <stdlib.h> void main() { char script[100]; // Allocate as much as you need here for your string, not int lines = 1; // necessarily 100 sprintf(script,...
AFAIK, after upgrading toMinGW 4.4.* some time ago all of my literally written strings (like"i'm the string") are treated as of the typestd::string. Is there any command line option to make MinGW treat them asconst char*as it was before?
Strings are per defaultchar */char[]in C / C++, only if you explicit say its astd::stringyou'll get those. Example: ``` std::cout << "first:\t" << typeid("aa").name() << std::endl; std::cout << "second:\t" << typeid(std::string("a")).name() << std::endl; ``` Output: ``` first: A3_c second: Ss ``` Result: first:...
Can anyone tell me how to verify the Password-based P12 file using openssl? Logic or sample code will be much helpful.
You can find a code sample that :- opens a pkcs#12 file with password- extracts the private key and certificates in the openssl source code at : ``` ./demos/pkcs12/pkread.c ```
I have read the following statement. The status argument given to _exit() defines the termination status of the process, which is available to the parent of this process when it calls wait().A process is always successfully terminated by _exit() (i.e.,_exit() never returns). Question If _exitdoesn't return, h...
When the child terminates, the kernel keeps some information about it. Among this information is the return code. Meanwhile, the parent hasn't terminated. By callingwaitorwaitpidit simply asks the kernel "Hey, you know that child of mine? What's his status?".
So, i am assuming that i will need to use sockets(i am a newbie to C). The program will be for Windows(in pure C). And i shall be using these examples http://cs.baylor.edu/~donahoo/practical/CSockets/winsock.html My question is, instead of the client program connecting via TCP, i want the server to accept connectio...
The simplest option that is supported by most web servers is CGI -Common Gateway Interface. Microsoft, of cource, has their own way of running web apps -ISAPI.
I want to know the method of converting an integer into char/string and vice-versa also. I have already used sprintf(&charvar,"%d",&intvar) but it produces wrong output, possibly garbage. i have also heard atoi() in gcc has bugs.Reference:GCC atoi bug What is the other method to convert string/char back to int ? A...
If you want to send an integer to another machine you can send it as binary data, just by sending theintvardirectly to the stream, you don't have to convert it to a char first. That will only introduce problems with knowing the length of the data as different values generate different lengths of strings.
Hi all, As per definition of Threaded binary tree given below A binary tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node, and all left child pointers that would normally be null point to the inorder predecessor of the node. But in above diag...
Look at C, what is it's predecessor? Successor? The order is ``` B then C then D ``` So B is C's predecessor, D is C successor. Where does C's left pointer point? B, that's the predecessor, seems good to me. Likewise, as expected, C's right pointer points to D. Seems like statement, diagram and logic all agree. W...
Hi I am working with a matrix of 448*448 elements of real(signed) data and wanted to display it as grayscale image in C as i did in MATLAB usingimagesc. Can anyone tell me which is the fastest and easiest library or code to display the grayscale image from the matrix in C? Thanks.
Also look atopenCVlibs. These libs are quite good. It has both c and C++ interface.
I need to discover all network neighbors in Linux(they are running Linux too) and I need to get theirs IP addresses(3rd layer). Any ideas how to do that? Btw, I need to do that inC, not inshell Many thanks in advance!
What you should do is, have the neighbours run a daemon which responds (with a unicast response to the sender) to UDP multicasts. Then send a UDP multicast with a TTL of 1 (so it will not be routed) and listen to see who responds. You will only receive responses from the neighbours which are running the agent. Anoth...
I'm getting a strange error when reading my data into an array. My goal is to read a file that has a single column of numbers into an array, line-by-line. ``` #include <stdio.h> int main() { int numArray = [20]; int i = 0; FILE *infile; infile = fopen("numbers", "r"); while(!feof(infile)) {...
the correct way to declare an array in c is like this: ``` int numArray[20]; ```
I would like to define/generate a GUID (interface class) for my test driver. What is the best way to do that 'programatically using C/C++' so it won't conflict with other devices/drivers in the system? Also, are there any standard guidelines to follow or other things to keep in mind while creating a new GUID? Please...
Use a GUID generator. There is one bundled with Visual Studio. In 2008, it's under Tools > Create GUID.
Going through K&R, I'm trying to get my head around C. I want to write a program that prints on the screen the user's previous line, unless the character was "a". ``` int main(){ int c; while((c=getchar())!=EOF){ if(c!='a') putchar(c); } return 0; } ``` Yes, the program isn't much. But it won't w...
The code should work as specified, but what you will find is that usinggetcharwith the while loop will print a carriage return when a is entered. This is because in the current implementationgetcharwill keep reading the input buffer till it is empty, if you wanted to stop this happening you could flush it in the if st...
I'm working in ANSI C with lots of fixed length arrays. Rather than setting an array length variable for every array, it seems easier just to add a "NULL" terminator at the end of the array, similar to character strings. Fot my current app I'm using "999999" which would never occur in the actual arrays. I can execu...
This approach is technically used by yourmainarguments, where the last value is a terminalNULL, but it's also accompanied by anargcthat tells you the size. Using just terminals sounds like it's more prone to mistakes in the future. What's wrong with storing the size along with an array? Something like: ``` struct f...
I'm trying to test C code with googletest but I'm having some problems when my C header files are included in the C++ test file because the g++ compiler handle them as C++ headers. I've tried to include these headers insideextern "C" {}with no success. Is there a way g++ compiler can handle these headers as C ones?
extern "C" only changes link stage name mangling. If you are using C features that aren't shared by C++ then you are SOL
I would like to ask, how to call a shell script with parameters in C. I have found this, but it seems not working. ``` #include <stdio.h> #include <stdlib.h> char script = "script.sh"; system(script); ``` Thanks in advance!
``` const char * script = "script.sh"; ``` instead of ``` char script = "script.sh"; ``` Note the «*» sign... thesystemfunction needs achar *, not a single char (a string, not a character).
In one of my C application I am using, below functions from ctype.h : isalpha(), isspace(), ispunct(), tolower(). After profiling I see there are some bottlenecks in the calls of these functions(Basically my app is a character/string processing from a input text file and hence these functions are called exhaustively...
You could implement them as macros or inline functions: ``` #define IS_ALPHA(x) (((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z')) #define IS_SPACE(x) ((x) == ' ' || (x) == '\t') ... etc. ``` Note however that the originalisalpha,isspace,ispunct, etc. depend on the current locale and may yield different resu...
How can I convert an unsigned 8bit PCM stream (0-255) into a signed 8bit PCM stream (-128-127). Is it as simple as subtracting 128 from every unsigned byte so that 0 becomes -128 and 255 becomes 127? Or is it more complicated? Thanks!
Why dont you try it? In my opinion it should suffice but I don't know what language you are using. When working with signed and unsigned integer/char bear in mind that the internal representation for negative values is the two's complement. Safest would be to calculate insigned intsize to avoid overflows.
``` int main() { // forward declaration struct myStruct_st *mS; // Note that this will expand as "struct struct myStruct_st *mS which does not make any sense to me" return 0; } // definition of myStruct_s typedef struct myStruct_s { int x; int y; } myStruct_st; ``` I understand that myStruct_s is the...
The local struct hasnothing to dowith the struct defined outside ofmain(). Inmain()you (forward-)declare a struct, define a pointer to that struct and never define the struct. That's perfectly OK. It so happens that you define a struct with the same name outsidemain().
What is the easiest way to get the UUID of a hard drive partition programmically in Linux? (Using C)
Uselibblkidfrom theutil-linux-ng distribution. It includes somesample code. (Your system probably already has a "blkid" utility linked against some version of libblkid.)
How can I (programmatically) give write permission on a file to a particular user in Linux? Like, for example, its owner? Everyone has read access to this file.
In a shell or shell script simply use: ``` chmod u+w <filename> ``` This only modifies the write bit for the user, all other flags remain untouched. If you want to do it in a C program, you need to use: ``` int chmod(const char *path, mode_t mode); ``` First query the existing mode via ``` int stat(const char *p...
Suppose I have a pointer *p which pointer to 10 memory blocks on the heap. Now, instead of free() it, I clear it manually with NULL (or '\0') like this: ``` for (int i = 0; i < length; ++i{ p[i] = '\0'; } ``` Is this considered a memory block is freed when every bit is cleared to zero? Or, I have to use free() ...
Youdohave to callfree()in order to return memory to the operating system. A memory block filled with zeroes is no more "free" than a block full of ones. For instance, consider a bitmap consisting only of black pixels. In most formats, the associated memory block will be filled with zeroes. Does that mean that block ...
Helo, I'm a bit confused about the definition of an inner loop in the case of imperfectly nested loops. Consider this code ``` for (i = 0; i < n; ++i) { for (j = 0; j <= i - 1; ++j) /*some statement*/ p[i] = 1.0 / sqrt (x); for (j = i + 1; j < n; ++j) { x = a[i][j]; for (k = 0; k <=...
Bothjloops are nested insideiequally,kis the inner most loop
Inlibname.h: ``` int add_libname(int, int); ``` Inlibname.c: ``` #include "libname.h" int add_libname(int a, int b) { return a+b; } ``` I can build the shared library this way: ``` gcc -shared -fPIC libname.c -o libname.so ``` But I can't use it in another programetest.c: ``` #include <stdio.h> #include "lib...
Because add_libname takes (int, int) you're giving it (1+5 = 6) or just (int) I think you meant add_libname(1, 5); Also to compile it correctly you must use gcc like so ``` gcc -o myapp test.c -L. -lname ``` the lib part of libname is ignored as it is implicit
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. here is a general implementation `...
You could use the Boyer-Moore algorithm, which is O(n).Here'ssample C code.
When a C/C++ program containing the dynamically allocated memory(using malloc/new) without free/delete calls is terminated, what happens to that dynamically allocated memory? Does the operating system takes back the memory or does that memory becomes unaccessible to other programs?
I don't think that there are any guarantees in the language standard, but modern operating systems which support sparse virtual memory and memory protection (such as MacOS X, Linux, all recent version of Windows, and all currently manufactured phone handsets) automatically clean up after badly-behaved processes (when ...
In PHP API we could usecurl_setopt($curl, CURLOPT_RETURNTRANSFER, true);but how to translate it into C? I triedcurl_easy_setopt(curl_handle, CURLOPT_RETURNTRANSFER, true);but failed.
There's noCURLOPT_RETURNTRANSFERin libcurl C API. You can do that with a callback function, it's one oflibcurls examples:get a remote file in memory only.
I have a list of records, at the starting I dont know the number of records. I need to read them into array. so is it advisable to read all record one by one & doing realloc one by one & go on increasing the array size as the element comes OR should I spend one pass in identifying the number of records & do malloc on...
Areallocisn't really very expensive. But callingreallocfor each element is a bit much. I suggest you do this: Start with a sizeWhen you add an element, check if you have enough spaceWhen you don't have enough space, double the currrent amount Correctly guessing an adequate initial size also helps. So if 60% of your ...
The content of a header file needs to be copied and paste onto a few of my classes. Reason been - using include directive does not make reference of the file available to an external compiler, therefore it looks like my only option been to copy the content of the header into my classes. I was wondering if I can use s...
How about using the m4 macro language? See, e.g., http://www.gnu.org/s/m4/http://mbreen.com/m4.htmlIf on a Linux system with GNU m4 installed, tryinfo m4. m4 is a general-purpose macro processing language. It is notably used heavily in GNU Autotools. You might be able to define some m4 macros to get what you want...
I have this code: ``` #!/usr/bin/python import urllib print 'Insert page to download:' page = raw_input() filehandle = urllib.urlopen(page) myFile = open('file.html','w') for lines in filehandle.readlines(): myFile.write(lines ) myFile.close() filehandle.close() ``` This basically just downloads the inpute...
Try thelibcurllibrary, which provides URL download functions for C (and many other languages including C++). If you're writing code for Windows, you can also use theWindows Internetlibrary.
What will be printed as the result of the operation below: ``` x=5; printf("%d,%d,%d\n",x,x<<2,x>>2); ``` Answer: 5,20,1 I thought order is undefined yet I found above as interview question on many sites.
From the C++ standard: The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified. However, your example would only have undefine...
I've written Unix Pipes but I don't have the good result. I'm wondering if it's possible to debugging Unix pipe in C langage with gdb. If no, do you know a method to do that ? thanks in advance.
Use netcat with the -U switch. You will be able to create a listen/sender, or sit in between.
What does following declaration mean in C? ``` char a = (10,23,21); ``` While printing the value of "a" with "%u" the output is 21.gccis not giving any error. What's this kinda declaration and what's the use of it?
You are seeing the comma operator at work. The comma operatora,bevaluatesa, throws away the result, then returnsb. Since10and23have no side effects, this is equivalent tochar a = 21;
My source file starts with: ``` #include "foo.h" ``` I am able to use all of my global variables, types, and structs from my header file. In my header file i started with a couple of includes: ``` #include<file.h> ``` Then move on to global variables: ``` #define GLOBAL ``` Then structs: ``` #typedef struct bo...
The problem's presumably in how you're linking.
ive gotstatic struct ARP_entry ARP_table[ARP_TABLE_SIZE];instart.cand I want to pass this table to afill()function intable.c ive got#include "table.c"in start.c, cause i need it for that function, right? if i include start.c in table.c it gets into some weird loop or what. Any suggestion? The point is to declare the...
declarations (used by multiple .c files) go to header files(.h). do not include .c files. include the header file in both .c files.
This question might just show that I haven't understand something important in C: The Intel Math Kernel library provides a way to set the memory alignment when allocating memory. On the other hand I pass arrays to mkl lapack routines just by reference. So how does the lapack routine know about the alignment of the ar...
The routine does not need to know about alignment. Alignment only determines the starting address of the array (which coincides with the address of the first element), the address of the rest of the elements is determined by the starting address and element size.
I can't see anyalloca.hequivalent inVisual C 2010. How can one perform stack allocation inVisual Con Windows? I miss the functionalloca.
See_alloca. Visual C uses an _ prefix for non-standard functions in the C headers.
This question already has answers here:Closed12 years ago. Possible Duplicate:Do you know tool building tree of include files in project\file? Currently reading the Minix source code (I'm interested in operating system & driver programming), I am looking for a program that would help me understand the tree view of t...
Try Eclipse CDT. It hasInclude Browser.
I know that #define replaced before the compiling to real values. so why the first code here compile with no error, and the 2nd not? the 1st; ``` #include <stdio.h> #include <stdlib.h> int main() { printf("bc"); return 0; } ``` the 2nd(not working); ``` #include <stdio.h> #include <stdlib.h> #define Str "bc"...
Because theStrmacro evaluates to"bc";— the semicolon is included. So your macro expands to: ``` printf("bc";); ``` You do not need to follow a #define with a semicolon. They end at a newline, rather than at the semicolon like a C statement. It is confusing, I know; the C preprocessor is a strange beast and was inven...
I would like to compile withMinGWon Windows. I am seeking for IDE (Visual Studio 2010 is out, because as far as I know it cannot useMinGW) with integrated SVN support like AnkhSVN plugin for Visual Studio 2010. One candidate isCodeBlocks. Does it have some SVN plugin? Or would you recommend another IDE? Thank you.
You can use Eclipse IDE for C/C++ Developers. With the subclipse plugin you have accesses tosvnas well Link:http://eclipse.org/downloads/moreinfo/c.php
I have two matrices A and B with same number of rows. Consider a Lattice generated by the rows of B. I want to reduce B and during the reduction change A accordingly. That is if i-th row and j-th row of B interchanges, need to sweep i-th row and j-th row of A also, similarly other elementary row operations. How can I ...
Thisis the source code to sage, a FOSS symbolic math program. It has an implementation of the triple-L that you could use provided you're willing to GPL the code once it's done.Thisis another standalone implementation.
``` include<stdio.h> include<stdlib.h> int main() { char a[20]="hello world"; system("./cool.bat a");\\here I need to pass the array as argument to batch file } ``` I believe you got what I wanted to say. I want to pass an array of the c program, as an argument to batch file. But if i say ``` syst...
you'll need to build a char[] consisting of the batch command, and the variable contents to pass to it
Basically the title is self explaining. I'm programming in C and i use fgets as the input function but i do not want that control characters get printed.
fgets()is rather simple, and doesn't offer you much control over what appears on the screen. I don't think that it's possible to do this. You may want to look into something more powerful - likereadline.
``` #include <stdio.h> // copy input to output // my version int main() { int c; printf("\n\nUse CONTROL + D to terminate this program\n\n"); while ((c = getchar()) != EOF) { putchar(c); } if ((c = getchar()) == EOF) { printf("\n\nProgram TERMINATED\n\n"); } return 0; ...
When you hit^D, input to the program is closed, sogetchar()will subsequently always returnEOF.
I am writing a program in C and I have several printf statements for debugging. Is there a way to change the precision for a HEX output on printf? Example. I have 0xFFF but I want it to print out 0x0FFF.
Sayprintf("%04X", x);. The0means "pad with zeros", the4means "at least four characters wide". For integers, one doesn't use the term "precision" (because integersareprecise), but rather "field width" or something like that. Precision is the number of digits in scientific notation when printing floats.
I want to program an access function that returns username and password. Here's what I came up with: ``` #include <stdio.h> char * getMySQLUsername() { return "myUsername"; } char * getMySQLPassword() { return "myPassword"; } int main() { printf("%s\n", getMySQLPassword()); } ``` It seems to work, but...
You should returnconst char *because you cannot change a literal string. You're also not returning anything frommain, which is only valid in C as of C99 and in C++.
here is the problem for example ``` in = "a b\nab c\ndd"; out = "a b\nb c\ndd" Here is my C code while(c=getchar()!=EOF){ if(c==' '){ while( (c1=getchar()) == ' '); // ignore all other contiguous blank putchar(c); // output one blank putchar(c1); // output the next non-blank character ...
Assuming you remove only' ': ``` int c; char space_found = 0; while ( ( c = getchar() ) != EOF) { if ( (!space_found) || (c != ' ') ) { // if the previous is not a space, or this is not a space putchar(c); } space_found = (c == ' '); // (un)set the flag } ``` You can change it to check for any white...
I've written Unix Pipes but I don't have the good result. I'm wondering if it's possible to debugging Unix pipe in C langage with gdb. If no, do you know a method to do that ? thanks in advance.
Use netcat with the -U switch. You will be able to create a listen/sender, or sit in between.
What does following declaration mean in C? ``` char a = (10,23,21); ``` While printing the value of "a" with "%u" the output is 21.gccis not giving any error. What's this kinda declaration and what's the use of it?
You are seeing the comma operator at work. The comma operatora,bevaluatesa, throws away the result, then returnsb. Since10and23have no side effects, this is equivalent tochar a = 21;
My source file starts with: ``` #include "foo.h" ``` I am able to use all of my global variables, types, and structs from my header file. In my header file i started with a couple of includes: ``` #include<file.h> ``` Then move on to global variables: ``` #define GLOBAL ``` Then structs: ``` #typedef struct bo...
The problem's presumably in how you're linking.
ive gotstatic struct ARP_entry ARP_table[ARP_TABLE_SIZE];instart.cand I want to pass this table to afill()function intable.c ive got#include "table.c"in start.c, cause i need it for that function, right? if i include start.c in table.c it gets into some weird loop or what. Any suggestion? The point is to declare the...
declarations (used by multiple .c files) go to header files(.h). do not include .c files. include the header file in both .c files.
This question might just show that I haven't understand something important in C: The Intel Math Kernel library provides a way to set the memory alignment when allocating memory. On the other hand I pass arrays to mkl lapack routines just by reference. So how does the lapack routine know about the alignment of the ar...
The routine does not need to know about alignment. Alignment only determines the starting address of the array (which coincides with the address of the first element), the address of the rest of the elements is determined by the starting address and element size.
I can't see anyalloca.hequivalent inVisual C 2010. How can one perform stack allocation inVisual Con Windows? I miss the functionalloca.
See_alloca. Visual C uses an _ prefix for non-standard functions in the C headers.
This question already has answers here:Closed12 years ago. Possible Duplicate:Do you know tool building tree of include files in project\file? Currently reading the Minix source code (I'm interested in operating system & driver programming), I am looking for a program that would help me understand the tree view of t...
Try Eclipse CDT. It hasInclude Browser.
I know that #define replaced before the compiling to real values. so why the first code here compile with no error, and the 2nd not? the 1st; ``` #include <stdio.h> #include <stdlib.h> int main() { printf("bc"); return 0; } ``` the 2nd(not working); ``` #include <stdio.h> #include <stdlib.h> #define Str "bc"...
Because theStrmacro evaluates to"bc";— the semicolon is included. So your macro expands to: ``` printf("bc";); ``` You do not need to follow a #define with a semicolon. They end at a newline, rather than at the semicolon like a C statement. It is confusing, I know; the C preprocessor is a strange beast and was inven...
I would like to compile withMinGWon Windows. I am seeking for IDE (Visual Studio 2010 is out, because as far as I know it cannot useMinGW) with integrated SVN support like AnkhSVN plugin for Visual Studio 2010. One candidate isCodeBlocks. Does it have some SVN plugin? Or would you recommend another IDE? Thank you.
You can use Eclipse IDE for C/C++ Developers. With the subclipse plugin you have accesses tosvnas well Link:http://eclipse.org/downloads/moreinfo/c.php
I have two matrices A and B with same number of rows. Consider a Lattice generated by the rows of B. I want to reduce B and during the reduction change A accordingly. That is if i-th row and j-th row of B interchanges, need to sweep i-th row and j-th row of A also, similarly other elementary row operations. How can I ...
Thisis the source code to sage, a FOSS symbolic math program. It has an implementation of the triple-L that you could use provided you're willing to GPL the code once it's done.Thisis another standalone implementation.
``` include<stdio.h> include<stdlib.h> int main() { char a[20]="hello world"; system("./cool.bat a");\\here I need to pass the array as argument to batch file } ``` I believe you got what I wanted to say. I want to pass an array of the c program, as an argument to batch file. But if i say ``` syst...
you'll need to build a char[] consisting of the batch command, and the variable contents to pass to it
Basically the title is self explaining. I'm programming in C and i use fgets as the input function but i do not want that control characters get printed.
fgets()is rather simple, and doesn't offer you much control over what appears on the screen. I don't think that it's possible to do this. You may want to look into something more powerful - likereadline.
``` #include <stdio.h> // copy input to output // my version int main() { int c; printf("\n\nUse CONTROL + D to terminate this program\n\n"); while ((c = getchar()) != EOF) { putchar(c); } if ((c = getchar()) == EOF) { printf("\n\nProgram TERMINATED\n\n"); } return 0; ...
When you hit^D, input to the program is closed, sogetchar()will subsequently always returnEOF.
I am writing a program in C and I have several printf statements for debugging. Is there a way to change the precision for a HEX output on printf? Example. I have 0xFFF but I want it to print out 0x0FFF.
Sayprintf("%04X", x);. The0means "pad with zeros", the4means "at least four characters wide". For integers, one doesn't use the term "precision" (because integersareprecise), but rather "field width" or something like that. Precision is the number of digits in scientific notation when printing floats.
As far as I know the smallest unit in C is abyte. Where does this constraint comes from? CPU? For example, how can I write anibbleor a singlebitto a file?
no, you can't... files are organized in bytes, it's the smallest piece of data you can save. And, actually, that 1 byte will occupy more than 1 byte of space, in general. Depending on the OS, the system file type, etc, everything you save as a file will use at least one block. And the block's size varies according to...
In Linux 2.6.32-32, is there a way to find the following information about a thread programmatically in apthreadsprogram? I need: run count, stack pointer, stack start/end, stack size, stack usage. Something like ThreadX, I guess, but within a program. Thanks.
pthread_getattr_np()should give you the pthread attributes of a threadpthread_attr_getstack()returns the stack address and sizeI don't know what you mean by run count.For the stack pointer of a thread different than your current one you might need to useptrace. Once you have it, you can use it to do the maths for dete...
I am trying to create a directory using the following code. It compiles, but it does not create a directory. Any suggestions? ``` #include <stdio.h> #include <string.h> #include <sys/stat.h> int main(void) { const char base[] = "filename"; char filename [ FILENAME_MAX ]; int number = 42; sprintf(filename, "%s...
Does the "filename" directory already exist?mkdir()will only create one directory at a time; if the parent directory doesn't exist either, you'll have to create it separately, first.
I need to know how to make this ignore the number 0 when 0 is input so that the program does not exit when 0 is input. ``` #include <stdio.h> int main() { int input = 0, previous = 0; do { previous = input; printf("Input Number"); scanf("%d", &input); } while( input!= previous*...
Pick a different value forprevious. TryINT_MAX >> 1from limits.h.
I can't return a pointer to a character array from a different file other than the main function. It always says "segmentation fault". But if I write the function in the same file as main, There is no problem. ``` /* this is in mainfunc.c file*/ int main() { char ch[5]={'a','b','c','d','\0'}; char *res=retc...
The function retchararray overflows your array. You use more memory than you have reserved. This happens in*(str+len+1) = '\0'and causes the segfault.
This is an interview question:- Write a C program which when compiled and run, prints out a message indicating whether the compiler that it is compiled with, allows /* */ comments to nest. The solution to this problem is given below :- Sol:- you can have an integer variable nest: ``` int nest = /*/*/0*/**/1; `...
If the compiler doesn't allow nesting, the first*/will terminate the opening of the multiline comment, meaning the0won't be commented out. Written with some spaces: ``` int nest = /*/*/ 0 * /**/ 1; ``` resulting in the code ``` int nest = 0 * 1; // -> 0 ``` If it allows nesting, it will be ``` int nest = /*/*/0*/...
I need to install VSE (2010, I guess) Java. Will that installation screw up my currently-installed VSE 2008 C/C++ in any way? Thanks!
Do you mean J# or something like that by any chance? I would say no. I don't use the express editions myself, but have various versions of visual studio on my machine that happily coexist.
I want to write a C or C++ program, that given an IP address, Pings it and then performs further action based on whether the Ping was successful or not. How to do this?
Have a blast atThe Ping Page, which has a link tofull sourceon the original Unixping(8).
I was trying to learn strings in C when I came across this code. ``` #include <stdio.h> int main(){ char s[] = "Hello world"; printf("%s" , s); printf("%s" , &s); return 0; } ``` Both gave Hello World as output. According to my understanding, this output is Ok for First case. How is i...
Taking the address of an array is the same as taking the address of it's first element. When the array's name is used, then it also decays to the address of it's first element- so the expressionssand&syield the same result.
Why does the following code run the while loop? I thought "mid = term" is an assignment, not a condition? Please explain. Thanks. ``` #include <stdio.h> main () { int mid = 4, term = 4; while ( mid = term) printf("%d\n", --term); } ```
The result of an assignment is the value. Therefore the expression evaluates to4or a non-zero and thus, in C,TRUE.
For example, I want such a function: ``` char *dst = (char*)malloc(512); char *src = (char*)malloc(1024); ... dst = (char*)realloc(dst, 1024); memcpy(dst, src, 1024); ``` As you see, I just want the function realloc() to extend the size of buffer, but the realloc() in C library may copy data from old address. So is ...
Why not just: ``` free(dst); dst = malloc(1024); ``` Also note thatreallocmay move the block as well as resizing it, so holding an old pointer returned by a previous call tomalloc,callocorreallocmay no longer refer to the same chunk.
I wanted to add a ZeroMQ socket to a glib program. The pitty is, a zmq socket is notpoll()-able, and they give their implementation, which overloads the oldpoll()func. How could I integrate that into the main loop efficiently? I tried using their poll (zmq_poll()) instead of the default one, but there's no good way o...
According toFAQyou could try "the other way" approach. Rather than makingpollon azmq sockettryzmq_poll()on a regularsocket. Check out questionHow can I integrate ØMQ sockets with normal sockets? Or with a GUI event loop?in the FAQ.
In the following lines of code, what does the asterisk in front of dup_func, free_func, and clear_free func, do? ``` void *(*dup_func)(void *); void (*free_func)(void *); void (*clear_free_func)(void *); ```
In your examples it means they arefunction pointers. In a nutshell, they allow you to do things like this: ``` void example() { printf("Example called!\n"); } void call_my_function(void (*fun)()) { printf("Calling some function\n"); (*fun)(); } /* Later. */ call_my_function(example); ```
This is probably a really stupid question, but how do I turn on these debug messages in my code? ``` #ifdef DEBUG_MSG printf("initial state : %d\n", initial_state); #endif ``` Many thanks in advance,
When compiling, try something like this: ``` $ gcc -DDEBUG_MSG -o foo foo.c ```
I need to install VSE (2010, I guess) Java. Will that installation screw up my currently-installed VSE 2008 C/C++ in any way? Thanks!
Do you mean J# or something like that by any chance? I would say no. I don't use the express editions myself, but have various versions of visual studio on my machine that happily coexist.
I want to write a C or C++ program, that given an IP address, Pings it and then performs further action based on whether the Ping was successful or not. How to do this?
Have a blast atThe Ping Page, which has a link tofull sourceon the original Unixping(8).
I was trying to learn strings in C when I came across this code. ``` #include <stdio.h> int main(){ char s[] = "Hello world"; printf("%s" , s); printf("%s" , &s); return 0; } ``` Both gave Hello World as output. According to my understanding, this output is Ok for First case. How is i...
Taking the address of an array is the same as taking the address of it's first element. When the array's name is used, then it also decays to the address of it's first element- so the expressionssand&syield the same result.
Why does the following code run the while loop? I thought "mid = term" is an assignment, not a condition? Please explain. Thanks. ``` #include <stdio.h> main () { int mid = 4, term = 4; while ( mid = term) printf("%d\n", --term); } ```
The result of an assignment is the value. Therefore the expression evaluates to4or a non-zero and thus, in C,TRUE.
For example, I want such a function: ``` char *dst = (char*)malloc(512); char *src = (char*)malloc(1024); ... dst = (char*)realloc(dst, 1024); memcpy(dst, src, 1024); ``` As you see, I just want the function realloc() to extend the size of buffer, but the realloc() in C library may copy data from old address. So is ...
Why not just: ``` free(dst); dst = malloc(1024); ``` Also note thatreallocmay move the block as well as resizing it, so holding an old pointer returned by a previous call tomalloc,callocorreallocmay no longer refer to the same chunk.
I wanted to add a ZeroMQ socket to a glib program. The pitty is, a zmq socket is notpoll()-able, and they give their implementation, which overloads the oldpoll()func. How could I integrate that into the main loop efficiently? I tried using their poll (zmq_poll()) instead of the default one, but there's no good way o...
According toFAQyou could try "the other way" approach. Rather than makingpollon azmq sockettryzmq_poll()on a regularsocket. Check out questionHow can I integrate ØMQ sockets with normal sockets? Or with a GUI event loop?in the FAQ.
In the following lines of code, what does the asterisk in front of dup_func, free_func, and clear_free func, do? ``` void *(*dup_func)(void *); void (*free_func)(void *); void (*clear_free_func)(void *); ```
In your examples it means they arefunction pointers. In a nutshell, they allow you to do things like this: ``` void example() { printf("Example called!\n"); } void call_my_function(void (*fun)()) { printf("Calling some function\n"); (*fun)(); } /* Later. */ call_my_function(example); ```
This is probably a really stupid question, but how do I turn on these debug messages in my code? ``` #ifdef DEBUG_MSG printf("initial state : %d\n", initial_state); #endif ``` Many thanks in advance,
When compiling, try something like this: ``` $ gcc -DDEBUG_MSG -o foo foo.c ```
``` #include <stdio> int main(){ int x = 4; int y = 3; int z; z = x---y; printf("%d" , z); return 0; } ``` The gcc compiler in Linux Mandriva evaluates it as(x--)-y. I am confused as to why is it so. It could have beenx - (--y). I know some of the answers would t...
The C lexical tokeniser is greedy, so your expression is tokenised as ``` x -- - y ``` before precedence rules are applied.
How do I append the string at the beginning of array? Is there any function to do that in C? Or should I create my own function? ``` strcat(a,".com") \\ if a = www.google it gets www.google.com after strcat() func. ``` But if array="google", how do i put www. at the beginning of it and make it www.google.com? We kno...
Append "google" to "www" or usesnprintf. ``` snprintf(large_enough_string, max_len, "%s.%s.%s", "www", "stackoverflow", "com"); ```
I have one .c file and one .h. I am not planning to have more than one .c file. Should I put structure definition in the header file? what is the best practice? ``` .h typedef struct cow_s { int legs; char eyes; } cow_t; ``` and ``` .c cow_t *ptr_to_cow; ``` note: I do not want struct to become global.
If you have no intention to expose this structure to some other module (and you say you have only one module) there is no real reason to put it in a header file, except of keeping things ordered.
First, defining two constant expressions without parentheses is my fault: ``` #define BIG_INTERVAL 60 * 60 * 1000 #define SMALL_INTERVAL 1 * 1000 int i = 1; if (i >= BIG_INTERVAL / SMALL_INTERVAL - 1) { printf("Oops!\n"); } ``` Theifstatement after the macro expansion isif(i >= 60 * 60 * 1000 / 1 * 1000 - 1). ...
All operators onints returnint. So yes,60 * 60 * 1000 / 1 * 1000 - 1is anint. But the expected result of 3599999999 is too big for anint, so the expression actually evaluates to -694967297 (assuming 32-bitintand two's complement). This doesn't happen with a literal3600000000because integer literals larger thanINT_M...
I would like to know if Microsoft Visual Studio 2010 supports C99. If not, how can I use the standard types likeintptr_tanduintptr_t?
Visual Studio 2010 does not support C99 syntax.stdint.his a very common file in all C/C++ compilers, though, which does exist in a Visual C++ 10.0 installation, included with theWindows SDK(regardless of the version of Visual Studio that you use). stdint.h can be found in: C:\Program Files (x86)\Microsoft Visual Stu...
Is there anyway given a string like,"my example\n", to get a pointer to it? For instance,&"my example\n"or&{"my example\n"}? EDIT: I guess asking rudimentary questions is what I get for not sleeping last night. Ah well, thanks for all your help anyway.
It's already a pointer: ``` char *string = "my string\n"; ``` stringwill be a pointer to the literal string.
Back in the good old days of 68k, both pre/post pointer increments/decrements were more or less guaranteed to be atomic, due to the relatively general relationship between the stack pointer and other more generic address registers. As this behaviour is clearly a 68k artefact which may not procure the most efficient im...
would I be correct in assuming that the C specification makes no claims as to the "atomicity" of these operations. Yes. The current standard (both C99 and C89, IIRC) makes no claims about atomicity. That is definitely platform-specific, and probably depends on the compiler as well. Why is it necessary for these oper...