question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I just ran into a smallish issue when working with size_t values in some code.
First I wanted to use size_t because it's [guaranteed] to be the same size on most platforms, that way going from 32 to 64 bit shouldn't cause any issues.
Then I negated the size_t value and got a really big number, looking back I realize... |
If you want to have exactly the same number of bits on all platforms, simply use for instance int32_t as defined instdint.h
|
```
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
float sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=1;i<=n;i++)
{
sum+=(pow(x,2*i+1) * pow(-1,i+1));
}
printf("%f",sum);
return 0;
... |
Yes, you're a bit wrong. In your code
```
printf("%f",sum);
```
sumis anintand using%fto print the value of anintisundefined behaviour.
The functionpow()returns adouble. You may want to change yoursumto typedouble.
If you don't mind using your own version, a better looking implementation, without usingpow()will be... |
```
#include <stdio.h>
#define ABS(a) (a) < 0 ? -(a) : (a)
int main(void)
{
printf("%d\n", ABS(-3) + 1);
return 0;
}
```
This code snippet, from Herbert Schildt's book, looks like it will produce the output4but it actually prints3. Why?
How do I fix it?
|
The correct way is to use aninlinefunction, with a_Genericcase for each type you want to support. Otherwise you evaluateatwice.
In lieu of that you can fix it by parenthesizing the expression in the macro. That is always a good idea to prevent exactly this sort of problem.
```
#define ABS(a) ((a) < 0 ? -(a) : (a))
`... |
I was trying to implement the following code.
```
#include <stdio.h>
#include <string.h>
void abc(char *, char *);
int main(int argc, char *argv[])
{
char *p="Hello XYZ";
char *q="ABC";
abc(p,q);
printf("%s", p);
}
void abc(char *p, char *q)
{
p+=6;
p=q;
}
```
I believe I am modifying the ref... |
C uses pass-by-value for function argument passing. So, you cannot actually changeporqfromabc(). To actually changepandqthemselves, you'll be requiring to pass a pointer to each of them.p=q;is not the way to copy a string, anyway. You need to make use ofstrcpy()to copy a string.You're making the call toabc()with argum... |
Given a file descriptor, I need to get its absolute path whether it is a regular file or aAF_UNIXsocket. The code atHow can I get a filename from a file descriptor inside a kernel module?works for regular files but withAF_UNIXsockets I get something like this"socket:[12345]"instead of the absolute path "/tmp/.X11-unix... |
netstat -xshows the full pathnames for unix sockets, by consulting/proc/net/unix, which is populated byunix_seq_showinnet/unix/af_unix.c. See here how it is done:
http://lxr.free-electrons.com/source/net/unix/af_unix.c?v=4.1#L2252
|
What is the difference when we declare variable before using in loop and when define variable in loop.
I am talking about this situation
```
int i;
for(i=0; i<100; i++);
```
and
```
for(int i=0; i<100; i++);
```
|
In the former case, you can accessioutside the for-loop. This can be advantageous if you have a conditional break in your loop, for example:
```
int i = 0;
for (i = 0; i < 100; i++) {
if (someUnexpectedConditionHappens()) {
break;
}
// do something
}
printf("The loop has been executed %d times"... |
What is the difference when we declare variable before using in loop and when define variable in loop.
I am talking about this situation
```
int i;
for(i=0; i<100; i++);
```
and
```
for(int i=0; i<100; i++);
```
|
In the former case, you can accessioutside the for-loop. This can be advantageous if you have a conditional break in your loop, for example:
```
int i = 0;
for (i = 0; i < 100; i++) {
if (someUnexpectedConditionHappens()) {
break;
}
// do something
}
printf("The loop has been executed %d times"... |
I am working on a google chrome extension wherein I am receiving an array of integers from the extension bypp::Var shared = dict_message.Get("shared_list");. Now I need to pass on this array to a C function, hence need to get the elements intoint*. How do I go about doing that ?
|
First, make sure thepp::Varis really an array.
```
if (shared.is_array()) {
```
Then, use the interfaces provided by classpp::VarArray.
```
pp::VarArray array(shared);
int * carray = new int[array.GetLength()];
for (uint32_t i = 0; i < array.GetLength(); ++i) {
pp::Var oneElem(array.Get(i));
... |
In the lecture, we were told that there is at least one prime number between k³ and (k + 1)³ for all k > 1. I would now like to know how to find such a prime numberefficientlyin C. I know the Sieve of Eratosthenes yet I have no clue how to implement it without polluting memory. Thanks for your help.
|
Youneed topollute your memory to increase the speed of finding the prime number. There is a simple approach that is fast and simple to implement.
```
primes = list of prime number below sqrt( (k+1)^3 )
for i = k^3 + 1 to (k+1)^3 :
is_prime = true
for p in primes:
if (i % p == 0) :
i... |
First, the char array is greater than 8 bytes, so we can't use it directly as a 64-bit integer.
In this case "relative" is defined as:
```
x = char[16]
y = char[16]
r = x / y
ax = approx_int64(char[16])
ay = approx_int64(char[16])
ar = ax / ay
ar ~= r
```
With a char array greater than 8 bytes, how could I effici... |
It's not entirely clear what you mean by "relatively sized 64-bit integer". However, I will assume you consider each char[] to represent some sort of ordered number.
If that is the case, the best way to approximate relative size is simply to take the 8 most significant bytes in that representation, and convert those... |
In Unix, C. After afork(), usually followed by await()orwaitpid()to wait thechildterminate. But can thechildexecute thewait()? Thechilddoesn't have a_child_, so when it execute thewait(), what will happen?
|
There are no child proccess for the child proces sowait()will return -1. From the man page:
wait(): on success, returns the process ID of the terminated child;
on error, -1 is returned.
|
This question already has answers here:Implicit int return value of C function(7 answers)Closed8 years ago.
Can someone please explain the behavior of the following code. How come the function message() with return typeintis returning the no of characters printed by printf() function without any return statement ?
`... |
This is caused by undefined behaviour.Here's asimilar question, and I couldn't put it any better than thesecond answerdoes:
That's simply undefined behaviour; if you don't populate the return area [...], it'll have the value last set up through some side-effect in your function.
...which is the value returned byprin... |
This question already has answers here:Why doesn’t putchar require a header?(2 answers)Closed8 years ago.
Why does this code work:
```
#include <stdio.h>
int main()
{
int x = isspace(getchar());
printf("%d", x);
return 0;
}
```
Whenever I enter whitespaceisspace()returns 8 and w... |
You're seeing this because your compiler (sadly, still) supports implicit declaration of a function.
If you enable strict checking, you compiler should refuse to compile the code. On and aboveC99, the implicit function declaration has been made non-standard. (To add, hopefully, future versions of compiler will strict... |
For some reason, whenever I use a numeric value in my compiler set-up (MinGW on Windows, using a CMD prompt to compile and run), it completely misreports numbers in the program.
Code example:
```
//C hello world example
#include <stdio.h>
int main()
{
int value;
value = 10;
printf("The number is %d \n"... |
valueandvalue2have to be passed as arguments, i.e.within the parantheses. Change it to the following:
```
printf("The number is %d \n", value);
```
And do similarly withvalue2.
Once again, this shows that compiling with-Walland-pedanticswitches on is useful. GCC most likely would have issued a warning message.
|
This question already has answers here:Implicit int return value of C function(7 answers)Closed8 years ago.
Can someone please explain the behavior of the following code. How come the function message() with return typeintis returning the no of characters printed by printf() function without any return statement ?
`... |
This is caused by undefined behaviour.Here's asimilar question, and I couldn't put it any better than thesecond answerdoes:
That's simply undefined behaviour; if you don't populate the return area [...], it'll have the value last set up through some side-effect in your function.
...which is the value returned byprin... |
This question already has answers here:Why doesn’t putchar require a header?(2 answers)Closed8 years ago.
Why does this code work:
```
#include <stdio.h>
int main()
{
int x = isspace(getchar());
printf("%d", x);
return 0;
}
```
Whenever I enter whitespaceisspace()returns 8 and w... |
You're seeing this because your compiler (sadly, still) supports implicit declaration of a function.
If you enable strict checking, you compiler should refuse to compile the code. On and aboveC99, the implicit function declaration has been made non-standard. (To add, hopefully, future versions of compiler will strict... |
For some reason, whenever I use a numeric value in my compiler set-up (MinGW on Windows, using a CMD prompt to compile and run), it completely misreports numbers in the program.
Code example:
```
//C hello world example
#include <stdio.h>
int main()
{
int value;
value = 10;
printf("The number is %d \n"... |
valueandvalue2have to be passed as arguments, i.e.within the parantheses. Change it to the following:
```
printf("The number is %d \n", value);
```
And do similarly withvalue2.
Once again, this shows that compiling with-Walland-pedanticswitches on is useful. GCC most likely would have issued a warning message.
|
I have a C function which returns a BSTR like "Hello world" and in Excel 11 I can call this function to print the string with the msgbox vba function.
With Excel 16, I only have an returned empty string.
If I am in debug with XCode, I can see my BSTR and it is not empty.
Do you have any idea to get a BSTR, returned b... |
I used SysAllocString but this function return NULL pointer. To fix my problem, I need to create my BSTR byte by byte
|
Is there such thing as a standard file chooser (and file save) dialogs in X? If yes, what's the extension/request for invoking that? If no, does that mean that Qt, GTK, wxWidgets, etc. each implement their own with different look and behavior, so I must do the same?
Thanks.
|
X11 does not have any standard widgets, graphics toolkits implement these features on top of the X display server. X is only responsible ofdisplaying, while toolkits are responsible fordrawing, two different responsibilities.
|
I know mach_timebase_info has a return type of kern_return_t, but I'm not able to locate documenation that specifies the possible return values. Where can I find this information?
|
According to the latest source for xnu-2782.1.97 (OS X 10.10.1) available athttp://www.opensource.apple.com/release/os-x-10101/, the only return value is KERN_SUCCESS:
```
/*
* mach_timebase_info_trap:
*
* User trap returns timebase constant.
*/
kern_return_t
mach_timebase_info_trap(
struct mach_timebase_in... |
I'm trying to load a file which has couple of infor, and I want to add them into a binary tree. For sure there is no problem with addToTree and printPreOrder functions, but i don't know why I can only print ( or maybe add ) the last item in the file. Whats the problem?
```
newTree = createBinTree(&cmpInt, &destroyNod... |
You are always adding to the same pointer tonewRes. While reading you overwrite your previousnewResentries. You need to callcreateResfor each object you are reading.
|
I was trying to use a c library libwebsockets(https://github.com/warmcat/libwebsockets) for my c++ program.
I followed the manual and it creates a visual studio solution and it works.
Since I am not used to develop a program on a windows 7 visual studio environment, I am not sure how library works. It looks like solu... |
Create two different Projects: One for the C lib and the other for your C++ Code. Then build the C Code into a *.lib File and add it to your C++ Project using this Answer:How to include libraries in Visual Studio 2012?
You can add both Projects into one Solution so they are easily accessible.
|
The extra Q at the end of rotor[0][0].order is from rotor[0][0].notch. What is the cause of this and what should be done to avoid this concatenation?
```
#include <stdio.h>
struct rotor_wirings
{
char order[26];
char notch[2];
};
/* rotor[MODEL][ROTORNAME] */
struct rotor_wirings rotor[10][10] =
{
/* Com... |
You didn't leave room for the trailing null at the end of theorderstring. It should be
```
char order[27];
```
|
I need to put 3 strings on anarray[3][3].
I tried to do it with pointers, but I only receive a single character.
```
#include <stdio.h>
int array[3][3]
char thing[5] = "thing";
main()
{
thing = array[0][0];
printf("%s", array[0][0];
}
```
|
Try this. With due respect your code absolutely incorrect and need many changes. You need to update your programming skills too.
```
#include <stdio.h>
#include <string.h>
char array[3][6]={0};
char *thing = "this";
main()
{
strcpy(array[0],thing);
printf("%s\n", array[0]);
}
```
|
I have a C program creating a detached thread as a child.
Inside of the function I pass to pthread_create I use pthread_detach to detach the thread. At the end I call pthread_exit((void *) 0)
I would like to know if it is normal behaviour that the memory consumption increases after the thread is created.
I did a val... |
I would like to know if it is normal behaviour that the memory consumption increases after the thread is created.
Yes, as
each thread gets its own stack assigned. The size is OS setting dependend and could be around 1M.some system resource will be used to manage each thread itself.
Both will be released if the thre... |
I am wondering if there is a graphical tool to decode data structures from multiple files? What I mean is, let us say we have the following
```
typedef struct herStruct;
...
typedef struct myStruct
{
void* hisStruct;
herStruct* ptr;
}myStruct;
```
It would have been great if there was a tool where in, we pass... |
You can try using Doxygen/GraphViz to generate visualizations.
Take a look atthis question.
|
I have a C function which returns a BSTR like "Hello world" and in Excel 11 I can call this function to print the string with the msgbox vba function.
With Excel 16, I only have an returned empty string.
If I am in debug with XCode, I can see my BSTR and it is not empty.
Do you have any idea to get a BSTR, returned b... |
I used SysAllocString but this function return NULL pointer. To fix my problem, I need to create my BSTR byte by byte
|
Is there such thing as a standard file chooser (and file save) dialogs in X? If yes, what's the extension/request for invoking that? If no, does that mean that Qt, GTK, wxWidgets, etc. each implement their own with different look and behavior, so I must do the same?
Thanks.
|
X11 does not have any standard widgets, graphics toolkits implement these features on top of the X display server. X is only responsible ofdisplaying, while toolkits are responsible fordrawing, two different responsibilities.
|
I know mach_timebase_info has a return type of kern_return_t, but I'm not able to locate documenation that specifies the possible return values. Where can I find this information?
|
According to the latest source for xnu-2782.1.97 (OS X 10.10.1) available athttp://www.opensource.apple.com/release/os-x-10101/, the only return value is KERN_SUCCESS:
```
/*
* mach_timebase_info_trap:
*
* User trap returns timebase constant.
*/
kern_return_t
mach_timebase_info_trap(
struct mach_timebase_in... |
I'm trying to load a file which has couple of infor, and I want to add them into a binary tree. For sure there is no problem with addToTree and printPreOrder functions, but i don't know why I can only print ( or maybe add ) the last item in the file. Whats the problem?
```
newTree = createBinTree(&cmpInt, &destroyNod... |
You are always adding to the same pointer tonewRes. While reading you overwrite your previousnewResentries. You need to callcreateResfor each object you are reading.
|
I was trying to use a c library libwebsockets(https://github.com/warmcat/libwebsockets) for my c++ program.
I followed the manual and it creates a visual studio solution and it works.
Since I am not used to develop a program on a windows 7 visual studio environment, I am not sure how library works. It looks like solu... |
Create two different Projects: One for the C lib and the other for your C++ Code. Then build the C Code into a *.lib File and add it to your C++ Project using this Answer:How to include libraries in Visual Studio 2012?
You can add both Projects into one Solution so they are easily accessible.
|
The extra Q at the end of rotor[0][0].order is from rotor[0][0].notch. What is the cause of this and what should be done to avoid this concatenation?
```
#include <stdio.h>
struct rotor_wirings
{
char order[26];
char notch[2];
};
/* rotor[MODEL][ROTORNAME] */
struct rotor_wirings rotor[10][10] =
{
/* Com... |
You didn't leave room for the trailing null at the end of theorderstring. It should be
```
char order[27];
```
|
I need to put 3 strings on anarray[3][3].
I tried to do it with pointers, but I only receive a single character.
```
#include <stdio.h>
int array[3][3]
char thing[5] = "thing";
main()
{
thing = array[0][0];
printf("%s", array[0][0];
}
```
|
Try this. With due respect your code absolutely incorrect and need many changes. You need to update your programming skills too.
```
#include <stdio.h>
#include <string.h>
char array[3][6]={0};
char *thing = "this";
main()
{
strcpy(array[0],thing);
printf("%s\n", array[0]);
}
```
|
I have a very simple macro for which I want to typecast its output tointonly. How to do that?
```
#define Numbits(A) (sizeof(A)*CHAR_BIT)
```
I tried:
```
#define int Numbits(A)({int val; val = sizeof(A)*CHAR_BIT; return val;})
```
but it also doesn't work
|
Are you saying that#define Numbits(A) (int)(sizeof(A)*CHAR_BIT)didn't work?
|
I am trying to initalize a structure using braces, but i am really trying to initalize the structure that is pointed to by a pointer returned from a malloc call.
```
typedef struct foo{
int x;
int y;
} foo;
foo bar = {5,6};
```
I understand how to do that, but i need to do it in this context.
```
foo * bar... |
(This was answered in comments, so making it a CW).
You need to cast the right-hand side of the assignment, like so:
```
*bar = (foo) {3,4};
```
As pointed out by @cremno in the comment, this isn't a cast but rather an assignment of acompound literal
The relevant section of the C99 standard is:6.5.2.5 Compound lit... |
If I have program with a main thread and a function running in a separated detached thread. If something in the detached thread is returning something > 0
will only the child thread exit or the main thread too?
|
A Posix thread returnsvoid *(ie. a pointer), so it cannot return anything less than zero since it's not an integer.
In any case, the return value from a detached thread is always ignored, and the process will not exit whatever the value.
|
Suppose I am writing a sorting-array method. At the time I did not know pointer, I usually defined array as global so that it automatically change.
Now I try to use it but it fails, basically it ends up with
```
int a[5];
sort(&a); // Calling sort
...
// My method
void sort(int *a[]) {
int key = *a[1]; // I'v... |
Change your function to just this ::void sort(int *a)or this ::void sort(int a[])
And when you callsortfrom the main, you need not callsort(&a),ais an array pointer itself, callingsort(a)will do it!
|
Doesalignof(N) == sizeof(N)where N is an integral type?
I'm asking for both C and C++, hope this isn't a problem.
|
It's machine-specific. On a 32-bit machine,alignof(int64_t)could easily be 4. Too, assumptions that are widespread now won't be for so very long.
|
I don't understand the output of this code:
```
main() {
int ret = ~(~0 <<5) << 2;
printf("ret: %d, %u\n", ret, ret);
}
output:
ret: 124, 124
```
If I process mentally, I do this:
resolving ~0 gives binary 1resolving ~0 << 5 gives binary 100000resolving ~(~0 << 5) gives binary 011111resolving ~(~0 << 5) <... |
Integral literals in C areints by default, andintis usually 4 bytes long (depending on the compiler). This means that~0is not1, it's 32 1s.
```
~0 == 11111111111111111111111111111111
~0 << 5 == 11111111111111111111111111100000
~(~0 << 5) == 00000000000000000000000000011111
~(~0 << 5) << 2 == 000000000000000000000000... |
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
At certain specified points in the execution sequence called sequence points, all side ef... |
Expressions such asn++have side effects, i.e. they not only produce a result, but also modify a variable.
The*operator doesnotintroduce a sequence point. Therefore, in the expressionn++ * n--it is not specified, whether the side effect ofn++(incrementingn) has already happened whenn--is evaluated. Depending on that,n... |
I want to write a script (orccode) that canautomaticallyprint the list of supported sys calls (the full function signature; specially, their names, return type and argument list)?
I have searched for the solutions for a while, and know syscall names are present in . But there is no argument list or return type?
My t... |
Based on @knm241 's comments, this will work:
```
grep '^asmlinkage.*sys_' /usr/src/linux-headers-3.16.0-30/include/linux/syscalls.h
```
|
In the following code,how to create a pointer to the variabletriangle.pluto.mars.aso it becomes unnecessary in the printf line to repeat the whole path for membera.
```
#include <stdio.h>
int main(){
struct euler {
int a;
int b;
};
struct gauss {
int f;
int g;
str... |
The band-aid solution:
```
int * someVariable = &(triangle.pluto.mars.a);
```
The long solution: Do a redesign.
|
This question already has answers here:Why is "a" != "a" in C?(11 answers)Closed8 years ago.
Given below is a piece of code that does not do what I want
```
do
{
printf("inserisci un nome: ");
scanf("%29s", s);
} while (s!="*");
```
My aim is to exit from the cycle if the string entered is "*".
Why doesn't ... |
Take a look atstrcmpto compare strings,!=will not do what you want.
In that case!=will compare the variables(apointerto the first element of the arrays) with the string"*". That is why it was not working properly.
|
Here is one way but the problem with it is unnecessary usage of output screen.
```
lenth=printf("%d",num);// or lenth=printf("%s",str);
```
How could i find length without having output from printf?
|
You can usesnprintf()with anemptybuffer (i.e. pass a null pointer), which will return the number of characters that would have been written into the buffer if there was enough space in it:
```
int length = snprintf(0, 0, "%d", num);
```
This way, you don't need to use an actual buffer and it won't print onstdoutlike... |
```
#include<stdio.h>
int power(int m,int n);
main()
{
int i;
for(i=0;i<10;i++)
printf("%d %d %d\n",i,power(2,i),power(-3,i));
return 0;
}
int power(int base,int n)
{
int i,p;
p=1; // doubt in this line
for(i=1;i<=n;++i)
p=p*base;
return p;
}
```
when p is declared as 1 ... |
I'm assuming by 2^0 you mean the inputs to the functionpowerare 2 and 0.
In that case,n = 0, and the for loop doesn't even run becausei = 1which is greater than 0. In that case, the function returns 1 because you initializedpto 1, and the loop didn't modify it.
|
Suppose I am writing a sorting-array method. At the time I did not know pointer, I usually defined array as global so that it automatically change.
Now I try to use it but it fails, basically it ends up with
```
int a[5];
sort(&a); // Calling sort
...
// My method
void sort(int *a[]) {
int key = *a[1]; // I'v... |
Change your function to just this ::void sort(int *a)or this ::void sort(int a[])
And when you callsortfrom the main, you need not callsort(&a),ais an array pointer itself, callingsort(a)will do it!
|
Doesalignof(N) == sizeof(N)where N is an integral type?
I'm asking for both C and C++, hope this isn't a problem.
|
It's machine-specific. On a 32-bit machine,alignof(int64_t)could easily be 4. Too, assumptions that are widespread now won't be for so very long.
|
I don't understand the output of this code:
```
main() {
int ret = ~(~0 <<5) << 2;
printf("ret: %d, %u\n", ret, ret);
}
output:
ret: 124, 124
```
If I process mentally, I do this:
resolving ~0 gives binary 1resolving ~0 << 5 gives binary 100000resolving ~(~0 << 5) gives binary 011111resolving ~(~0 << 5) <... |
Integral literals in C areints by default, andintis usually 4 bytes long (depending on the compiler). This means that~0is not1, it's 32 1s.
```
~0 == 11111111111111111111111111111111
~0 << 5 == 11111111111111111111111111100000
~(~0 << 5) == 00000000000000000000000000011111
~(~0 << 5) << 2 == 000000000000000000000000... |
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
At certain specified points in the execution sequence called sequence points, all side ef... |
Expressions such asn++have side effects, i.e. they not only produce a result, but also modify a variable.
The*operator doesnotintroduce a sequence point. Therefore, in the expressionn++ * n--it is not specified, whether the side effect ofn++(incrementingn) has already happened whenn--is evaluated. Depending on that,n... |
I want to write a script (orccode) that canautomaticallyprint the list of supported sys calls (the full function signature; specially, their names, return type and argument list)?
I have searched for the solutions for a while, and know syscall names are present in . But there is no argument list or return type?
My t... |
Based on @knm241 's comments, this will work:
```
grep '^asmlinkage.*sys_' /usr/src/linux-headers-3.16.0-30/include/linux/syscalls.h
```
|
In the following code,how to create a pointer to the variabletriangle.pluto.mars.aso it becomes unnecessary in the printf line to repeat the whole path for membera.
```
#include <stdio.h>
int main(){
struct euler {
int a;
int b;
};
struct gauss {
int f;
int g;
str... |
The band-aid solution:
```
int * someVariable = &(triangle.pluto.mars.a);
```
The long solution: Do a redesign.
|
This question already has answers here:Why is "a" != "a" in C?(11 answers)Closed8 years ago.
Given below is a piece of code that does not do what I want
```
do
{
printf("inserisci un nome: ");
scanf("%29s", s);
} while (s!="*");
```
My aim is to exit from the cycle if the string entered is "*".
Why doesn't ... |
Take a look atstrcmpto compare strings,!=will not do what you want.
In that case!=will compare the variables(apointerto the first element of the arrays) with the string"*". That is why it was not working properly.
|
Here is one way but the problem with it is unnecessary usage of output screen.
```
lenth=printf("%d",num);// or lenth=printf("%s",str);
```
How could i find length without having output from printf?
|
You can usesnprintf()with anemptybuffer (i.e. pass a null pointer), which will return the number of characters that would have been written into the buffer if there was enough space in it:
```
int length = snprintf(0, 0, "%d", num);
```
This way, you don't need to use an actual buffer and it won't print onstdoutlike... |
```
#include<stdio.h>
int power(int m,int n);
main()
{
int i;
for(i=0;i<10;i++)
printf("%d %d %d\n",i,power(2,i),power(-3,i));
return 0;
}
int power(int base,int n)
{
int i,p;
p=1; // doubt in this line
for(i=1;i<=n;++i)
p=p*base;
return p;
}
```
when p is declared as 1 ... |
I'm assuming by 2^0 you mean the inputs to the functionpowerare 2 and 0.
In that case,n = 0, and the for loop doesn't even run becausei = 1which is greater than 0. In that case, the function returns 1 because you initializedpto 1, and the loop didn't modify it.
|
If I want to dynamically link a shared library (.so) for a C++ application (which was built with g++) using LD_PRELOAD, does it matter if the .so is generated from a C source file (using gcc) or a C++ source file (using g++)? And why or why not?
Thanks for helping me understand this.
|
Yes, a C++ executable can be linked (both statically and dynamically) to a C library.
This is completely deliberate. The C++ ABIs aredesignedto be backwards compatible.
You will have to ensure that the declarations of functions and so on of the library symbols, as written in your C++ program, are markedextern "C"to ... |
I am finding out information related to usb mass storage using udev library functions like (vendor ID, product ID, Manufacturer, Product, Serial etc).
Can any one suggest how to get usb mass storage size using udev.
|
Size is apparently not among the property values. It is, however, one of the sysfs attributes but I don't know how long it has been there. It is not mentioned inDocumentation/ABI/testing/sysfs-blockfor some reason.
You can get the value as a string like any other sysattr:
```
blocks_string = udev_device_get_sysattr_... |
Inex26of 'Learn C the Hard Way' in thedb.cfile Zed defines two functions:
```
static FILE *DB_open(const char *path, const char *mode) {
return fopen(path, mode);
}
static void DB_close(FILE *db) {
fclose(db);
}
```
I have a hard time understanding the purpose/need for wrapping these very simple calls tofopenandfclo... |
In this particular case a wrapper is used to hide the detail thatDB_open,DB_readorDB_closeall map to file operations.
This approach implements anabstraction layerthrough which all database related functions are to be accessed. Also this providesmodularity, which may later allow adding more methods to open/read/close ... |
I am troubleshooting a recent session ID collision and want for this purpose exercise the functionphp_session_createand compute an empirical probability for this function to generate colliding session IDs in some standardised (labor) conditions.
However that function is not directly bound in PHP, but seems to be only... |
If you want to generate random strings you can use PHP'smcrypt_create_ivfunction.
```
$NUM_BITS = 256;
$random_bits = mcrypt_create_iv($NUM_BITS / 8);
$printable_key = base64_encode($random_bits);
```
|
I've used typedef before, but I've never used one with a pointer. What effect does this have on the typedef?
Code for reference:
```
typedef struct node NODE, *PNODE, **PPNODE;
```
|
Instead of usingstruct nodeyou can replace it withNODE
Instead of usingstruct node*you can replace it withPNODE
Instead of usingstruct node**you can replace it withPPNODE
The statement can be broken down to
```
typedef struct node NODE;
typedef struct node* PNODE; // PNODE is pointer to node
typedef struct node*... |
What combination of preorder,inorder and postorder Traversal generate a unique binary Tree?
|
following combination can uniquely identify a tree.
Inorder and Preorder.
Inorder and Postorder.
Inorder and Level-order.
And following do not.
Postorder and Preorder.
Preorder and Level-order.
Postorder and Level-order.
For more infomation refer:Geeksforgeek
|
I'm trying to allocate some memory using MACROS. But I get this errors:
error: expected expression before ‘)’ tokenerror: expected statement before ‘)’ token
This is my code:
```
#define ALLOC(p,n) (p*)malloc(sizeof(p)*n)
int main(){
char *ponteiro;
ponteiro=ALLOC(5,ponteiro);
return 0;
}
```
|
Change:
```
#define ALLOC(p,n) (p*)malloc(sizeof(p)*n)
```
to:
```
#define ALLOC(p,n) malloc(sizeof(*(p))*(n))
```
and in themain()free the allocated memory beforereturn
```
int main(){
char *ponteiro;
ponteiro = ALLOC(ponteiro,5);
/* Do something */
free(ponteiro);
return 0;
}
```
|
Is it possible to lock a socket for a thread? For example usingflock?
These locks are designed for files, but they take a generic file descriptor as a parameter.
|
The documentation specifically states that flock is meant for files. From the MacOS documentation page (man): (emphasis added)
Flock() applies or removes an advisory lock on thefileassociated with the file descriptor fd.
In particular, this is meant for inter-process synchronization on the samefile. Assuming that yo... |
I get the following error :
argument of type "const char *" is incompatible with parameter of type "LPCWSTR"
Here is my code :
```
static char *getFmuPath(const char *fileName) {
char pathName[MAX_PATH];
int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);
return n ? strdup(pathName) : NULL;
}
`... |
GetFullPathNamedoesn't take achar *. Look at the docs, it takesLPTSTRandLPCTSTR.
Depending on your build settings,LPTSTRand related types will become eitherchar*(ANSI builds) orwchar_t*(Unicode builds). You are building as Unicode.
Also, I don't know why you are definingMAX_PATH. That is a Windows constant so you sh... |
```
int main()
{
printf("%c", "\n");
return 0;
}
```
Here according to type specifier a character is required. But we are passing itconst char *. I was hoping that it would give me a warning message in code blocks GNU GCC compiler but it is not giving me any warning and printing the$character.
why it is not giving ... |
You need to enable that warning.
Compiling your code astest.cppand adding#include <stdio.h>forprintfwith the correct warning flag under gcc 4.7.2:
```
$ gcc -c -Wformat test.cpp
test.cpp: In function 'int main()':
test.cpp:5:18: warning: format '%c' expects argument of type 'int', but argument 2 has type 'const char... |
I trying to use Gstreamer in Visual Studio 2012. So I installed gstreamer-1.0-devel-x86-1.5.2.msi and gstreamer-1.0-x86-1.5.2.msi, then I added gstreamer-1.0.props in Property Sheet and changed working directory in "properties->configuration properties->debugging" to MY\GSTREAMER\PATH\bin. And tried to compile this:
... |
I found solution: my program used not right dll, that was the same named dll of GTK#, after deleting GTK#(wrong, but quick ;)) my program started to load the right dll from Gstreamer.
|
I read somewhere that withscanf()I can input a maximum of 15chars. Is it right? Is it bounded?
|
Hasscanf()a limited bound on the number of bytes that the user can input?
NO.
However, FWIW, we can impose a limit on the length of the input actually to be scanned. For that. we use the maximum field width along with the conversion specifier. A simple example will be
```
char arr[15] = {0};
scanf("%14s", arr);
```... |
This question already has answers here:size of int variable(6 answers)Closed4 years ago.
Why in Turbo C compilersizeof(int)is 2 bytes and in gcc Linux compiler is of 4 bytes?
|
sizeof(int)is not a constant across all platforms.
It varies from system to system.
PS: Only sizeof object which is constant across all platforms issizeof(char)
|
How can I improve this function in regard to speed :
```
void chrapp (char arr[], char chr, int pos)
{
memmove(arr + pos + 1, arr + pos, strlen(arr + pos));
*(arr + pos + 1) = chr;
}
```
Also, it unfortunately doesn't work with appending a character to the very beginning of thearray, which is also a rein f... |
Your original code is going through the string twice. Once for calculating the length of the string and the second time for moving it. You can do it in one loop, however considering that the standard library functions are implemented in highly optimized manner it is not sure it will actually speed up things. Try the f... |
Malloc function on success returns pointer to the memory location allocated and returns null value on failure. If I put malloc() in an infinite while loop, will this loop ever stop? After malloc() allocates the entire memory available, will it stop execution or just keep returning null value?
|
Repeated calls tomallocthis way will just keep returning null pointers forever. (However, if you try to use that null pointer, you'll of course get a segfault).
This is different behavior fromnewin C++, which throwsbad_allocif it can't allocate new memory.
|
```
/*Program to print all the numbers between a lower bound and a upper bound values*/
#include<stdio.h>
#include<stdlib.h>
void recur(int a, int b);
int main(void)
{
int x,y;
printf("Enter the lower and upper bound values: \n");
scanf("%d %d",&x,&y);
void recur(x,y);
return 0;
}
void recur(... |
Both
```
void recur(x,y);
void recur(a,b);
```
declaresthe functions (prototype). Tocallthem, change them to
```
recur(x,y);
recur(a,b);
```
|
I have two functions in my c programs. Lets name thema()anda(). In some where in the code I use their result in an equation: take a look at this:
```
int number = 2;
int x;
int a(){
number += 3;
return number;
}
int b(){
number *= 2;
return number;
}
x = a() + b();
printf("%d", x);
```
Here I exp... |
In the statement,
```
x = a() + b();
```
The order in which the functions a() and b() will be called isunspecified. But there's a sequence point before calling each function and after returning from each function.
That means there are two possible orders of calls:1) a() first and then b().2) b() first and then a().... |
I am a beginner in coccinelle and try to run my first example.
Currently I'am following the steps ofthis article
I created the c fileI created the coccinelle scriptI run it using$ spatch -sp_file test.cocci test.c
In the terminal I got the expected result as mentioned in the article
```
--- test.c
+++ /tmp/cocci-o... |
using
```
spatch --help
```
I got all the option for the command spatch .
So i should use
```
$ spatch -sp_file test.cocci test.c -o /tmp/newtest.c
```
the result of runing the patch is in /tmp/newtest.c
|
For Example int and INT.
About this two i just know int is the fundamental type and INT is windows data type both gain 4 bytes in memory and INT is use with window API.
But i don't understand what is the major and proper different between both of them.
Help me to understand this both fully?
|
intis a language keyword,INTis not.
The size and range of values that anintcan take is constrained, but not fixed, by the C++ standard.
INTis a data type defined by Windows that is a 4 byte signed integral type with 2's complement.
With a MSVC compiler targetting Windows, it is probablytypedeffed or#defined toint, ... |
I have a function designed to make a socks handshake packet; but I can't find any information regarding how the authorization fields are filled. How is the authentication packet formatted?
```
void socks_auth(int sd, char *buffer) {
char *ptrBuff;
ptrBuff = buffer;
*(ptrBuff++) = SOCKS_V;
*(ptrBuff++)... |
I'd suggest you start withRFC1928,SOCKS Protocol Version 5and possiblyRFC1961GSS-API Authentication Method for SOCKS Version 5.
If neither of those help, perhaps looking at the source ofsocat, which can act as a SOCKS5 proxy, will help.
|
I'm trying to read a character that has to be 'C' or 'n'.In case it is not, print an error and ask for another char.
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
int c;
printf("Enter the character: ");
c = getchar();
while (!(c=='C' && c=='n')){
printf("Wrong!.\n");
... |
Two things:
1) You are pressing a character and then hitting enter. That's two characters. If you want to read a whole line, don't usegetchar.
2) Your conditional makes no sense. It will never be the case thatcis both equivalent to'C'and equivalent to'n', so you're testing something that cannot be. Your loop will ne... |
I am passing a python module to C as aPyObject. I want to check to see if this value is NONE in my C code, using this form:
```
int func(PyObject tmp)
{
if(tmp)
{
// etc
```
I am getting the following error. How can I convert from a PyObject to boolean value, simillar to the way Python's if function beh... |
PyObject_IsTrueseems to do what you want:
```
int PyObject_IsTrue(PyObject *o)
Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.
```
|
I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors.
https://msdn.microsoft.com/en-us/library/027c4t2s.aspx
|
CFLAGS+= -fdiagnostics-absolute-paths
|
I've asorted arraybut it'snot necessarily sequential, and I need to knowIF it contains any duplicates.
```
Array : | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 8 |
```
I know we can linearly traverse in O(n) check if it contains any duplicates, but I was wondering if it is possible using Binary Search.
|
No, You can't do it with binary search. All algorithms will take at least linear time.
|
Given an index and an array of integers, I need to delete the element in the given array which was stored in the given index through the use ofmemcpy(). The new set of elements will be stored on the given array.
Here's an illustration of what I want to do, though I'm having trouble implementing it.
SoarrayElemafte... |
You can't usememcpy, because source and destination overlap, but you can usememmove, e.g.:
```
memmove(&a[1], &a[2], 5 * sizeof(a[0]));
```
This copies the 5 elements starting ata[2]down to the 5 elements starting ata[1], taking care of the fact that the source and destination regions overlap.
|
I have a function designed to make a socks handshake packet; but I can't find any information regarding how the authorization fields are filled. How is the authentication packet formatted?
```
void socks_auth(int sd, char *buffer) {
char *ptrBuff;
ptrBuff = buffer;
*(ptrBuff++) = SOCKS_V;
*(ptrBuff++)... |
I'd suggest you start withRFC1928,SOCKS Protocol Version 5and possiblyRFC1961GSS-API Authentication Method for SOCKS Version 5.
If neither of those help, perhaps looking at the source ofsocat, which can act as a SOCKS5 proxy, will help.
|
I'm trying to read a character that has to be 'C' or 'n'.In case it is not, print an error and ask for another char.
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
int c;
printf("Enter the character: ");
c = getchar();
while (!(c=='C' && c=='n')){
printf("Wrong!.\n");
... |
Two things:
1) You are pressing a character and then hitting enter. That's two characters. If you want to read a whole line, don't usegetchar.
2) Your conditional makes no sense. It will never be the case thatcis both equivalent to'C'and equivalent to'n', so you're testing something that cannot be. Your loop will ne... |
I am passing a python module to C as aPyObject. I want to check to see if this value is NONE in my C code, using this form:
```
int func(PyObject tmp)
{
if(tmp)
{
// etc
```
I am getting the following error. How can I convert from a PyObject to boolean value, simillar to the way Python's if function beh... |
PyObject_IsTrueseems to do what you want:
```
int PyObject_IsTrue(PyObject *o)
Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.
```
|
I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors.
https://msdn.microsoft.com/en-us/library/027c4t2s.aspx
|
CFLAGS+= -fdiagnostics-absolute-paths
|
I have a very stupid question, I just can't answer.
Can somebody tell me why the following code works?
```
char hello[]="Hello World\n";
char *hptr = hello;
while(*hptr)
{
printf("%c", *hptr++);//here the output must be "ello World", but C thinks otherwise!!!
}
```
|
You're using a post-increment:
```
*hptr++
```
This uses the value ofhptrfirst, and then increments it. If you wanted to skip the first letter, you would use a pre-increment:
```
*++hptr
```
This increments the pointer value,thenuses it as a function argument.
|
What is wrong in this function?
```
void stringReverse (char stringa[])
{
if (stringa[0]!='\0')
{
return stringReverse(&stringa[1]);
printf("%c", stringa[0]);
}
}
```
I have to write a function that invert a string (ex: "Hello" in "olleH") using recursion; the ... |
returnreturns a value from the function and performs no further statements in that scope. Have a think about where you want that statement to be...
Not answering in full because this sounds like homework!
|
I'm trying to get my program to open files with paths that I declare earlier in the program.
My declared string
```
char *pathToFile="/var/www/mcc-libhid/";
```
My current code
```
fptr=fopen("configurationSettings.txt","r"))
```
How I want the program to read it:
```
ftpr=fopen("/var/www/mcc-libhid/configuratio... |
Usesnprintf()and prefix the path into the buffer.
```
char buf[PATH_MAX];
snprintf(buf, sizeof buf, "%s/configurationSettings.txt", pathToFile);
```
and usebufinfopen():
```
ftpr=fopen(buf, "r");
```
|
I just finished coding my c program in visual studio (VS) and what I had done is just drag the compiled .exe file out of the folder to run it on other computers, except on other computers for that to work I guess I need VS since it says the MSVCR110D.dll is missing which is from VS. So how can I run my program on othe... |
You can useIExpresswhich is used for distributing self-contained installation packages. It is there in every windows machine preinstalled. Using this utility you can make the executable.exewhich will be incorporated with dependentdlls. You can seeStep by step guide, to see how to use it.
|
Can we include static variable in header files.
If yes,Can other files can access it ?
Can we include static function in header files and use it in another files.
Can we pass static variable as function arguments ?suppose some function is there in header file header.h :
fun(static int a,static int b)
|
Any name declared in the global namespace with specifierstatichas internal linkage. This means that the name is visible within the translation unit where it is declared.
So if a header with a declaration of a name with static keyword is included in several translation units then each translation unit will have its ow... |
I haveenumin header file.
```
typedef enum{
up = 8, down = 2, left = 4, right = 6
}direction;
```
I want use enum to identify type of move.
Like this:
```
void sayTypeOfMove(int type){
switch(type){
case direction.up:
printf("IT IS UP MOVE...");
break;
}
... |
C understands the enum elements when it knows you're dealing with that enum, so the right code would be
```
void sayTypeOfMove(direction type){
switch(type){
case up:
printf("IT IS UP MOVE...");
break;
}
}
```
By the way,typeis a really bad name, because it fee... |
In my project I useget_cpu()andput_cpu()to disable and enable the preemption in the kernel on asmpmachine.
Is there asafe wayto get the current preemption status in an smp machine i.e. whether the preemption is turned on or off.
|
preempt_count() returns current thread's preemption count. 0 value means that preemtion is allowed.
Usually, you shouldn't request preemtion status unless for the selfcheck. If some block of code requires preemtion to be disabled, it should be wrapped withpreempt_disable()/preempt_enable()calls (or their alternatives... |
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed8 years ago.
I want to understand the syntax of the struct which i have seen some where. Can some please explain the meaning ofunsigned int xyz:1;. Is it just assigning default value to ... |
It's abit field. You are telling the structure that you will only be using one bit ofxyz.
This allows the compiler to make packing optimisations.
|
I was just studying about structures and classes. I created a sample structure for getting familiar with it and tried to initialize an array in it. when I compiled the program it gave me error
```
error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
char arr[5] = {2,3,8,67,87};
struct abc{
char a;
... |
I guess in C you can do like this:
```
struct abc{
char a;
char b;
char c;
char arr[5];
};
struct abc test= { 5, 2, 3, { 'a', 'b', 'c', 'd', 'e' } };
```
|
Other than being able to dereference avoid**, I don't understand the following:
```
void * foo, **bar;
foo++;//error
bar++;//no error
```
Why doesn't the first work but the second does? What's the difference?
|
First snippet
```
foo++;//error
```
because,foois pointer tovoidand you cannot have pointer arithmetic onvoid *, size of thevoidtype is not defined.
Second snippet,
```
bar++;//no error
```
because,baris a pointer toa pointer tovoid. So, arithmetic operation is permitted, as the size of a pointer to pointer type ... |
I'm working on a homework problem and I already got the answer correct, but it was the result of adding operators out of frustration so I'm hoping someone can clarify this for me.
I'm testing to see if a number is positive or negative, return 1 if x > 0, return 0 otherwise. Only using the bit operations ! ~ & ^ | + <... |
Where you're off is in #2:
if x is positive, x >> 31 == 0 and !x == 0 so !(0 | 0) == 1if x is negative, x >> 31 == 1 and !x == 0 so !(1 | 0) == 0if x is zero, x >> 31 == 0 and !x == 1 so !(0 | 1) == 0
|
How do I get the numerical value/position of a character in the alphabet (1-26) in constant time (O(1)) without using any built in method or function and without caring about the case of the character?
|
If your compiler supports binary literals you can use
```
int value = 0b00011111 & character;
```
If it does not, you can use 31 instead of 0b00011111 since they are equivalent.
```
int value = 31 & character;
```
or if you want to use hex
```
int value = 0x1F & character;
```
or in octal
```
int value = 037 & ... |
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.Closed8 years ago.Improve this question
I am trying to export some C code for my application in Android Studio using the NDK, but I am having this ... |
rindexis an old name (averyold name!) forstrrchr. If it looks like it's trying to find characters in strings, try changing all the calls tostrrchr. (Similarly, you may need to changeindextostrchr.)
|
I would like to change the default label color of a GtkCheckButton. I surely need to access its GtkContainer or GtkBin and iterate through its children.
However, I have not found any code to do this.
I have:
```
GtkWidget* myCheckbox = gtk_check_button_new_with_label("Hello");
GdkColor color;
gdk_color_parse ("#FF0... |
OK, this code works:
```
if(GTK_IS_BIN(myCheckbox)) {
GtkWidget *child = gtk_bin_get_child(GTK_BIN(myCheckbox));
GdkColor color;
gdk_color_parse ("#FF0000", &color);
gtk_widget_modify_fg (child, GTK_STATE_NORMAL, &color);
}
```
The idea came fromFinding children of a GtkWidget.
H... |
I have text files weighing ≈ 200GB.I'm storing in DB pairs ofkey-position_in_file,and reaching the data usingfseek.
Is there recommended way to compress the files,and seek to position in a compressed file,without decompressing from the beginning of the file.
[I prefer to use C as language][No need to perform writes.... |
Here is anexample of random access of deflated data. It runs through the compressed data once to build a random access index with entry points at about every 1 MB of uncompressed data. (You can change that density.) Each entry point is at a deflate block boundary, and saves the 32K of uncompressed data that precede... |
I have set stack size to 2000Kb by ulimit -s 2000 and ulimit -Ss 2000 for hard limit. And in the below program i have allocated appox 2040000(510000 x 4) bytes which is less than i limited i.e,. 2048000(2000*4)bytes but i see that my program crashes! Can anybody suggest why this happens.
```
#include <stdio.h>
#inclu... |
int a[510000]will be an array with index from0to509999.a[510000]is outside the array range.
|
The code excerpt:
```
int main(int argc, char *argv[]){
PySys_SetArgv(argc, argv);
```
produces error message
error: cannot convert ‘char**’ to ‘wchar_t**’ for argument ‘2’ to ‘void PySys_SetArgv(int, wchar_t**)’
How do I convertargv?
|
You could look into whether your compiler supportswmain. If so, you can replacemainwith:
```
int wmain(int argc, wchar_t *argv[])
{
PySys_SetArgv(argc, argv);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.