question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
The precision specifier for floating point values given toprintfallows a programmer to specify the number of digits to be printedafterthe decimal place. Doesprintfhave a similar precision specifier which allows the programmer to specify how many digitsbeforethe decimal point to round the value?
For example, if I pass... |
So far as I know, there's no way to getprintfto do that. You'd have to round the value manually before passing it toprintf. For example:
```
printf("%d\n", myRound(157, 10));
int myRound(int x, int b) {
return ((x + b/2) / b) * b; // TODO: handling for overflow, etc.
}
```
|
I have two functions:
```
void a(int * p);
int b();
```
Is it possible to pass the address of the return value of functionbto functionasomething like this:a(&b())?
|
A compound literal seems to do the trick (requires a C99 compiler):
```
int a()
{
return 5;
}
void b(int *a)
{
// do something with a
printf("%d\n", *a);
}
int main(void)
{
b(&(int){ a() });
}
```
Output is5.
|
```
( s1[i] = s2[i] ) != '\0'
```
Does the inequality checks2[i]with'\0'ors1[i]?
|
s2[ i ]will be assigned tos1[ i ]and then value ofs1[ i ]will be compared against ZERO.
Pleaserefer herefor more info.
|
I've been tried to printExtended ASCII characters:
http://www.theasciicode.com.ar/
But all those symbols were printed asquestion-character on the white background?.
I use the following cycle to print that symbols:
```
for (i = 0; i <= 30; i++)
printf("%c", 201);
```
Question:Is there any way to print thoseExt... |
It's better to use unicode than extended ASCII, which is non-standard. A thread about printing unicode characters in C :printing-utf-8-strings-with-printf-wide-vs-multibyte-string-literals
But indeed you need to copy paste unicode characters..
A better way to start:
```
#include <stdio.h>
int main() {
printf("... |
The following two programs use some basic pointer manipulation. But they perform differently.
```
#include<stdio.h>
#include<string.h>
int main(void){
int a = 1;
int b = 2;
int *pb, *pc;
pb = &a;
pc = pb;
pb = &b;
printf("%d %d\n", *pb, *pc);
}
```
This program prints two differen... |
The second example only contains a single string buffer, the arrays.
Makingptrpoint tosdoesn't in any way create a second copy of the character data, so when you print bothptrands, they result in the same string since they evaluate to the exact same address.
|
I am trying to write a function that is gracefully shutting down the program which is getting the messages from the queue.
The MQGET is started with MQGMO_WAIT option which suits me perfectly. However, I get an error when trying to issue another MQI call (MQCLOSE and MQDISC in this case).
The error is about graceful... |
You need to use the new call-back feature in WMQ v7.1 rather than MQGET with wait. Or shorten your wait to 1 or 2 seconds and loop over a "flag".
|
I just installed glib in Raspbian(Debian version). I want to read a config file using glib. I am trying to write a C application in Codeblocks and I use the header
```
#include <glib.h>
```
But I have an error in gtypes.h
```
fatal error:glibconfig.h No such file or directory
```
I used this path
```
project->Bui... |
Usepkg-config.
```
gcc `pkg-config --cflags glib-2.0` foo.c `pkg-config --libs glib-2.0`
```
|
I'm developing a program with C for an ARM processor, in my program when my memory usage grows(when the program flows through functions which have defined arrays in them) the program behaves unexpectedly and I think some variables are overwritten, that is when it runs out of memory it starts allocating memory from the... |
Yes, You are right. When the stack memory is full it starts to fill it from bottom address(0x00..0).This causes older variables to be overwritten and program behaves unexpectedly.
solution: The easiest way to solve this problem is never define array directly instead use malloc or calloc to allocate memory and free th... |
If my understanding is correctva_endis called for cleanup and in the same context, man page forva_endsays that
va_end()Each invocation of va_start() must be matched by a corresponding
invocation of va_end() in the same function. After the call va_end(ap)
the variable ap is undefined. Multiple traversals of the li... |
From C99 7.15.1.3/2 "Theva_endmacro":
If there is no corresponding invocation of the va_start or va_copy macro, or if the va_end macro is not invoked before the return, the behavior is undefined.
|
The following program:
```
int main( )
{
static char s[25]="The cocaine man";
int i=0;
char ch;
ch=s[++i];
printf("%c",ch);
ch=s[i++];
printf("%c",ch);
ch=i++[s];
printf("%c",ch);
ch=++i[s];
printf("%c",ch);
return 0;
}
```
The output of the program is :
hhe!
Thehhei... |
Because it is
```
ch=++(i[s]);
```
Wherei[s]=' '. And in ASCII Code,'!' = ' ' + 1
|
This question already has answers here:how does do{} while(0) work in macro?(3 answers)Why use apparently meaningless do-while and if-else statements in macros?(9 answers)Closed10 years ago.
What is the reason to define macro this way:
```
#define test_errno(msg) do{if (errno) {perror(msg); exit(EXIT_FAILURE);}} whi... |
It allows things like
```
if (condition)
test_errno(...);
```
to work properly with or without braces.
|
The precision specifier for floating point values given toprintfallows a programmer to specify the number of digits to be printedafterthe decimal place. Doesprintfhave a similar precision specifier which allows the programmer to specify how many digitsbeforethe decimal point to round the value?
For example, if I pass... |
So far as I know, there's no way to getprintfto do that. You'd have to round the value manually before passing it toprintf. For example:
```
printf("%d\n", myRound(157, 10));
int myRound(int x, int b) {
return ((x + b/2) / b) * b; // TODO: handling for overflow, etc.
}
```
|
I have two functions:
```
void a(int * p);
int b();
```
Is it possible to pass the address of the return value of functionbto functionasomething like this:a(&b())?
|
A compound literal seems to do the trick (requires a C99 compiler):
```
int a()
{
return 5;
}
void b(int *a)
{
// do something with a
printf("%d\n", *a);
}
int main(void)
{
b(&(int){ a() });
}
```
Output is5.
|
```
( s1[i] = s2[i] ) != '\0'
```
Does the inequality checks2[i]with'\0'ors1[i]?
|
s2[ i ]will be assigned tos1[ i ]and then value ofs1[ i ]will be compared against ZERO.
Pleaserefer herefor more info.
|
I've been tried to printExtended ASCII characters:
http://www.theasciicode.com.ar/
But all those symbols were printed asquestion-character on the white background?.
I use the following cycle to print that symbols:
```
for (i = 0; i <= 30; i++)
printf("%c", 201);
```
Question:Is there any way to print thoseExt... |
It's better to use unicode than extended ASCII, which is non-standard. A thread about printing unicode characters in C :printing-utf-8-strings-with-printf-wide-vs-multibyte-string-literals
But indeed you need to copy paste unicode characters..
A better way to start:
```
#include <stdio.h>
int main() {
printf("... |
The following two programs use some basic pointer manipulation. But they perform differently.
```
#include<stdio.h>
#include<string.h>
int main(void){
int a = 1;
int b = 2;
int *pb, *pc;
pb = &a;
pc = pb;
pb = &b;
printf("%d %d\n", *pb, *pc);
}
```
This program prints two differen... |
The second example only contains a single string buffer, the arrays.
Makingptrpoint tosdoesn't in any way create a second copy of the character data, so when you print bothptrands, they result in the same string since they evaluate to the exact same address.
|
I am trying to write a function that is gracefully shutting down the program which is getting the messages from the queue.
The MQGET is started with MQGMO_WAIT option which suits me perfectly. However, I get an error when trying to issue another MQI call (MQCLOSE and MQDISC in this case).
The error is about graceful... |
You need to use the new call-back feature in WMQ v7.1 rather than MQGET with wait. Or shorten your wait to 1 or 2 seconds and loop over a "flag".
|
I just installed glib in Raspbian(Debian version). I want to read a config file using glib. I am trying to write a C application in Codeblocks and I use the header
```
#include <glib.h>
```
But I have an error in gtypes.h
```
fatal error:glibconfig.h No such file or directory
```
I used this path
```
project->Bui... |
Usepkg-config.
```
gcc `pkg-config --cflags glib-2.0` foo.c `pkg-config --libs glib-2.0`
```
|
WithWriteFilecommand, I am trying to write to file in the design I wish. The problem is I have to write to file using a string, or a buffer.
I have to print in the format:
```
a1 a2 a3 a4 a5
b1 b2 b3 b4 b5
.
.
.
```
and these are double types. The major problem I am having is concatenating strings a... |
One option is to usestd::ostringstream(orstd::wostringstreamfor wide characters) to format the data into a string then write it out to the file.
```
std::ostringstream strm;
double a = 1.1;
double b = 2.2;
strm << "hello " << a << " world " << b;
DWORD written;
WriteFile(handle, strm.str().c_str(), strm.str().size()... |
This is a function designed to insert a new node at the end of a basic linked list.
```
node *insert(node *head, int data)
{
if (head == NULL)
return createNode(data);
head->next = insert(head->next, data);
return head;
}
```
How can I modify it so that it has no return value and instead passes a po... |
Like this:
```
void insert(node **head, int data)
{
if (*head == NULL)
*head = createNode(data);
insert(&(*head)->next, data);
}
```
|
On calling the function
```
int sum_array(int array[], int arr_length)
{
int sum = 0;
while(--arr_length >= 0)
sum += array[arr_length];
return sum;
}
```
in main function
```
int main()
{
int b[10];
...
total = sum_array(b,10);
...
}
```
why passing the argumentb, notb[]assum_arr... |
In C, arrays are passed as apointerto the first element. Thetypeofbis array.
When passingb, you're actually passing a pointer to the first element of the array.
|
From a friend of mine, I heard that the pow function is slower than its equivalent in simply multiplying the base by itself, the amount of times as its exponent. For example, according to him,
```
#include <stdio.h>
#include <math.h>
int main () {
double e = 2.71828
e2 = pow (e, 2.0)
printf("%le", e2)
}
... |
pow(double,double)needs to handle raising toany power, not just an integer based power, or especially2. As such, it's far more complicated than just doing a simple multiplication of two double values.
|
I have a Python code calling some C code (.so file).
Is there a way, from within the C code, go get the line number it has been called from at the Python side?
|
I eventually found thePyFrame_GetLineNumber(PyFrameObject *f)C function, whose source is located inframeobject.c.
|
I'm creating a camera driver for Android. I've got my mydriver.c file.
Apparently I need to compile it into a .ko, is that right ?
And then to load it I should do a#insmod ./mymodule.ko, will it work ?
Do I need to be root ? And how I put the .ko file on my Android tablet ?
|
Yes, you need to be root. And, insmod ./yourmodule.ko should work fine.
|
I there any way to use objective c types for exampleNSRange,CGRect, etc. (they are structs) from C?
I'm using objective c runtime to access objective c classes, but some methods returns and accepts objective c types which are structs, and my problem is how to use returned objective c struct from C?
|
Provided that you import the correct headers, of course you can, being those plain and simple C structs. Specifically you will findNSRangedefined in<Foundation/NSRange.h>andCGRectin<CoreGraphics/CGGeometry.h>.
There's nothing ofObjective-C-specific inNSRange,CGRectand similar structs.
|
I need to get the milliseconds as well using only the "time.h" library.
For seconds, this is what I have:
```
time_t now;
time(&now);
printf("seconds since Jan 1, 1970 %d", now);
```
|
The<time.h>or<ctime>header files, as specified by the C and C++ standards respectively, does not support subsecond timing.
If you can use C++ and have a C++11 compatible environment, then you can get portable support with thestd::chronofunctionality. There's also aboost::chronothat could be used in older versions of ... |
I'm using a GeomagnetismLibrary and one of the function declarations have a format
```
int MAG_robustReadMagModels(char *filename, MAGtype_MagneticModel *(*magneticmodels)[], int array_size)
```
For the sake of simplicity I've dumbed it down to just focus on my goal
```
void blah(int *(*a)[])
{
(*a)[0] = malloc... |
This would do:
```
int * b;
blah((int *(*)[]) &b);
```
|
We want to pass a string to the vc++ from a csharp programme.
Following is the code :
In C#
```
[DllImport("ConsoleApplication2.dll")]
public static extern int main_c(StringBuilder IpAddr, int p);
public string[] tcp()
{
StringBuilder buffer = new StringBuilder("192.168.1.100"); ... |
Personnally, I'd try declaring it so:
```
[DllImport("ConsoleApplication2.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int main_c([MarshalAs(UnmanagedType.LPStr)] String IpAddr, int port);
```
And declare the pointer const in the VC++ function, since it's not supposed to write there. You do... |
I'm literately just doing a multiplication of two floats. How come these statements produce different results ? Should I even be using floats ?
500,000.00 * 0.001660 = 830
|
How come these statements produce different results ?
Becausefloating-point arithmetic is not exactand apparently you were not printing the multiplier precisely enough (i. e. with sufficient number of decimal digits). And it wasn't.00166but something thatseemed0.00166rounded.
Should I even be using floats ?
No. For... |
I would like to ask if there is any fast way(using memset for example) to clear a char table like
```
char mytable[2][10];
```
For example as I know using memset
```
memset(mytable, 0, sizeof(mytable));
```
is used for 1D tables.
|
They're calledarrays,not "tables".
And thevery same code worksfor any array with arbitrary number of dimensions.
|
Assuming we have R, G, and B created images:
```
IplImage *R=cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1);
IplImage *G=cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1);
IplImage *B=cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1);
```
and we are having an image A like:
```
IplImage *A=cvCreateImage(cvSize(640, ... |
The OpenCV's default channel order isBGR
|
Does the standard Cctimefunction return the Gregorian calendar date? In particular, I want to verify that it will account for leap years and thus displayFeb 29for the respective dates.
|
For times in the future and in the recent past, yes. For times before the Gregorian calendar reform... I don’t know, but those times are only relevant on systems with 64 bittime_t.
|
I have some functions where I would like to return NULL on failure, and on success they do not need to return anything. I have been usingvoid * function_name(...), but it still requires me to return something.
The reason I am doing this is to detect failure as part of a python C extension and they recommend that the ... |
In pure C terms, the easiest is to return a Boolean flag indicating success/failure.
As far as integration with Python is concerned, another approach is:
```
PyObject* func() {
...
if (error) {
/* set the exception */
PyErr_Format(PyExc_..., ...); /* TODO: fill in as appropriate */
re... |
I used the fflush() in Linux GCC but it did not work. Are there any alternatives for that function? Here is my code:
```
#include<stdio.h>
void main()
{
char ch='y';
while(ch=='y')
{
int a;
printf("Enter some value:");
scanf("%d",&a);
fflush(stdin);
printf("Do you want to continue?");
sc... |
Don't use fflush, use this function instead:
```
#include <stdio.h>
void clean_stdin(void)
{
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
```
fflush(stdin)depends of the implementation, but this function always works. In C, it is considered bad practice to usefflush(stdin).
|
Let's say I have a struct:
```
struct location
{
int x;
int y;
};
```
Then I want to define a invalid location for use later in the program:
```
#define INVALID_LOCATION (struct location){INT_MAX,INT_MAX}
```
However when I use that in my program, it ends up in an error:
```
struct location my_loc = { 2... |
You can't compare structures for equality with==.
|
I have the following code:
```
int resource;
sem_t s;
void function2()
{
// do some operation to resource
}
void function1()
{
sem_wait(&s);
function2();
sem_post(&s);
}
```
if we have different process call thefunction1simultaneously, andfunction1is already protected by semaphore, do we need to hav... |
What you really need to do, is to protect your share data using semaphore. Atleast this is the best practice. Semaphore is basically use to protect data, which is accessible from various functions. A typical use might look like this:
```
struct data {
yoursharedata;
sem_t lock;
}
```
Whenever you'll ac... |
I have some variables in my C code that are declared with__attribute__((section(".data.mystuff"))). I would like to define two symbols,mystuff_startandmystuff_sizethat have the position and size of the section. It looks likeld'sLOADADDRandSIZEOFwill do what I want, but I don't want to write the whole linker script. I ... |
The easiest thing to do is to put them into a section that has a valid C identifier as it's name. For example, use:
```
__attribute__((section("mystuff")))
```
and you'll have automagic variables__start_mystuffand__stop_mystuffwhich will give you the start and end addresses of the section which you can declare in y... |
It was asked in an interview .
As like the idea of reading right to left i can interpret
```
char *const *p declares p as pointer to constant pointer of character.
```
while
```
char * *const p declares p as a constant pointer to character pointer.
```
but since i didn't get the exact meaning of these so please v... |
char * const *pmeans the character pointer thatppoints to cannot be changed.
```
char arr[] = "";
char *ptr = arr;
char * const *p = &ptr;
**p = '\0'; // ok
*p = 0; // error
p = 0; // ok
```
char ** const pmeans thatpcannot be changed.
```
char arr[] = "";
char *ptr = ar... |
strtolparses out a long integer from a given string. Okay. But how could I check whether there was parsed anything at all?
For example:
usingstrtolon the following string yields0:0abcdefhowever, usingstrtolon the following string yields0too:abcdef
So, I have no indicator whether the function parsed a valid0or did n... |
That's the signature of strtol():
```
long int strtol(const char *nptr, char **endptr, int base);
```
Ifendptris not NULL,strtol()stores the address of the first invalid character in*endptr.
So you can simply compare*endptrtonptrafterwards and if it differs,strtol()has parsed the characters before*endptr.
|
I have:
```
#define MAX_STR_LEN 100
```
and I want to put intoscanfpattern so I can control the string length:
```
scanf("%100[^\n]s",sometext)
```
I tried:
```
scanf("%MAX_STR_LEN[^\n]s",sometext)
scanf("%"MAX_STR_LEN"[^\n]s",sometext)
scanf("%",MAX_STR_LEN,"[^\n]s",sometext)
```
And it didn't work. I just want... |
I wasn't happy with any of these solutions, so I researched further, and discovered GNU GCC macrostringification
which can be used as:
```
#define XSTR(A) STR(A)
#define STR(A) #A
#define MAX_STR_LEN 100
scanf("%"XSTR(MAX_STR_LEN)"[^\n]s", sometext)
```
Maybe VS2010 offers something similar?
|
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 feel I'm missing something basic about number system but I'm really confused with below piece of code I'... |
All exactly as expected. Start with a 0 and it's octal. Start with 0x and it's hex. Otherwise, it is decimal.
What is the problem?
|
Let me clear you first that I'm not a college student and this is not my home assignment. I am just curious to know the solution of this question which was once asked to me. I think this is a nice and tricky question which I feel worth sharing.The question was--
How do you input a string(said in general sense, indepe... |
You can try recursion.
```
void print_reverse_str() {
int c = getchar();
if (c != EOF) {
print_reverse_str();
putchar(c);
}
}
```
|
can somebody explain these answers? I can understand 2. , 4. but the rest i can not
```
int a[ ] ={2,4,3,1,10,5,9,6,8,7};
int *pa = &a[4],*pb = &a[1];
What is the value of the below?
1.*(a + 3)
2.*pb-*pa
3.pb[3]
4.*pa + 5
5.*(pa-2)
6.pa[4]
Answer:
1.*(a + 3)=1
2.*pb-*pa=-6
3.pb[3]=10
4.*pa + 5=15
5.*(pa-2)=3
6.p... |
x[y]is equivalent toy[x], which is equivalent to*(x+y)or*(y+x). So*(a+3)is equivalent toa[3]or3[a].
|
Trying to compile in win7 x64 cmd prompt. The following command:
```
nvcc -o kernal.cu
```
yields the following error message.
```
nvcc : fatal error : No input files specified; use option --help for more information
```
|
try
nvcc -o xxx kernal.cu
where xxx is the output file name you want.
|
I'm trying to return a char array from a function. According to everything I have read I understand I cannot return the array itself because arrays are second class citizens. But from what I understand I can create a pointer to it and make it static. I have tried both and am failing to compile. Any ideas why?
```
int... |
compile error because of type mismatch. @JustinPeel points out thatconstis needed too.
```
int main(void)
{
char **hold_array = get_array ();
return 0;
}
char **get_array(void)
{
static const char *array[] = {"test1", "test2"};
return (array);
}
```
|
my function:
```
int f1(int* r1, int* r2, int* r3, int* r4) {
*r1 = 1;
*r2 = 343;
*r3 = 34;
*r4 = 3;
return c; // c = 1 if success
}
caller:
f1 (&r1, &r2, &r3, &r4);
```
if I want to simplify my function, should I pass in an array of fourintpointers? or should i do it with an array of fourint... |
Since arrays decay into pointers when passed to a function, an array would do:
```
void f(int *p)
{
p[0] = 1;
p[1] = 2;
p[2] = 3;
p[3] = 4;
}
int arr[] = { 0, 0, 0, 0 };
f(arr);
```
|
Since ANSI C99 there is_Boolorboolviastdbool.h. But is there also aprintfformat specifier for bool?
I mean something like in that pseudo code:
```
bool x = true;
printf("%B\n", x);
```
which would print:
```
true
```
|
There is no format specifier forbooltypes. However, since any integral type shorter thanintis promoted tointwhen passed down toprintf()'s variadic arguments, you can use%d:
```
bool x = true;
printf("%d\n", x); // prints 1
```
But why not:
```
printf("Your boolean variable is: %s", x ? "true" : "false");
```
inste... |
I am trying to get a list of all of the library files in my Mac OS X's c package, but I don't even know what the name of the package is, or how to get the files once I know the package. Are there any command-line tools that I can use to extract these files?
|
Mac OS X does not have a “C” package that I know of. You can list the packages installed on your system withpkgutil --packages. You can list the files installed by a specific package, such ascom.apple.pkg.clang, withpkgutil --files <name of package>.
|
I am developing a C code on Linux environment. I usefwriteto write some data to some files. The program will be run on an environment that power cut offs occur often (at least once a day). Therefore, I wantfwriteto ensure that the file should not be updated if a power cut occurs while it is writing data. It should onl... |
First write the file to a temporary path on the same filesystem, like/etc/routing_table.tmp. Then just rename the copy on top of original file. Renames are guaranteed atomic.
So, the sequence of calls would be,fopen,fwrite,fclose,rename.
|
I wrote a simple Linux kernel module:
```
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/reboot.h>
static int my_init(void)
{
machine_power_off();
return 0;
}
static void my_exit(void)
{
return;
}
module_init(my_init);
module_exit(my_exit);
```
Source comp... |
@Amir, traversed through the files in the linux kernel, w.r.t. all the architecture files wheremachine_power_off()is used, it is not exported so cannot be used in your module.
|
If a programPROGis invoked with pipes,
```
progA | progB | PROG | progC ...
```
Is there a way for it to tell in what context it was invoked - i.e., from/to what other programs (A, B, C...) it is receiving or sending piped output?
I'm mostly interested in the immediate predecessor toPROG(in the example above,progB)... |
If you're on Linux you can use the/procfilesystemto check how commands communicate over pipes. However, this is not really portable.
|
I am going through some C codes. Some of them are a little difficult to understand. For instance, what does following assignment do:
```
MY_TYPE my_var[3]={0};
```
MY_TYPEis some fixed point arithmetic type. I have not yet come across variables with[]brackets and assignment with{}around values.
That was too easy, I... |
It creates an arraymy_varof typeMY_TYPEthat is of size 3 and is initialised to all 0s (I suspectMY_TYPEis some sort of integer type). Note that only one initialisation is necessary for the rest to be init`ed too.
Also note that if you declare the array globally as opposed to within a block, then it will be initialise... |
This question already has answers here:size of character array and size of character pointer(6 answers)Closed10 years ago.
I have a C code:
```
char s1[20];
char *s = "fyc";
printf("%d %d\n", sizeof(s1), sizeof(s));
return 0;
```
It returns
```
20 8
```
I'm wondering how does the 8 come from, thanks!
|
sizeof(s1)is the size of the array in memory, in your case 20 chars each being 1 byte equals 20.
sizeof(s)is the size of the pointer. On different machines it can be a different size. On mine it's 4.
To test different type sizes on your machine you can just pass the type instead of a variable like soprintf("%zu %zu\... |
When linking a static library as athin archivethe .o-files are not copied into the archive, but rather they are referenced with their relative path from the .a file.
How can I check if a given .a file is a thin archive or not?
|
How can I check if a given .a file is a thin archive or not?
```
head -1 t.a
!<thin>
```
Eventually,file(1)should be able to tell you. Myfile-5.09just saysdata.
|
I have a macro which is used inafile.candbfile.c(both in module A)
This macro is inaheader.h
Both of these are in different modules/directories and aheader.h module is complied before module A is complied.
Now one way is to do#include "aheader.h"in each of the .c files.
But instead of doing this, is there a way to m... |
#include "aheader.h"is the simple and correct thing to do. C has no feature to auto-include headers when a macro is used.
If you insist on doing it in the makefile, you can add-include aheader.has a compilation flag. It will include it in all files.
It's possible to use the makefile to add this flag only when the ma... |
I was wondering whether declaring multiple things of the same type affects the compile time, such as below.
```
void a(),
b(),
c();
```
vs
```
void a();
void b();
void c();
```
|
I would be surprised if it didn't matterat allsince the compiler will execute different code for the two cases, but it's impossible to guess which one would be faster, and whether one would be consistently faster than the other.
I would also be surprised if it were possible to measure the difference in any meaningful... |
I copied and pasted the code of a friend into my xcode C project, ran it to see where he went wrong and then closed it, after i had given him the solution. Unfortunately, i did all that in my own project. I thought everything would be fine, as i didn't save his code into my project, but when i opened my project later,... |
From the Xcode menu on top, click preferences, select the locations tab, look at the build location option.
|
I am going through couple of VS solutions. The c files belonging to the project do not have main function, they do have functions like MainWindProc and several others.
Are VS soln files significantly different in the sense that their main function is declared somewhere else e.g. in .sln file rather than in.c file?
|
Just as every C application and C++ application must have amainfunction as its starting point,every Win32-based application must have a WinMainfunction.
Take a look:http://msdn.microsoft.com/en-us/library/vstudio/bb384843.aspx
|
Is there any preference/convention/rule on order for defining a variable asstaticandlong/doubleor other types?
e.g. is
```
static double a;
```
same as
```
double static a;
```
is it any different for functions? above, a is variable.
|
They are equivalent butstaticat the beginning is preferred.
(C99, 6.11.5p1) "The placement of a storage-class specifier
other than at the beginning of the declaration specifiers in a
declaration is an obsolescent feature"
|
In the main function of C:
```
void main(int argc, char **argv)
{
// do something here
}
```
In the command line, we will type any number for example1or2as input, but it will be treated as char array for the parameter of argv, but how to make sure the input is a number, in case people typedhelloorc?
|
Another way of doing it is by using isdigit function. Below is the code for it:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
char input[MAXINPUT] = "";
int length,i;
scanf ("%s", input);
length = strlen (input);
for (i=0;i<le... |
I have a graphic application under development but I am unable to change the font in that. If anyone knows about any page or link explaining the method to change fonts in framebuffer on linux, it will be very helpful.
|
Linux frame buffer is a memory location which is mapped to your display area. What ever you write in to this memory area that reflects on the display. Coming to your question, For frame buffer there is nothing like font. every thing is a binary data. For making your own font, first you need to get hexadecimal values c... |
In the following case, is the compiler allowed to optimize away the call tofoo()and\or the entireifblock?
```
if( foo() && 0 )
{ ... }
```
|
From a standards point-of-view, the compilermustevaluate the left-hand side, i.e.foo()must be called:
[C99, 6.5.13]Unlike the bitwise binary&operator, the&&operator guarantees left-to-right evaluation;
there is a sequence point after the evaluation of the first operand. If the first operand
compares equal to 0, the... |
Generally, we usetypedefto get alternate names for datatypes.
For example --
```
typedef long int li; // li can be used now in place of long int
```
But, what does the below typedef do?
```
typedef int (*pf) (int, int);
```
|
```
typedef int (*pf) (int, int);
```
This means that variables declared with thepftype are pointers to a function which takes twointparameters and returns anint.
In other words, you can do something like this:
```
#include <stdio.h>
typedef int (*pf)(int,int);
int addUp (int a, int b) { return a + b; }
int main... |
This question already has answers here:size of character array and size of character pointer(6 answers)Closed10 years ago.
I have a C code:
```
char s1[20];
char *s = "fyc";
printf("%d %d\n", sizeof(s1), sizeof(s));
return 0;
```
It returns
```
20 8
```
I'm wondering how does the 8 come from, thanks!
|
sizeof(s1)is the size of the array in memory, in your case 20 chars each being 1 byte equals 20.
sizeof(s)is the size of the pointer. On different machines it can be a different size. On mine it's 4.
To test different type sizes on your machine you can just pass the type instead of a variable like soprintf("%zu %zu\... |
When linking a static library as athin archivethe .o-files are not copied into the archive, but rather they are referenced with their relative path from the .a file.
How can I check if a given .a file is a thin archive or not?
|
How can I check if a given .a file is a thin archive or not?
```
head -1 t.a
!<thin>
```
Eventually,file(1)should be able to tell you. Myfile-5.09just saysdata.
|
I have a macro which is used inafile.candbfile.c(both in module A)
This macro is inaheader.h
Both of these are in different modules/directories and aheader.h module is complied before module A is complied.
Now one way is to do#include "aheader.h"in each of the .c files.
But instead of doing this, is there a way to m... |
#include "aheader.h"is the simple and correct thing to do. C has no feature to auto-include headers when a macro is used.
If you insist on doing it in the makefile, you can add-include aheader.has a compilation flag. It will include it in all files.
It's possible to use the makefile to add this flag only when the ma... |
I was wondering whether declaring multiple things of the same type affects the compile time, such as below.
```
void a(),
b(),
c();
```
vs
```
void a();
void b();
void c();
```
|
I would be surprised if it didn't matterat allsince the compiler will execute different code for the two cases, but it's impossible to guess which one would be faster, and whether one would be consistently faster than the other.
I would also be surprised if it were possible to measure the difference in any meaningful... |
I copied and pasted the code of a friend into my xcode C project, ran it to see where he went wrong and then closed it, after i had given him the solution. Unfortunately, i did all that in my own project. I thought everything would be fine, as i didn't save his code into my project, but when i opened my project later,... |
From the Xcode menu on top, click preferences, select the locations tab, look at the build location option.
|
I am going through couple of VS solutions. The c files belonging to the project do not have main function, they do have functions like MainWindProc and several others.
Are VS soln files significantly different in the sense that their main function is declared somewhere else e.g. in .sln file rather than in.c file?
|
Just as every C application and C++ application must have amainfunction as its starting point,every Win32-based application must have a WinMainfunction.
Take a look:http://msdn.microsoft.com/en-us/library/vstudio/bb384843.aspx
|
Is there any preference/convention/rule on order for defining a variable asstaticandlong/doubleor other types?
e.g. is
```
static double a;
```
same as
```
double static a;
```
is it any different for functions? above, a is variable.
|
They are equivalent butstaticat the beginning is preferred.
(C99, 6.11.5p1) "The placement of a storage-class specifier
other than at the beginning of the declaration specifiers in a
declaration is an obsolescent feature"
|
In the main function of C:
```
void main(int argc, char **argv)
{
// do something here
}
```
In the command line, we will type any number for example1or2as input, but it will be treated as char array for the parameter of argv, but how to make sure the input is a number, in case people typedhelloorc?
|
Another way of doing it is by using isdigit function. Below is the code for it:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
char input[MAXINPUT] = "";
int length,i;
scanf ("%s", input);
length = strlen (input);
for (i=0;i<le... |
I have a graphic application under development but I am unable to change the font in that. If anyone knows about any page or link explaining the method to change fonts in framebuffer on linux, it will be very helpful.
|
Linux frame buffer is a memory location which is mapped to your display area. What ever you write in to this memory area that reflects on the display. Coming to your question, For frame buffer there is nothing like font. every thing is a binary data. For making your own font, first you need to get hexadecimal values c... |
In the following case, is the compiler allowed to optimize away the call tofoo()and\or the entireifblock?
```
if( foo() && 0 )
{ ... }
```
|
From a standards point-of-view, the compilermustevaluate the left-hand side, i.e.foo()must be called:
[C99, 6.5.13]Unlike the bitwise binary&operator, the&&operator guarantees left-to-right evaluation;
there is a sequence point after the evaluation of the first operand. If the first operand
compares equal to 0, the... |
Generally, we usetypedefto get alternate names for datatypes.
For example --
```
typedef long int li; // li can be used now in place of long int
```
But, what does the below typedef do?
```
typedef int (*pf) (int, int);
```
|
```
typedef int (*pf) (int, int);
```
This means that variables declared with thepftype are pointers to a function which takes twointparameters and returns anint.
In other words, you can do something like this:
```
#include <stdio.h>
typedef int (*pf)(int,int);
int addUp (int a, int b) { return a + b; }
int main... |
Whats the significance of first argument in anifstatement if it's just going to be ignored? For instance, in:
```
#include<stdio.h>
main()
{
if(1,0)
printf("abc");
else
printf("qwe");
}
```
|
That's not an argument list, it's the comma operator.
If you have a statement likefoo(), bar(), thenfoo()will be called and its result discarded, thenbar()will be called and the entire statement's result will bebar()'s result. Something likeif(foo(),bar())might be used if callingfoo()has some side effect that needs t... |
In my driver, I am trying to map an address returned fromioremapto a userspace address.
What kind of an address is returned fromioremap?How is it different from akmallocaddress ?How can I map an address returned fromioremap?Which address should be inserted toremap_pfn_range?
|
You don't needioremap()if you're usingremap_pfn_range().ioremap()maps a physical address into a kernel virtual address.remap_pfn_range()maps physical addresses directly to user space. Just pass your physical address (downshifted by PAGE_SHIFT to produce a pfn) directly toremap_pfn_range(). Your questions in order:
... |
I want to define an array of strings, with defining and assignment splitted in two lines like the following:
```
char **test;
test = { "Snakes", "on", "a", "Plane" }; // <--
printf("Test: %s\n", test[3]);
```
But I get an error in the indicated line:
```
Line 4: error: expected expression before '{' token
```
What... |
You cannot assigning an array by this way.
In your case your array is not allocated.
The way to do this is :
```
char *test[4];
test[0] = "Snake";
test[1] = "on";
test[2] = "a";
test[3] = "plane";
```
|
The following function is to return the length of a line that is entered through keyboard. But its saying that (The C Programming language K & R)it will return the length of the line, or zero if end of file is encountered.But when I analyzed with my basic knowledge in C at least it is returning the length of the line ... |
When there's nothing, EOF will be there e.g. in case ofEmpty line,c==EOFand you have entered a condition in yourforloop that(c=getchar())!=EOF. Thusiwon't change and when it will be returned after execution ofreturn i;, it will return0
I hope this helps.
|
I was trying to implement LCS in C language, but am stuck at equivalent of following code in C :
```
return backtrack(C, X, Y, i-1, j-1) + X[i]
```
I tried usingstrcat():
```
char *str = sequence(arr,pGene1,pGene2,i-1,j-1);
char chr= pGene1[i-1];
char *chr1 = &chr;
return strcat(str,chr1);
```
but it gives me a... |
You are missing a\0terminator fromchr. Also you don't really need the additional pointerchr1. The following should work:
```
char *str = sequence(arr, pGene1, pGene2, i-1, j-1);
char chr[2] = { pGene1[i-1], '\0' };
return strcat(str, chr);
```
|
I've encountered the following line in a .cuh file:
```
#define mp_ptr(n) P##n
```
What does theP##npart mean?
|
It means concatenation. It's a C preprocessor directive.
So,mp_ptr(1)becomesP1,mp_ptr("foobar")becomesP"foobar", etc.
|
To read multi-word strings, I have been using the gets() function. The behaviour of thegets()function is unpredictable to me and I use the statementfflush(stdin)before everygets()statement to avoid issues. Is using this statement this way appropriate? What can be an alternative approach?
|
fflushonly flush output streams.
If you want toflushstdin, keep reading until you getEOF, something like:
```
int i;
while (((i = getchar()) != '\n') && (i != EOF));
```
|
```
int a;
scanf("%d",&a);
```
How can I ensure the code doesn't work if a non-digit character is given as input to thescanf()statement? [I need a solution that doesn't make me change the data type tochar]
|
If the first character is not a digit, then%dwill fail to match, andawill not be assigned. The return value ofscanftells you how many items were assigned. If it's one, then clearly it was at least partially a valid number. If it's zero, that means it couldn't be parsed as a number, and you may want to signal an error.... |
I had a question that may sound dumb to many, but I can't stop to post it here as found nothing there on the Internet.
Why does java doesn't have clrscr sort of function that we use in C?
If I created a java concole application that iterates over and over based on user input and then if I want to provide the user an... |
OOP has nothing to do with it. It's more clrscr is more a function of the environment the Java is running in than Java itself, and so it is not in Java's scope.
Or to put it another way: since Java is cross platform and can be run without a console, the meaning of clrscr has to change depending on how the app is run ... |
I am getting lvalue not modifiable in this expression
```
tmp_ux =tmp_ux+ tau*(-G*tmp_phi*grad_phi_x)/tmp_rho;
```
the variables I am using are
```
double tmp_ux
#define tau 1.0
#define G -6.0
double tmp_phi
double grad_phi_x
double tmp_rho
```
|
Due to the macro#define G -6.0, the expression,
```
tmp_ux =tmp_ux+ tau*( -G *tmp_phi*grad_phi_x)/tmp_rho;
```
becomes,
```
tmp_ux =tmp_ux+ tau*( --6.0 *tmp_phi*grad_phi_x)/tmp_rho;
```
Here,--6.0is illegal as you are trying to decrement6.0.
To avoid this, either change the expression as,
```
tmp_ux =tmp_ux+ ... |
In C,
```
int* a, b;
```
Will makeaan integer pointer and b an integer.
What about this? Isban integer or an integer pointer?
```
typedef int* foo;
foo a, b;
```
|
In C,typedefis not a preprocessor directive: unlike#define, it is not a textual substitution. It gives an alternative name to an existing type, so bothaandbwill be of the same type - namely,foo, which is an alias forint*. Moreover, you can write this:
```
foo a, *b;
```
to makeaanint*andbanint**.
|
I am not sure of the precise definition of this term.
I know that a bitwise XOR operation is going bit by bit and taking the XOR of corresponding bits position wise. Is this result termed the 'XOR sum'? If not, what is an XOR sum, and how do you use XOR to implement this addition?
|
In a bit wise XOR operation:
```
a b a^b
-----------
0 0 0
0 1 1
1 0 1
1 1 0
```
XOR sum refers to successive XOR operations on integers.Suppose you have numbers from1toNand you have to find their XOR sum then forN = 6, XOR sum will be1^2^3^4^5^6 = 7.
```
1 = 001, 2 = 010, 3 = 011, 4 = ... |
I have the following code:
```
typedef struct
{
int a;
float b;
int c;
} Hello;
Hello hello[100];
```
I know I can assign value to the first element of this array:
```
hello[0] = {1,2.0,3};
```
but how to assign the first element when we declare thehello: Hello hello[100];
|
Requires additional set of{}(outer{}for the array, inner set(s) for the elements of the array):
```
Hello hello[100] = { {1, 2.0, 3} };
```
|
I need to place * on every lowercase letter, but my program blocks always. Although this seems like a simple problem I cant find simple solution. Please help.
```
#include <stdio.h>
void f(char *p)
{
int i = 0;
char c = '*';
while(p[i] != '\0')
{
if(p[i]> 96 && p[i] < 122 )
{
... |
You cannot modify string literals.
Try:
```
int main(void)
{
char buf[] = "tesT";
f(buf);
return 1;
}
```
also, never hardcode ASCII values, useislower()from<ctype.h>.
|
I understand in general terms how a buffer overflow attack works, but how can someone use this technique specifically to gain root access to a host? A simple example and explanation would be helpful. Thank you
|
Usually, it's about exploiting a vulnerability in a process that runs as root: Either a server that accepts connections (sockets, pipes, etc.) or an executable with the SETUID flag.
If by "gain root access" you mean take control of a shell running as root, the buffer overflow payload must start a shell and usedup2to ... |
Whats the significance of first argument in anifstatement if it's just going to be ignored? For instance, in:
```
#include<stdio.h>
main()
{
if(1,0)
printf("abc");
else
printf("qwe");
}
```
|
That's not an argument list, it's the comma operator.
If you have a statement likefoo(), bar(), thenfoo()will be called and its result discarded, thenbar()will be called and the entire statement's result will bebar()'s result. Something likeif(foo(),bar())might be used if callingfoo()has some side effect that needs t... |
In my driver, I am trying to map an address returned fromioremapto a userspace address.
What kind of an address is returned fromioremap?How is it different from akmallocaddress ?How can I map an address returned fromioremap?Which address should be inserted toremap_pfn_range?
|
You don't needioremap()if you're usingremap_pfn_range().ioremap()maps a physical address into a kernel virtual address.remap_pfn_range()maps physical addresses directly to user space. Just pass your physical address (downshifted by PAGE_SHIFT to produce a pfn) directly toremap_pfn_range(). Your questions in order:
... |
I want to define an array of strings, with defining and assignment splitted in two lines like the following:
```
char **test;
test = { "Snakes", "on", "a", "Plane" }; // <--
printf("Test: %s\n", test[3]);
```
But I get an error in the indicated line:
```
Line 4: error: expected expression before '{' token
```
What... |
You cannot assigning an array by this way.
In your case your array is not allocated.
The way to do this is :
```
char *test[4];
test[0] = "Snake";
test[1] = "on";
test[2] = "a";
test[3] = "plane";
```
|
The following function is to return the length of a line that is entered through keyboard. But its saying that (The C Programming language K & R)it will return the length of the line, or zero if end of file is encountered.But when I analyzed with my basic knowledge in C at least it is returning the length of the line ... |
When there's nothing, EOF will be there e.g. in case ofEmpty line,c==EOFand you have entered a condition in yourforloop that(c=getchar())!=EOF. Thusiwon't change and when it will be returned after execution ofreturn i;, it will return0
I hope this helps.
|
I was trying to implement LCS in C language, but am stuck at equivalent of following code in C :
```
return backtrack(C, X, Y, i-1, j-1) + X[i]
```
I tried usingstrcat():
```
char *str = sequence(arr,pGene1,pGene2,i-1,j-1);
char chr= pGene1[i-1];
char *chr1 = &chr;
return strcat(str,chr1);
```
but it gives me a... |
You are missing a\0terminator fromchr. Also you don't really need the additional pointerchr1. The following should work:
```
char *str = sequence(arr, pGene1, pGene2, i-1, j-1);
char chr[2] = { pGene1[i-1], '\0' };
return strcat(str, chr);
```
|
I've encountered the following line in a .cuh file:
```
#define mp_ptr(n) P##n
```
What does theP##npart mean?
|
It means concatenation. It's a C preprocessor directive.
So,mp_ptr(1)becomesP1,mp_ptr("foobar")becomesP"foobar", etc.
|
I want to write #ifdef syntax in c
how should I write this?
```
#ifdef OP1
foo1(categoryName);
#endif
#ifdef OP2
foo2(categoryName);
#endif
```
is there neater way?
```
#ifdef OP1
foo1(categoryName);
#elseif #ifdef OP2
foo2(categoryName);
#endif
```
|
```
#ifdef OP1
foo1(categoryName);
#elif defined(OP2)
foo2(categoryName);
#endif
```
For greater symmetry, you could start with:
```
#if defined(OP1)
```
But that's just a matter of taste.
|
I have a piece of C code and I don't understand how thesizeof(...)function works:
```
#include <stdio.h>
int main(){
const char firstname[] = "bobby";
const char* lastname = "eraserhead";
printf("%lu\n", sizeof(firstname) + sizeof(lastname));
return 0;
}
```
In the above code sizeof(firstname) is 6 and... |
firstnameis achararray carrying a trailing0-terminator.lastnameis a pointer. On a 64bit system pointers are 8 byte wide.
|
I can't find what is wrong with my code in C:
error.h
```
#ifndef ERROR_H_INCLUDED
#define ERROR_H_INCLUDED
void myfunc(bool**,int); //error line 1
#endif
```
Here is the function declaration:
error.c
```
#include "error.h"
void myfunc(bool **rel,int num){ //error line 2
//function code here
}
```
... |
booltype is not recognized, you need to includestdbool.hin yourerror.hheader.
|
I have just started my Data types revised chapter. I am currently studying the concept of signed and unsigned character. My doubt is that the signed char has a range from -128 to 127, then why the below code is still running ? Also, the below code is giving the infinite o/p which is not understandable to me.
```
main... |
```
for ( ch = 0 ; ch <= 255 ; ch++ )
```
Ifchis a signed character, it will start at 0 and increment to 127. Then, at the next increment, it will "wrap around" and become -128. Using anunsignedchar:
```
127 = 0x7F
128 = 0x80
```
But, using asignedchar,0x80becomes -128.
So nowchwill run from -128 through 127. A... |
Is there a more efficient way to get the sum of absolute differences of twomemory blocksarrays ofdoublein C/C++ than to perform a loop on the array elements? So, what I wonder is if there is a function for this purpose similar tomemset,memcpy,memcmpetc.
How do you define the difference?
The memory blocks containdoub... |
Yes, there isSIMD. If you use GCC you can try adding things like-msse2 -O3and see if it automatically generates SIMD instructions for you. If it does, or if you choose to use a library to do explicit SIMD, you can process four floats per instruction. To improve your chances, try to make your inner loop nice and sim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.