question
stringlengths
25
894
answer
stringlengths
4
863
I want to merge two string arrays into one array: array 1: ``` firstnames[NUMBER_NAMES][LEN_NAME] = {"luca","tomas"} ``` and array 2: ``` secondname[NUMBER_NAMES][LEN_NAMES] = {"goirgi", "edison"} ``` and i want to put them in an array where the first name and last name can be together
First, include : ``` #include <string.h> ``` Now, let the string be stored in names[NUMBER_NAMES][LEN_NAMES] ``` char name[sNUMBER_NAMES][LEN_NAMES]; ``` Finally, a for loop for each element in the array: ``` for(i=0;i<NUMBER_NAMES;i++) { strcpy(names[i],firstnames[i]); //To initialize ith names element with fir...
I used Cython to convert a.pyxfile to.c. Now, I'm trying to compile it to.pyd, using thetcccompiler: ``` C:\Users\USER>"C:\Program Files\tcc\tcc.exe" tkExtra.c -o tkExtra.pyd - shared -IC\Python27\include -LC\Python27\libs -lpython27 ``` However, I get this error: ``` tkExtra.c:8: error: include file 'pyconfig.h' n...
Seems like you're missing some colons. Try: ``` C:\Users\USER>"C:\Program Files\tcc\tcc.exe" tkExtra.c -o tkExtra.pyd -shared -IC:\Python27\include -LC:\Python27\libs -lpython27 ```
I'm using visual studio to write a c code. This is the malloc code line i was told to use: ``` root = (Coor)malloc(sizeof(Coor)); ``` It doesn't let me use it for the following error: ``` identifier not found ``` Can anyone tell me why it happens and how to fix it? Thanks,
Please check if you have included<stdlib.h>and<malloc.h>.
The I/p to the algo will be an expression like this: ``` a+(-b) a*-b+c ``` i.e any expression that a standard C compiler would support. Now I've the input already formatted as a stream of tokens , the tokens contain info whether its an operator or an operand. The algorithm should take this in and give me a postfix ...
If an operator is the first thing in your expression,orcomes after another operator,orcomes after a left parenthesis, then it's an unary operator. You have to use other symbols for unary operators in your output string, because otherwise it is not possible to distinguish between binary and unary variants in the postf...
Does (int*) arr[2] have to with typecasting? If yes, where is it used? This problem arose when I tried to compile the follwing code : ``` int* arr[2]; int arr1[] = { 1,2}; int arr2[] = { 1,6}; arr[0] = arr1; arr[1] = arr2; ``` by replacing ``` int* arr[2] with (int*)arr[2] ``` Thanks.
First one makesarras an array of pointers to int. So yourarris a variable. That is a declaration line. The second one: assuming thatarris a an array (which was allready declared!), takes the value which isarr[2]and casts apointer to inttype on it.
I was reading a program in Programming Windows by Charles Petzold. I was stuck at one point. There was a Line : ``` cxCaps=(tm.tmPitchAndFamily & 1?3:2)*cxChar/2; ``` wherecxCaps(a static variable) saves an average width of uppercase letters My Question is what is& 1 ? 3 : 2? I know it is conditional operator but ...
It's a series of operations. Lets put it in parentheses: ``` ((tm.tmPitchAndFamily & 1) ? 3 : 2) * (cxChar / 2); ``` So first thetm.tmPitchAndFamily & 1operation is performed, which check iftm.tmPitchAndFamilyis odd (if the least significan bit is set, then it's odd). The result of this operation is then part of the...
I'm trying to figure out how many processes this program creates, including the initial parent process. The correct answer should be 9, but I don't understand why the answer is 9. How are these 9 processes created? Thanks in advance! ``` #include <stdio.h> #include <unistd.h> … int main() { pid_t john; john = for...
Remember that on thefork();fork();fork();, both the parent and the child hit the next fork. ``` main | |\ john = fork() | \ | \ | |\ fork() | | \-----\ | |\ |\ fork() | | \ | \ | | \ | \ | | \ | \ | |\ |\ |\ |\ fork() | | | | | | | | | 1 2 ...
I'm writing a loadable kernel module and trying to test it. After inserting it I was trying to remove it usingrmmod xxxcommand, but I get an error sayingmodule xxx is in useand the module gets stuck and I can't remove it. Any idea how to remove the module without rebooting the entire machine ? (linux Kernel v. 3.5.0) ...
This only happens to me when there is a bug in my driver which is causing the code in the module to panic or crash in some way. In my experience once this happens reboot is the only possible course. As I said, the kernel usually panics so you should check out dmesg after inserting it or running you application to ex...
Got it working, thanks all ;] code ``` enum genre {A, B, C, D, E}; struct recipe { genre category; char name[50]; char ingredients[50]; char instruction[1000]; }; void menu(); void file_check(char *name); ``` errors: ``` error C2016: C requires that a struct or union has at least one member err...
C requires you to use: ``` enum genre category; ``` instead of ``` genre category; ``` To usegenre categorydeclaration, you'd need totypedef: ``` typedef enum {A, B, C, D, E} genre; ``` instead of ``` enum genre {A, B, C, D, E}; ```
I am new to C/C++, so I have a couple of questions about a basic type: I have read somewhere that the operator % can't be applied to float or double type operands. Then how can I check the divisibility of float or double type variables? I have shown my program with error below:#include <stdio.h> int main() { dou...
then how can i check the divisibility of float or double type variables. ??` Usefmod.%only work with integer operands.%does not work with floating point values because C already provides thefmodlibrary function.
This question already has answers here:Does `break` work only for `for`, `while`, `do-while`, `switch' and for `if` statements?(6 answers)Closed10 years ago. If i write break statement in for loop then will variable be updated and then for loop exits,or after just excecution of break statement for loop exits? for e.g...
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.It can be used to terminate a case in the switch statement
Overriding 'malloc' using the LD_PRELOAD mechanism How canLD_PRELOADbe used to setptrto NULL or to any other memory address in order to avoid dangling pointer exploits. ``` void free(void *ptr) { real_free(ptr); ptr = NULL // will only set local ptr to NULL } ```
It cannot. With LD_PRELOAD you can override symbols, such as a function. To alter the pointer passed in to free() you would need access to the variable of the caller of free() in order to set it to NULL. But you only have access to a copy of the pointer passed in. Note that a caller might even do something as: ``` ...
This question already has answers here:What's the meaning of this piece of code? void (*signal(int sig, void (*func)(int)))(int);(5 answers)Closed10 years ago. Insignal.hthere is declaration ofsignalfunction: ``` void (*signal(int signo, void (*func)(int))) (int); ``` How to interpret this and what's the use of dec...
Thesignalfunction takes anintand a function pointer as arguments, and returns a function pointer. The function pointer argument and the returned function pointer each take anintargument, and returnsvoid. Thesignalprototype is sometimes written this way: ``` typedef void (*signal_handler_type) (int); signal_handler_...
``` int main(void) { #if 0 something" #endif return 0; } ``` A simple program above generates a warning:missing terminating " characterin gcc. This seems odd, because it means that the compiler allow the code blocks between#if 0andendifhave invalid statement likesomethinghere, but not double quotes"th...
See thecomp.Lang.c FAQ, 11.19: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that the characters " and ' must each be paired just as in real C code, and the pairs mustn't cross line boundaries.
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. I want to use pure c and print some...
You're looking forAA-lib. Or if you need color,libcaca.
I currently have this program that prints a text file on the console, but every line has an extra new line below it. if the text was hello world it would output hello world the code is this ``` #include <iostream> #include <stdio.h> #include <string.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { ...
Typically one would use fputs() instead of puts() to omit the newline. In your code, the ``` puts(input); ``` would become: ``` fputs(input, stdout); ```
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this question I assume that a pipeline should work that looks something like ``` |-> mpeg2dec -> autovideosink appsrc -> dvddemux = ...
You need a queue after the demuxer in both branches.
I have a selection of #defines in a header that are user editable and so I subsequently wish to check that the defines exist in case a user deletes them altogether, e.g. ``` #if defined MANUF && defined SERIAL && defined MODEL // All defined OK so do nothing #else #error "User is stoopid!" #endif ``` This wo...
``` #if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL) ```
How do i read a text written in console and then put it in the text file until user gives a terminating word?? I have written this but the problem seems to be that when i type exit it does not stop. ``` int _tmain(int argc, _TCHAR* argv[]) { FILE *fp; char sentence[80]; fp=fopen("c:\\users\\kostas\\desktop\\origina...
Change this:- ``` while(sentence!="exit") ``` to ``` while (strcmp (sentence,"exit") != 0) ```
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
You can get a good idea ofmostof the AirPlay specification by looking at the"Unofficial AirPlay Protocol Specification". As an example of an open source UDP media streaming protocol, check outPJSIP, in particular theUDP Media Transport.
\band\rare rarely used in practice. I just found out that I misunderstood these two escape sequences. A simple test: ``` printf("foo\bbar\n"); ``` I expected it to outputfobar, because\bwill backspace the cursor, andbwill overwrite the secondo, but instead it outputs:foobar The same is with\r: ``` printf("foo\rbar...
The characters will get send just like that to the underlying output device (in your case probably a terminal emulator). It is up to the terminal's implementation then how those characters get actually displayed. For example, a bell (\a) could trigger a beep sound on some terminals, a flash of the screen on others, o...
I receive a binary 64bit-float on the udp server in C. I can´t convert the char array buf which receives the binary float to the number. any ideas? ``` rc=recvfrom(s,buf,9,0,(SOCKADDR*)&remoteAddr,&remoteAddrLen); if(rc==SOCKET_ERROR) { printf("Fehler: recvfrom, fehler code: %d\n",WSAGetLastError()); system("Paus...
I have the Solution. I send binary Code... For Exemple the dezimal 322.. If i send it with 32 Bit integer it hat 32 Bits... I Receive it as Char.. One Char is 8 Bit Long... For the decimal 322 i reiceve 0 0 1 66... Its because the binary Code is 00000000 00000000 00000001 01000010 every Char[3] Stands for 0 char[2] fo...
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
False is printed as0. x!=5is false, hence%dwill print0, if you dox==5, it will print1. http://codepad.org/t8DAMu3A
I'm interested in knowing how theprintf()function's flush works when the program exits. Let's take the following code: ``` int main(int ac, char **av) { printf("Hi"); return 0; } ``` In this case, how doesprintf()manage to flush its buffer tostdout? I guess it's platform dependent, so let's take Linux. It...
The C runtime will registeratexit()handlers to flush standard buffers whenexit()is called. See thisexplanation.
I am using a c/c++ API which uses concept of main loop abstraction so I am confuse how the flow of programm works in main loop abstraction concept? is there any documentation for it ?? if anybody knows then, explain it with an example.
So, let's say you have one awesome library (for example OpenGL). It initializes some things via callbacks and then it enters awhile (1)loop in which it tests for events from the users of the library. Consider a GUI program. Each time you press a key or move your mouse or click a button an event is sent to the above l...
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. I want to use pure c and print some...
You're looking forAA-lib. Or if you need color,libcaca.
I currently have this program that prints a text file on the console, but every line has an extra new line below it. if the text was hello world it would output hello world the code is this ``` #include <iostream> #include <stdio.h> #include <string.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { ...
Typically one would use fputs() instead of puts() to omit the newline. In your code, the ``` puts(input); ``` would become: ``` fputs(input, stdout); ```
I want to implementing my own system call. (See below link) http://www.tldp.org/HOWTO/html_single/Implement-Sys-Call-Linux-2.6-i386/ But adding new system call requires kernel compilation. How to implement my own system call without recompiling the Linux kernel?
You can't. Without recompiling the kernel, all you can do is build and load kernel modules, and kernel modules cannot add new system calls.
I'm trying to output the offset of a struct member during compile time. I need to know the offset and later I'd like to add an #error to make sure the member stays at the same offset. There are a couple of ways I saw working methods to do that already in VS, but I'm using GCC and they didn't work properly. Thanks!
You can use theoffsetofmacro, along with the C++11static_assertfeature, such as follows: ``` struct A { int i; double db; ... unsigned test; }; void TestOffset() { static_assert( offsetof( A, test ) == KNOWN_VALUE, "The offset of the \"test\" variable must be KNOWN_VALUE" ); } ```
This question already has answers here:Where do the values of uninitialized variables come from, in practice on real CPUs?(4 answers)Closedlast year. Suppose I declare a variablexand leave it uninitialized. I go on to print its value. I see some junk. Where does it come from? Also why is it not used to generate rand...
The 'random' value is simply what's left in memory at that location. Memory usually isn't erased/zeroed when it's freed so whatever was there will linger until it's overwritten.
How can I select a random element from a character array in c ? For instance: ``` char *array[19]; array[0] = "Hi"; array[1] = "Hello"; ``` etc I am looking for something like array[rand], where rand is the random integer number between o and the array's length(in this case 20) like 1, 2, 3 , 19 etc.
To start things off, since you have an array of strings, not of characters, you have to declare it aschar* array[19]; Then, you can declare the following (always useful) macro #define ARR_SIZE(arr) ( sizeof((arr)) / sizeof((arr[0])) ) Last, you can choosearr[rand() % ARR_SIZE(arr)](while keeping in mind that perfor...
Given a command line tool which I use in the command line like this:./tool img/file.png How can I assign the first argument to a variable? I tried*argv[1],&argv[1],malloc(sizeof(argv[1]))but then I get aninvalid initializererror. Did I just not get a basic C concept or where am I stuck? Thanks for your help! ``` int...
``` char* block1_arg_Filename = argv[1]; ``` Of course, checkargc > 1before trying this.
``` #include <stdio.h> int myfunc(char *str) { char *ptr =str; while(*ptr++); printf("%s %s\n",str,ptr); return ptr-str-1; } int main() { printf("%d\n", myfunc("Princess Leia")); return 0; } ``` OUTPUT: ``` Princess Leia %d 13 ``` How does ptr got%das string in it? And why isptr-str-1i...
``` while(*ptr++); ``` incrementsptrstill whenptrpoints to the terminating 0 of the passed string, so after that it points behind the 0-terminator. With"Princess Leia"as argument,ptris incremented 14 times, so the return value is14 - 1 = 13. What is printed is - undefined behaviour aside, since dereferencingptris u...
For wcscmp() and wcscoll() are wide-character comparison. What is differences ?
Thewcscollwill interpret the parameters as appropriate to theLC_COLLATEcategory of the current locale. If local is not an issure,wcscmpfunctions should be used, especially with large wstrings for performance.
My today's task is to create a Python script (sayA.py) which can do the following things: Start a C program (sayCProg) passing some paramsStart another Python script (sayB.py) passing other paramsJoin/Wait untilB.pyhas finishedSend a SIGINT toCProgIterate (this won't be a problem at all I think :P) Since I'm pretty ...
Usesubprocessmodule. ``` import os import signal import subprocess import sys params = [...] for param for params: proc = subprocess.Popen(['/path/to/CProg', param.., param..]) subprocess.call([sys.executable, 'B.py', param.., param...]) os.kill(proc.pid, signal.SIGINT) proc.wait() ```
I have to implement 4 Hash Tables. The size of hash tables are going to be very large ~ 1 GB Each. The hash values will be the address of accessing the data. Now, since the hash values will be randomly distributed, I have to insert and read data from the hash tables randomly. What is the best way to implement such a d...
Berkeley DBsupports on-disk hash tables.
In a small application written in C/C++, I am facing a problem with therandfunction and maybe the seed : I want to produce a sequence of random numbers that are of different orders, i.e. with different logarithm values (base 2). But it seems that all the numbers produced are of the same order, fluctuating just betwee...
There are only 3% of numbers between 1 and 230which are NOT between 225and 230. So, this sounds pretty normal :) Because 225/ 230= 2-5= 1/32 = 0.03125 = 3.125%
I have a function like this: ``` void readString(char* str){ str="asd"; } ``` Can I know ifstrwill be dealloced? Or must I free it? Note: I can't use string library as I am programming a microprocessor.
free()must only be called ifmalloc(),calloc()orrealloc()was used to allocate memory. This is not the case in the posted code so callingfree()is unrequired. The"asd"is a string literal and exists for the lifetime of the program (has static storage duration).
While I went through some code, I found this declaration. ``` typedef int (*tMeshTable)(tOutPar *); ``` What is its intended purpose?
tMeshtable typedef'd to be a pointer to a function taking an tOutPar pointer and returning an int. It's easier to say tMeshTable than that whole thing every time. So when you want to pass it around to a function, for instance: ``` void functionThatCallsFunction(tMeshTable myFunction) { tOutPar * outPar; /* ...
I have 8 uint32 elements and i want to break each uint32 into 4 uint8 then add all uint8 beside each others as unsigned chars in the array , how can i do that ?
You can make use of the power ofunionfor this ``` union value { uint32 number; struct bytes { uint8 bytevalue[4]; }; }; ```
I'm trying to output the offset of a struct member during compile time. I need to know the offset and later I'd like to add an #error to make sure the member stays at the same offset. There are a couple of ways I saw working methods to do that already in VS, but I'm using GCC and they didn't work properly. Thanks!
You can use theoffsetofmacro, along with the C++11static_assertfeature, such as follows: ``` struct A { int i; double db; ... unsigned test; }; void TestOffset() { static_assert( offsetof( A, test ) == KNOWN_VALUE, "The offset of the \"test\" variable must be KNOWN_VALUE" ); } ```
This question already has answers here:Where do the values of uninitialized variables come from, in practice on real CPUs?(4 answers)Closedlast year. Suppose I declare a variablexand leave it uninitialized. I go on to print its value. I see some junk. Where does it come from? Also why is it not used to generate rand...
The 'random' value is simply what's left in memory at that location. Memory usually isn't erased/zeroed when it's freed so whatever was there will linger until it's overwritten.
How can I select a random element from a character array in c ? For instance: ``` char *array[19]; array[0] = "Hi"; array[1] = "Hello"; ``` etc I am looking for something like array[rand], where rand is the random integer number between o and the array's length(in this case 20) like 1, 2, 3 , 19 etc.
To start things off, since you have an array of strings, not of characters, you have to declare it aschar* array[19]; Then, you can declare the following (always useful) macro #define ARR_SIZE(arr) ( sizeof((arr)) / sizeof((arr[0])) ) Last, you can choosearr[rand() % ARR_SIZE(arr)](while keeping in mind that perfor...
Given a command line tool which I use in the command line like this:./tool img/file.png How can I assign the first argument to a variable? I tried*argv[1],&argv[1],malloc(sizeof(argv[1]))but then I get aninvalid initializererror. Did I just not get a basic C concept or where am I stuck? Thanks for your help! ``` int...
``` char* block1_arg_Filename = argv[1]; ``` Of course, checkargc > 1before trying this.
``` #include <stdio.h> int myfunc(char *str) { char *ptr =str; while(*ptr++); printf("%s %s\n",str,ptr); return ptr-str-1; } int main() { printf("%d\n", myfunc("Princess Leia")); return 0; } ``` OUTPUT: ``` Princess Leia %d 13 ``` How does ptr got%das string in it? And why isptr-str-1i...
``` while(*ptr++); ``` incrementsptrstill whenptrpoints to the terminating 0 of the passed string, so after that it points behind the 0-terminator. With"Princess Leia"as argument,ptris incremented 14 times, so the return value is14 - 1 = 13. What is printed is - undefined behaviour aside, since dereferencingptris u...
For wcscmp() and wcscoll() are wide-character comparison. What is differences ?
Thewcscollwill interpret the parameters as appropriate to theLC_COLLATEcategory of the current locale. If local is not an issure,wcscmpfunctions should be used, especially with large wstrings for performance.
My today's task is to create a Python script (sayA.py) which can do the following things: Start a C program (sayCProg) passing some paramsStart another Python script (sayB.py) passing other paramsJoin/Wait untilB.pyhas finishedSend a SIGINT toCProgIterate (this won't be a problem at all I think :P) Since I'm pretty ...
Usesubprocessmodule. ``` import os import signal import subprocess import sys params = [...] for param for params: proc = subprocess.Popen(['/path/to/CProg', param.., param..]) subprocess.call([sys.executable, 'B.py', param.., param...]) os.kill(proc.pid, signal.SIGINT) proc.wait() ```
I have to implement 4 Hash Tables. The size of hash tables are going to be very large ~ 1 GB Each. The hash values will be the address of accessing the data. Now, since the hash values will be randomly distributed, I have to insert and read data from the hash tables randomly. What is the best way to implement such a d...
Berkeley DBsupports on-disk hash tables.
In a small application written in C/C++, I am facing a problem with therandfunction and maybe the seed : I want to produce a sequence of random numbers that are of different orders, i.e. with different logarithm values (base 2). But it seems that all the numbers produced are of the same order, fluctuating just betwee...
There are only 3% of numbers between 1 and 230which are NOT between 225and 230. So, this sounds pretty normal :) Because 225/ 230= 2-5= 1/32 = 0.03125 = 3.125%
Or put differently, are there equivalents tointmax_tand%jdbut for floating point numbers? This has already been asked as a side questionhere, but the question is so large that I think people forgot to answer the side question. Also that was tagged as c++, and I'm looking for a c solution. Related questions: Are the...
To my knowledge C does not have extended floating point types. The only floating point types arefloat,double, andlong double. Thus,%La,%Le,%Lf,%Lg, andlong doubleseem to be your answers. Some implementations may provide additional extended types, but they are completely outside the scope of the standard.
I would like to synchronize folders and files between a server and some client. Due to the fact that the client part is limited by firewalls and proxy server, I'm forced to use a HTTP based solution. Is there any HTTP/REST based library (both server and client side) optimized for file synchronization? (Python or C b...
You could tryWebDAV Python hassome librariesto handle it
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. I'd like to know what is the differ...
The reason for your question is exactly shown in the figure given below In JAVA int [] arr1=int [5];is invalid in java
I have encountered this piece of code: ``` struct test { uint32 num_fields; char array_field []; }; ``` How can I understandarray_field? Is this a gcc extension for the C language?
It's a C99 feature, calledflexible array memberwhich is typically used to create a variable length array. It can only be specified as the last member of astructwithout specifying the size (as inarray_field [];). For example, you can do the following and the memberarrwill have 5 bytes allocated for it: ``` struct ...
I want to detect duplicates in a given array using divide and conquer approach. Can I use Merge Sort for this: First split the array in log N stepsThen sort by mergingWhile merging use a counter variable to detect duplicates. O(N) So in total it will take O(N log N) steps... Is this approach correct?
You don't need to. You can do it in O(n) You have the original array int A[N]; Create a secound array bool a[N] too, of type bool=false. Iterate the first array and set a[A[i]]=true if was false, else you have found a duplicate.
I have a piece of code which works well in debug mode in visual studio but crashes in release mode. After a lot of guess work, i found the piece of code which is causing the crash. ``` char *buff ="some random text"; char *temp = NULL; char *pos = NULL; int len = strlen("random text"); pos = strstr(buff,"random"); t...
The code section shown looks fine.As an addition with unwind's answer.Possible reasons of failing may be 1)uninitialised variables 2)the preprocessor symbols _DEBUG and NDEBUG. If you have any code inside an #ifdef _DEBUG / #endif block. 3)compiler optimisation
When I run the program for the first time, the file gets created. But it seems the while loop takes a long time to get over. Doesnt it get an EOF in the beginning of the file since the file is empty as of now? ``` #include<stdio.h> void main(){ FILE *p; int b, a=0;b=0; p=fopen("text.txt", "a+"); while...
Make surefscanf returns 1: ``` #include<stdio.h> int main(){ FILE *p; int b=0, a=0; p=fopen("text.txt", "a+"); while((b=fscanf(p,"%d",&a)) == 1) printf("%d\n",a); // no need to seek, or flush fprintf(p, " %d %d",1,6); fclose(p); return 0; } ```
Here is a C language function, which I am having a little trouble understanding. I need to show what values ofrcome out when I input values of 6 or 10 or 13 into the function: ``` int factor(int val){ int r=val-1; while(val%r){ r--; } return r; } ``` I'm not sure if I misunderstood the question but wouldn't the r...
Test for yourself:4 % 2. The result should be0as the%operator returns the remainder of a division. while(x % y) {}translates in this context to something like: as long asxis not dividable byy, do something, whereby 'do something' is decreaseyin your case.
This question already has answers here:Forcing GCC to compile .cpp file as C(2 answers)Closed10 years ago. I have a C++ project [IDE = codelite] which tries to compile .c extention using g++ I want to specify a flag for .c file so that g++ treats it as c What is the g++ command line option to make it behave as gcc ?...
Either ``` gcc file.c ``` or ``` g++ -x c file.c ``` will do what you want...
Essentially, I'm simulating object-oriented programming in basic C, due to necessity. For my own convenience, I'd like to use a macro or an inline function to reduce the amount of code I need to write. For my 400+ variables, each needs a structure like ``` int x; int get_x(){ return x; } void set_x(int a){ x ...
``` #define MAKE_OOP_VAR(var_type, var_name) \ var_type var_name; \ var_type get_##var_name() { return var_name; } \ void set_##var_name(var_type tmp) { var_name = tmp; } \ MAKE_OOP_VAR(int, x); ``` Not compile tested but off the top of my head.
I don't know if this is possible, nor even if it is correct, but I have a macro defined in a .c file and now I want to expose that macro, so I need put it in the .h file. But I dont want to expose how it is implemented, just the signature for use. ``` //.c #define sayhi() printf("hi"); //.h sayhi() //another.c int ...
Don't make it a macro then. Just make it a function call. Your .h file: ``` extern void DoSomething(int x, int y, int z); ``` Your .c file: ``` void DoSomething(int x, int y, int z) { // your code goes here. } ```
Considering 64 bit ``` #include<stdio.h> int main() { unsigned a=0xffffffff; a=~a; printf("%u\n",a); printf("%x\n",+ + a); return 0; } OUTPUT: 0 0 ``` after taking ~a , a is now 0. but in statement "+ + a". "a" is not incrementing why? does space matters here or what ?i am asking for ou...
+ + ais parsed as the unary+operator applied twice, so the value remains unchanged. +(+a)is what the compiler saw, which is just 0 in this case
Is there a convenient library call that allows me to open the default browser that I can use from C? I poked around in glib and didn't see anything. There is xdg-open, and I can just system that I guess. Any better ideas?
Since you tagged this question with "glib", the right solution is probably to useg_app_info_launch_default_for_uri(or one of the other GAppInfo methods, depending on your exact use case).
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question I am using an array,i want to call 4 element from the array at the same time so i can use them in an equa...
using C#: 1234 = 1*1000 + 2*100 + 3*10 + 4*1 ``` double result = 0; int ex = 3; // Math.Pow(10,3) = 1000.00 for(int i = 0; i < 4 0; i++) { result += a[i] * Math.Pow(10, ex); ex--; } result += 15; ```
Given an application's pid, is there any way, programatically, of detecting if that application is running in an OSX sandbox environment? Ideally, I'd like to know if there's an API call somewhere, preferably in C, rather than objective-C (for a daemon, so not using Cocoa), but if not, is there any other way of check...
@Linuxios was right partly right about there being a CoreFoundation call. In fact, there are a few that when combined, can be used to solve this and it's based on the call toSecStaticCodeCheckValidityWithErrors For anyone that may want, or need to programmatically test for an app being sandboxed can followthis blog. ...
I have a programe, which is so simple. The code as below. I compiled it with ``` gcc -g -Wall -I../software/libxml2-2.9.0/include/ -lxml2 -L/usr/lib test.c -o test ``` I can absolutely run it with "./test", but when I run it with "gdb test" and then print "run" it will receive signal SIGSEGV. So I want to k...
If you are debugging usinggdb testyou may actually be debugging/bin/testrather that your own program. If the backtrace does not correspond to your expected program switch togdb ./test(in a similar manner to how you are running the program as./test)
Is there any way to determine the number of characters printed to an output stream in java? Like for example in C the printf returns the number of characters printed in that particular statement. ``` int i=printf("hello"); printf(i); ``` the above piece of code would print hello and 4; is there any way to achieve ...
You are printing so you know the string to be displayed. Simple is that you get the string length. ``` string str="Hello World!"; System.out.println(str); System.out.println(str.length()); ```
I need a function that can clear the screen in both Linux and Windows. To do this, I want to know if there are some instructions that can tell me what operating system I'm working with. I have searched for solution and I found the following code: ``` void clear_screen() { #ifdef WINDOWS std::system ( "CLS" );...
Macros such as_WIN32,__gnu_linux__,__linux__are defined by the compiler in question. You can find a comprehensive list of pre-defined compiler macroshere. _WIN32is defined for both 32-bit and 64-bit environments of Windows.
I have a symbolic link /home/me/symlink -> /home/me/realdir when I try to getcwd in the directory /home/me/symlink I get /home/me/realdir with the following program: ``` int main(int argc, char **argv) { int ret; char path[PATH_MAX]; getcwd(path, PATH_MAX); printf("path %s\n", path); return 0; } `...
I. No (docs) : The pathname shall contain no components that are dot or dot-dot, or are symbolic links. However, there's a workaround: ``` char *cwd = getenv("PWD"); ``` II. Yes (docs) : ``` chdir("/path/to/newcwd"); ```
``` if(turn==2) { if(forward) /*then what to do if this if comes true for coming out of outer loop*/ if(columnHead>0) { columnHead--; addr[columnHead] |=1<<(rowHead-1); } else { columnHead =7; addr[columnHead] |=1<...
You should create function of this code, and return from the block where the condition becomes true.
To copy an arrayb[]into the arraya[], one can use functionmemcpyas follows;memcpy(a,b,sizeof(a)).Butmemcpysimply copies bytes from one place to another.My questions are: 1.Howmemcpycopies elements of arrayb[]intoa[]by copying bytes?2.Whysizeof(a)is supplied as arguments? I am new to programming so, be gentle.
sizeof(a)is the total size of the arraya. For example, in ``` int a[3]; printf("%d", sizeof(a)); ``` sizeof awill be12on most systems (sinceintis usually 4 bytes and you have 3 of them). memcpydoesn't know thatais an array. All it knows is thatapoints to some memory address, so you have to tell it how many bytes ...
What is the method to use a timer in C? I need to wait until 500 ms for a job. Please mention any good way to do this job. I usedsleep(3);But this method does not do any work in that time duration. I have something that will try until that time to get any input.
Here's a solution I used (it needs#include <time.h>): ``` int msec = 0, trigger = 10; /* 10ms */ clock_t before = clock(); do { /* * Do something to busy the CPU just here while you drink a coffee * Be sure this code will not take more than `trigger` ms */ clock_t difference = clock() - before; msec ...
What are constant arrays? If we define ``` const char hex_char[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; ``` Then, it should not be mod...
It means that you can't modify its content. For example you are not allowed to dohex_char[i] = 'A', it will result in compilation time error.
I am trying to link the my C code, and I got the following error message: ``` Error 126: Inconsistent structure definition 'unnamed' ``` there is no line number indicated which line has problems, and I do not have any structure of "unnamed", so I can not post the suspected code to here, have anyone experience this a...
Error 126: The named structure (or union or enum) was inconsistently defined across modules. The inconsistency was recognized while processing a lint object module. Line number information was not available with this message. Alter the structures so that the member information is consistent. Maybe a tagles...
I know that with the usage of ctime like this ``` time_t now; time(&now); fprintf(ft,"%s",ctime(&now)); ``` returns me the datetime in this way ``` Tue Jun 18 12:45:52 2013 ``` My question is if there is something similar with ctime to get the time in this format ``` 2013/06/18 10:15:26 ```
Usestrftime ``` #include <stdio.h> #include <time.h> int main() { struct tm *tp; time_t t; char s[80]; t = time(NULL); tp = localtime(&t); strftime(s, 80, "%Y/%m/%d %H:%M:%S", tp); printf("%s\n", s); return 0; } ```
everybody. I have installed gdb (throw cygwin) on my Windows 8 machine with NetBeans 7.3. As the title said my problem is that the breakpoints just disappear when I run the debug ( to reappear as soon as it finished), so basically I have a normal run. Any ideas how to fix that, the tutorial on the Netbeans page doe...
If you compiled your code with optimizer flags, then the line may not exist. When debugging, compile your code with-gand remove-O
I am trying to implement following command, ls | grep "SOMETHING" in c programming language. Can anybody please help me with this. I want to fork a child , where i will run ls command using execlp. In the parent i get the output of the child and grep (once again using execlp). Is it not possible?
I finally found the code for it. ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { int pfds[2]; pipe(pfds); if (!fork()) { close(1); /* close normal stdout */ dup(pfds[1]); /* make stdout same as pfds[1] */ close(pfds[0]); /* we don't need this */ execlp("ls", "ls...
I have the following code: ``` char temp[32] = ""; sprintf(temp, "%02s", "A"); ``` but it has warning as:Warning 566: Inconsistent or redundant format char 's', then I changed to code to:sprintf(temp, "%2s", "A");, the warning disappeared, what is the difference?
The%0format means "0-padding", but you can't combine that with a string format specifier (s), that's undefined. Seethe manual page: 0The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - f...
I have a dynamically allocated array of structs. I want to cast it to an array type so my debugger will show the whole array. Is it possible? I know that this cast is not a good idea, but it's only a cast for expression evaluation of the debugger. –
I want to cast it to an array type so my debugger will show the whole array. Is it possible? Yes. For example, if you allocated array of 100 elements of typet_my_structthen cast pointer tot_my_struct=> pointer to array of 100 elements of typet_my_struct: ``` t_my_struct * Dynamic = ( t_my_struct * )calloc( 100, size...
I have the following code: ``` int number; char temp[32] = ""; number = snprintf(temp, sizeof(char), "%c", 'A'); ``` I made this variablenumberbecausesnprintfhas a return value, number can remove the warning of"ignore of return value of snprintf", then it gets another lint warning:Warning 550: Symbol 'number' not ...
In this case number receives the bytes printed bysnprintfand lint is warning about a non used variable, you can skip this lint warning with number = snprintf(temp, sizeof(char), "%c", 'A'); /* lint -save -e550 */ or as others says ``` (void)snprintf(temp, sizeof(char), "%c", 'A'); ```
There is a task to build some sort of a dictionary for list of suffixes, for an instance: ``` [., .com., a.com., a.b.com., org., some.org., ...] ``` and for each incoming string, for an instance "test.some.org." find the longest suffix in the built dictionary. There are some memory limitations. What is the most pro...
For an immutable set of string, thecompressed trieworks very well. The main idea is to represent a single branch in the trie as one node. There are many useful descriptions/papers of this method in the web.
I was wondering what the most suitable tool is for extracting c (and eventually c++) function names, arguments and their types from source code. I would like to use a tool that can be automated as much as possible. I want to extract the signature types then have the output read by another program written in Erlang. M...
Surely there is something better, but if you don't find it: ``` gcc -aux-info output demo.c sed '/include/d' output ``` Extracts functions form source code skipping standard functions
I need to create user timer and thread in windows kernel program. Anyone please give a clue that if the regular threading headers are applicable in this mode?
You need to look into KMDF or WDM if you are using some old drivers. For timers see this: http://msdn.microsoft.com/en-us/library/windows/hardware/ff550050(v=vs.85).aspx And here are threads or work items: http://msdn.microsoft.com/en-us/library/windows/hardware/ff551203(v=vs.85).aspx
This question already has answers here:Use sed to replace all backslashes with forward slashes(9 answers)Closed10 years ago. I am porting my C programs from Windows to Linux. The problem is that Linux (Unix-like) does not recognize\as directory separator, sayshere. So I have to substitute\to/in all my#includestatemen...
Try this command invim: ``` :g/#include/s@\\@/@g ``` You can also usesed: ``` $ sed -i '/#include/s@\\@/@g' code.c ``` If you want to substitute multiple files: ``` $ vim *.c :argdo your_command | update ``` Or ``` $ sed -i your_command *.c ``` Or ``` $ find . -name '*.c' -exec sed -i your_command {} \; ```...
How can I resize the Windows console window in C?
Alright, after much deliberation, I got the code working. Using this include: ``` #include <windows.h> ``` This struct: ``` struct SMALL_RECT { SHORT Left; SHORT Top; SHORT Right; SHORT Bottom; }; ``` And this function: ``` void adjustWindowSize() { struct SMALL_RECT test; HANDLE hStdou...
How do you block until the request response finished in libcurl? I need to block becauseCURLOPT_WRITEFUNCTIONasynchronously writesto the C-String; so I need to be sure that I can get the full output from a request before I act on the data.
I fixed this by making the callback function returnreturn nmemb*size; See here for more info:http://curl.haxx.se/mail/lib-2002-12/0065.html ``` char *array; int arraySize = 0; size_t storeContent(char *ptr, size_t size, size_t nmemb, void *userdata) { int thisSize = nmemb * size; arraySize += thisSize; array...
How to do transpose for tptrs in blas? I want to solve: ``` XA = B ``` But it seems that tptrs only lets me solve: ``` AX = B ``` Or, using the 'transpose' flag, in tptrs: ``` A'X = B ``` which, rearranging is: ``` (A'X)' = B' X'A = B' ``` So, I can use it to solve XA = B, but I have to first transpose B manu...
TPTRS isn't a BLAS routine; it's an LAPACK routine. If A is relatively small compared to B and X, then a good option to unpack it into a "normal" triangular matrix and use the BLAS routine TRSM which takes a "side" argument allowing you to specify XA = B. If A is mxm and B is nxm, the unpacking adds m^2 operations wh...
This question already has answers here:Since I can't return a local variable, what's the best way to return a string from a C or C++ function?(8 answers)Closed10 years ago. I have a main function that has to receive a string. ``` main() { char *c = fun(); } char* fun() { char a[] = "hello"; return a; } ...
You return a pointer to a local variable. The variable is stack-allocated, and it is destroyed when the function exits. Using such pointer is undefined behaviour.
I have a programe, which is so simple. The code as below. I compiled it with ``` gcc -g -Wall -I../software/libxml2-2.9.0/include/ -lxml2 -L/usr/lib test.c -o test ``` I can absolutely run it with "./test", but when I run it with "gdb test" and then print "run" it will receive signal SIGSEGV. So I want to k...
If you are debugging usinggdb testyou may actually be debugging/bin/testrather that your own program. If the backtrace does not correspond to your expected program switch togdb ./test(in a similar manner to how you are running the program as./test)
Is there any way to determine the number of characters printed to an output stream in java? Like for example in C the printf returns the number of characters printed in that particular statement. ``` int i=printf("hello"); printf(i); ``` the above piece of code would print hello and 4; is there any way to achieve ...
You are printing so you know the string to be displayed. Simple is that you get the string length. ``` string str="Hello World!"; System.out.println(str); System.out.println(str.length()); ```
I need a function that can clear the screen in both Linux and Windows. To do this, I want to know if there are some instructions that can tell me what operating system I'm working with. I have searched for solution and I found the following code: ``` void clear_screen() { #ifdef WINDOWS std::system ( "CLS" );...
Macros such as_WIN32,__gnu_linux__,__linux__are defined by the compiler in question. You can find a comprehensive list of pre-defined compiler macroshere. _WIN32is defined for both 32-bit and 64-bit environments of Windows.
I have a symbolic link /home/me/symlink -> /home/me/realdir when I try to getcwd in the directory /home/me/symlink I get /home/me/realdir with the following program: ``` int main(int argc, char **argv) { int ret; char path[PATH_MAX]; getcwd(path, PATH_MAX); printf("path %s\n", path); return 0; } `...
I. No (docs) : The pathname shall contain no components that are dot or dot-dot, or are symbolic links. However, there's a workaround: ``` char *cwd = getenv("PWD"); ``` II. Yes (docs) : ``` chdir("/path/to/newcwd"); ```
``` if(turn==2) { if(forward) /*then what to do if this if comes true for coming out of outer loop*/ if(columnHead>0) { columnHead--; addr[columnHead] |=1<<(rowHead-1); } else { columnHead =7; addr[columnHead] |=1<...
You should create function of this code, and return from the block where the condition becomes true.
To copy an arrayb[]into the arraya[], one can use functionmemcpyas follows;memcpy(a,b,sizeof(a)).Butmemcpysimply copies bytes from one place to another.My questions are: 1.Howmemcpycopies elements of arrayb[]intoa[]by copying bytes?2.Whysizeof(a)is supplied as arguments? I am new to programming so, be gentle.
sizeof(a)is the total size of the arraya. For example, in ``` int a[3]; printf("%d", sizeof(a)); ``` sizeof awill be12on most systems (sinceintis usually 4 bytes and you have 3 of them). memcpydoesn't know thatais an array. All it knows is thatapoints to some memory address, so you have to tell it how many bytes ...
What is the method to use a timer in C? I need to wait until 500 ms for a job. Please mention any good way to do this job. I usedsleep(3);But this method does not do any work in that time duration. I have something that will try until that time to get any input.
Here's a solution I used (it needs#include <time.h>): ``` int msec = 0, trigger = 10; /* 10ms */ clock_t before = clock(); do { /* * Do something to busy the CPU just here while you drink a coffee * Be sure this code will not take more than `trigger` ms */ clock_t difference = clock() - before; msec ...
What are constant arrays? If we define ``` const char hex_char[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; ``` Then, it should not be mod...
It means that you can't modify its content. For example you are not allowed to dohex_char[i] = 'A', it will result in compilation time error.
I am trying to link the my C code, and I got the following error message: ``` Error 126: Inconsistent structure definition 'unnamed' ``` there is no line number indicated which line has problems, and I do not have any structure of "unnamed", so I can not post the suspected code to here, have anyone experience this a...
Error 126: The named structure (or union or enum) was inconsistently defined across modules. The inconsistency was recognized while processing a lint object module. Line number information was not available with this message. Alter the structures so that the member information is consistent. Maybe a tagles...
I know that with the usage of ctime like this ``` time_t now; time(&now); fprintf(ft,"%s",ctime(&now)); ``` returns me the datetime in this way ``` Tue Jun 18 12:45:52 2013 ``` My question is if there is something similar with ctime to get the time in this format ``` 2013/06/18 10:15:26 ```
Usestrftime ``` #include <stdio.h> #include <time.h> int main() { struct tm *tp; time_t t; char s[80]; t = time(NULL); tp = localtime(&t); strftime(s, 80, "%Y/%m/%d %H:%M:%S", tp); printf("%s\n", s); return 0; } ```
everybody. I have installed gdb (throw cygwin) on my Windows 8 machine with NetBeans 7.3. As the title said my problem is that the breakpoints just disappear when I run the debug ( to reappear as soon as it finished), so basically I have a normal run. Any ideas how to fix that, the tutorial on the Netbeans page doe...
If you compiled your code with optimizer flags, then the line may not exist. When debugging, compile your code with-gand remove-O
I am trying to implement following command, ls | grep "SOMETHING" in c programming language. Can anybody please help me with this. I want to fork a child , where i will run ls command using execlp. In the parent i get the output of the child and grep (once again using execlp). Is it not possible?
I finally found the code for it. ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { int pfds[2]; pipe(pfds); if (!fork()) { close(1); /* close normal stdout */ dup(pfds[1]); /* make stdout same as pfds[1] */ close(pfds[0]); /* we don't need this */ execlp("ls", "ls...
I have the following code: ``` char temp[32] = ""; sprintf(temp, "%02s", "A"); ``` but it has warning as:Warning 566: Inconsistent or redundant format char 's', then I changed to code to:sprintf(temp, "%2s", "A");, the warning disappeared, what is the difference?
The%0format means "0-padding", but you can't combine that with a string format specifier (s), that's undefined. Seethe manual page: 0The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - f...