question
stringlengths
25
894
answer
stringlengths
4
863
So, basically, I have two different structures defined in two different .h files (vcard.h and bst.h), both of which are included in the current file. Here are the structure definitions: ``` struct bst { vcard *c; bst *lsub; bst *rsub; }; struct vcard { char *cnet; char *email; char *fname; char *lname;...
c is a pointer, you need t->c->cnet
I have this example on how to convert from a base 10 number to IEEE 754 float representation ``` Number: 45.25 (base 10) = 101101.01 (base 2) Sign: 0 Normalized form N = 1.0110101 * 2^5 Exponent esp = 5 E = 5 + 127 = 132 (base 10) = 10000100 (base 2) IEEE 754: 0 10000100 01101010000000000000000 ``` This makes sense...
Simple place value. In base 10, you have these places: ... 103102101100.10-110-210-3...... thousands, hundreds, tens, ones . tenths, hundredths, thousandths ... Similarly, in binary (base 2) you have: ... 23222120.2-12-22-3...... eights, fours, twos, ones . halves, quarters, eighths ... So the second place after ...
I'm a little confused about the correct syntax for assigning a function pointer to a variable. If I have a function foo ``` int foo(); ``` and I am assigning a pointer to foo to variable bar ``` void * bar; ``` it does not seem to matter if I use ``` bar = foo; // or bar = &foo; ``` It seems to me that only on...
fooand&foovalues are equivalent in C and have same type. The&operator here is correct but redundant. Note that assigning a function pointer to avoid *is not valid in C. ``` void *fp1 = foo; // invalid int (*fp2)() = foo; // valid int (*fp3)() = &foo; // valid ``` (These are actually declarations but the constr...
I have a nanosleep function in while loop. This is an example I found in book "Linux System Programming: Talking Directly to the Kernel and C Library" ``` while(nanosleep(a, b) && errno==EINTR){ struct timespec *tmp =a; a=b; b=tmp; } ``` Works perfect but I am not sure how can I check for...
You can simply store the return value in the loop condition: ``` int ret; while((ret = nanosleep(a, b)) && errno==EINTR){ struct timespec *tmp =a; a=b; b=tmp; } if (ret) { perror("nanosleep"); exit(1); } ```
In the C++ standard 18.4 it specifies: ``` typedef 'signed integer type' intmax_t; ``` By the standard(s) on a platform with a 64-bitlong intand a 64-bitlong long intwhich should this "signed integer type" be? Note thatlong intandlong long intaredistinctfundamental types. The C++ standard says: The header defines...
Yes, your reasoning is correct. Most real-world implementations choose the lowest-rank type satisfying the conditions.
I have this function declaration: ``` void gaussian_blur ( const unsigned char* const inputChannel, unsigned char* const outputChannel, const float* const filter ) {..} ``` I'm new to C. I've gone through basic tutorials and understand the concept of pointers and constants, but I can't make sense what i...
``` const unsigned char* const inputChannel; ``` Input channel is a constant pointer to a constant unsigned char. ``` unsigned char* const outputChannel; ``` OutputChannel is a constant pointer to a unsigned char. ``` const float* const filter ``` filter is a constant pointer to a constant float. Constant pointe...
I need read the stdin in Linux, although my program will receive only messages without new line. I tried this code, but is not working: ``` int main ( void ) { char p_char[48]; memset( p_char, 0, sizeof(p_char) ); fcntl( STDIN_FILENO, F_SETFL, FNDELAY ); read( STDIN_FILENO, p_char, sizeof(p_char) );...
You'd need to change the terminal settings so that each character is sent immediately. You can do it by manipulatingtermios(the man page has details). Essentially it just involves creating twotermiosstructures, initialising one with the current settings withtcgetattr, copying the struct to the other structure, modify...
I have an Win32 application with no window written in C. My question is: is there any way to handle the termination of my application. Ex. closing it from the task manager or via the console.
It is unclear from the question, but if this is a console mode application then you can callSetConsoleCtrlHandlerto install a callback that Windows will call just before it terminates your app. Beware that this callback runs on a separate thread and that you have to complete the callback function quickly. If it is a...
``` int main(){ char a[80] = "Angus Declan R"; char b[80]; char *p,*q; p = a; q = b; while(*p != '\0'){ *q++ = *p++; } *q = '\0'; printf("\n p:%s q:%s \n",p,q); puts(p); //prints the string puts(q); //doesnt print the string return 0; } ``` why the strings are not copied from p to q? when trying to prin...
add ``` p = a; q = b; ``` again before ``` printf("\n p:%s q:%s \n",p,q); puts(p); //prints the string puts(q); //doesnt print the string ``` Because thepandqpointers are incremented in thewhileloop and they are not pointing any more in the beginning of theaandbchar arrays BTWand Just as remark: You can replac...
I know that you can tell C to interpret a value as hex using printf("\xab"). If you input "\xab" to a C program as input it will interpret it as the characters -x-a-b. Is there any way to embed printf-style formatting information into raw input?
No, it all depends on how the code that reads the characters interpret them. You can't magically force a program to do something else from the outside, by giving it text. I guess a buffer overrun attack is a bit of a counter-example, but that's rather extreme. Many programs that use e.g.strtol()automatically support0...
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...
Yes, you can use C programming language on Mac. The main programming language on Mac OS X is Objective-C, which is based on C language. You can download Xcode from the AppStore and start developing your own application. C is perfectly fine, as it is subset of Objective-C. I suggest you to start here:http://www.cocoa...
How much space a character takes when saving it to file in binary mode [8 bits or 12 bits]? ``` fprintf(f,"%ld",ch); ``` also if I save a long [say 5] then how much space it gonna take 3bits [101] or 8bits[00000101]
``` fprintf(f,"%ld",...) ``` will convert your number to a decimal number and will take log_10(ch) bytes to store. When you store it withfwriteit will take as much bytes as you specify. ``` fwrite (buffer , 1 , sizeof(buffer) , f ) ``` Also attention as you will never store single bits to a file as the read write ...
How to kill/close application/process by PID or name? I tried to use C function but it doesn't work. (E.g. try to kill LinkedIn application/process). ``` pid_t pid = 3696; //GetProcessPIDForLinkedIn(); kill(pid, SIGQUIT); ``` I don't plan to deploy it on App Store but it should work for non jailbroken devices
Unless you are root and on a jailbroken device, you cannot kill other apps programmatically. Apps live in a sandbox and are unable to affect other apps or their documents or data. THe only exception is launching an app and passing data to it. If all these apps are your own then you could use this as by passing them s...
The following test code produces an undesired output, even though I used a width parameter: ``` int main(int , char* []) { float test = 1234.5f; float test2 = 14.5f; printf("ABC %5.1f DEF\n", test); printf("ABC %5.1f DEF\n", test2); return 0; } ``` Output ``` ABC 1234.5 DEF ABC 14.5 DEF ``...
The following should line everything up correctly: ``` printf("ABC %6.1f DEF\n", test); printf("ABC %6.1f DEF\n", test2); ``` When I run this, I get: ``` ABC 1234.5 DEF ABC 14.5 DEF ``` The issue is that, in%5.1f, the5is the number of characters allocated for the entire number, and1234.5takes more than five char...
I'm using Doug Lea'smalloc.candmalloc.hin the following code: ``` #include <stdio.h> #include <string.h> #include "dlmalloc.h" #define USE_DL_PREFIX int main() { char *test = dlcalloc(5, 1); strcpy(test, "helloextra"); dlfree(test); /* Shouldn't this crash? */ printf("%s", te...
Your code hasundefined behaviourinstrcpy(). It is permitted to crash, but not required to. Basically, once the behaviour is undefined,anything can happen.
i wanna know what is the difference between ``` void fct1(int *p) ``` and ``` void fct1(int p[]) ``` i know that both are pointers but are there any differences
There is absolutely no difference when used as a function parameter like that. The compiler treats both forms identically.
According to pthread_create man page, the argument of the function is: ``` int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); ``` regarding the void*arg, I just wonder if I can pass multiple argument to it, because the function that I ...
With yourvoid*you can pass a struct of your choosing: ``` struct my_args { int arg1; double arg2; }; ``` This effectively allows you to pass arbitrary arguments in. Your thread start routine can do nothing other than un-pack those to call the real thread start routine (which could in itself come from that struct...
I'm using C++, but I decided to parse the lines of a log file withsscanf. After reading each line, it should extract data and store them to variables. ``` string test = "[06/03/2013 18:15:23] INFO - Open [Johny Cage]"; int day, month, year, second, minute, hour; char name[128]; int c = sscanf(test.c_str(), "[%d/%d/...
Use[^]]instead of[^\n]. Also, remove the%cat then end of your scan format string. ``` int c = sscanf(test.c_str(), "[%d/%d/%d %d:%d:%d] INFO - Open [%127[^]]]", &day, &month, &year, &second, &minute, &year, name); ```
This question already has answers here:Nested case statements(2 answers)Closed9 years ago. This code works for some reason but it does not make sense at all. ``` #include <stdio.h> int main(void) { switch(1) { case 0: while(1) { case 1: puts("Works"); break; } ...
Thecaselabels are almost exactly like labels used bygoto.1If you think of your code in those terms, it should be clear that it's valid. Namely, you can consider aswitchstatement to be a glorified conditionalgoto. That said, I would slap anyone who wrote code like that in a production environment.2 In fact, they ...
I'm learning C (I just finished Chapter 2 or Unit 2) of the C Programming Language, I skimmed to the end and saw that at no point anything was said about how to create a GUI, and from what I've looked up, it seems I have to use a framework, but I hate the idea of that. How would I create a GUI without a framework? How...
You can build your own framework based on OpenGL or Xlib. Or use good graphics library likeMotiforCGUI. Or use something awful like GTK.
I am working on the following problem of SPOJ , http://www.spoj.com/problems/ARITH/ It is said that the number should contain atmost 500 digits , what is the appropriate datatype for a number with maximun 500 digits
There is no builtin datatype to hold an integer of 500 digits. Thus, you have to come up with a way to store them in an array of bytes. Get inspired by whathttp://gmplib.org/does. In short, you will have to first store the digits somewhere: ``` struct Digit { size_t len; char sign; char* digits; }; ``...
all:There is a shell script a.sh: ``` #/bin/bash -x -n source /etc/profile ``` and a test.c program use system() function to invoke this script: ``` #include <stdio.h> int main(void) { system("/data/nan/a.sh"); return 0; } ``` I find when call a.sh directly in console: ``` ./a.sh ``` It is OK. But exec...
You are missing a!in the shebang: ``` #!/bin/bash -x -n ^ ```
I have a bug that I've found boils down to this: ``` #include <sys/types.h> #include <sys/stat.h> #include <fts.h> #include <stdlib.h> int main () { char *LOG_ROOT = "/var/log"; FTS *ftsp; FTSENT *p, *chp; int fts_options = FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR; char *paths[] = { LOG_ROOT ...
The first arg. is expected to be aNULL terminated arrayof character pointers. ``` char *paths[] = { LOG_ROOT, NULL}; ```
I need to allocatet2but I don't know exactly how. ``` char *reverse(char *t) { int length= strlen(t); char *t2 = (char *) malloc(length * sizeof(char*)); for(int i= (length-1);i>=0;i--) t2[i]=t[length-1]; return t2; } ``` Any help please?
You're close. ``` char *t2 = malloc(length + 1); // reserve space for a null terminator ``` You probably want that loop to start atlength, and notlength - 1, though. The assignment inside the loop is wrong, too (you only change the destination location, not the source). Make sure to null terminate the string befor...
The first call to printf below prints out my line. The second call to printf prints out whitespace. What's going on? ``` while (getline(&line, &size, config_file) != -1) { printf("line: %s\n", line); /* check to see if this line is a comment */ char marker[1]; sscanf(line, "%1s", marker); pri...
``` sscanf(line, "%1s", marker); ``` Apart from the one character you did specify it also stores a\0terminator inmarker. It's obviously undefined but my guess is that\0overwritesline. In other wordsmarkerneeds to be at least 2 characters wide to store a one character string.
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...
Useprintf("%d", x)instead ofprintf("%d", &x).
I have created a kernel module, which handles interrupts. Also, there is a C program. This program causes interrupts during its execution. When the interrupt is coming, the program should be suspended, and stay suspended - until the interrupt handler in kernel module will finish handling this interrupt. Please tell ...
You could wait on a mutex with attributePTHREAD_PROCESS_SHAREDset while your kernel module is doing it's thing, when the kernel module is done, you can signal the mutex so that your process can continue. To set this you can usepthread_mutexattr_setpshared There is also this: For inter-process synchronization, a mut...
This question already has answers here:Underscore `_` before the format string(3 answers)Closed3 years ago. In C code I came across this bit ``` _("test") ``` What does it do? (I tried to look it up myself, but as you can imagine, search engines do not support searching for that...)
It is calling the function called_. For instance: ``` #include <stdio.h> void _(int a) { printf("%d",a); } int main(void) { _(3); return 0; } ``` _is an existing function ingettext libraryand is used for internationalization. As said inthis answer: This function basically replaces the given st...
I have the following line (in C): ``` char *tmp; ``` Now, I want that variabletmpbe initialized to some pointer in my code (a few lines bellow), and after that want be initialized to an array. Is there a way to allocate totmpthe pointer to a new created array on the stack, without creating another variable? So, ins...
You can do it like this, using thecompound literalfeature: ``` tmp = (char[]){'a', 'b', 'c'}; ```
This question already has answers here:min and max value of data type in C(10 answers)Closed10 years ago. I'm trying to figure out the minimum and maximum values for C data types like short, int and long. I found minimum sizes in a wikipedia article, but I have no idea how to find the maximum for my computer. I hav...
You can use{TYPE}_[MIN|MAX]macros defined inlimits.hto check type range: ``` printf("range of short int: %d - %d", SHRT_MIN, SHRT_MAX); ``` You can usesizeofoperator, to check type size: ``` printf("size of short int: %zu", sizeof(short int)); ``` EDIT: Also check @JoachimPileborg answer as he has provided a bett...
Consider: ``` #include <stdio.h> #define macro(a) a=a<<4; main() { int a = 0x59; printf("%x", a); printf("\n"); macro(a) printf("%x", a); } ``` For the above code, I am getting the below output: ``` 59 590 ``` Why am I not getting the below output as the left shift operation? ``` 59 90 ```
Left shifts donottruncate the number to fit the length of the original one. To get90, use: ``` (a<<4) & 0xff ``` 0x59is anintand probably on your platform it hassizeof(int)==4. Then it's a0x00000059. Left shifting it by 4 gives0x00000590. Also, form a good habit of usingunsigned inttypes when dealing with bitwise o...
So I'm trying to figure out why the following C code doesn't work: ``` int isBlank(char *s){ for(;*s != '\0';s++){ if(*s != '\n' || *s != '\r'){ return 0; } } return 1; } ``` The idea is that it should return 0 if it hits anything BUT a \n or \r character otherwise it will ret...
Your logic is slightly off - change: ``` if(*s != '\n' || *s != '\r'){ ``` to: ``` if(*s != '\n' && *s != '\r'){ ```
I'm learning C (I just finished Chapter 2 or Unit 2) of the C Programming Language, I skimmed to the end and saw that at no point anything was said about how to create a GUI, and from what I've looked up, it seems I have to use a framework, but I hate the idea of that. How would I create a GUI without a framework? How...
You can build your own framework based on OpenGL or Xlib. Or use good graphics library likeMotiforCGUI. Or use something awful like GTK.
I am working on the following problem of SPOJ , http://www.spoj.com/problems/ARITH/ It is said that the number should contain atmost 500 digits , what is the appropriate datatype for a number with maximun 500 digits
There is no builtin datatype to hold an integer of 500 digits. Thus, you have to come up with a way to store them in an array of bytes. Get inspired by whathttp://gmplib.org/does. In short, you will have to first store the digits somewhere: ``` struct Digit { size_t len; char sign; char* digits; }; ``...
all:There is a shell script a.sh: ``` #/bin/bash -x -n source /etc/profile ``` and a test.c program use system() function to invoke this script: ``` #include <stdio.h> int main(void) { system("/data/nan/a.sh"); return 0; } ``` I find when call a.sh directly in console: ``` ./a.sh ``` It is OK. But exec...
You are missing a!in the shebang: ``` #!/bin/bash -x -n ^ ```
I have a bug that I've found boils down to this: ``` #include <sys/types.h> #include <sys/stat.h> #include <fts.h> #include <stdlib.h> int main () { char *LOG_ROOT = "/var/log"; FTS *ftsp; FTSENT *p, *chp; int fts_options = FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR; char *paths[] = { LOG_ROOT ...
The first arg. is expected to be aNULL terminated arrayof character pointers. ``` char *paths[] = { LOG_ROOT, NULL}; ```
I would like to know how/proc/interruptsis getting up to date? is it have onlyirqof drivers were probed or it contains the list of all the possibleirqsin the system?
As you can see in the source of the kernel, it displays all possible irqs of the system.Insource/fs/proc/interrupts.c:39a sequence operation is initialized to return as many elements as interrupts exist in the system for/proc/interrupts. Insource/kernel/irq/proc.c:479we can see that the counters of every interrupt ge...
I want to return a null-terminated char* that contains a backspace characterwithoutmalloc'ing it. Specifically, I want the string to be {backspace-character, space-character, backspace-character, null-character} and nothing else. For a "regular" string, I know I could say ``` char* s = "regular"; return s; ``` Then...
You can include a backspace in a string literal as\be.g."\b \b"
Using the Mongodb C Driver, how can I issue shell commands like db.mydb.remove()? The API seems pretty limited:http://api.mongodb.org/c/current/api/annotated.html
To drop collection usemongo_cmd_drop_collection(…), to drop DBs usemongo_cmd_drop_db(…). Most commands are insidemongo.h. Edit: To perform the requestedremove(…)usemongo_remove(…).
I have a small server program in C which prints a message to the client. This program uses UDP Port for communication. My question is: Is there a way or application by which I can test the functionality of my program from my windows machine. Example, if I type in some command, I can see the response from my program o...
Not aware of any existing tools. I assume your server receives a message from the client and sends a response message back. If this is correct, create a basic client program which sends a message (sendto()) and then calls recvfrom() (default is blocking mode on my platform), then print the response message received. T...
I want to use the function__sync_lock_test_and_setwhich is not available in ANSI c, but is an GNU C extension. When compile a piece of code which uses this extension, I get the following error, ``` /tmp/cc7Iat9G.o: In function `main': swap.c:(.text+0x40): undefined reference to `__sync_lock_test_set' collect2: ld re...
I think you typed__sync_lock_test_setwhen you meant__sync_lock_test_and_set. The latter is mentioned in theGCC documentation on atomic builtins; the former is not.
How can I assign non-ASCII characters to a wide char and print it to the console? This code down doesn't work: ``` #include <stdio.h> int main(void) { wchar_t wc = L'ć'; printf("%lc\n", wc); printf("%ld\n", wc); return 0; } ``` Output: ``` 263 Press [Enter] to close the terminal ... ``` I'm using M...
You should usewprintfto print wide-character strings: ``` wprintf(L"%c\n", wc); ```
Can anyone tell me what this means:"%.*s" For example, it is in use here: ``` sprintf(outv->deliveryAddressCity, "%.*s", sizeof(outv->deliveryAddressCity)-1, mi->deliveryAddressCity); ```
%.*smeansprint the first X number of characters from the following buffer. In this case, print the firstsizeof(outv->deliveryAddressCity) - 1characters frommi->deliveryAddressCity, preventing writing beyond the bounds ofoutv->deliveryAddressCity. A shorter example: ``` printf("%.*s", 4, "hello world"); ``` would pr...
I thought of writing a program to evaluate factorial of a given integer. Following basics I wrote the below code in java : ``` long fact(int num){ if(num == 1) return 1; else return num*fact(num-1); } ``` But then I realized that for many integer input the result may not be what is desired and hence for testing d...
BigIntegeris your class. It can storeintegers ofseeminglyany size. ``` static BigInteger fact(BigInteger num) { if (num.equals(BigInteger.ONE)) return BigInteger.ONE; else return num.multiply(fact(num.subtract(BigInteger.ONE))); } ```
Using the Mongodb C Driver, how can I issue shell commands like db.mydb.remove()? The API seems pretty limited:http://api.mongodb.org/c/current/api/annotated.html
To drop collection usemongo_cmd_drop_collection(…), to drop DBs usemongo_cmd_drop_db(…). Most commands are insidemongo.h. Edit: To perform the requestedremove(…)usemongo_remove(…).
I have a small server program in C which prints a message to the client. This program uses UDP Port for communication. My question is: Is there a way or application by which I can test the functionality of my program from my windows machine. Example, if I type in some command, I can see the response from my program o...
Not aware of any existing tools. I assume your server receives a message from the client and sends a response message back. If this is correct, create a basic client program which sends a message (sendto()) and then calls recvfrom() (default is blocking mode on my platform), then print the response message received. T...
i use realloc for dynamically increase size of a char pointer(*seqA). is there another way to do is better? it's part of my code: ``` while((holder=fgetc(fileA)) != EOF) { lenA++; temp=(char*)realloc(seqA,lenA*sizeof(char)); if (temp!=NULL) { seqA=temp; seqA[lenA-1]=holder; } else { ...
As your code is reading in the complete file into a string, why not use the following code: ``` #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> .... struct stat buf; fstat(fileno(fileA), &buf); seqA = malloc(buf.st_size); fread(seqA, buf.st_size, 1, fileA); ``` Of course you should check the retur...
My code passes around pointers to scalar types that represent different things that are easily confused. I thought the compiler could help me with this. Here is a test program: ``` typedef int type_a; typedef int type_b; type_a do_something_with_a(type_a* pa) { return *pa + 3; } int main(void) { type_b b =...
instead oftypedef int type_a;etc., usetypedef struct { int value; } type_a;
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. How i can generate for example 100 ...
Ifris a random number in the range0..25,'A'+ris a random capital letter.
All, I want to controlthe number of passed parametersin a va_list. ``` va_list args; va_start(args, fmts); vfprintf(stdout, fmts, args); va_end(args); ``` Is there any possibility to get the number of parameters just after ava_start?
Not exactly what you want, but you can use this macro to count params ``` #include <stdio.h> #include <stdarg.h> #define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N #define NARGS(...) NARGS_SEQ(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1) #define fn(...) fn(NARGS(__VA_ARGS__) - 1, __VA_ARGS__) static void (fn)(int n,...
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'm writing a C tokenizer and I wan...
A Lex scanner list of tokens for ANSI C 2011 can be found here:http://www.quut.com/c/ANSI-C-grammar-l-2011.html Edited: As pointed out by Jens: The list does neither show the digraph nor the trigraph tokens: Tables from "C in a Nutshell"
I am trying to strcat a pathname to pass to fopen to create multiple filenames in a while loop. ``` char path[30]=""; while(!feof(stdin)) { strncat(path,folder,8); strcat(path,filename); strncat(path,ext,4); printf("file path:%s\n",path); File[n] = fopen(path,"a"); path=0; } ``` How do I retu...
Since it is null terminated, just do ``` path[0] = 0; ```
I have a thread where I want to wait (at a particular line of code) for three callback events from another thread. Only after these three events are received then I want to proceed forward. I am trying to use semaphores. I am aware that a semaphore can be locked at a point and it keeps waiting till it is released by ...
If the threads can have assignable numbers, you maybe can have just a boolean variable per controlling thread and then check if all are set before the suspended thread is released. Writing a byte is probably atomic. Normal semaphores would have atomic counters, however.
I'm trying to create an array of doubles, and I know I can do it like this, ``` double a[200]; ``` but why can't I create one like this? ``` int b = 200; double a[b]; ``` It does not work. Can anyone help me? UPDATE: ``` int count; count = 0 while (fgets(line,1024,data_file) != NULL) { count++; } double *...
C doesn't support dynamic array sizes. You'll have to dynamically allocate memory and use a pointer. ``` int b = 200; double *a; a = malloc(b * sizeof (double)); ``` After this, you can access a as if it were an array.
I am referring to this tutorial for creating menu bar in window: http://www.winprog.org/tutorial/menus.html The program gets successfully compiled and runs. I can see the window but not able to see the menu bar. What am I missing? I am using Dev-C++ IDE. My resource.h and programName.rc files are placed in the same ...
Most certainly the resources are not link into the executable. You might like to follow the instructions here:http://cboard.cprogramming.com/windows-programming/54934-resource-files-dev-cplusplus.htmlto added the rc file to the project and though have it linked into the binary resulting form the build process.
``` int a[10],sum,*p; sum=0; for(p=&a[0];p<&a[10];p++) sum += *p; printf("%d",sum) ``` Hi I'm new in turbo c, especially in pointers. Can someone please explain to me how the pointer was used in this program. Thank you in advance. I know how the program works, but what I cannot understand is why did the program ...
This is an illustrative example of Pointers in C, However this code can also be written without using pointers. Here p=&a[0] ^ stores the memory address of the First value of the arraya. And the For loop will execute till the Pointer stores the memory address of the last Array value i.e.a[10]. sum += *p; ^ in the ...
So, I have two double variables, and I want to compare them till 3 decimal places. So, for variables (for example): ``` double x = 0.695999; double y = 0.695111; ``` if I check for (x==y), it should return true (since both are equal till 3 decimal places). Thanks!
You can (ab)use integer comparison and truncation: ``` int is_equal_3decplaces(double a, double b) { long long ai = a * 1000; long long bi = b * 1000; return ai == bi; } ``` As @DavidRF's benchmarks have shown it, this solution offers a slight (~40%) improvement in performance compared to calculating the...
I am currently working on a project and I'm not entirely sure how to do this but I want to have an if statement that has something along the lines of this ``` if(a != b[]){ printf("Use another value!"); } ``` Where b[] is any value within the array. So for example if I have 100 values and what the user inputted ...
you can iterate thorugh the loop and check it's value ``` for(int i=0;i<sizeof(b);i++) { if(a!=b[i] { printf("Use another value"); break; } } ``` i guess its done in this way.I have not really used C in a long time.
I have a problem with this piece of C code: ``` int y = 0, h = 640, ih = 640; h = y + h - max(0, (y + h) - ih); ``` It should set h to 640, but instead it is setted to 0! You can see it running here:http://ideone.com/zBZSsr Any idea about this strange behavior? Am I doing something wrong?
The max macro in the example you linked needs an extra pair of parentheses. You have: ``` #define max(x, y) ((x) > (y)) ? (x) : (y) ``` In your example, this expands to: ``` h = y + h - ((0) > ((y+h)-ih)) ? (0) : ((y+h)-ih); ``` I believe the operator precedence means that everything on the left is subsumed into ...
I have the usual PHP and MYSQL server running but I want to perform some CPU intensive computations. Therefore I wish to run a C program to handle that part. Is it possible to exchange data between a PHP and a C/C++ program on the server itself? Regards PP
It's possible and you have multiple ways to achieve that. write an extension (as it was already suggested)call your C program with 'exec()'useGearmanrun C program as a service and communicate with it via pipe or a socket From the above I would choose an extension or Gearman.
I'm using net-snmp. Given a specific OID such as.1.3.6.1, how do I find the correspondingMIB/module/filename/anythingwhere that OID is described? I've looked through all the#include file in <net-snmp/*>but I cannot figure it out. I was expecting something along the lines of: ``` struct module *netsnmp_get_module_f...
I figured it out. It is a 3-step process: ``` struct tree *head = get_tree_head(); struct tree *t = get_tree( o, l, head ); struct module *m = find_module( t->modid ); ``` This gives the module name, the filename, and a list of imports made by the module which can then be looked up further. When calling this with ...
I cannot find the answer for this one: what will happen if I read from socket 4bytes (I set the limit for 4 bytes) but there are actually 256bytes awaiting to be read? Will they be lost or will they wait until the next call of read function?
If it's a TCP socket, then no data will get lost; it'll get queued up. Bear in mind that you have to be prepared to deal with partial reads, i.e. where you get fewer bytes than requested and have to callread()again to get more.
I am writing an application in C using socket programming. I wish to send the data from the server node to the client node. I use the read and write commands on the socket descriptor to get and send the data over the network respectively. Since, the underlying protocol used is TCP/IP, finally I receive the correct dat...
/proc/net/tcphas a fieldretrnsmt, you simply need tofind your socketin this list. An alternative would be to use theTCP_INFOsockopt. The current layout ofstruct tcp_infocan be found inlinux/tcp.h. The field you want to use is probablytcpi_retrans.
I am referring to this tutorial for creating menu bar in window: http://www.winprog.org/tutorial/menus.html The program gets successfully compiled and runs. I can see the window but not able to see the menu bar. What am I missing? I am using Dev-C++ IDE. My resource.h and programName.rc files are placed in the same ...
Most certainly the resources are not link into the executable. You might like to follow the instructions here:http://cboard.cprogramming.com/windows-programming/54934-resource-files-dev-cplusplus.htmlto added the rc file to the project and though have it linked into the binary resulting form the build process.
``` int a[10],sum,*p; sum=0; for(p=&a[0];p<&a[10];p++) sum += *p; printf("%d",sum) ``` Hi I'm new in turbo c, especially in pointers. Can someone please explain to me how the pointer was used in this program. Thank you in advance. I know how the program works, but what I cannot understand is why did the program ...
This is an illustrative example of Pointers in C, However this code can also be written without using pointers. Here p=&a[0] ^ stores the memory address of the First value of the arraya. And the For loop will execute till the Pointer stores the memory address of the last Array value i.e.a[10]. sum += *p; ^ in the ...
So, I have two double variables, and I want to compare them till 3 decimal places. So, for variables (for example): ``` double x = 0.695999; double y = 0.695111; ``` if I check for (x==y), it should return true (since both are equal till 3 decimal places). Thanks!
You can (ab)use integer comparison and truncation: ``` int is_equal_3decplaces(double a, double b) { long long ai = a * 1000; long long bi = b * 1000; return ai == bi; } ``` As @DavidRF's benchmarks have shown it, this solution offers a slight (~40%) improvement in performance compared to calculating the...
I am currently working on a project and I'm not entirely sure how to do this but I want to have an if statement that has something along the lines of this ``` if(a != b[]){ printf("Use another value!"); } ``` Where b[] is any value within the array. So for example if I have 100 values and what the user inputted ...
you can iterate thorugh the loop and check it's value ``` for(int i=0;i<sizeof(b);i++) { if(a!=b[i] { printf("Use another value"); break; } } ``` i guess its done in this way.I have not really used C in a long time.
I have a problem with this piece of C code: ``` int y = 0, h = 640, ih = 640; h = y + h - max(0, (y + h) - ih); ``` It should set h to 640, but instead it is setted to 0! You can see it running here:http://ideone.com/zBZSsr Any idea about this strange behavior? Am I doing something wrong?
The max macro in the example you linked needs an extra pair of parentheses. You have: ``` #define max(x, y) ((x) > (y)) ? (x) : (y) ``` In your example, this expands to: ``` h = y + h - ((0) > ((y+h)-ih)) ? (0) : ((y+h)-ih); ``` I believe the operator precedence means that everything on the left is subsumed into ...
I have the usual PHP and MYSQL server running but I want to perform some CPU intensive computations. Therefore I wish to run a C program to handle that part. Is it possible to exchange data between a PHP and a C/C++ program on the server itself? Regards PP
It's possible and you have multiple ways to achieve that. write an extension (as it was already suggested)call your C program with 'exec()'useGearmanrun C program as a service and communicate with it via pipe or a socket From the above I would choose an extension or Gearman.
I'm using net-snmp. Given a specific OID such as.1.3.6.1, how do I find the correspondingMIB/module/filename/anythingwhere that OID is described? I've looked through all the#include file in <net-snmp/*>but I cannot figure it out. I was expecting something along the lines of: ``` struct module *netsnmp_get_module_f...
I figured it out. It is a 3-step process: ``` struct tree *head = get_tree_head(); struct tree *t = get_tree( o, l, head ); struct module *m = find_module( t->modid ); ``` This gives the module name, the filename, and a list of imports made by the module which can then be looked up further. When calling this with ...
I cannot find the answer for this one: what will happen if I read from socket 4bytes (I set the limit for 4 bytes) but there are actually 256bytes awaiting to be read? Will they be lost or will they wait until the next call of read function?
If it's a TCP socket, then no data will get lost; it'll get queued up. Bear in mind that you have to be prepared to deal with partial reads, i.e. where you get fewer bytes than requested and have to callread()again to get more.
I am writing an application in C using socket programming. I wish to send the data from the server node to the client node. I use the read and write commands on the socket descriptor to get and send the data over the network respectively. Since, the underlying protocol used is TCP/IP, finally I receive the correct dat...
/proc/net/tcphas a fieldretrnsmt, you simply need tofind your socketin this list. An alternative would be to use theTCP_INFOsockopt. The current layout ofstruct tcp_infocan be found inlinux/tcp.h. The field you want to use is probablytcpi_retrans.
When i cout holder(is char) value, an ambiguity letters shown. how can read letters and save to an array then print them? ``` while (holder=fgetc(fileA) != EOF) { cout << holder; lenA++; temp = (char*) realloc(seqA,lenA*sizeof(char)); if (temp != NULL) { seqA = temp; seqA[lenA-1] = hol...
For starters you need some parentheses or you'll keep storing the comparison between the result offgetcandEOF: ``` while((holder=fgetc(fileA)) != EOF) ^ ^ ```
I have a program that I am running on two different compilers, and each compiler has a different file handling library. For example on library requires: ``` fwrite(buffer,size,elements,file) ``` While the other is: ``` f_write(file,buffer,size,elements) ``` is there anyway I could use a global#definein my main he...
Sure: ``` #ifdef STUPID_COMPILER # define fwrite(ptr, size, nitems, stream) f_write(stream, ptr, size, nitems) #endif ``` Then just usefwrite()in your code -- no wrapper function needed. The preprocessor will translate it to anf_write()call if you're using the compiler/library that requires that.
This question already has answers here:Accessing an array out of bounds gives no error, why?(18 answers)Closed10 years ago. who can tell me why the code below still works? it is obvious that the str[4] is out of boundry: ``` #include<stdio.h> int main(){ char str[3]; scanf("%s", str); printf("%c\n", str[...
str[4] gives you a pointer to the memory address after the last element of your string. You can still convert this to a character, but you never know what you get and your software might crash.
What is the value of0x1.921fb82c2bd7fp+1in a human readable presentation? I got this value byprintfusing%a.
The mantissa is hexadecimal and the exponent is a decimal value representing the power of 2 the mantissa is scaled by.
``` #define power(a) #a int main() { printf("%d",*power(432)); return 0; } ``` can anyone explain the o/p??the o/p is 52
It is equivalent to: ``` printf("%d",*"432"); ``` which is equivalent to: ``` printf("%d", '4'); ``` and the ASCII value of'4'is52.
``` In the following program: Ctrl+z and ctrl+c both are interrupts. The code is supposed to handle any interrupt. Then why does only one of them(ctrl+c) work? ``` Code: ``` #include <signal.h> #include<stdio.h> void handler(int sig) { printf("Caught SIGINT\n"); exit(0); } int main() { printf("\nYou...
Because Ctrl-Z causes aSIGTSTP, not aSIGINT.
If I implement the following within iPhone code: ``` NSString* soundPath = [[NSBundle mainBundle] pathForResource:soundFile ofType:@"wav"]; SystemSoundID feedbackSound; AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundPath], &feedbackSound); AudioServicesPlaySystemSound(feedbackSound);...
You should. The correct method to call is: ``` AudioServicesDisposeSystemSoundID ``` (reference). In general ARC only deals with Objective-C objects. When you deal with lower-level framework (Core Graphics, AudioServices, etc.) many calls will allocate memory "under the hood" for whose disposal you are responsible....
I know that the following ``` unsigned short b=-5u; ``` evaluates to b being 65531 due to an underflow, but I don't understand if 5u is converted to a signed int before being transformed into -5 and then re-converted back to unsigned to be stored in b or -5u is equal to 0 - 5u (this should not be the case, -x is a u...
5uis a literal unsigned integer,-5uis its negation.. Negation for unsigned integers is defined as subtraction from 2**n, which gets the same result as wrapping the result of subtraction from zero.
What is the conventional way to have C header files and source with function pointers in structs? For example; I've declared my struct in the header file and all functions and source code in the code file. Is it convention to declare the struct in the source file and assign all function pointers to the proper functio...
You did right , structures are usually placed in header files. Generally Header files are used to design the framework of the code. The actual code is implemented in another file. Typically a header file will contain , 1) Function Prototypes 2) Class Definitions 3) Structure and union Definitions 4) Macros Refe...
For exampleputs()calls the system callwrite(). Does that mean it callswrite()every time we callputs(), or does puts accumulate into some buffer before callingwrite()?
The stdio functions do utilise buffering. In the specific case ofputs(), it always writes a complete line tostdout, and ifstdoutis connected to a terminal then it will usually be line-buffered, so each call toputs()will result in a call towrite(). However, it is possible to havestdoutbe fully buffered - either using...
I have a variable that I intend to use in multiple files, is a mutex initializer. So I wrote in one header file this : ``` #ifndef LISTEN_H_ #define LISTEN_H_ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #endif ``` I tried to include the header in the files in witch I intend to use the variable. But i get ...
The proper way would be todefine it in a.cfileanddeclare it asexternin the header file. Now you would be able to use it wherever you want to use it, without errors.
I have a file where each line looks like this: ``` cc ssssssss,n ``` where the two first 'c's are individual characters, possibly spaces, then a space after that, then the 's's are a string that is 8 or 9 characters long, then there's a comma and then an integer. I'm really new to c and I'm trying to figure out how...
I'm assuming this is a C question, as the question suggests, not C++ as the tags perhaps suggest. Read the whole line in.Usestrchrto find the comma.Do whatever you want with the first two characters.Switch the comma for a zero, marking the end of a string.Callstrcpyfrom the fourth character on to extract thessssssspa...
I am trying to pass a file pointer array to a function (not sure about the terminology). Could anyone please explain the proper way to send 'in[2]'? Thank you. ``` #include<stdio.h> #include<stdlib.h> void openfiles (FILE **in[], FILE **out) { *in[0] = fopen("in0", "r"); *in[1] = fopen(...
Try: ``` void openfiles (FILE *in[], FILE **out) { in[0] = fopen("in0", "r"); in[1] = fopen("in1", "r"); *out = fopen("out", "w"); } ``` And call itopenfiles (in, &out);. Also, "pointer array" is ambiguous. Perhaps call it "array of FILE pointers" ?
I just discovered that the open() (man 2 open) system call has two versions: ``` int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); ``` And indeed, one can use either in a single C file and both would work. How can standard C achieve this?
In fact, it's not C++-style function overloading. It's just thatopen()is variadic: ``` int open(const char *fname, int flags, ...); ``` And only if "flags" require it, will it look for the third argument.
Apparently C doesn't like the declaration: char some_array[n] = "Text here";<== wherenis an int of suitable size.... Well, actually, I guess it likes it just fine, but the output surprises me! Here's an example. ``` char two[4] = "What"; printf("2: %s \n", two); ``` Output is: ``` 2: WhatWhat ``` WhatWhat th...
String literals have an extra character - the nul terminator. So you need to have it be length 5: ``` char two[5] = "What"; ``` Or this if possible: ``` char two[] = "What"; ``` (you're getting a buffer overrun or something otherwise)
can someone help please? i'm trying to compile in c but it gives me this error: "error: lvalue required as left operand of assignment" this is the part of the code ``` if(anoc%4==0 && anoc%100!=0||anoc%400=0) ```
In the last part of the check, you are assigning the value 0 to anon%400. That is not possible. ``` anoc%400=0 ``` You need to do: ``` anoc%400==0 ``` EDIT — In future, please be more explanative about the type of variables you are using. As a good coding practice, use proper variable names. Good luck.
test1.c ``` #include <stdio.h> int main(void) { printf("test\n"); delay(1000); printf("test2\n"); } ``` When I try to compile... ``` gcc test1.c -o test1 Undefined symbols for architecture x86_64: "_delay", referenced from: _main in ccUnw3tY.o ld: symbol(s) not found for architecture x86_64 collect2:...
There's no delay function in C, you have to usesleeporusleepdepending on what OS you're on.
I'm trying to insert into the front of a linked list and also return an allocated head for when head is NULL, but it seems to only work in the event that head is not NULL. essentially, if ``` node* x = NULL; ``` is ``` x = addfront(x, 3) ``` valid?
Is using a function that assigns to a null pointer using the null pointer as an argument valid in C? It depends onaddfrontcontents. As long as you don't dereferencexinaddfront, it is perfectly valid, because dereferencing a null pointer is an undefined behavior. it seems to only work in the event that head is not NU...
In the code below I am callingsystemwith"gedit filename". It's openinggeditwith the specified file correctly.However, in the next line I am trying to print the modified data (which I am going to update throughgedit), but it will not wait untilgeditexits. ``` strcpy(tt1,"gedit "); strcat(tt1,tt); system(tt1); ...
I believe this is handled by the--waitcommand line argument, which does seem to be a prettyrecent addition. You could try building gedit on your own, to at least verify if it works (since your distro probably won't have a recent-enough build).
I wrote this .sh file to compile any c source file, so that when I run it, it asks for a filename and gcc compiles it and then, runs the executable a.out. But this doesn't work properly when error is present in .c files. It also shows that a.out is not present. I don't want this error message ( a.out is not present )...
If you enable abort-on-error in shell scripts, life will be a lot easier: ``` #!/bin/sh set -eu # makes your program exit on error or unbound variable # ...your code here... ```
This question already has answers here:What is the difference between char * const and const char *?(19 answers)Closed10 years ago. What's the difference between the following three pointer declarations in C: ``` void * const myPointer1; void const *myPointer2; const void *myPointer3; ``` And which one is used to p...
Read the rules from right to left: ``` void * const myPointer1; ``` myPointer1 is aconstpointer tovoid. ``` void const *myPointer2; ``` myPointer2 is a pointer to aconstvoid. ``` const void *myPointer3; ``` myPointer3 is a pointer to avoidconst. Conclusions: myPointer1is what you are looking for -- it's aconst...
Ist there any possibility to read values from the pins of the COM Port? Any solution in C under Linux is appreciated!
Yes, see for instancethis guide. You use theioctl()function, to read the various control pins. Data is, of course, best read through the normalread()handling, you don't want to be polling asynchronuous serial data. I don't think your assumption (expressed in a comment) that the driver must check the pin-states to ha...
I have a variable that I intend to use in multiple files, is a mutex initializer. So I wrote in one header file this : ``` #ifndef LISTEN_H_ #define LISTEN_H_ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #endif ``` I tried to include the header in the files in witch I intend to use the variable. But i get ...
The proper way would be todefine it in a.cfileanddeclare it asexternin the header file. Now you would be able to use it wherever you want to use it, without errors.
I have a file where each line looks like this: ``` cc ssssssss,n ``` where the two first 'c's are individual characters, possibly spaces, then a space after that, then the 's's are a string that is 8 or 9 characters long, then there's a comma and then an integer. I'm really new to c and I'm trying to figure out how...
I'm assuming this is a C question, as the question suggests, not C++ as the tags perhaps suggest. Read the whole line in.Usestrchrto find the comma.Do whatever you want with the first two characters.Switch the comma for a zero, marking the end of a string.Callstrcpyfrom the fourth character on to extract thessssssspa...
I am trying to pass a file pointer array to a function (not sure about the terminology). Could anyone please explain the proper way to send 'in[2]'? Thank you. ``` #include<stdio.h> #include<stdlib.h> void openfiles (FILE **in[], FILE **out) { *in[0] = fopen("in0", "r"); *in[1] = fopen(...
Try: ``` void openfiles (FILE *in[], FILE **out) { in[0] = fopen("in0", "r"); in[1] = fopen("in1", "r"); *out = fopen("out", "w"); } ``` And call itopenfiles (in, &out);. Also, "pointer array" is ambiguous. Perhaps call it "array of FILE pointers" ?
I just discovered that the open() (man 2 open) system call has two versions: ``` int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); ``` And indeed, one can use either in a single C file and both would work. How can standard C achieve this?
In fact, it's not C++-style function overloading. It's just thatopen()is variadic: ``` int open(const char *fname, int flags, ...); ``` And only if "flags" require it, will it look for the third argument.
I need to know how to read a string and split in two as in the example below. i have this string in a file @amanda:@bruna, but i can't read as separate words, and each store in two diferent variables like this: ``` char userA[20]; char userB[20]; scanf("%s:%s", userA, userB); ``` Can you help me?
Use a scanset to prevent the first%sconsuming the entire line, as the%swill only stop consuming when it encounters whitespace: ``` if (scanf("%19[^:]:%19s", userA, userB) == 2) { /* 'userA' and 'userB' have been successfully assigned. */ } ``` where%19[^:]meansread at most 19 characters but stop when a colon is ...
Ive looked online and have not been able to satisfy myself with an answer. Is memcpy threadsafe? (in Windows) What I mean is if I write to an area of memory shared between processes (using boost::shared_memory_object) using a single memcpy and then try read that area from another process using a single memcpy then ...
memcpy is typically coded for raw speed. It will not be thread safe. If you require this, you need to perform the memcpy call inside of a critical section or use some other semaphor mechanism. ``` take_mutex(&mutex); memcpy(dst, src, count); yield_mutex(&mutex); ```