question
stringlengths
25
894
answer
stringlengths
4
863
If you have a pointer that is not initialized and, by mistake, try to free it, is this going to result in undefined behavior? Like: ``` int main(void){ char *string; free(string); return 0; } ```
Does freeing an uninitialized pointer result in undefined behavior? Yes. However, freeing a null pointer is well-defined. From the C99 standard: Thefreefunction causes the space pointed to byptrto be deallocated, that is, made available for further allocation. Ifptris a null pointer, no action occurs. Otherwise, i...
When I write a simple program using C / C++ , what's the address range I get? I mean, I can point to wherever I want.. like : ``` void* ptr = (int*)0xFFFFFFFF; ``` Where does that pointer actually point to? I guess its not the real address in the main memory but just the "cover" address of my program. Can anyone e...
Your program runs in a virtual address space, and pointers point to locations within virtual memory. So no, you cannot expect to conjure up a pointer with the same numeric value as one in another program and have them both point to the same actual memory. On the contrary, if you do that your program will likely cras...
Suppose that I want to get the real path of a symlink. I know that bothreadlinkandstatsystem calls can dereference the link and give me its real path. Do they operate in the same way (only regarding the dereferencing, I know thatstatdoes lots more)? Should I prefer one over the other?
Usestat()to tell you about the file at the end of any chain of symlinks; it does not get you the path in any way. Uselstat()to get information about the symlink, if any, that is referred to; it acts likestat()when the name given is not a symlink. Usereadlink()to obtain the path name stored in the symlink named as it...
``` #include <stdio.h> #include <stdlib.h> char number[5000]="37107287533902102798797998220837590246510135740250\ 46376937677490009712648124896970078050417018260538\ .....more numbers....."; char numbers[100][50]; main() { int x,z; extern char numbers[100][50],number[5000]; for(x=0;x<100;x++) { ...
``` for(x=0;x<100;x++) { for(z=0;z<50;z++) { numbers[x][z]=number[50*x+z]; } numbers[x][z+1] ='\0'; //Did you miss this ? } ```
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.Closed10 years ago.Improve this question Consider the following recursive C function that takes two arguments. ``` unsigned int foo(unsigned int n...
This code ,actually is a recursion. follow the return happened: ``` If n == 0; return 0; If n == 1; return 1+foo(0,2) If n == 2; return 0 + foo(1,2); If n == 4; return 0 + foo(2,2); ... if n == 2^n return 0 + foo(0+foo(z^n-1,2)); .... So foo(512,2) == foo (2^n,2) == 0+f(1,2) == 1 +f(0,2) = 1; ``` It ret...
``` typedef struct { long blarg; } item; typedef struct { item* items; int size; } list; ``` List and Item structs, fairly simple. ``` list l; l.size = 3; realloc(l.items, l.size*sizeof(item)); ``` Create a list, allocate it to hold 3 items. ``` item thing; item thing2; item thing3; thing.blarg = 13...
You should changel.items[sizeof(item)+1]andl.items[(sizeof(item)*2)+1]-->l.items[1]andl.items[2]
``` #include <iostream> using namespace std; int main() { cout << 1; while (true); return 0; } ``` I thought that this program should print 1 and then hung. But it doesn't print anything, it just hungs.cout << endlorcout.flush()can solve this pro...
You writing to a buffer. You need to flush the buffer. As @Guvante mentioned, usecout.flush()orfflush(stdout)for printf. Update: Looks likefflushactually works with cout. But don't do that - it may not be the fact in all cases.
This question already has answers here:Clearing output of a terminal program Linux C/C++(7 answers)Clear screen in C and C++ on UNIX-based system?(10 answers)Closed10 years ago. I want to clear all the text that is on the screen. I have tried using: ``` #include <stdlib.h> sys(clr); ``` Thanks in advance! I'm using...
You need to check outcurses.h. It is a terminal (cursor) handling library, which makes all supported text screens behave in a similar manner. There are three released versions, the third (ncurses) is the one you want, as it is the newest, and is ported to the most platforms. Theofficial website is here,andthere are...
I am readingThe C Programming Languageby Brian Kernigan and Dennis Ritchie. Here is what it says about the bitwise AND operator: The bitwise AND operator&is often used to mask off some set of bits, for example,n = n & 0177sets to zero all but the low order 7 bits ofn. I don't quite see how it is masking the lower se...
The number0177is anoctalnumber representing the binary pattern below: ``` 0000000001111111 ``` When youANDit using the bitwise operation&, the result keeps the bits of the original only in the bits that are set to1in the "mask"; all other bits become zero. This is because "AND" follows this rule: ``` X & 0 -> 0 for...
So I have some code for the iodefine of my board. I see a lot of these in structs. What exactly is it doing? Is it just a placeholder for the last 4 bits? Why doesn't it cause a compiler error and what is it used for? ``` union { unsigned char BYTE; struct { unsigned char OVRF:1; unsigned char...
It's an unnamed bit-field. It is used to provide padding (usually between adjacent bit-fields). (C99, 6.7.2.1p11) "A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field"
I have a written a simple c code as follows ``` #include<stdio.h> void main() { int a[3]; int i; for(i=0;i<=2;i++) { printf("i is %d\n",i); scanf("%d ",&a[i]); } for(i=0;i<=2;i++) printf("a[%d] is %d\n",i,a[i]); } ``` The problem is when I run the program I have to enter two values when i is 0(n...
Change: ``` scanf("%d ",&a[i]); ``` to: ``` scanf("%d",&a[i]); ``` That extra space is the source of all your problems, because it's eating whitespaces.
``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> void koaneeye(){ static int j=0; int n,i=0,rev=0; while( scanf("%d",&n) == 1) koaneeye(); while(n) { i=n%10; rev=rev*10+i; n=n/10; } printf("%d\n",rev); } int main() { koa...
The printf statement is called one too many times. You need to stop execution in the case that you didn't read data. Since you are using recursion anyway, you don't need to loop: ``` if( scanf("%d",&n) != 1) return; koaneeye(); ```
When I run the following code inClanguage, my compiler shows the error "xxx has stopped working". However, when I take array sizes as 1000 instead of 100000 it runs fine. What is the problem and how can I fix it? If there is some memory problem then how can I take input of 100000 numbers in these arrays without excee...
Declarea,l,r,ans,xandyas global variables so that they will be allocated in the heap instead of the stack. ``` int a[100000], l[100000], r[100000], ans[100000], x[100000], y[100000]; int main() { ```
I am striving to maximize speed of my program (in order to get results in real-time) and avoid unnecessary loading of data from hard drive. Program is supposed to process a huge amount of images and I would like to handle in RAM as much processed data as possible. But I found out thatmallocwon't allocate more than 2G...
I believe the windows equivalent ofmmap(2)isVirtualAlloc This should allow you to use a lot more memory. Please keep in mind that the OS may still decide to page out your memory. You can lock it in RAM withVirtualLock. The amount of lockable memory may be limited though. Also as mentioned in the comments make sure t...
how to understand the following lines of c# code in terms of its bit operation ``` a = 15 & ( a ^ (b << 3)); ``` and the bit operations in the following segment of code, especially the way to declareuint8_t aanduint8_t b ``` int decode(const void* raw_in, void* raw_out, uint32_t password, size_t len) { ...
``` a = 15 & ( a ^ (b << 3)); | | | | | |_left shift (b's bits left shifted by 3) | | | |_bitwise xor (a XOR result of (b<<3) ) | |_ bitwise and ( 15 AND result of all above ) ``` Similarly>>is right shift operator
I want to establish build-time cross-language ABI compatibility with Waf. How would I go about checking the size of a type (or any arbitrary type-like checks), and recording it into the build configuration?
You can create a program which outputs that size. I saw this apporach on several./configurefiles: ``` cat << EOF > test.c #include <stdio.h> int main () { printf("int %d\n", sizeof(int)); return 0; } EOF $(CC) test.c -o out ./out >> sizes rm -f test.c out ``` Of course, with testing of erroneous cases and su...
I'm a bit confused between thread vs process scheduling. I've read about process scheduling policies at http://man7.org/linux/man-pages/man2/sched_getscheduler.2.html and I've read about thread scheduling at http://man7.org/linux/man-pages/man3/pthread_getschedparam.3.html Do threads inherit scheduling policy fro...
Linux does not support process scheduling at all. Scheduling is entirely on a thread basis. Thesched_*functions incorrectly modify the thread scheduling parameters of the target thread id instead of the scheduling parameters of a process. See: http://sourceware.org/bugzilla/show_bug.cgi?id=14829andhttp://sourceware.o...
Code: ``` int a = 5; int *ptr; ptr = &a; printf("%d",*ptr); printf("\n%d",*(ptr++)); printf("\n%d",(*ptr)++); printf("\n%d",++(*ptr)); ``` Output: ``` 5 5 1638268 1638268 ``` and I am expecting the output to be: 5 junk 5 7 Sory, my pointer and operator precedence concept is very bleak. Can't under...
The first is obviously 5, just dereferencing a pointerStill five because the postfix operator returns the pointer preincrement3 and 4 are junk because the pointer no longer points to memory that has been assigned If you want the second to act like you expected and print junk you can use the prefix++instead
I'm trying to understand what's wrong with: ``` typedef *void (*pfun)(**int, *float); ``` as far as I understand the problem is that I can't pass the function the pointers as ``` typedef *void (*pfun)(int, float); ``` doesn't generate an error but I have no idea why that is the case.
Did you meanvoid*,int**andfloat*?
While reading "The C Programming Language" by Dennis M. Ritchie I came across this line: For external and static variables, the initializer must be a constant expression. I am unable to understand what constant expression means here because the below code compiles without any error, isn't the statement:static int a ...
It's necessary in C, but not in C++. They are different languages. The code compiles as C++, but not as C. ``` void foo() { this line is here because of stupid restrictions of Stack Overflow } ```
I have two compilers, one that recognizes uint8_t(GCC ARM-EABI), and one that doesn't(Renesas M16 Standard Toolchain). The Renesas Toolchain is NOT ANSI C compliant, so you can throw out . So uint8_t, uint16_t,... aren't defined as existing types. In order to maintain portability, I would like to have the same type...
Is there a way to check if uint8_t exists as a type? Use: ``` #include <stdint.h> #ifdef UINT8_MAX ... #endif ```
I am trying to write code on OSX in c (can use objective-c too if easier) to determine if multicast is enabled on the current machine (router the machine is connected to). To do this I am trying the following steps: Open a port and send data over multicast.Listen for responses on all active adapters.Filter out the '...
To determine if a machine has IP multicast addresses active (which is what I think you mean by "multicast is enabled"), look at the routing table and see if you find one or more IP v4 addresses in the range 224.0.0.0 to 239.255.255.255.
Suppose I have a macro defined, and I am using that macro within an if else statement ``` #include <iostream> #define LOG(x) {if (x) std::cout << "What is up" << std::endl;} int main(void) { if (true) LOG(true); else false; return 0; } ``` Now this is a tricky case, I realized that depending on the i...
You should define your macro this way: ``` #define LOG(X) do { if (some_condition) dosomething(); } while (0) ```
Is it possible to initialize a variable-sized object likestruct IP_addresses ip_addr[no_of_users] below? ``` void foo(int no_of_users){ struct IP_addresses{ char IPaddr[16]; }; struct IP_addresses ip_addr[no_of_users]; //..... } int main(void){ int no_of_users = 4; foo(no_of_users); ...
You cannot initialize variable-length arrays. From C 2011 (N1570) 6.7.9, “Initialization”, paragraph 3: The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type. You must assign values to the array by another method, such as a loop ...
I have the following macro I want to print a variable name then the value, so the macro will help having the variable name to show then its value the result of my example show var = 1.234printed on the screen. ``` #include <stdio.h> #define str(s) #s #define PRINTER(X) printf("% 12s = % f\n", str(X), X); int mai...
Сhange ``` #define PRINTER(X) printf("% 12s = % f\n", str(X), X); ``` to ``` #define PRINTER(X) printf("%12s = %f\n", str(X), X);` ``` Notice the space removed between%and specifier.
In order to usestrncmpto compare twounsigned char *buffers, I have to cast them toconst char *. I'm writing a computationally heavy program, and this test appears in one of the most critical parts. Is it better to write my own comparison function withunsigned char *buffers ? I mean, does the casting toconst char *fr...
No. In that case (casting pointers) you're just skirting the type safety features that are supposed to help protect you at compile time. It won't affect the resulting compiled code.
I have device which uses all char signs to communicate. I know fixed length of transferred messages, and I am using termio.h to communicate with this device. The problem is that I can't read whole message when one of signs array is null sign (\0). Read function stops at this moment and my message is incomplete. This ...
Open your serial port in non-canonical mode a below options.c_lflag &= ~ICANON; If you don't have this flag, by default serial port is opened in canonical mode. In non-canonical mode way you will receive "raw" bytes, which I guess is what you need if you are receiving all kinds of characters.
I am using a library and there are some functions before which I have to addAPI_EXPORTEDas given in documentation. Like: ``` API_EXPORTED int fpi_img_compare_print_data(struct fp_print_data *enrolled_print, struct fp_print_data *new_print) ``` I dont know what is the use of this keyword.
Your library seems to be libfprint in whichAPI_EXPORTEDis a macro defined as: ``` #define API_EXPORTED __attribute__((visibility("default"))) ``` which would enable the API (e.g.fpi_img_compare_print_data) to be made public.
Got a bit confused about this error I'm getting ... So, in this code snippet, I have 2 structs : ``` typedef struct { char *cMake; model *testModel; } make; typedef struct { char * cModel; } model; ``` Now, if I compile, I receive the following errors : ``` Error 1 error C2061: syntax er...
Declaremodeltype beforemake: ``` typedef struct { char * cModel; } model; typedef struct { char *cMake; model *testModel; } make; ``` Generally an identifier name cannot be used before it has been fully declared.
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.Closed10 years ago.Improve this question There are several applications for android such as "C4droid" that can compile C code, i want to know how a...
Android Provides C/C++ SDK known as"Android NDK"which communicate with the hardware.Upon that harware Android OS is installed followed by native Application. Application which require real time compilation are build on Android NDK.
What's wrong in the code below? Codeblocks closes when i try to run it, why? I need to create a matrix with 700 rows and 50 column and fill with words. Is it possible using static matrix or the dinamic one? Won't it cause stack overflow because of it's size? ``` #include <stdlib.h> #include <stdio.h> #include <string...
This line causes the problem ``` printf("%s\n" ,mat_palavras[i][j]); ``` Instead of%s, use%c.
I'm a little Confused about this code result: ``` #include <stdio.h> int g; void afunc(int x) { g = x; /* this sets the global to whatever x is */ } int main(void) { int g = 10; /* Local g is now 10 */ afunc(20); /* but this function will set it to 20 */ printf("%d\n", g); /* so this will print "...
The local variablegshadows the globalg. If you want theprintf()to show 20, you have to shadow your local variablegwith a declaration of the global one you want to print: ``` int main(void) { int g = 10; /* Local g is now 10 */ afunc(20); /* Set global g to 20 */ printf("%d\n", g); ...
I'm developing an audio application (in C++) and I have lots of functions that call each other that either take the number of frames (i.e. 1 mono or 2 stereo float samples) or the raw number of samples... It is getting harder to keep track of the semantics of each function (samples or frames?) and when to mult or div...
You could go all out and define your own system withinboost.units, or alternatively just use theBOOST_STRONG_TYPEDEFmacro to create a strong typedef for each type.
I'm trying to send commands using UDP. The receiver is supposed to receive the UDP datagram and reply. However, I would like the reply to always be sent to the sender's source port. I know how to parse the the port (struct header and move the pointer to the right position...), however, I'm looking for a function that ...
What about therecvfrom()function? It allows you to grab the data and it fills asockaddrstruct from which you can find the source port of the sender.
I need to print aULONGLONGvalue (unsigned __int64). What format should i use inprintf? I found%lluin another question but they say it is for linux only. Thanks for your help.
Using Google to search for “Visual Studio printf unsigned __int64” producesthis pageas the first result, which says you can use the prefixI64, so the format specifier would be%I64u.
I am a beginner in C and there is one problem i can't seem to solve. I want to go from main() for example, to another function with a line or two of code. I have searched the Internet and nothing has answered this specific question, or so it seems to my amateur eyes. For example, i want to do this: ``` int main(void)...
Just call the function you want to go to. For example: ``` void functionToCall(int x, int y, int z); int main() { //some code... functionToCall(x, y, z); //more code... } void functionToCall(int x, int y, int z) { //more code... } ```
I'm building a program that requires the inclusion of some input parameters. This is a C++ example: ``` int main(int argc, char *argv[]){ if(argc == 1){ //Run programm without any parameter } else{ /* *Flags */ if(!strcmp(argv[1], "-t")){ //action t return 0; } if(!strcm...
You should really consider usingBoost Program Optionslibrary. Next best alternative is GNU'sgetopt. There are alsoPoco's Option Processor,tclap,The Lean Mean C++ Option Parser,AnyOptionand many more.
I develop a C code on Linux and I would like to execute a binary say/usr/sbin/binary_program -p xxx, Is there another way thansystem()call to execute a binary?
Yes, and in general,systemshould never be used, for at least these reasons: It suffers from all the dangers of shell quoting issues, so anything but a hard-coded command line is potentially dangerous.It is not thread-safe.It interferes with signal handling in the calling program.It provides no way to get output from ...
I was making a program on doubly linked lists but I kept getting the following errors: ``` expected constructor, destructor, or type conversion before = token expected , or ; before = token expected constructor, destructor, or type conversion before -> token expected , or ; before -> token ``` The following ...
Movehead=(n *)malloc(sizeof(n));andhead->next=head->prev=NULL;inside ofmain()or another relevant function. You can't have arbitrary statements in the toplevel.
This question already has answers here:What does the "undefined reference to varName" in C mean?(6 answers)Closed10 years ago. I have got a source code in which there is a function that calculates week checksum. I need to pass a char array, let say, 'hello world'. How can I do that?? I tried some ways, e.g.: ``` cha...
make sure your function rs_calc_weak_sum is prototyped/defined before main.
how can I copy part of the string after the token I have this input Microsoft Corporation; NASDAQ MSFT 259.94B how can I copy part of string that begin from NASDAQ to the end of the string, the token here would be the semicolon would something like this work? ``` strcpy(tempString, strtok(buffer, ";")+4) ```...
Something likeyour code would work. I don't understand the+ 4, though, as far as I'm concerned, it should be+ 2. Also, don't usestrtok()for finding a character in a string - usestrchr()for that, it's more lightweight and it doesn't require the base string to be modifiable. So, ``` strcpy(tempString, strchr(buffer, '...
Suppose I have the words: tiger, lion, giraffe. How can I store it in a two dimensionalchararray usingforloop andscanfand then print the words one by one using aforloop? Something like ``` for(i=0;i<W;i++) { scanf("%s",str[i][0]); //to input the string } ``` PS Sorry for asking such a basic question, but I co...
First you need to create an array of strings. ``` char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD]; ``` Then, you need to enter the string into the array ``` int i; for (i=0; i<NUMBER_OF_WORDS; i++) { scanf ("%s" , arrayOfWords[i]); } ``` Finally in oreder to print them use ``` for (i=0; i<NUMBER_OF_WORDS...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
Put a newline at the end of the output. Without it the text goes into the output buffer but doesn't get flushed.
Am writing a code to reverse a text file. ex: abc should become cba I wrote the code fine and it works. But I noticed this peculiar behavior. If I give the reversed output as the input again, it skips the last character of the reversed input file. How come it works fine for the first time and skips a character next t...
You need to write the last char from fin as the last char to fout.
The long answer to my own question, having Googled it and not found anything useful, is to sift through the source of 'ps'. But before I do that, is there anyone willing to provide the lazy man's solution? :-) I found this question:Knowing the process status using procf/<pid>/statusHowever, the solution doesn't seem...
At the moment, the only viable solution I can come up with is something along the lines of this. Obviously, not gone to the effort to see if this actually works as I would expect it to yet...: ``` int len, pid, n, fd = open("/proc/12345/status", O_RDONLY | O_NOATIME); char buf[4096], whitespace[50]; if (0 < (len = ...
I have a question about scope or lifetime of variables, let me explain my question with an example.The code below, I've created a local variable c and returned it. In main() function the linea=foo(), I think since c is a local variable and the function foo() was done, the memory cell for variable c should have been de...
its basically a function activation record,which will be pushed on the system stack and when your function is returning it will first copy all values to the return result area,that is nothing but a=foo(); and then it will destroy that function activation record from the system stack,I hope it would help
I don't understand why I got an error when I try to initialize a struct in such a way ``` typedef struct _floor { int room; int height; int room_dim[room][2]; }Floor; ``` Why can't I use room to initialize room_dim array?
Astructmust have a size that is known at compile-time.roomis a struct variable, and could have any value; therefore, it is not a compile-time constant andcannotbe used to size astructmember. Instead, you can make the final element a flexible array member and allocate it at runtime: ``` struct floor { int rooms; ...
What are the differences between writing: ``` if(condition1 && condition2){ //some code } ``` And: ``` if(condition1){ if(condition2){ //some code } } ``` If there are any, which one is better?
The differences are mainly in readability and maintenance. Concatenation of 2 logical conditions should usually imply that there is a semantic relation between them. Another thing to consider is the scoping. The nestedifgives you additional flexibility in this area.
Deleting the i-th character from a writable char array (the first index is 0, second is 1 and etc). Do you think this is a legitimate way to perform this task: ``` void delete_char(char *str, int i) { strcpy(str + i,str + i + 1); } ``` Can we count on it that the function strcpy will always copy the characters f...
The posted code has undefined behaviour, fromstrcpy(): Copies the byte string pointed to by src to byte string, pointed to by dest.If the strings overlap, the behavior is undefined.Also copies the terminating null-byte. memmove()can used to accomplish the task, remembering to copy the null terminator.
How to check whether value is set or not ``` if (A) Indicator |= 0x10; if (B) Indicator |= 0x04; if(Indicator ) ?? ``` Here inside if I want to check whether Indicator have value0x10or not, Some case Indicator wil have value0x10and0x04. I need to check0x10is ther eor not
check if(Indicator & 0x10)is equal to0x10or else. If0x10then that bit (or bits) is (are) not set if non-zero then that bit is set. This is because the&will and each bit of the variable, therefore ANDing with0x10(or any other integer sayMASK) means iffIndicatorhas a1in each location of that ANDed integer (MASK), the re...
Why does the below statement: ``` int a = 10; a&8 == 8; ``` return false (0) ? I know that==has more precedence over&, but still it should check whether8 == 8and it should have evaluated true, but its evaluating as false. Can anyone please help me through reasoning.
a & 8 == 8isa & (8 == 8)because==has higher precedence than&(here) So8 == 8is1anda = 10which is1010in binary So ``` 00000001 & 00001010 -------- 00000000 ``` Interesting fact: Although false is a zero and true is any non-zero value in C Language. But, if the equality operator evaluates to be true it guarantees...
I am in need of a way to parse multiple switches that come out as a single argument ( argv ), some of the switches in my program would be, for example: ``` -rRsc ``` How would I implement getopt so that the user can enter multiple switches all as one argument, no spaces or dashes between switches, so no: ``` -r -R ...
Getopt already handles this case by default. You don't need to do anything special. (Scroll down to the end ofthis pageto see an example.)
The long answer to my own question, having Googled it and not found anything useful, is to sift through the source of 'ps'. But before I do that, is there anyone willing to provide the lazy man's solution? :-) I found this question:Knowing the process status using procf/<pid>/statusHowever, the solution doesn't seem...
At the moment, the only viable solution I can come up with is something along the lines of this. Obviously, not gone to the effort to see if this actually works as I would expect it to yet...: ``` int len, pid, n, fd = open("/proc/12345/status", O_RDONLY | O_NOATIME); char buf[4096], whitespace[50]; if (0 < (len = ...
I have a question about scope or lifetime of variables, let me explain my question with an example.The code below, I've created a local variable c and returned it. In main() function the linea=foo(), I think since c is a local variable and the function foo() was done, the memory cell for variable c should have been de...
its basically a function activation record,which will be pushed on the system stack and when your function is returning it will first copy all values to the return result area,that is nothing but a=foo(); and then it will destroy that function activation record from the system stack,I hope it would help
I don't understand why I got an error when I try to initialize a struct in such a way ``` typedef struct _floor { int room; int height; int room_dim[room][2]; }Floor; ``` Why can't I use room to initialize room_dim array?
Astructmust have a size that is known at compile-time.roomis a struct variable, and could have any value; therefore, it is not a compile-time constant andcannotbe used to size astructmember. Instead, you can make the final element a flexible array member and allocate it at runtime: ``` struct floor { int rooms; ...
What are the differences between writing: ``` if(condition1 && condition2){ //some code } ``` And: ``` if(condition1){ if(condition2){ //some code } } ``` If there are any, which one is better?
The differences are mainly in readability and maintenance. Concatenation of 2 logical conditions should usually imply that there is a semantic relation between them. Another thing to consider is the scoping. The nestedifgives you additional flexibility in this area.
Deleting the i-th character from a writable char array (the first index is 0, second is 1 and etc). Do you think this is a legitimate way to perform this task: ``` void delete_char(char *str, int i) { strcpy(str + i,str + i + 1); } ``` Can we count on it that the function strcpy will always copy the characters f...
The posted code has undefined behaviour, fromstrcpy(): Copies the byte string pointed to by src to byte string, pointed to by dest.If the strings overlap, the behavior is undefined.Also copies the terminating null-byte. memmove()can used to accomplish the task, remembering to copy the null terminator.
How to check whether value is set or not ``` if (A) Indicator |= 0x10; if (B) Indicator |= 0x04; if(Indicator ) ?? ``` Here inside if I want to check whether Indicator have value0x10or not, Some case Indicator wil have value0x10and0x04. I need to check0x10is ther eor not
check if(Indicator & 0x10)is equal to0x10or else. If0x10then that bit (or bits) is (are) not set if non-zero then that bit is set. This is because the&will and each bit of the variable, therefore ANDing with0x10(or any other integer sayMASK) means iffIndicatorhas a1in each location of that ANDed integer (MASK), the re...
Why does the below statement: ``` int a = 10; a&8 == 8; ``` return false (0) ? I know that==has more precedence over&, but still it should check whether8 == 8and it should have evaluated true, but its evaluating as false. Can anyone please help me through reasoning.
a & 8 == 8isa & (8 == 8)because==has higher precedence than&(here) So8 == 8is1anda = 10which is1010in binary So ``` 00000001 & 00001010 -------- 00000000 ``` Interesting fact: Although false is a zero and true is any non-zero value in C Language. But, if the equality operator evaluates to be true it guarantees...
I am in need of a way to parse multiple switches that come out as a single argument ( argv ), some of the switches in my program would be, for example: ``` -rRsc ``` How would I implement getopt so that the user can enter multiple switches all as one argument, no spaces or dashes between switches, so no: ``` -r -R ...
Getopt already handles this case by default. You don't need to do anything special. (Scroll down to the end ofthis pageto see an example.)
Deleting the i-th character from a writable char array (the first index is 0, second is 1 and etc). Do you think this is a legitimate way to perform this task: ``` void delete_char(char *str, int i) { strcpy(str + i,str + i + 1); } ``` Can we count on it that the function strcpy will always copy the characters f...
The posted code has undefined behaviour, fromstrcpy(): Copies the byte string pointed to by src to byte string, pointed to by dest.If the strings overlap, the behavior is undefined.Also copies the terminating null-byte. memmove()can used to accomplish the task, remembering to copy the null terminator.
How to check whether value is set or not ``` if (A) Indicator |= 0x10; if (B) Indicator |= 0x04; if(Indicator ) ?? ``` Here inside if I want to check whether Indicator have value0x10or not, Some case Indicator wil have value0x10and0x04. I need to check0x10is ther eor not
check if(Indicator & 0x10)is equal to0x10or else. If0x10then that bit (or bits) is (are) not set if non-zero then that bit is set. This is because the&will and each bit of the variable, therefore ANDing with0x10(or any other integer sayMASK) means iffIndicatorhas a1in each location of that ANDed integer (MASK), the re...
Why does the below statement: ``` int a = 10; a&8 == 8; ``` return false (0) ? I know that==has more precedence over&, but still it should check whether8 == 8and it should have evaluated true, but its evaluating as false. Can anyone please help me through reasoning.
a & 8 == 8isa & (8 == 8)because==has higher precedence than&(here) So8 == 8is1anda = 10which is1010in binary So ``` 00000001 & 00001010 -------- 00000000 ``` Interesting fact: Although false is a zero and true is any non-zero value in C Language. But, if the equality operator evaluates to be true it guarantees...
I am in need of a way to parse multiple switches that come out as a single argument ( argv ), some of the switches in my program would be, for example: ``` -rRsc ``` How would I implement getopt so that the user can enter multiple switches all as one argument, no spaces or dashes between switches, so no: ``` -r -R ...
Getopt already handles this case by default. You don't need to do anything special. (Scroll down to the end ofthis pageto see an example.)
``` short rtimer_arch_now(void) { short t1, t2; do { t1 = TA1R; t2 = TA1R; } while(t1 != t2); return t1; } ``` TA1R is a The Timer_A Register. I still dont get why there is a loop. If they want to return the time whydont they simply return TA1R. What is the loop for?
It tries to avoid the case when you ask the current time but it returns the value right before the time ticks. So it only returns the current time if the reading is stable.
After you have opened a file using: ``` const char *fMode = "r"; FILE *filePointer = fopen(location,fMode); ``` What's the fastest cross platform (Windows and Linux) way to get its size so you can allocate the right amount of memory usingmalloc? I've seen thatftellonly works if you open the file in binary mode.
You can find the size usingstatorfstatbefore you open the file.
Is it possible to stop an io buffer from flushing itself in C/C++? To get maximum performance, I'm trying to save data and then flush after an operation is complete. I can just write to an array and then print that out later, I was just wondering if this is possible.
You can increase the size of the buffer by using a call tosetvbuf.
I know thatfwritetakes the following parameters: ``` fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ); ``` As far as I know,size_tis a typedef and nothing else than: ``` typedef unsigned long size_t; ``` Is it possible to use values greater thansize_tfor count and write? And if it is not could...
No,fwriteaccepts only values that fit in thesize_ttype. There may be implementation-specific ways to write more but, for standard C, the approach is generally just to do sequentialfwritecalls. Each subsequent call will append to what you've already written. And keep in mind thatsize_tis a distinct type. It may be de...
What is exactly the .cproject file? I didn't add any new files to my project. I didn't change any project properties. Is it auto-generated? Is it safe to take the remote version if I didn't touch this file explicitly?
add this file to your git ignore so it will not be added to the repository. You can use this online tool for that: ``` http://gitignore.io/ ``` or simply edit (or create) '.gitignore' it in your root folder with the following content: ``` .cproject ```
``` typedef struct { char *s; char d; }EXE; EXE *p; ``` For the abovestructhow do I initialize the structure with pointer? I know for a non-pointer we doEXE a[] = { {"abc",1}, {"def",2} };. Similarly Is it possible with a pointer after allocating the memory? Say likep[] = { {"abc",1},.. so on}. Basically I want ...
We can initialise the structure with pointer as below ``` example: int i; char e[5]="abcd"; EXE *p=malloc(sizeof(*p)); for(i = 0;i < 5;i++) *(p+i)=(EXE){e,i+48}; ```
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.Closed10 years ago.Improve this question I have some information in a .log file. Is there any way to read a .log file in C language and convert it ...
Most of the time a log file is just a formatted text file, so there is no need to convert. Just use therename()function from stdio.h. Here a reference:http://www.cplusplus.com/reference/cstdio/rename/.
Interview asked question: ``` while(1) { void * a = malloc(1024*1024); } ``` How many times this loop will run on a2 gbram and a8 gbram ? I said infinite loop because there is no terminating condition even if memory will be full. He din't agree.I don't have any idea now.Please help.
It should run indefinitely. On most platforms, when there's no more memory available,malloc()will return 0, so the loop will keep on running without changing the amount of memory allocated. Linux allows memory over-commitment so thatmalloc()calls continue to add to virtual memory. The process might eventually get k...
I added comments in the program. In which step it will be removed during devolopment like compiling, linking ,loading.
It's specified as happening during phase 3 of translation (§:2.2/1): 3 - The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment.Each comment is replaced by one spac...
I have created a verilog FPU and I was wondering how I would go about running SPECfp benchmarks on it, or is that even possible?
Coordination between e.g. memory access and floating point arithmetic is critical to real-world floating point performance, which is what SPECfp is intended to measure. Often, the limiting factor is getting the operands to the floating point ALU, and the results back to memory, not doing the arithmetic once the right...
I am new to file I/O, and I am writing a program in C to read a file that I already created. The examples in the book I have do not use literals with spaces. I was wondering if: ``` #define kErrorLog "/Dropbox/Dev/Learn%20C%20on%20Mac/Error%20Log" ``` would give me the appropriate path that corresponds touser/d...
No, you should just use spaces: ``` #define kErrorLog "/Dropbox/Dev/Learn C on Mac/Error Log" ``` The%20escape is interpreted by web servers. Filenames are just character strings.
The size of char is 1 byte, and wikipedia says: sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type. However, i can store11 bytesinunsigned char array[10]0..10 but when i dosizeof(array)i get10 bytes. can someone explain explain this behavior? note:...
However, i can store 11 bytes in unsigned char array[10] No, you cannot: 10 is not a valid index ofarray[10]. Arrays are indexed from zero to size minus one. According to C99 Standard 6.5.3.4.3When [sizeofoperator is] applied to an operand that has typechar,unsigned char, orsigned char, (or a qualified version ther...
I want to write a function prototype for a function, whose argument is a pointer to a struct. ``` int mult(struct Numbers *n) ``` However, the struct Numbers, which is defined as ``` struct Numbers { int a; int b; int c; }; ``` is not defined yet. How should I write a suitable prototype for mult?
Just declarestruct Numbersas an incomplete type before your function declaration: ``` struct Numbers; int mult(struct Numbers *n); ```
I have function: ``` gint isfileexists(gchar *filename) { struct stat buffer; gint i = stat(filename, &buffer); if (i == 0) { return 1; } return 0; } ``` and if I call them: ``` isfileexists("/etc/myfile") ``` it search "myfile" in "/home/user/etc/myfile". How to do this well?
It should only look for/home/USER/etc/myfileif: you leave off the leading/when callingisfileexists; andthat directory/home/USERis your current working directory. In other words, if the argument is arelativepath name. Since youhavethe leading/, it will be an absolute path name and should access/etc/myfile. If I've ...
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.Closed10 years ago.Improve this question I have some information in a .log file. Is there any way to read a .log file in C language and convert it ...
Most of the time a log file is just a formatted text file, so there is no need to convert. Just use therename()function from stdio.h. Here a reference:http://www.cplusplus.com/reference/cstdio/rename/.
Interview asked question: ``` while(1) { void * a = malloc(1024*1024); } ``` How many times this loop will run on a2 gbram and a8 gbram ? I said infinite loop because there is no terminating condition even if memory will be full. He din't agree.I don't have any idea now.Please help.
It should run indefinitely. On most platforms, when there's no more memory available,malloc()will return 0, so the loop will keep on running without changing the amount of memory allocated. Linux allows memory over-commitment so thatmalloc()calls continue to add to virtual memory. The process might eventually get k...
I added comments in the program. In which step it will be removed during devolopment like compiling, linking ,loading.
It's specified as happening during phase 3 of translation (§:2.2/1): 3 - The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment.Each comment is replaced by one spac...
I have created a verilog FPU and I was wondering how I would go about running SPECfp benchmarks on it, or is that even possible?
Coordination between e.g. memory access and floating point arithmetic is critical to real-world floating point performance, which is what SPECfp is intended to measure. Often, the limiting factor is getting the operands to the floating point ALU, and the results back to memory, not doing the arithmetic once the right...
I am new to file I/O, and I am writing a program in C to read a file that I already created. The examples in the book I have do not use literals with spaces. I was wondering if: ``` #define kErrorLog "/Dropbox/Dev/Learn%20C%20on%20Mac/Error%20Log" ``` would give me the appropriate path that corresponds touser/d...
No, you should just use spaces: ``` #define kErrorLog "/Dropbox/Dev/Learn C on Mac/Error Log" ``` The%20escape is interpreted by web servers. Filenames are just character strings.
The size of char is 1 byte, and wikipedia says: sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type. However, i can store11 bytesinunsigned char array[10]0..10 but when i dosizeof(array)i get10 bytes. can someone explain explain this behavior? note:...
However, i can store 11 bytes in unsigned char array[10] No, you cannot: 10 is not a valid index ofarray[10]. Arrays are indexed from zero to size minus one. According to C99 Standard 6.5.3.4.3When [sizeofoperator is] applied to an operand that has typechar,unsigned char, orsigned char, (or a qualified version ther...
I want to write a function prototype for a function, whose argument is a pointer to a struct. ``` int mult(struct Numbers *n) ``` However, the struct Numbers, which is defined as ``` struct Numbers { int a; int b; int c; }; ``` is not defined yet. How should I write a suitable prototype for mult?
Just declarestruct Numbersas an incomplete type before your function declaration: ``` struct Numbers; int mult(struct Numbers *n); ```
I have function: ``` gint isfileexists(gchar *filename) { struct stat buffer; gint i = stat(filename, &buffer); if (i == 0) { return 1; } return 0; } ``` and if I call them: ``` isfileexists("/etc/myfile") ``` it search "myfile" in "/home/user/etc/myfile". How to do this well?
It should only look for/home/USER/etc/myfileif: you leave off the leading/when callingisfileexists; andthat directory/home/USERis your current working directory. In other words, if the argument is arelativepath name. Since youhavethe leading/, it will be an absolute path name and should access/etc/myfile. If I've ...
The documentation for ldap_parse_reference says to free the references with a call to ldap_value_free (seehttp://linux.die.net/man/3/ldap_parse_referencefor the man page.) However, the routine ldap_value_free is deprecated. Any pointers to the proper way to do it? (Note that I looked at the openldap code and saw th...
I went and looked at the openLDAP code. In the file clients/tools/ldapsearch.c, the routine print_reference does a call to ldap_parse_reference. The resulting references are freed (after printing) by a call to ber_memvfree((void **)refs). I can only presume that this is the correct way to free the memory.
I was trying to write a program that lists the factors of a given number. It works when I write this: ``` int main () { int num, i; printf("\nEnter a number: "); scanf("%d", &num); for(i == 0; i <= num; ++i) { if (num % i == 0) { printf("\n\t%d", i); } } } ``` but not when t...
You should start the loop in this case withi=1as infor(i = 1; i <= num; ++i), otherwise you are trying to divide a number by0. Factor can never be0.
I have N strings representing points in for of (x,y,z). I'm trying to create one string with all of my points in the following form: [(x_0,y_0,z_0),(x_1,y_1,z_1),...,(x_n,y_n,z_n)] The following is the method I'm trying but If feel it gets overcomplex: Calculate the beginning of the next point in the string.Use spri...
sprintfreturns the number of characters 'printed' (added to the string), so you can start with an index of 0 and then simply add the result of each nextsprintf (string + index, ...
When I simply pass the int I get the warning: WARNING: Incompatible integer to pointer conversion passing int to parameter of type int * In another words what isint *
This requires theaddressof an integer variable, not the integer variable itself. You can get the address of a variable with the&operator. So the following code would work: ``` int i = 10; wait( &i ); ```
``` void funct(char *err_msg) { err_msg = "some_err"; } void main() { char err_msg[1024] = { 0 }; funct(err_msg); //funct(&err_msg); //can't do this :( //after this err_msg still empty } ``` I also tried ``` void funct(char err_msg[]) ```
If you want to seterr_msginsidefunct, you need to pass a pointer to it ``` void funct(char **err_msg) { *err_msg = "some_err"; } ``` and changemainto just declare achar*and callfunctlike ``` char* err_msg; funct(&err_msg); ``` Since you have allocated storage for a string in the calling function, it'd be easie...
I know how to get current date & time and save it into an array. But I would like to print it in format:dd.mm.YYY_HH:MM:ss. How can I change my code to achieve this? ``` #include <stdio.h> #include <time.h> char *datetime() { char *array = (char*)malloc(sizeof(char)*25); time_t result; result = time(NULL...
Using strftime - seehere This will look like this - ``` time_t rawtime; time (&rawtime); struct tm *timeinfo = localtime (&rawtime); strftime(array, sizeof(array)-1, "%d.%m.%y_%H:%M:%S", timeinfo); ```
I am trying to read from keyboard (usingscanf) the variablechar *pathI don't know how to pass thepathas argument of scanf to get the input from keyboard. How can I do it? P.S. This is what I have tried: ``` char *filePath = ""; printf("Path: "); scanf("%s", &filePath); ``` But my application always stops.
``` char *filePath = ""; ``` Compiler should have warned you for the above statement.filePathtype isconst char*and notchar*. filePathis pointing to an empty string literal. String literals reside in read only location and you can not edit them. You have to allocate and memory usingmallocand then take input. Once yo...
When we pass an array as an argument we accept it as a pointer, that is: ``` func(array);//In main I invoke the function array of type int and size 5 void func(int *arr) or void fun(int arr[])//As we know arr[] gets converted int *arr ``` Here the base address gets stored inarr. But when the passed array is acce...
Does the memory gets allocated for arr[5]? No, it doesn't. If no,why memory is not allocated? Because it's not necessary. The array, when passed to a function,alwaysdecays into a pointer. So, while arrays are not pointers and pointers are not arrays, in function arguments, the following pieces of code are equivalen...
I was trying to write a program that lists the factors of a given number. It works when I write this: ``` int main () { int num, i; printf("\nEnter a number: "); scanf("%d", &num); for(i == 0; i <= num; ++i) { if (num % i == 0) { printf("\n\t%d", i); } } } ``` but not when t...
You should start the loop in this case withi=1as infor(i = 1; i <= num; ++i), otherwise you are trying to divide a number by0. Factor can never be0.
I have N strings representing points in for of (x,y,z). I'm trying to create one string with all of my points in the following form: [(x_0,y_0,z_0),(x_1,y_1,z_1),...,(x_n,y_n,z_n)] The following is the method I'm trying but If feel it gets overcomplex: Calculate the beginning of the next point in the string.Use spri...
sprintfreturns the number of characters 'printed' (added to the string), so you can start with an index of 0 and then simply add the result of each nextsprintf (string + index, ...
When I simply pass the int I get the warning: WARNING: Incompatible integer to pointer conversion passing int to parameter of type int * In another words what isint *
This requires theaddressof an integer variable, not the integer variable itself. You can get the address of a variable with the&operator. So the following code would work: ``` int i = 10; wait( &i ); ```
``` void funct(char *err_msg) { err_msg = "some_err"; } void main() { char err_msg[1024] = { 0 }; funct(err_msg); //funct(&err_msg); //can't do this :( //after this err_msg still empty } ``` I also tried ``` void funct(char err_msg[]) ```
If you want to seterr_msginsidefunct, you need to pass a pointer to it ``` void funct(char **err_msg) { *err_msg = "some_err"; } ``` and changemainto just declare achar*and callfunctlike ``` char* err_msg; funct(&err_msg); ``` Since you have allocated storage for a string in the calling function, it'd be easie...
I know how to get current date & time and save it into an array. But I would like to print it in format:dd.mm.YYY_HH:MM:ss. How can I change my code to achieve this? ``` #include <stdio.h> #include <time.h> char *datetime() { char *array = (char*)malloc(sizeof(char)*25); time_t result; result = time(NULL...
Using strftime - seehere This will look like this - ``` time_t rawtime; time (&rawtime); struct tm *timeinfo = localtime (&rawtime); strftime(array, sizeof(array)-1, "%d.%m.%y_%H:%M:%S", timeinfo); ```
I am trying to read from keyboard (usingscanf) the variablechar *pathI don't know how to pass thepathas argument of scanf to get the input from keyboard. How can I do it? P.S. This is what I have tried: ``` char *filePath = ""; printf("Path: "); scanf("%s", &filePath); ``` But my application always stops.
``` char *filePath = ""; ``` Compiler should have warned you for the above statement.filePathtype isconst char*and notchar*. filePathis pointing to an empty string literal. String literals reside in read only location and you can not edit them. You have to allocate and memory usingmallocand then take input. Once yo...