question
stringlengths 24
425
| answer
stringlengths 5
405
|
---|---|
Sayais my number.
And I wanta1to be a with all bits on even positions inverted.
This is my current solution
```
int a1 = ((a & 0xaaaaaaaa) | (~(a) & 0x55555555));
```
How can I make this faster?
| Use the bitwise xor (^) operator:
```
a1 ^= 0x55555555;
```
this will invert bits 0, 2, 4, and so on.
|
Sayais my number.
And I wanta1to be a with all bits on even positions inverted.
This is my current solution
```
int a1 = ((a & 0xaaaaaaaa) | (~(a) & 0x55555555));
```
How can I make this faster?
| Use the bitwise xor (^) operator:
```
a1 ^= 0x55555555;
```
this will invert bits 0, 2, 4, and so on.
|
There are several basic MPI datatypes however, what if it is needed to send/receive an instance of a class. If this is possible, could you give an example?
| To send astruct, you may useMPI_Type_create_structhttp://www.mpich.org/static/docs/v3.1/www3/MPI_Type_create_struct.html
Here is an example of how to do so :
http://mpi.deino.net/mpi_functions/MPI_Type_create_struct.html
Bye,
|
could we reallocated a shared memory ? by passing it's address toreallocfunction , if NO , how I can reallocate the shared memory ?
| You can callmremap(). Alternatively, you can callmmap()again, copy the data, andmunmap()the original.
|
could we reallocated a shared memory ? by passing it's address toreallocfunction , if NO , how I can reallocate the shared memory ?
| You can callmremap(). Alternatively, you can callmmap()again, copy the data, andmunmap()the original.
|
Is it for ipv6? If ipv4 is s_addr just the dotted quad reinterpreted as a 32 bit integer?
| unsgined longguarantees that the size of the variable is at least 4 bytes, thus holding the entire ip. An unsigned int can be smaller.
|
I want to write a function which would redirect the standard output to a file where the name of the file is "name".log where "name" is the argument to the function
```
void redirect(char *name) {
```
I don't know where to begin.
| You can usefreopen()
```
// code copied from the link
#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);
...
```
|
Is it for ipv6? If ipv4 is s_addr just the dotted quad reinterpreted as a 32 bit integer?
| unsgined longguarantees that the size of the variable is at least 4 bytes, thus holding the entire ip. An unsigned int can be smaller.
|
I want to write a function which would redirect the standard output to a file where the name of the file is "name".log where "name" is the argument to the function
```
void redirect(char *name) {
```
I don't know where to begin.
| You can usefreopen()
```
// code copied from the link
#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);
...
```
|
I want to know how to use gettext in C with dynamic message id in the argument.
For example,
```
char *var = fun(); //where fun returns char * type.
char *val = gettext(var);
```
| Your code is fine, but you will of course also need to make sure thatfun()returns a static string, that's going to stick around. Alsovalshould beconst char *, you cannot change the strings owned by gettext.
|
What is the fastest way to make the last 2 bits of a byte zero?
```
x = x >> 2 << 2;
```
OR
```
x &= 252;
```
Is there a better way?
| Depends on many factors, including the compiler, the machine architecture (ie processor).
My experience is that
```
x &= 252; // or...
x &= ~3;
```
are more efficient (and faster) than
x = x >> 2 << 2;
|
I'm studying C and TCP/UDP.
As the title... Is there any difference between inet_aton() and gethostbyname() in C? From what I know, both convert an IP address from a string to a number.
| gethostbyname() is obsolete. You should usegetaddrinfo().
inet_aton() only works for IPv4.
Also,inet_aton() only convert a IPv4 notion (0.0.0.0) to int,getaddrinfodoes DNS resolution.
|
What is the version of C used in GCC? C99, C11 or C90? I thought was the GCC use C99 but I was mistaken:
```
for(int i = 0; i < 100; i++){
...
}
```
error: βforβ loop initial declarations are only allowed in C99 mode.
| According to2 Language Standards Supported by GCC:
The default, if no C language dialect options are given, is-std=gnu90; this is intended to change to-std=gnu11in some future release.
|
In my current program I am having an issue where, when I divide a number by a larger number I am just given 0. For example if I divide -272 by 400 I receive 0.
```
y=x/400;
printf("%f\n", y);
```
This is the only piece of code causing issues. x is a negative integer 1-500 and y is initialized as a float.
Where am I going wrong?
| Write something like this y = x/400.0f or y = (float)x / 400
|
In my current program I am having an issue where, when I divide a number by a larger number I am just given 0. For example if I divide -272 by 400 I receive 0.
```
y=x/400;
printf("%f\n", y);
```
This is the only piece of code causing issues. x is a negative integer 1-500 and y is initialized as a float.
Where am I going wrong?
| Write something like this y = x/400.0f or y = (float)x / 400
|
I think i may be losing it but can anyone double check my sanity? This is the only code i wrote in a new file to see my project file is not messed up.
Error: This declaration has no storage class or type specifier
Error: Expected a ";"
| On a global level you can only have declarations and definitions, not statements (likeg.a = 1;is) or expressions.
|
I'm trying to write an extension for php using swig. I need to know the absolute path of the current php file in my extension code. I used __ FILE __ in my C code but it returns current c file name.
| finally i found the solution. to access __ FILE __ in your php extension, you can use like this:
```
char *file_name = zend_get_executed_filename();
```
|
As the title says, would all the pointers be freed after the child dies or do I have to free them manually?
| Yes,
The OS is a good housekeeper and tidys up for you.
But being a good guest it is better to do it yourself.
Perhaps files need to be closed, network connections tidied up
|
Is there any way to call category or test name from code in MSTest during test run?
| I don't now if it's possible for the test category but you can call the test name using theTestContext.
```
[TestClass]
public class TestClass
{
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual("TestMethod1", TestContext.TestName, "Something went really wrong...");
}
public TestContext TestContext { get; set; }
}
```
|
As the title says, would all the pointers be freed after the child dies or do I have to free them manually?
| Yes,
The OS is a good housekeeper and tidys up for you.
But being a good guest it is better to do it yourself.
Perhaps files need to be closed, network connections tidied up
|
```
#include<stdio.h>
int main(){
int main =22;
printf("%d\n",main);
return 0;
}
```
output:22
I am defining main as function and variable both even though compiler is not giving error. It should give error "error: redefinition of βmainβ " . I am not able to understand why this code is working.
| It will not give you an error becausemainis not a keyword.but main is define 2 times- Scoping rules come into play.
|
I have complied and run the code on a single machine , If I want to run the code on multiple machines in a client server architecture , which file do I place on server and which file do I place on client ?
| I'm assuming green indicates an executable file and that the file names follow normal naming practices.
Putint_clienton the clients.
Putint_serveron the server(s).
|
Can someone help me convert this line to an if-else statement?
temp = head->left ? head->left : head->right;
Thanks!
| ```
if ( head->left )
temp = head->left;
else
temp = head->right;
```
|
I have an input text in a single line of the form "part1 part2". How can i get in 2 different variables part1 and part2 if they have been input in the same line?
| You can use two different format specifiers :
```
#include <stdio.h>
int main(void)
{
char part1[100],part2[100];
scanf("%99s%99s",part1,part2);
printf("%s,%s\n",part1,part2);
return 0;
}
```
|
I have my main C file, another C file (which I'm using as a library) and two header files containing the function prototypes for each C file.
How can I compile and link them into one executable file with GCC? I'd like to use the-oand-gflags too.
| ```
gcc -g -c first_file.c
gcc -g -c second_file.c
gcc -o executable first_file.o second_file.o
```
In general though, try googling for agcctutorial first.
|
I want to initialise a 2d array having all its elements are 0.
I have tried this:
```
scanf("%d",&n);
int arr[n][n]={0};
```
but i got the [Error]:"variable-sized object may not be initialized"
So,how to do this?
| Be explicit.
```
#include <string.h>
const int got = scanf("%d", &n);
int arr[n][n];
memset(arr, 0, sizeof arr);
```
Note that ifgotisn't 1, the above has undefined behavior. This is pretty dangerous.
|
I saw that MinGW has a makefile too which is not supported in NetBeans/Eclipse. Why? And why MSYS? I also heard MSYS is Unix like env, so why do I need it for Windows programming?
| Simply put msys is a unix/linux like enviorenment on windows. means you can run your program in unix/linux which you're making on windows
|
Im writing a hexdump function in C.
How can I truncate a given address (void* start) to the greatest multiple of 16 that's less than the given start argument?
Is there a simple way to do this?
Thanks
| ```
uintptr_t rounded = ((uintptr_t)start) & ~0xF;
```
|
I was wondering how to include files like LUA scripts, dlls, ect in a code:blocks build (debug and release) or would I just have to copy over all the files manually to the folders?
| As far as I know, it is done by manual organization
|
Ok, so I have an array of srings
```
char array[4][20];
//initialized
strcpy(array[0], "PERSON1");
strcpy(array[1], "PERSON2");
...
```
My question is how would I use shmget, and shmat to turn this array into shared memory?
Any help appreciated!
| ```
int segment_id = shmget(IPC_PRIVATE, sizeof(array),0660 | IPC_CREAT);
char** shared = shmat(segment_id,NULL,0);
```
This is a possible solution.
|
From the kernel 3.4code,I could not make out that where the UART Base address is mapped ?As far as I know for mapping the base address we should userequest_mem_regionandio_remapfunction.But I could not find this in the code.Base address for UART4 is 0x4806E000
| This should be defined in the dts file in arch/arm/boot/dts/omap4.dtsi file. I'm not sure if DT is enabled for your kernel.If enabled, it reads in the probe function
|
I was wondering how to include files like LUA scripts, dlls, ect in a code:blocks build (debug and release) or would I just have to copy over all the files manually to the folders?
| As far as I know, it is done by manual organization
|
Ok, so I have an array of srings
```
char array[4][20];
//initialized
strcpy(array[0], "PERSON1");
strcpy(array[1], "PERSON2");
...
```
My question is how would I use shmget, and shmat to turn this array into shared memory?
Any help appreciated!
| ```
int segment_id = shmget(IPC_PRIVATE, sizeof(array),0660 | IPC_CREAT);
char** shared = shmat(segment_id,NULL,0);
```
This is a possible solution.
|
I'm trying to use the hardware instructions to compute some mathematical functions. For example the square root (sqrtpd instruction). I'm compiling my C code with GCC.
Does Anybody know what are the gcc options to force to compile with the hardware instructions and not to use the libc? Or if I need to do something special on my source code? (Without writing asm code).
| On gcc you should use__builtin_ia32_sqrtpd.
|
I am aware of what the ceil function does, it rounds numbers up.
So; 1.3 to 2.0 and 5.9 to 6.0.
But I want it to round up with steps of 0.5.
So; 1.3 to 1.5 and 5.9 to 6.0.
Is this possible?
Thanks!!!
| ```
y = ceil(x * 2.0)/2.0;
```
should do what you need:
```
x x*2.0 ceil(x*2.0) y
------------------------------
1.3 2.6 3.0 1.5
1.6 3.2 4.0 2.0
5.9 11.8 12.0 6.0
```
|
on page 23 in the K&R second edition, there is some code
```
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
```
It goes on. My question is, why do the integers have the ' on each side?
and what is the c-'0'?
| '0'is a character. It has the integer value 48.'9'has the value 57. The value ofc - '0'is equal toc - 48, and will be the integer value of the corresponding character.'0'will be0,'1'will be1, etc.
|
on page 23 in the K&R second edition, there is some code
```
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
```
It goes on. My question is, why do the integers have the ' on each side?
and what is the c-'0'?
| '0'is a character. It has the integer value 48.'9'has the value 57. The value ofc - '0'is equal toc - 48, and will be the integer value of the corresponding character.'0'will be0,'1'will be1, etc.
|
I want to do a screenshot of a GUI window from C/C++ into the memory.
It would be really nice if it's a two dimension array of RGB values or something similar.
Im at the moment searching for a Linux based solution, but would be nice if there is a platform independent solution.
| You could utilizexlibfor Linux:How do take a screenshot correctly with xlib?
AndGDIon Windows:MSDN - Capturing an Image
|
I want to do a screenshot of a GUI window from C/C++ into the memory.
It would be really nice if it's a two dimension array of RGB values or something similar.
Im at the moment searching for a Linux based solution, but would be nice if there is a platform independent solution.
| You could utilizexlibfor Linux:How do take a screenshot correctly with xlib?
AndGDIon Windows:MSDN - Capturing an Image
|
I cannot find in Internet any links to "official" GLU downloads or documentation. The links about GLU on opengl.org are defunct. The only GLU API documentation that I found is on MSDN about windows version of GLU. Is there such page as "official" GLU page and documentation and downloads for Linux?
| http://www.opengl.org/sdk/docs/man2/
GLU documentation is the part of OpenGL 2 documentation. There isa special section for GLU functions.
|
If I want to return strdup from a function whose return type is char*, then what are the risks or chances of memory leak ?
```
char* fun () {
return strdup("hello");
}
int main() {
for(;;)
printf("%s\n", fun());
}
```
| strdup()returns a pointer to newly-allocated memory that must be freed later withfree(). You'll leak memory if you don't callfree()on it β which, in your example, you don't.
|
I am working on a linux system. I have a multi-threaded application that hasnfile handles open on a single filef. How can I see during run-time how many file handles in my process refer ton?
| You could check the symbolic links in/proc/self/fd/and see if there are multiple descriptors pointing to the same file.
|
Here is my structure:
```
typedef struct {
char apagado;
char prop[MAXPLEN];
char mat[6];
double valor;
} veiculo_t;
veiculo_t.apagado='\0';
```
Why can't I initialize theapagadovariable like that?
| veiculo_tisn't a variable. It's a type. You still have to create a variable of that type:
```
veiculo_t veiculo;
veiculo.apagado='\0';
```
|
I have a variable of typeint array[10]. Is it possible to initialize only the last item of the array?
| Yes, using designated initializers (introduced in C99), you can write code like this:
```
int array[10] = {[9] = 42};
```
which is equivalent to:
```
int array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 42};
```
This feature is also available in some compiler as an extension, for instance,GCC.
|
I'm not very familiar with the source code behind the entity we know as PHP, so I don't know whether the SPL library in general and SplFixedArray in particular are implemented in C/C++. Would anyone have the information?
| Here youΒ΄ll find a link to a "spl_fixedarray.c" file:http://git.php.net/?p=php-src.git;a=tree;f=ext/spl=> It is C
|
What are equivalents for_tsystem and _wsystemin linux?βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Justsystem. There are no wide-string (Unicode) APIs in Linux.
|
In the below code why does the struct have two variable names?
```
#include <sys/resource.h>
int main (int argc, char **argv)
{
const rlim_t kStackSize = 64L * 1024L * 1024L;
struct rlimit rl; //HERE
int result = getrlimit(RLIMIT_STACK, &rl);
return 0;
}
```
| In C, struct with its tag together is a name, unless it'stypedefed.
In C++, you can omit thestructkeyword.
|
This question already has answers here:What does ~0 do?(4 answers)Closed9 years ago.
I see this type data in code program. But I don't know this type data. What means this type of data?
```
(uint16_t)~0U
```
| ```
(uint16_t) ~ 0 U
^ ^ ^ ^
| | | |____ unsigned constant
| | |______ the number 0
| |________ bitwise not operator
|______________ casting to 16 bits integer
```
As a result you get a 0xffff
|
What is the inner working ofgetchar_unlocked()?Why is it thread unsafe?And why it is not employed in windows POSIX?
| getchar_unlocked() is not threadsafe, because it might manipulates internal data structures without locking or any other type of synchronisation. For any more detailled answer, you must look at the exact implementation in question.
Omitting thread safety (and being inlined/a preprocessor define) is what makes it fast.
|
I would like to check if the firewall is enabled in Windows through C code, I found some methods in C# but only a little bit information from C, How I could do that?, thanks
| You could use theWindows Firewall API. For Windows XP you read theInetFwProfile::FirewallEnabledproperty. On Vista or later you could use theWindows Firewall with Advanced Security API.
|
I'm very confused on how these two functions work with mutex and what they do. Can someone explain them to me and give an example? Thanks!
| pthread_cond_signal() -> This is explainhere
More explanation :
You can do a lots of actions with thread, create, remove, make them stop (lock), make them unlock ... ect
pthread_cond_signal() permit to unlock some lock thread.
pthread_cond_wait() is used to lock some thread.
|
I encountered code where:
```
typedef wchar_t str_param_t[WP_STR_MAX_LEN];
```
And then:
```
typedef struct work_t
{
u32_t val1;
u32_t val2;
str_param_t data[WP_MAX_COUNT_STR];
} work_t;
```
My question is what type isdata?
| It is an array of lengthWP_MAX_COUNT_STRcontainingwchar_t-based strings of lengthWP_STR_MAX_LENeach.
|
I encountered code where:
```
typedef wchar_t str_param_t[WP_STR_MAX_LEN];
```
And then:
```
typedef struct work_t
{
u32_t val1;
u32_t val2;
str_param_t data[WP_MAX_COUNT_STR];
} work_t;
```
My question is what type isdata?
| It is an array of lengthWP_MAX_COUNT_STRcontainingwchar_t-based strings of lengthWP_STR_MAX_LENeach.
|
So, I'm getting an error on this line of code;
```
else if(lockError == EBUSY)
```
I get the error;
```
use of undeclared identifier 'EBUSY'
```
How do I compare my int lockError to the EBUSY that might be returned when I try a pthread_mutex_unlock.
| You forgot to include#include<errno.h>whereEBSUYis defined. Seeerrno.h.
|
So, I'm getting an error on this line of code;
```
else if(lockError == EBUSY)
```
I get the error;
```
use of undeclared identifier 'EBUSY'
```
How do I compare my int lockError to the EBUSY that might be returned when I try a pthread_mutex_unlock.
| You forgot to include#include<errno.h>whereEBSUYis defined. Seeerrno.h.
|
I am new to open CV and C. How do i specify multiple images for the same kind of operation.
| if your images are (sequentially) numbered, you could abuse a hidden feature with VideoCapture, just pass it a (format) string:
```
VideoCapture cap("/my/folder/p%05d.jpg"); // would work with: "/my/folder/p00013.jpg", etc
while( cap.isOpened() )
{
Mat img;
cap.read(img);
// process(img);
}
```
|
I want to check if a library is present either in my app or the System. In java I usually do System.loadlibrary, but does anyone know a similar corresponding call in C ?
| It isdlopento open a library, anddlsymto get pointer to function from loaded library. Beware, some details may vary in thisglibcdocumentation and actual android implementation. See ChrisStratton comment.
|
I could use following code to get the /proc entry, but how to get the /proc entry directly? Any function in the kernel to do this directly(without creating one dummy sub-entry)?
```
new_proc = proc_create("dummy", 0644, 0, &fileops_struct);
root = new_proc->parent;
```
| I haven't found a function, but you might accessproc_rootdirectly.
It is located infs/proc/root.cand should be accessible from outside.
|
Just confused, why is not mL = 1?
| Visual studio treatsint mL = 400/400as two step process.
First step would be allocating memory in stack. So, you see a garbage value. Press F10/F11 (step once more) you should see 1.
-858993460 translates to 0xCCCCCCCC which is a bit pattern used by Microsoft compilers to detect buffer overruns and to initialize an empty stack.Some more details here -softwareverify.com/memory-bit-patterns.php
|
I want to convert some bytes to an int.
This is my code so far:
```
unsigned char *bytePtr = (unsigned char *)[aNSDataFrame];
```
I want to take 4 bytes from this unsigned char:myFrame[10],myFrame[11],myFrame[12]andmyFrame[13]and convert them to an integer.
| ```
int val = *(const int*)&myFrame[10];
```
|
How can I usesched_setschedulerexplained in thistopic? It seems that I have to write a C code and run it on shell?
| To change the policy of a process from the shell you need to usechrt. To choose real time priorities you must be root. Beware that this is dangerous, raising priorities higher than the kernel interrupts will definitely have strange side effects!
|
I am using aLinux operating systemand the library functions I am talking about C programming language.
| Those functions are part of the system's C library, which on most GNU/Linux systems isGNU libc, also known as "glibc". Since glibc is open-source free software, you can download its source code and read whatever parts you're interested in. Thedownload pageis the place to start.
|
Should there be any errors, if a.hfile contains a signature, which has no implementation in a.cfile?
| If you use the function, and it isn't implemented, you will get a link error. Otherwise, no errors or warnings will occur.
|
Hello i'm new to C and have some confusion Regardingfprintf
I'm trying to create a Data table and i want it to look exactly like this:
```
Rectangle A Rectangle B
SW corner Height Width SW corner Height Width
```
Most of my confusion is coming from the white spaces, surely there is a better way than just adding an empty String.
| You can use width specifier:
```
printf("[%5d] [%-5d]\n", 42, 42);
```
|
Need to write a program to take input from a user in the form of an int and validate that what they entered is not a char from a-z.
Is there another way to do this other than:
if((num != 'a') && (num != 'b') && (num != 'c') && (num != 'd') etc.....)
printf("You entered %d", num);
| Yes, use theisdigit()function provided in thectype.hheader file
|
I'm trying to track a certain applications behaviour, I've grabbed the visible thread that draws the Window, having that thread is there any way to determine the process it belongs to?
| You can useGetProcessIdOfThreadapi for newer versions of windows.
For older versions you have to find it manually using the ToolHelp library functionsThread32First/Thread32Nextsearching for the threadid and getting the process id from the THREADENTRY32 structure.
|
```
if(tree->left)
if(!(*tree))
```
Do they mean:
```
if(tree->left==0)
if((*tree)==1)
```
I did not find anything about this.
| In C there are not booleans but only integers. The if statement just check for equality with 0, evaluating 0 as false and everything else as true, so your examples are equivalent to
```
if(tree->left != 0)
if((*tree)==0)
```
|
```
if(tree->left)
if(!(*tree))
```
Do they mean:
```
if(tree->left==0)
if((*tree)==1)
```
I did not find anything about this.
| In C there are not booleans but only integers. The if statement just check for equality with 0, evaluating 0 as false and everything else as true, so your examples are equivalent to
```
if(tree->left != 0)
if((*tree)==0)
```
|
This question already has answers here:How do I check if an integer is even or odd? [closed](30 answers)Closed9 years ago.
How can I check if a variable (an int) is even (that is, not odd) in C without using "%" operator?
I am running on linux platform.
Thank you.
| ```
if (!(v & 1))
```
should be true for even numbers
|
What does the following c code trying to do. I am not sure what does it calculate the value of width to
```
(width+31)&~31
```
Thank you.
| It is rounding up to the next multiple of 32. It only works because 32 is a power of 2.
```
The bit pattern for 31 is ...000000000011111
The bit pattern for ~31 is ...111111111100000
```
When you and ~31 with any positive integer, you get a multiple of 32 (five low order bits are all zeroes).
|
I executed following piece of code:
```
int a[] = {5,1,15,20,25};
int i,j,m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d",i,j,m);
```
and I got output as follow :-
```
3 2 15
```
The part which I don't understand is how I got value ofias3
It should be2right?
Or is it related with C compiler's right to left evaluation ofprintf()statement?
| Them = a[i++]line incrementedifor a second time, from 2 to 3.
|
I roughly read
http://linux.die.net/man/2/forkandhttp://linux.die.net/man/3/fork
got confused.
can anybody briefly explain to me difference between fork(3) and fork(2)
thank you
| fork(2) is the kernel call and fork(3) is the posix library call
|
I executed following piece of code:
```
int a[] = {5,1,15,20,25};
int i,j,m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d",i,j,m);
```
and I got output as follow :-
```
3 2 15
```
The part which I don't understand is how I got value ofias3
It should be2right?
Or is it related with C compiler's right to left evaluation ofprintf()statement?
| Them = a[i++]line incrementedifor a second time, from 2 to 3.
|
I roughly read
http://linux.die.net/man/2/forkandhttp://linux.die.net/man/3/fork
got confused.
can anybody briefly explain to me difference between fork(3) and fork(2)
thank you
| fork(2) is the kernel call and fork(3) is the posix library call
|
As we know, the C can open the /dev file node by the Linux system API. Like this:
```
int fd = open("/dev/hello", O_RDONLY|O_NONBLOCK);
```
So , is there any way to do this using JAVA without JNI ?
Thanks.
| Yes, since on Unix "everything is a file". You just open/dev/hellolike you open your file/home/jerikc/some.txt...
Perhaps your question is how to passO_NONBLOCKtoopen(2)syscall in Java....
|
This question already has answers here:What is the difference between int* ptr and int *ptr in C? [duplicate](5 answers)Closed9 years ago.
I have seen,
```
int *pnum;
int * pnum;
int* pnum;
```
Are these all the same?
| Yes, all those three are the same. And in them, that*is notdereferencing operator, it is part of the typeint *, pointer toint.
|
```
int b = 0xf ^ 0xc;
printf("value is %04X", b);
```
Output is:
```
value is 0003
```
I know that the decimal value of the xor operation between1111and1100is3although I want integerbto be printed out in hex.
| 0003 is a hexadecimal value; a hexa digit has values between 0..F
|
This question already has answers here:What is the difference between int* ptr and int *ptr in C? [duplicate](5 answers)Closed9 years ago.
I have seen,
```
int *pnum;
int * pnum;
int* pnum;
```
Are these all the same?
| Yes, all those three are the same. And in them, that*is notdereferencing operator, it is part of the typeint *, pointer toint.
|
For example if I received the following ASCII value: 123456
How would I combine two digits into a byte? So my bytes become like this ...
```
byte1 = 0x12;
byte2 = 0x34;
byte3 = 0x56;
```
Thanks!
| This is called BCD (binary-coded decimal).
```
char s[] = "123456";
byte1 = (s[0] - '0') * 0x10 + (s[1] - '0');
```
|
How can I clonechar** argvtochar** copy?
original -char** argvcopyto -char** copy
| Withargcbeing the number of elements in argv:
```
char** copy = (char**)malloc(argc * sizeof(char*)) ;
for (int i = 0; i < argc ; i++)
{
copy[i] = strdup(argv[i]) ;
}
```
Freeing the allocated memory once we are done with the clone, is left as an exercise to the reader.
|
Is there a way to find out if a particular interface exits using C .
| getifaddrs. There is an example program on the manpage. Basically you would have to just loop through the list looking for a match. Optionally you can look atif_nameindexif_indextonameandif_nametoindex
|
What's the difference betweenstrtokandstrtok_rinCand when are we supposed to use which?
| strtokis equivalent to (and often defined as):
```
char *strtok(char *str, const char *delim) {
static char *save;
return strtok_r(str, delim, &save);
}
```
in general, you should usestrtok_rdirectly rather thanstrtok, unless you need to make your code portable to pre-POSIX-2001 systems that only supportstrtok
|
I'm trying to access a website url(https) and read back it's contents(a json from an api).
What c commands would I use?
| Have you looked atlibcurl? Never used it, but I've seen it used quite a bit. Otherwise it's going to be somewhat system dependant, if you're on linux you could use popen() on a command that dumps to stdout.
|
Whenever I try to compile my c program on mac it gives the following error. I am completely clueless about it.
'sys/cdefs.h' file not found
| have you installed "Xcode Command Line Tools" ? just install it in your terminal.
```
sudo xcode-select --install
```
|
So I need to print a title using \ __ ||
it will become something like this
```
______
|_ _ \
| |_) |
| __'.
_| |__) |
|_______/
```
how to print all, and i get error even though i use \ to print \
| To print \ you need to put \\ in your string, because \ is an escape (e.g. \n for a new line).
|
I added this to my.profile but I stil get warnings :
```
QMAKE_CXXFLAGS_WARN_OFF = -Wunused-parameter
```
| UseQMAKE_CXXFLAGS_WARN_ON += -Wno-unused-parameter,because the flags in QMAKE_CXX_FLAGS will always before QMAKE_CXXFLAGS_WARN_ON, and QMAKE_CXXFLAGS_WARN_ON contains the flag -Wall. This means your flag will be overwrite by flag -Wall.
|
How do I execute below mentioned command using exec inside a C language program in linux?
wget -P ./Folder http://www.google.com
| execl("/usr/bin/wget", "-P", "./Folder", "http://www.google.com", NULL);
Unless you have to use exec, I suggest usingsystemfrom libc, since it is more portable (in case you ever decide you want to port it).
|
As we known, we can usepoll/selectwith Netmap:http://info.iet.unipi.it/~luigi/netmap/
Is it possible to useepolland whether it makes sense to use epoll with Netmap, or it has no advantages in speed?
| netmap author here: we have changes to enable epoll() for linux (the equivalent kevent() on FreeBSD is already supported). The advantage only exists when you have to handle several file descriptors in the same poll/select/epoll/kqueue operation.
|
I suppose I am just stupid (I tried all). Help me out of here:
```
#include <stdio.h>
#include <string.h>
int main()
{
const char * y = "747.0";
double x;
x = atof(y);
printf("%.5f\n",x);
printf("%e\n",x);
return 0;
}
```
result:
```
0.00000
0.000000e+00
```
| You need to includestdlib.hto offeratof()a prototype, without proper prototype, compiler will suppose its return value be anint.
|
As we known, we can usepoll/selectwith Netmap:http://info.iet.unipi.it/~luigi/netmap/
Is it possible to useepolland whether it makes sense to use epoll with Netmap, or it has no advantages in speed?
| netmap author here: we have changes to enable epoll() for linux (the equivalent kevent() on FreeBSD is already supported). The advantage only exists when you have to handle several file descriptors in the same poll/select/epoll/kqueue operation.
|
I suppose I am just stupid (I tried all). Help me out of here:
```
#include <stdio.h>
#include <string.h>
int main()
{
const char * y = "747.0";
double x;
x = atof(y);
printf("%.5f\n",x);
printf("%e\n",x);
return 0;
}
```
result:
```
0.00000
0.000000e+00
```
| You need to includestdlib.hto offeratof()a prototype, without proper prototype, compiler will suppose its return value be anint.
|
I want to know if there is any alternate C library for the unix command groups,
$ groups ---- lists all the group id's of the user.
There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.
| ```
#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
```
|
I want to know if there is any alternate C library for the unix command groups,
$ groups ---- lists all the group id's of the user.
There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.
| ```
#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
```
|
I'm looking for an easy way to trigger a real page fault (and not a segfault resulting from accessing an already mapped address or a protected address).
What could be one?
I thought of simply run
```
int main(void) {
int *x = 1000;
*x = 2000;
}
```
But it does not seem to result in a page fault but rather a memory violation.
| I believemmap()a disk file, and read from or write to it should be enough. At least it is enough on Linux.
|
This question already has answers here:Character size in Java vs. C(5 answers)Closed9 years ago.
I've stumbled on this while learning JAVA
I've noticed that char takes 16 bit , while I remember that it takes 8 in C.
can someone explain why they are not resemble ?
| C# chars are Unicode, which is 16-bit, while C only uses ASCII, which is actually only 7 bits.
|
how can I sscanf the following string
empty(1)
empty(20)
I tried the following but always failed
```
int count;
sscanf(buf, "%*s(%d)", &count)
```
Thanks in advance!
| change to
```
sscanf(buf, "%*[^(](%d", &count);
```
|
This question already has answers here:Character size in Java vs. C(5 answers)Closed9 years ago.
I've stumbled on this while learning JAVA
I've noticed that char takes 16 bit , while I remember that it takes 8 in C.
can someone explain why they are not resemble ?
| C# chars are Unicode, which is 16-bit, while C only uses ASCII, which is actually only 7 bits.
|
how can I sscanf the following string
empty(1)
empty(20)
I tried the following but always failed
```
int count;
sscanf(buf, "%*s(%d)", &count)
```
Thanks in advance!
| change to
```
sscanf(buf, "%*[^(](%d", &count);
```
|
how can I sscanf the following string
empty(1)
empty(20)
I tried the following but always failed
```
int count;
sscanf(buf, "%*s(%d)", &count)
```
Thanks in advance!
| change to
```
sscanf(buf, "%*[^(](%d", &count);
```
|
I am working on a bit complex project, and i wonder is it possible to debug just part of code not entire application because its too slow.
Like i write some lines and code, compile, and then tell to debugger from where to start execution and to assign variable values manually.
| This is only possible if you set up the environment for your part of code which will model the real project. Look atmock objects(brief description).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.