question
stringlengths
24
425
answer
stringlengths
5
405
How would you simplify the following if-else-if ladder such that the function call is made only once? ``` if (Condition A){ A(); } else { if (Condition B) { A(); } } ```
Change it to: ``` if ((Condition A) || (Condition B)) { A(); } ``` As you want the functionA()to run ifCondition Aistrueor ifCondition Bistrue, you can use the||(OR) operator. This returnstrueif either conditions aretrue.
If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?
Use this: #define DOSTUFF(X) dostuff_##X() The preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x(). On the other hand, consider renaming your methods to something meaningful.
I have only a compiled binary code (.hex) of pic microcontroller,how can i convert it to code line in mikroc in order to see the instruction of program?
When it's compiled, it ismachine codeand there's no (automatic) way of translating machine code to C. Youcanget a readable version of the code,assembly, using adisassemblerfor your target CPU. This of course requires you learning your CPU's assembly language.
I have a string"2017-07-30_00:00:00"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be helpful.
strptime()is suported by bionic (i.e. available in NDK).
I have a string"2017-07-30_00:00:00"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be helpful.
strptime()is suported by bionic (i.e. available in NDK).
I want my program to convert characters into integers, but not into their ASCII equivalents. For example,'A'should equal 0, not 65, while'B'should equal 1. Then I want to add that number to an ASCII character and convert that value back to achar.
``` char test = 'C'; int num = test - 'A'; // result: 2 with ASCII and any other encoding // having the uppercase letters in sequence ```
what is the true path to prevent codeblocks error. I know question very short but when I selected any path I am getting error
1-Create New console C project 2-Right Click your project and click properties in the context menu 3-go to the libraries page 4-click 'Avaliable in pkg-config' in the known libraries layout 5-and make it like the following picture
I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it? I tried to look for information on the Internet, but unfortunately I did not succeed. :)
So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?
I am creating an apache module using eclipse c/c++ on eclipse but I am getting this errorType 'apr_pool_t' could not be resolved Eclipse C/C++I included/usr/include/apacheand/usr/libwhere is the structureapr_pool_t?
I solved by myself. It is as simple as include /usr/include/apr-1.0 in right click on my project properties->C/C++General->Paths & Symbols.
I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it? I tried to look for information on the Internet, but unfortunately I did not succeed. :)
So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?
I'm trying to compile android-kernel-goldfish-2-6-29 but when i use make -j2 to compile it, i get this error: include/linux/compiler-gcc.h:86:30: fatal error: linux/compiler-gcc6.h: No such file or directory #include gcc_header(__GNUC__) my ubuntu is 17.04 and i downgrade my gcc to gcc version 4.7.4 (Ubuntu/Linaro 4.7.4-3ubuntu12) can any body fix the problem?
I changed the goldfish version from 2.6.29 to 3.18 and now everything is okay.
I'm unable to understand below this line , could somebody tell me what it does ? ``` fscanf(file_pointer, "%*[^\n]"); ```
From thedocsone might see, that: *- assignment-suppressing character which is used not to assign the value being read to any receiveing argument offscanf. [^\n]- conversion specifier which matches any symbol except (^) new line (\n). As a result, thisfscanfreads all symbols until new line is met.
i'm a new devopler in CUDA 8 and compiling my codes with nvcc how can i install conio.h into my compiler by the way i'm running my code on server at a company thanks
The short answer: you can't. CUDA is based on C, but is a different language and a different compiler. And conio.h is not even part of C standard. You ca however use printf from a Cuda kernel
I have the text file with 2000 lines and each line contains up to 256 characters. I need to detect EOF as I'm reading the file. Should the code process a line as it is read or should it read the lines into an array and then process the array one element at a time?
If the data don't change in your file, you should stock the data in an array. In the other case, you have to read your file each time you need to check a line.
Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state. Is this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.
Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.
Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state. Is this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.
Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.
``` char* p = init(); p = foo(p); /* this one */ ``` the functionfooprototype: ``` char* foo(char* p); ``` Is it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?
Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.
``` char* p = init(); p = foo(p); /* this one */ ``` the functionfooprototype: ``` char* foo(char* p); ``` Is it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?
Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.
How to detect if cable is unplugged on W5100 Ethernet controller?. IndatasheetI can't find register for cable detection. But chip provides LAN status LED.
W5100does not support reading register to get status if cable is plugged or not (network available or not). You can only check by doingfake connectionand wait for either any response or timeout. Instead, you should useW5200which has this feature.
I am getting the following compilation error: prog.c:13:5: error: called object is not a function or function pointer a=250(n-1)+192; ``` #include <stdio.h> int main(){ long long n,a; int t; scanf("%d",&t); while(t--){ scanf("%lld",&n); a=250(n-1)+192; printf("%lld\n",a); } } ```
In C, you always have to write a*character for multiplication, as this: ``` a=250*(n-1)+192; ```
I am getting the following compilation error: prog.c:13:5: error: called object is not a function or function pointer a=250(n-1)+192; ``` #include <stdio.h> int main(){ long long n,a; int t; scanf("%d",&t); while(t--){ scanf("%lld",&n); a=250(n-1)+192; printf("%lld\n",a); } } ```
In C, you always have to write a*character for multiplication, as this: ``` a=250*(n-1)+192; ```
In Allegro, I can set the Window to be resizeable by running ``` al_set_new_display_flags(ALLEGRO_RESIZABLE); ``` before ``` display = al_create_display(800, 600); ``` however, if I resize the window, how will I know how big the window is that I resize?
useal_get_window_constraints(ALLEGRO_DISPLAY *display, int *min_w, int *min_h, int *max_w, int *max_h). Source
I have a message encoded with Nanopb implementation of Google Protocol Buffers. I have to decode it to display the decoded result on a php page. Is it possible to do it with PHP ? If not, what is the best solution to do it in order to get an exploitable result in php ? Thanks for your help.
Use php implementation of google protocol buffers like for instance: google/protobuf/php protobuf-php
I have a message encoded with Nanopb implementation of Google Protocol Buffers. I have to decode it to display the decoded result on a php page. Is it possible to do it with PHP ? If not, what is the best solution to do it in order to get an exploitable result in php ? Thanks for your help.
Use php implementation of google protocol buffers like for instance: google/protobuf/php protobuf-php
I am running my C program and I want to see the memory used by this. I am using the profilergprof. Is it possible withgprof? Or maybe I have to study theValgrindprofile?
If you want to go down the Valgrind route, Massif is the tool to use: valgrind --tool=massif your_app -your_options
This the short code, that produces adouble free or corruptionerror. ``` SDL_Surface *surface; SDL_Surface *surface2; surface = NULL; surface2 = SDL_LoadBMP("someImg.bmp"); surface = surface2; SDL_FreeSurface(surface); SDL_FreeSurface(surface2); ``` I don't understand, why I can't free second surface before I free first.
Both variablessurfaceandsurface2point to the same object. You are effectively freeing twice the same object.
I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line. ``` #include <stdio.h> int main(){ printf("Hello World"); return 0; ``` }
Use a newline character, represented as'\n'. The slash is an escape character for a few special characters, such as tab'\t', and carriage return'\r'. printf("Hello World\n");
I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line. ``` #include <stdio.h> int main(){ printf("Hello World"); return 0; ``` }
Use a newline character, represented as'\n'. The slash is an escape character for a few special characters, such as tab'\t', and carriage return'\r'. printf("Hello World\n");
This question already has answers here:What is the full "for" loop syntax in C?(7 answers)Closed6 years ago. My question is simple,thus I will not go in deep can we usefor()loop without condition like this ``` for(;;space+=1) { printf(" "); break; } ```
Of course you can. An empty condition is taken to evaluate to1. for (;;){/*ToDo - your code here*/}is idiomatic C.
If I use uninitialized global variable in C program, What happens? Is it undefined behavior? ``` #include <stdio.h> int i; int main() { while(i < 5) { i++; } printf("%d\n", i); return 0; } ```
Is it undefined behavior? No. What happens? ihas static storage duration (file scope). It will initialize to zero by default.
This is what I'm trying to do:- ``` double x = 4.0 double y = 4.0 x+y = 8.0 ``` The input has to be of double type only (given condition of the problem).
``` printf("%.1lf", yournumber); ``` will do the trick. This will print value to1decimal place. In case number is1.123, printed number will be rounded, in this case to1.1.
Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?
If you're not planning on doing math on a "number", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.
Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?
If you're not planning on doing math on a "number", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.
What isSuper Loopin Embedded C programming language?
This refers to the eternal loop usually located inmain()of a "bare metal" system (no OS), since such systems can never return from main. A typical bare metal embedded system looks like this: ``` void main (void) { // various initializations for(;;) // "super loop" or "main loop" { // do stuff } } ```
I am using struct module for serializing the data to send the data over socket. I observed thatstruct.pack(frmt, value1, ...)returns a string of the value 1 intwo byteshexadecimal format. Why does it returnonly in two bytes format? There should be some reason. Maybe I am missing something while understanding struct class. Thanks in advance.
Read the documentation of thepython struct module If you concern about the size of the packed result readthis
In GCC the following C code compiles correctly- ``` int i = 7; i = 5i; printf("%d", i); ``` And prints-0. The statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?
This is aGCC extension for representing the imaginary component of complex numbers. The compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.
In GCC the following C code compiles correctly- ``` int i = 7; i = 5i; printf("%d", i); ``` And prints-0. The statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?
This is aGCC extension for representing the imaginary component of complex numbers. The compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.
I want to know number of tokens in the statement given below ``` a+++b---c ``` Please tell me number of tokens I told my viva teacher that there are 7 tokens but he said it is wrong.
You are correct. There are seven tokens: (in C) ``` a ++ + b -- - c ```
Is there some tutorial available for Bullseye code coverage tool. Is it automated? How do we find line coverage using this tool?
Function coverage and decision coverage are supported in Bullseye coverage tool.I dont think line coverage/statement coverage is supported. Please see this link. http://www.bullseye.com/measurementTechnique.html
Confused, Why does this work when I compile, when hold is an integer? ``` char value = 'p'; int hold = value; printf("%c", hold); ```
First, in ``` int hold = value; ``` is performed implicit conversion fromchartoint. Second, in ``` printf("%c", hold); ``` the%cspecifier means something asconvert it tocharand print it as symbol.
Confused, Why does this work when I compile, when hold is an integer? ``` char value = 'p'; int hold = value; printf("%c", hold); ```
First, in ``` int hold = value; ``` is performed implicit conversion fromchartoint. Second, in ``` printf("%c", hold); ``` the%cspecifier means something asconvert it tocharand print it as symbol.
Confused, Why does this work when I compile, when hold is an integer? ``` char value = 'p'; int hold = value; printf("%c", hold); ```
First, in ``` int hold = value; ``` is performed implicit conversion fromchartoint. Second, in ``` printf("%c", hold); ``` the%cspecifier means something asconvert it tocharand print it as symbol.
I want to detect the last element of an array of integer in C code. Otherwise i need to stop handling array data when the array element is empty. really my array have a maximum size fixed and it was filled from an external file so i dont know when it stop filling the array.
Last element is in position ``` sizeof(array)/sizeof(array[0]) - 1 ```
I want to write in Makefile like this ``` foo: foo.c $(CC) -o foo -Wall foo.c ``` but I'm not sure if allccimplementations support-Wall.
No, there is no standard regarding the command-line interface of C compilers. The Microsoft compiler (in Windows) for instance does not accept options starting with-at all, since that's not the syntax typically used with Windows programs.
I know how to use the two functions, but I do not know what the suffix "at" means. Does it represent the abbreviation of "another"?
At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.
I know how to use the two functions, but I do not know what the suffix "at" means. Does it represent the abbreviation of "another"?
At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.
``` #include <stdio.h> int main(void) { int i; i = 10; i*= 10+2; printf("%d",i); return 0; } ``` why is the output of the following code 120 and not 102?
Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=. C reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence
``` #include <stdio.h> int main(void) { int i; i = 10; i*= 10+2; printf("%d",i); return 0; } ``` why is the output of the following code 120 and not 102?
Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=. C reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence
If you're going to define these at all, why not define them as ``` #define SIZEOF_INT sizeof(int) ``` etc. so they are correct even if someone tries to use them to compile against a different architecture?
I found the answer a minute after asking the question. These macros are sometimes used in the predicates of #if etc. where sizeof calls cannot be evaluated. For example ``` #if SIZEOF_LONG_LONG_INT == 8 stuff #endif ```
Is there any way in MPI to get the total number of bytes transferred by my entire MPI program in C?
The best way is to use a MPI profiling tool such as the simplempiP. There are more sophisticated / heavyweight tools that can also do that, such as Score-P. You should check if there is something available if you are running your code on an HPC site.
What is the optimal code for the following block: ``` if (a != b) a = b ```
You can just do ``` a = b; ``` because this way only one assignment will be run every time instead of the possibility of a condition check and an assignment.
If i create a pointer like: ``` int *pointer; ``` is also a variable (called pointer) created in the C Language? Why/why not?
Let's get the terminology straight: int *pointerdeclares a variableVariables have a name and a typeThe name of the variable ispointerThe type of the variable is "pointer toint"
i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?
Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.
i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?
Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.
This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago. I got this message when I compiled a C program "fatal error: dos.h: No such file or directory compilation terminated." I am currently using Ubuntu 16.04
I believe you can't do that, because from the sound of it, "dos.h" is specific to MS-DOS.
This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago. I got this message when I compiled a C program "fatal error: dos.h: No such file or directory compilation terminated." I am currently using Ubuntu 16.04
I believe you can't do that, because from the sound of it, "dos.h" is specific to MS-DOS.
I'm looking at a program that was written in C and I need to write it in C#. What is the C# equivalent of this whole line?: ``` printf("%s", " "); ```
If you can use C# 6, you could use string interpolation, and go like this. ``` Console.WriteLine($"{variableName} text"); ```
This question already has answers here:Escape character in C(6 answers)Closed6 years ago. I need to check into a loop if the user inserts '\' for exiting from the menu. ``` while(choise != '\'){ // do stuff } ``` But I get this error: error: missing terminating ' character
Backslashes are special characters and need to be escaped with another backslash: ``` while (choice != '\\') { ```
I'd like to store the variable(two spaces) in C. It looks like there are no string data types in C, so how can I store such a value without having to create astring s = get_stringfunction?
Strings in C programming are built as arrays of chars. In your case:char c[] = " ";
When we are writingprintf()in C, are we declaring it or defining? If it is a definition then where is the declaration and vice versa?
When we are writingprintf()in C, we are making a call toprintf, which has adeclarationin the<stdio.h>header like thisint printf(const char *format, ...);, and we should include that header in the C program. Thedefinitionofprintfis in the standard library implementation that gets linked with the application code.
When we are writingprintf()in C, are we declaring it or defining? If it is a definition then where is the declaration and vice versa?
When we are writingprintf()in C, we are making a call toprintf, which has adeclarationin the<stdio.h>header like thisint printf(const char *format, ...);, and we should include that header in the C program. Thedefinitionofprintfis in the standard library implementation that gets linked with the application code.
I am getting stuck because of this error and can't test my application.
You only can specific value indimentag. So, please give them aspordpvalue instead of name. Hope this helped.
Will this work? I expect ``` foo(myArraypointer + 10); ``` be the same as ``` foo( &(myArraypointer[10])); ``` will this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?
For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.
Will this work? I expect ``` foo(myArraypointer + 10); ``` be the same as ``` foo( &(myArraypointer[10])); ``` will this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?
For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.
I have a function which splits a string into tokens and stores it in an array. How to determine the size of an array of strings of typechar**? ``` ie: char **input; ```
Keep a variable globally and increment that variable value in the function which is splitting the string into tokens & storing into array.
How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?
I solved the problem by adding following linker flag in project'sCMakeList.txt ``` MATH(EXPR stack_size "16 * 1024 * 1024") # 16 Mb set(CMAKE_EXE_LINKER_FLAGS "-Wl,--stack,${stack_size}") ```
How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?
I solved the problem by adding following linker flag in project'sCMakeList.txt ``` MATH(EXPR stack_size "16 * 1024 * 1024") # 16 Mb set(CMAKE_EXE_LINKER_FLAGS "-Wl,--stack,${stack_size}") ```
When duplicating a file descriptor fd calling dup, and closing the original file descriptors. Do all the duplicated file descriptors get closed also?
No the duplicates won't be closed. Otherwise the main use-case (duplicating intoSTDOUT_FILENOandSTDIN_FILENO) would be pretty useless.
If I use goto instruction inside a recursive function (wanting to exit the function before it finishes naturally) is the stack freed automatically or not?
no, and so far as I know most compilers will not goto to exit the current function. if you must escape directly from deep recursionthrowanexception(c++) or uselongjmp(c) these actions will restore the stack.
I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.
You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.
Suppose I'm writing a program for an environment that has 32 bits for virtual spaces addresses (4294967296 addresses), what happens if create more than 4294967296 variables, effectively exceeding the number of possible addresses? Or all programs in an environment collectively use over 4294967296 addresses?
It depends precisely how you try to do it. It may crash, it may return an error, it may throw an exception.
I have a string char * a = '343'. I want to convert it into integer value. Example. char *a = "44221" I want to store that value into into int a;
This is is part of most C runtimes: ``` #include <stdlib> char *a = "1234"; int i = atoi(a); ``` That's theatoifunction. Do read through the various methods available. C's library is pretty lean so it won't take long.
I'm writing some kind of protocol to transmit with the NRF24 module so, the procotol is declared like this: ``` unsigned char protocol[16]; ``` that protocol have 16bits or 16bytes size?
16 bytes. 1 char is generally 1 byte on most systems.
I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.
You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.
I have a cordova project and I added windows platform but when I run the project I have this error: ``` MSBuild v4.0 is not supported, aborting. Error: AppPackages doesn't exists ```
Try to set OS environment variable VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\ which points to your Visual Studio folder with MSBuild directory.
I have a cordova project and I added windows platform but when I run the project I have this error: ``` MSBuild v4.0 is not supported, aborting. Error: AppPackages doesn't exists ```
Try to set OS environment variable VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\ which points to your Visual Studio folder with MSBuild directory.
I have a cordova project and I added windows platform but when I run the project I have this error: ``` MSBuild v4.0 is not supported, aborting. Error: AppPackages doesn't exists ```
Try to set OS environment variable VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\ which points to your Visual Studio folder with MSBuild directory.
I have define below array in int data types with hexa decimal data. ``` volatile int Send_Data[3] = {0x0H11, 0xAAAC, 0x0DD0}; ``` How can I initialize hex array with int data type in c language?
Hex array does not exist. Hex is only representation for numbers in computer language (used for programmers). ``` volatile int Send_Data[3] = {1, 2, 3}; ```
I'm having issues with a c program that I want to debug. I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it. Thanks :)
For GCC specify-gwhen compiling. More here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
I'm having issues with a c program that I want to debug. I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it. Thanks :)
For GCC specify-gwhen compiling. More here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago. like 52.7-->53, 5.5-->6, 3.2->3
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative: ``` ((int)(num + ((num > 0)? +0.5 : -0.5))) ```
This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago. like 52.7-->53, 5.5-->6, 3.2->3
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative: ``` ((int)(num + ((num > 0)? +0.5 : -0.5))) ```
I know thatint *(*func)()means a function pointer which takes no arguments and returns an integer pointer but what does the following syntax means in C: ``` int *(*func())[] ``` Any explanations on how do we read such syntax in C would be very helpful.
funcis a function and returning a pointer to an array of pointers to int. reference link :http://gateoverflow.in/35193/regarding-pointers
I have a dynamic array of c-strings char **my_strings = (char**)malloc(50 * sizeof(char*)); and I want to find it's actual length (how many strings it actually contains). How can I do this?
You can't tell: it's your job to keep track of the size, or to use a magic value (NULL, say) to mark the final element. Note that the c runtime probably keeps track of the amount of memory allocated, but this is not exposed to you in any portable way.
When attempting to compile ``` #include<stdio.h> int main(){ printf("Hello World"); return 0; } ``` I get the following errors with Solaris11 gcc: hello.c:4:23: error: expected expression before ';' tokenhello.c:6:1: error: expected ';' before '}' token Visual C++ can compile this code.
the ';' in line four (thereturnstatement) is not a standard ';'.
My function isvoid x(int *y); I want to call it likex(&6);orx({6});, I do not want to define an integer and assign 6 to it, I want single line.
What you need iscompound literals ``` #include <stdio.h> void x(const int *y) { printf("%d\n", *y); } int main(void) { x(&(int){6}); return 0; } ```
I'm trying to read 4 user inputs that can either be one digit, two digits, or a letter. I've tried using %c, but that can't contain any two digit numbers. I've also tried %d, but that reads all letters as 0. Is there anything that can cover all the bases?
In C there %c is usually for character inputs and %d is for integer. Usually you use these when scanning. Try %s this scans a string.
``` '#include <stdio.h> int main() { short arr[3][2]={3, 6, 9, 12, 15, 18}; printf("%d %d", *(arr + 1)[1], **(arr + 2)); }' ``` The output of the program is 15,15?
As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]
``` '#include <stdio.h> int main() { short arr[3][2]={3, 6, 9, 12, 15, 18}; printf("%d %d", *(arr + 1)[1], **(arr + 2)); }' ``` The output of the program is 15,15?
As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]
How to do stop scrolling uitableview if new rows are not there in tableview in objective c?
For disabling bounces for the tableView you can use: ``` self.tableView.bounces = NO; ``` this will disable it when it gets to the last row
Im new to programming with C and I'm having a hard time coming up with the proper formula to where it ignores, spaces, tabs, and new lines when I enter a string My Current Code
Replaceelse specialCharacter++;withelse if(!isspace(str[x])) specialCharacter++;.
For a class project I am writing, my teacher's style guide for functions says that "input parameters must appear before out parameters." I am not too sure what they mean by this?
If I have a function ``` void foo(int a, int b, int* c) { *c = a+b; } ``` In the above case a and b are inputs while c is an output. Generally you use "outputs" in this way if you are returning an array.
I did not understand why this works: ``` if(1) { int i; } ``` and this not: ``` if(1) int i; ``` error: expected expression before int If you could supply some standard reference.
In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).
I did not understand why this works: ``` if(1) { int i; } ``` and this not: ``` if(1) int i; ``` error: expected expression before int If you could supply some standard reference.
In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).
Got this ``` char array1[10][10]; ``` Is it possible to get address of array1 ? In which type could I stock it ? Already tried the following: ``` char *hold[10][10]; hold = &array1; ``` But doesnt work, ideas?
What you have now is a 2D array ofchar *. You need some parenthesis in this type. ``` char (*hold)[10][10]; ``` This is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.
Can someone please explain to me the difference between saya=1and*a=1in C. I'm having difficulty conceptualizing how pointers are used.
a = 1assigns1toa. *a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)
Got this ``` char array1[10][10]; ``` Is it possible to get address of array1 ? In which type could I stock it ? Already tried the following: ``` char *hold[10][10]; hold = &array1; ``` But doesnt work, ideas?
What you have now is a 2D array ofchar *. You need some parenthesis in this type. ``` char (*hold)[10][10]; ``` This is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.
Can someone please explain to me the difference between saya=1and*a=1in C. I'm having difficulty conceptualizing how pointers are used.
a = 1assigns1toa. *a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)
Can anyone explain what $(%SYMBOLIC) means in the make file target below? ``` R_all: $(%SYMBOLIC) $(CD_MAKE) $(BASE_ROOT) R_all ```
That's just a variable called%SYMBOLIC. Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve
Can anyone explain what $(%SYMBOLIC) means in the make file target below? ``` R_all: $(%SYMBOLIC) $(CD_MAKE) $(BASE_ROOT) R_all ```
That's just a variable called%SYMBOLIC. Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve