question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I've been reading on Makefiles, but I'm still clueless about how to go about writing the following commands into a Makefile.
```
gcc -std=c89 A.c -c
gcc -std=c89 B.c -c
gcc -std=c89 C.c -c
gcc -std=c89 A.o B.o -o A
gcc -std=c89 C.o B.o -o C
```
A and C are dependent on B, but are separate programs.
This is what I c... |
This is a no gimmicks makefile, and what is before gcc and rm must be the 'tab' character, they are not spaces.
```
all: A C
A.o: A.c
gcc -std=c89 -c A.c
B.o: B.c
gcc -std=c89 -c B.c
C.o: C.c
gcc -std=c89 -c C.c
A: A.o B.o
gcc -std=c89 -o A A.o B.o
C: C.o B.o
gcc -std=c89 -o C C.o B.o
clean:... |
How can I make timeout = 1 second for wait_event_timeout function?
Function :wait_event_timeout (wq,condition,timeout);
How can I make timeout = 1 second.
And if call function like that :wait_event_timeout(queue,flag!='n',30*HZ);
timeout =???
|
The function wait_event_timeout takes its timeout value in jiffies. Use the constantHZ(number of timer ticks per second) to specify time in jiffies. The expressionHZis the equivalent of one second. The expression30 * HZis the equivalent of 30 seconds.
```
wait_event_timeout (wq,condition,HZ);
```
|
I've been following a couple of C tutorials and there is a certain point I'm not sure I understand. Some examples show function prototypes but without function definitions. The tutorials say that the code should compile ok, even if they won't run.
Is this correct? Should C programs with missing function definitions c... |
The source code will compile with declarations only, but if any of the functions are called then a linker error will occur if the functions are not defined somewhere.
|
I just came across below question on Internet:
Macros and function are related in what aspect?(a)recursion(b)varying no of arguments(c)hypochecking(d)type declaration"
I am ruling out the option d cause macros just do argument substitution. Option a is not applicable to macros.
I am weighing between option b and c.... |
"Is there any terminology called “hypochecking” in C/C++?"
NO
|
Which line is the correct (best) way for defining a pointer?
```
typedef ptrdiff_t pointer; // pointers are ptrdiff_t.
-- or --
typedef void* pointer; // pointers are void*.
pointer ptr = malloc(1024);
```
|
Pointers in C are of typeT*whereTis the type pointed to;void*is the generic pointer type. Usually, you let C implicitly convertvoid*to something useful, e.g.
```
char *buffer = malloc(1024);
```
ptrdiff_tis the type returned by the subtraction of two pointers, e.g.
```
ptrdiff_t d = write_ptr - buffer;
// now you k... |
I am reading a C book, talking about ranges of floating point, the author gave the table:
```
Type Smallest Positive Value Largest value Precision
==== ======================= ============= =========
float 1.17549 x 10^-38 3.40282 x 10^38 6 digits
double 2.22507 x 10^-308 1.... |
A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:
```
(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) =
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) =
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38
```
|
I have a rooted device and set the build properties as given in the Android Dev Linkhttp://android-developers.blogspot.in/2011/07/debugging-android-jni-with-checkjni.html
```
$ adb shell stop
$ adb shell setprop debug.checkjni 1
$ adb shell start
```
But after doing this i am getting CheckJNI is OFF in the DDMS log
... |
Try this:
Go to data > localpropertiesIn localproperties if have write permissionHave a file with local.prop in your local disk with this text dalvik.vm.checkjni=true.adb push /data/local.prop /local.prop.Then restart the device then you will see CheckJNI Option in LOGCAT.
|
How to pass the param like char * as a reference?
My function uses malloc()
```
void set(char *buf)
{
buf = malloc(4*sizeof(char));
buf = "test";
}
char *str;
set(str);
puts(str);
```
|
You pass the address of the pointer:
```
void set(char **buf)
{
*buf = malloc(5*sizeof(char));
// 1. don't assign the other string, copy it to the pointer, to avoid memory leaks, using string literal etc.
// 2. you need to allocate a byte for the null terminator as well
strcpy(*buf, "test");
}
char *... |
I want to increment up where I use a[0]. Something likea++. The only other solution I can think of is a switch case or a bunch of if/else if statement, but that seems inefficient. Is this possible?
```
#include <stdio.h>
int
main(void)
{
const char *a[6];
a[0]="one";
a[1]="two";
a[2]="three";
... |
What about this?
```
printf(..., a[i]);
```
|
What is the equivalent ofpthread_mutex_lockandpthread_cond_waitin the linux kernel. and how to use them. Could you please provide simple (hello world) examples.
|
For the mutex (as Als said ):
mutex_lock()andmutex_unlock()and we should init the mutex before we use it withmutex_init()(from#include <linux/mutex.h>)
For the equivalent ofpthread_cond_wait
wait_event_interruptible()andwake_up_interruptible()and we should init the wait_queue_head withinit_waitqueue_head()(from#inc... |
I'm coding something in C and dealing with situations where it would be helpful to be able to say "cast this to a pointer pointing to a datatype with the same number of bytes as this number".
An example will make it clearer - I'm usingsize_tto get the size of a pointer on the system. Now I want to portably cast avoid... |
What wrong aboutsize_t*(assuming I understood your question)
In the general case, where you need pointer to a type withnbytes, you can do:
```
void *voidptr=... //assign whatever you want.
char (*myptr)[n]=voidptr; //a pointer to char[n]
```
|
For example, I define a macro:
```
#ifdef VERSION
//.... do something
#endif
```
How can I check ifVERSIONexist in my object file or not? I tried to disassemble it withobjdump, but found no actual value of my macroVERSION.VERSIONis defined in Makefile.
|
Try compiling with-g3option ingcc. It stores macro information too in the generated ELF file.
After this, if you've defined a macroMACRO_NAMEjustgrepfor it in the output executable or your object file. For example,
```
$ grep MACRO_NAME a.out # any object file will do instead of a.out
Binary file a.out matches
```
... |
I am trying to implement a Data Flow Anomaly Detection using ptrace. After a bit of research I implemented a program which is similar to strace. Now, I'm confused about this, which is what the wiki tells me about system calls:
"System calls provide the interface between a process and the operating system"
When I am ... |
You are operating in the address space of a separate process; this requires the intercession of (and permission from) the kernel, since independent processes cannot normally affect each others' address spaces.
|
I'm trying to get the contents from the file yh.dat which HAS the text like "456 78921" and somthing else by C.But when I try debug the code,the FILE pointer isn't NULL(0x00428af8) and the _ptr and the _base is NULL(0x000000).They says "CXX0030:Error:expression cannot be evaluated".How to solve it?
```
int main(){
... |
To allow you to change the file buffering, C doesn't set up the buffer for a file until you issue the first read. As such, until you attempt at least one read, it's normal for the members of whatever struct the FILE * points at to be in an only semi-initialized state.
Have you tried just reading data to see if it wor... |
My classmate asked me a question:
What's the value of x,y,z after this:
```
x=5;
y=8;
z=((x++)<(y++)?(x++):(y++));
```
I 'm not sure about it, so I tested it and answer is:
```
x=7,y=9,z=6
```
I can understand why "x=7" and "y=9", but why "z=6" ? Shouldn't this expression return the value calculated by "x++" ?
T... |
There is asequence pointbetween the evaluation of the first operand of?operator and second or third operator and hence firstx++would completely take effect resulting in x=6. But the increment in the secondx++would take effect only after the evaluation of the complete expression as there are no more sequence points in ... |
In this document, the author said
Only a POD-type can be an argument for the ellipsis "..." while std::string is not a POD-type.
I'm understanding this asPassing NON-POD type to Variadic function is undefined behavior. Is it right?Though, is he saying C/C++ standard? I tried to find it at n3242 C++ spec. But can not... |
It's specified in C++11 5.2.2/7:
Passing a potentially-evaluated argument of class type having a non-trivial copy constructor, a non-trivial move contructor, or a non-trivial destructor, with no corresponding
parameter, is conditionally-supported with implementation-defined semantics.
So it's up to each compiler w... |
Our school's project only allows us to compile the c program into 64-bit application and they test our program for speed and memory usage. However, if I am able to use 32-bit pointers, then my program will consume much less memory than in 64-bit, also maybe it runs faster (faster to malloc?)
I am wondering if I can u... |
Using GCC?
The -mx32 option sets int, long, and pointer types to 32 bits, and generates code for the x86-64 architecture. (Intel 386 and AMD x86-64 Options):
i386-and-x86_64-OptionsOther targets, GCC
Then benchmark :)
|
It seems like we need to create separate folder for each build type (debug/release), run cmake on each, and generate separate makefile for debug/release configuration. Is it possible to create one single makefile using cmake that supports both debug/release configuration at the same time and when we actually run "make... |
As far as I know, this cannot be achieved using a single set of build scripts. However, what you can do is have two sub-directories of your working area:
```
build/
build/debug
build/release
```
Then do:
```
$ cd build
$
$ cd build/debug
$ cmake -DCMAKE_BUILD_TYPE=Debug ../..
$ make
$
$ cd ../release
$ cmake -DCMA... |
I want to get the user ID of a given process ID using C
How can I do it?
Any insight appreciated ;)
|
If you have theprocfsfile system, then the effective user ID of the files in/proc/<pid>are that of the user.
|
Following is the code snippet.
```
int main()
{
int i =0;
while (i++ < 5)
{
// Do some heavy processing
printf("i = %d\n", i);
sleep(1);
}
}
```
The heavy processing part is doing its part every 1 second.
I want to display 'i' after 1 s as well but its displaying the entire outpu... |
You need to flush stdout; you can use fflush(3) to do so:
```
fflush(stdout);
```
You could also disable buffering entirely on stdout:
```
setbuf(stdout, NULL);
```
|
I have the following piece of code:
```
FILE *fpa;
fpa = fopen(argv[2], "r");
if (fpa == NULL) {
printf("Error: could not open seqA file!\n");
exit(0);
}
unsigned int N_a;
fscanf(fpa, "%d\n", &N_a);
char *seq_a = malloc((N_a+1) * sizeof(char *));
strcpy(seq_a,"");
fscanf(fpa... |
char *seq_a = malloc((N_a+1) * sizeof(char *));
should be:char *seq_a = malloc((N_a+1) * sizeof(char));
If you want to print each char then use%c:
```
printf("%c", seq_a[i]);
```
|
I have a string of characters that is something like " asdf + lghd + ewre + fdsf + ..." that is of varying length. From this I also have a template for use with the sscanf function that is similar to "%s + %s + %s + ...". Because both of these are of varying lengths, is it possible to replace those additional argumen... |
sscanf()doesn't support this, but you could write your own version of scanf.
I've done this already in C# and posted the codehere. Perhaps my code will give you some ideas for writing a custom version in C.
|
I worte the code below
```
void * ptr1 = VirtualAlloc((void*)0x70000000, 32*1024*1024, MEM_RESERVE, PAGE_READWRITE);
void * ptr2 = VirtualAlloc((void*)0x80000000, 4*1024*1024, MEM_RESERVE, PAGE_READWRITE);
```
But VirtualAlloc fails and the value of ptr1,ptr2 are always NULL.
I want to use the adress 0x70000000,0x8... |
This part of the memory is not accessible for usermode applications. From the followingMSDN page:
User applications cannot callVirtualAllocwith shared heap address
range (0x70000000 to 0x7fffffff) because this is read-only for user
applications and read/write for kernel mode.
|
Why this code is unsecured?
```
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf(argv[1]);
printf("\n");
return 0;
}
```
|
printfwill process its first parameter, looking for things like%dand%s.
Based on those values, it will get more data from the stack and print it out.
So if someone called your program:
```
a.out "%d %d %d %d %d %d %d %d %d %d %d %d"
```
They could view a section of your computer's callstack.
If they got even more... |
Is it possible to convert anadjacency matrixof ones and zeros as definedhereinto adistance matrixas definedherewhere each link would be of unit length 1?
|
An adjacency matrix of ones and zeros is simply a representation of an undirected graph. To get the distances between any two vertices of an unweighted graph, you can usebreadth first search.
Assuming you have annbynmatrix:
```
for each vertex i:
initialize an nxn matrix M
run breadth-first search starting a... |
I want to print time in the format hh:mm:ss:ms(milliseconds). I could print in the form of hh:mm:ss. What can be the way to print remaining milliseconds?
|
```
#include<sys/timeb.h>
#include<time.h>
int main(void) {
struct timeb tp;
ftime(&tp);
char timeString[80];
strftime(timeString, sizeof(timeString), "%H:%M:%S", localtime(&tp.time));
printf("%s:%d", timeString, tp.millitm);
return 0;
}
```
|
I am trying to implement dijkstra's algorithm for path finding and need some sort of priority queue to store the information.
In the past, for example a fifo or filo PQ i've simply used an array and then two pointers to the current insert and the current "look" position and then to "remove" and item shifted the look ... |
The easiest option is to implement abinary heapbased on C arrays.
|
The question is to write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. so, if a user types 932, the program should display 'nine three two'..
My algorithm is to reverse the number first so that 932 becomes 239. Now I extract the last digit u... |
You can skip all mod processing/reversing if you input the string withfgetsetc
Something on these lines ( No error checking on my part, its just a pseudo code )
```
char *numArray[]={"One", "Two", ....};
fgets(buffer, 80, stdin)
while ( buffer[i] )
{
printf("%s ", numArray[buffer[i]-'0'])
i++;
}
```
|
i have values like 12, 13 which i want assign to single integer example, k.
i tried the following program but i am not getting expected results.
```
enter code here
#include <stdio.h>
int main()
{
int k = 0;
printf("k address is %u\n", &k);
char* a = &k;
printf("%u\n", a);
*(a) = 12;
a++;
printf("%u\n", a);
*(a) = 1... |
On your system,ints are evidently stored inlittle-endianformat, because 13*256 + 12 = 3340.
|
I've built a C application, and when I build it, it shows no errors, but when I run it, it gives me the error "Segmentation Fault: 11".
If it helps, here is the code I am using:
```
#include <stdio.h>
int main(char *argv[]) {
printf("The project path is: ./Projects/%c", argv[1]);
return 0;
}
```
|
The correctmainprototyped syntax is
```
int main(int argc, char *argv[]) { ... }
```
Also%cconversion specification inprintfprints a character, to print a string use%s.
|
I've found the following code in a legacy project that seems to cause some trouble:
```
for( ; *str; ++str )
*str = tolower(*str);
```
The trouble is, we get an SIGSEGV at the moment the result of tolower() should be written back to *str . This is what I got from using printf() debugging and the stracktrace prod... |
String literals are non-modifiable:
```
char blop[] = "modifiable string";
char *bla = "non-modifiable string";
*blop = tolower(*blop); // OK
*bla = tolower(*bla); // not OK, modifying a string literal
```
|
My classmate asked me a question:
What's the value of x,y,z after this:
```
x=5;
y=8;
z=((x++)<(y++)?(x++):(y++));
```
I 'm not sure about it, so I tested it and answer is:
```
x=7,y=9,z=6
```
I can understand why "x=7" and "y=9", but why "z=6" ? Shouldn't this expression return the value calculated by "x++" ?
T... |
There is asequence pointbetween the evaluation of the first operand of?operator and second or third operator and hence firstx++would completely take effect resulting in x=6. But the increment in the secondx++would take effect only after the evaluation of the complete expression as there are no more sequence points in ... |
In this document, the author said
Only a POD-type can be an argument for the ellipsis "..." while std::string is not a POD-type.
I'm understanding this asPassing NON-POD type to Variadic function is undefined behavior. Is it right?Though, is he saying C/C++ standard? I tried to find it at n3242 C++ spec. But can not... |
It's specified in C++11 5.2.2/7:
Passing a potentially-evaluated argument of class type having a non-trivial copy constructor, a non-trivial move contructor, or a non-trivial destructor, with no corresponding
parameter, is conditionally-supported with implementation-defined semantics.
So it's up to each compiler w... |
Our school's project only allows us to compile the c program into 64-bit application and they test our program for speed and memory usage. However, if I am able to use 32-bit pointers, then my program will consume much less memory than in 64-bit, also maybe it runs faster (faster to malloc?)
I am wondering if I can u... |
Using GCC?
The -mx32 option sets int, long, and pointer types to 32 bits, and generates code for the x86-64 architecture. (Intel 386 and AMD x86-64 Options):
i386-and-x86_64-OptionsOther targets, GCC
Then benchmark :)
|
It seems like we need to create separate folder for each build type (debug/release), run cmake on each, and generate separate makefile for debug/release configuration. Is it possible to create one single makefile using cmake that supports both debug/release configuration at the same time and when we actually run "make... |
As far as I know, this cannot be achieved using a single set of build scripts. However, what you can do is have two sub-directories of your working area:
```
build/
build/debug
build/release
```
Then do:
```
$ cd build
$
$ cd build/debug
$ cmake -DCMAKE_BUILD_TYPE=Debug ../..
$ make
$
$ cd ../release
$ cmake -DCMA... |
I want to get the user ID of a given process ID using C
How can I do it?
Any insight appreciated ;)
|
If you have theprocfsfile system, then the effective user ID of the files in/proc/<pid>are that of the user.
|
Following is the code snippet.
```
int main()
{
int i =0;
while (i++ < 5)
{
// Do some heavy processing
printf("i = %d\n", i);
sleep(1);
}
}
```
The heavy processing part is doing its part every 1 second.
I want to display 'i' after 1 s as well but its displaying the entire outpu... |
You need to flush stdout; you can use fflush(3) to do so:
```
fflush(stdout);
```
You could also disable buffering entirely on stdout:
```
setbuf(stdout, NULL);
```
|
Can I pass an array to printf directly:
```
char text[1024] = "text";
printf("%s", text);
```
Or should I explicitly cast it to a char pointer:
```
char text[1024] = "text";
printf("%s", (char*) text);
```
I'm asking because I thought maybe it copies the array elements directly into the va_list instead of putting ... |
Yes, you can pass an array directly. Exactly, name of array represents address of the array which makes no difference withchar *.
|
How can I generate human readable llvm bitcode (extension .ll) from the binary llvm bitcode (extension .bc) file?
|
Here is a useful link with all thellvm commands. Obviouslyllvm-disdoes what you ask.
|
I'm trying to produce assembly code like this (so that it works with nasm)
```
;hello.asm
[SECTION .text]
global _start
_start:
jmp short ender
starter:
xor eax, eax ;clean up the registers
xor ebx, ebx
xor edx, edx
xor ecx, ecx
mov al, 4 ;syscall write
mov bl, 1 ... |
This is Intel style.
What's wrong with the commandline you wrote in the question?
|
What exactly does execve() do? I've tried looking at the documentation (http://linux.die.net/man/2/execve) but given that I'm very new to linux and this sort of programming it doesn't make a lot of sense. What I want to do is be able to execute this command:
```
nc -l -p someport -e /bin/sh
```
Can I do something ... |
execveasks the operating system to start executing a different program in the current process.
Chances are pretty decent that you wantexecvporexeclpinstead -- you haven't mentioned anything about wanting to provide the environment for the child, but from the looks of things you probably do want the path searched to f... |
In fortran, I can declare a character string as:
```
character*80 mystring
```
and then send it as:
```
call MPI_Send(mystring,len(mystring),MPI_CHARACTER,...,ierr)
```
Alternatively, I could declare my string as an array of characters (much more in line with the way things are traditionally done in C)
```
charac... |
http://www.mcs.anl.gov/research/projects/mpi/mpi-standard/mpi-report-1.1/node37.htm#Node38
Basically don't do the latter.
|
I'm having a problem with passing a pointer to a struct to a function. My code is essentially what is shown below. After calling modify_item in the main function, stuff == NULL. I want stuff to be a pointer to an item struct with element equal to 5. What am I doing wrong?
```
void modify_item(struct item *s){
stru... |
Because you are passing the pointerby value. The function operates on a copy of the pointer, and never modifies the original.
Either pass a pointer to the pointer (i.e. astruct item **), or instead have the function return the pointer.
|
Based on this SOpost, and thisexample, I expect that, when I use fork(), will allow me executing system/execvp in non-blocking manner. However, when I try to issue a long-running child process in a fork block in the above mentioned example code, the control does not return to parent block, till the child has finished.... |
forkwill immediately return to both the child and parent. However, that example (test3.c) callswait4, which like it sounds, waits for another process to do something (in this case exit).
|
I was revisiting pointers when I had this doubt.
```
int *ptr;
int arr[5] = {10,20,30,40,50};
ptr = &arr[0];
```
Nowprintf("Value: %d",*ptr);would print10
if I do:
```
ptr++;
printf("Value: %d",*ptr);
```
the result would be:20
Similarly if I do:
```
*ptr++;
printf("Value: %d",*ptr);
```
the result is:30
But
... |
Because ofprecedence.
*ptr++is the same as*(ptr++), the pointer is incremented, but itspreviousvalue is dereferenced.ptr++is the same as, well,ptr++.++*ptris the same as++(*ptr), i.e. it increments the thing being pointed to, not the pointer.
|
I was reading about buffer, stack and heap overflows. I read thispostas well. my question is like that: if I use only global variables in my code, can I say it prevents all the exploits of overflow?
let's say I have this buffers in code declared in the global scope:
```
char buf1[10];
char buf2[100];
```
If I sendb... |
No, not at all. Whilst its harder to directly modify return addresses, etc. on the stack, it's still possible to corrupt or maliciously attack such a program (if it's careless about buffer overflows).
|
I know that to find out the size of the udp packet before reading you can issue this syscall to the kernel:
```
ioctl(s,FIONREAD,&num_bytes);
```
But, can I find out the same with one of the following syscalls ?
```
poll()
select()
epoll()
```
The key is to know the size of the datagram before reading it, to alloc... |
The multiplexing syscalls likepollorselectare expecting a set of conditions to watch (like input is available on fd #5, output is possible on fd #7) and tell you which file descriptors are readable (and which ones are writable, etc.). Once you know which file descriptor can be read, you can use yourioctl(fd, FIONREAD,... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
Is there any one who can explain th... |
On classic real-mode x86 architectures, you could trigger a system boot by doing an unconditional JMP to address 0xFFFF0000.
The code is basically definingx()as a function, and setting the function's in-memory address as 0xFFFF0000. When you invoke the function, the system would doCALL 0xFFFF000or similar at the asse... |
I have a C-array that looks like this:
```
char hexc[] = {
0x41, 0x80, 0x7a, 0x39, 0xea, 0x7e, 0x27, 0xfc,
0xe6, 0x45, 0x9c, 0x8b, 0xb5, 0xce, 0xa7, 0x35,
0x5f, 0xf2, 0x43, 0xcf, 0x89, 0xd8, 0x61, 0xec,
0xe7, 0xed, 0x2e, 0x34, 0x45, 0x0c, 0x32, 0xae,
0x71, 0x4f, 0x1c, 0xd8, 0xb5, 0x8c, 0x1e, 0... |
You would just open the file and write to it:
```
FILE *f = fopen("filename.gif", "wb");
if (!f) return; // or do something else
fwrite(hexc, 1, sizeof(hexc), f);
fclose(f);
```
Make sure to#include <stdio.h>.
|
I write the following macro for debug convinience,
```
1 #ifndef DEF_H
2 #define DEF_H
3 #define DEBUG_MODE
4 #define DEBUG_INFO(message) \
5 #ifdef DEBUG_MODE \
6 cout << message << endl; \
7 #endif \
8 #endif
```
but gcc complains as the following
... |
You cannot have#ifdefs inside a macro definition. You need to turn it inside out:
```
#ifdef DEBUG_MODE
#define DEBUG_INFO(message) cout << (message) << endl
#else
#define DEBUG_INFO(message)
#endif
```
|
I'm looking for a C function similar to the C# Array.Copy().
I found memcpy() only, but I need to copy from specific index too.
|
If you have an array like this:
```
SomeType myArray[50];
```
And you want to copy elements indexed 19-29 (the 20th through 30th elements).
Then you do:
```
memcpy(dest, &myArray[19], 10 * sizeof(SomeType));
```
Note: this code-segment makes no provision for initializingmyArray, or allocating memory todest
|
I have a doubt regarding unions. Suppose there is a union defined as
```
union emp{
float f;
int i;
};
```
Is there a way to determine which field of union is used. I have come across a situation in which I have to print float if float field is used and print int if int field is used.The function may be like... |
You can't tell with just theunion; typically you wrap it in astructwhich includes a tag value of some kind.
```
struct val {
enum { EMP_INT, EMP_FLOAT } tag;
union emp {
int i;
float f;
} emp;
};
```
|
Can I pass an array to printf directly:
```
char text[1024] = "text";
printf("%s", text);
```
Or should I explicitly cast it to a char pointer:
```
char text[1024] = "text";
printf("%s", (char*) text);
```
I'm asking because I thought maybe it copies the array elements directly into the va_list instead of putting ... |
Yes, you can pass an array directly. Exactly, name of array represents address of the array which makes no difference withchar *.
|
How can I generate human readable llvm bitcode (extension .ll) from the binary llvm bitcode (extension .bc) file?
|
Here is a useful link with all thellvm commands. Obviouslyllvm-disdoes what you ask.
|
This question already has answers here:how to calculate size of pointer pointed memory?(9 answers)Closed9 years ago.
Say if i want to print out my integer stored inside a "array" , which indeed a pointer in memory.When i use the code:
```
int main(void)
{
int *arr = malloc(3*sizeof(int));
int *p = arr;
*arr++=... |
C does not provide a built-in way to find the size of dynamically allocated chunks of memory. You have to store the size, and pass it "on the side".
One way to address this would be to create astructcombining a pointer and asize_tvalue describing the number of elements allocated in the array.
|
Ok, suppose I want to store the address0xcdddd298in a C string so that it stores the bits for this address in little endian format. How would I do this? Would it be something like\x98d2ddcd?
|
No. It would be"\x98\xd2\xdd\xcd".
But I'm not sure why you'd want to store an address in a string.
|
I am trying to create a programming judge likespoj.pl. I have to measure the time and memory a C/C++/Java program is using. I want to set a maximum memory limit for the program that I wish to execute. Can you please suggest how I can do that.
|
System-, where-, how-, what-,...- dependent.
To limit, i.e.:
Linux command line: >$ ulimit -v NNN && ./tha_prog,$ man ulimit,$ ulimit -a.
Linux C coded: >setrlimit()linux.die:setrlimit, opengroup:setrlimit
Windows:CreateJobObject,Job Objects
Then the question also becomes what to limit. Static vs dynamic librar... |
I'm writing a C/C++ program that involves putting a hex representation of a number into a string and I'm confused as to how\xworks. I've seen examples where people have written things such as "\xb2". In this case, how does the program know if you want the hex of b followed by the number 2 or if you want the hex of b... |
From the C99 standard (6.4.4.4):
Each octal or hexadecimal escape sequence is the longest sequence of characters that can
constitute the escape sequence.
|
I compiled this (gcc compiler):
```
#include <stdio.h>
main() {
struct {
a:1;
b:2;
} t;
t.b=6;
t.a=2;
printf("%d %d",t.a,t.b);
}
```
Error shown was:
expected specifier-qualifier list before 'a'
Why it is needed when unnamed data variables are taken as int by default. Please ... |
This is required by theC language standard. According to section 6.7.2.1 part 4:
A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.
|
I compiled this (gcc compiler) :
```
#include< stdio.h>
main() {
unsigned char ch;
FILE *fp;
fp=fopen("trial","r");
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}
```
It gives the follwing:
```
Warning: comparison is always true due to limited range of the data type
```
On ... |
Because EOF is -1 and yourchis unsigned char which means ch will never become -1.
Instead useint ch;
|
I want to know whether there is any way to debug (using gdb) both child and parent processes simultaneously. I know the command used to change processes to child one. But that is not the solution I am looking for, as this method only has control of either the child or the parent. I am looking for simultaneous executio... |
I want to know whether there is any way to debug(using gdb) both child and parent processes simultaneously.
Yes,there is. Documentationhereandhere. If you are on Linux, you'll want to
```
(gdb) set detach-on-fork off
```
|
I want a debugger to debug my OS. At many places i am not being able to figure out what is wrong.So is there any debugger which can debug operating systems? can i do it with gdb?
|
You will need to use a solution which emulates another computer on your computer - essentially, a virtual machine. The most obvious ones which come to mind instantly are VirtualBox and VMware, but those weren't designed with debugging the machine and/or the OS.
What you're looking for is eitherBochsorQEMU. Both (as f... |
If I write something like
```
#define INT_PTR int*
INT_PTR ptr4, ptr5, ptr6;
```
In this case only ptr4 is pointer to an integer, rest of the values (ptr5 and ptr6) are integers. How they are taking the integer value ? Either it should give some compilation error.
Why is it this way that compiler is treating ptr5 a... |
Because to declare pointer objects you would do:
```
int *ptr4, *ptr5, *ptr6;
```
In C, the token*does not belong to the type information, so you have to repeat it when you declare several objects. Note that this is a frequent mistake in C.
What you can do is totypedefinstead:
```
typedef int * INTPTR;
```
|
I am learning aboutsscanfand came across a format string as below:
```
sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c);
```
I understood the part%[^:]means scan till a':'is encountered and assign it toa.:in format string mean match for a':'.
But
I understood that%*dmean suppress the assignment till a number is encountered. ... |
The*inside square brackets is just a literal *.
This call tosscanfwill match everything up to a * or = in the second directive, and assign the result tob. Then the third directive will grab all * or = characters, and throw away the result.
|
There was a exercise in my book, which asked me to write a for loop equivalent to :
```
for(i=0;(i<4) && (i<5);i++)
```
but without using&&and||operator.
I came up with a solution like this :
```
for (i=0;;i++)
if((i<4))
if((i<5))
printf("Works!!!\n");
else
... |
Your&&is combining two conditions such that one is a logically weaker one with respect to the other. If an integer is less than 4 it is necessarily less than 5. Thus(i<4) && (i<5)can just be replaced with(i<4).
|
I use wcsncasecmp inside c/c++ app.
Compile have following error:
```
error: 'wcsncasecmp' was not declared in this scope
```
Gcc 4.2.1, macos.
How to solve this error?
|
wcsncasecmpis a GNU-specific function. It's not available on Mac OS X.
|
I'm writing a function that returns the firstn(n <= strlen(src)) characters of a string.
```
char* substring(char *src, int n)
{
char *substr;
int i;
for (i = 0; i < n; i++)
*substr++ = *src++;
src = src - n;
*substr = '\0';
return substr - n;
}
```
This function returns the right answer when ... |
No memory is allocated forsubstrand the function therefore deferences an uninitialized pointer and is writing to memory where it is not supposed to resulting inundefined behaviour. The fact it works the first time is complete chance.
Allocate memory forsubstr:
```
char* substr = malloc(n + 1); /* Plus one for null t... |
Below is my locale set.
```
LANG=en_US.UTF-8
LC_CTYPE=zh_CN.UTF-8
LC_NUMERIC=en_US.UTF-8
LC_TIME=en_US.UTF-8
LC_COLLATE=en_US.UTF-8
LC_MONETARY=en_US.UTF-8
LC_MESSAGES=en_US.UTF-8
LC_PAPER=en_US.UTF-8
LC_NAME=en_US.UTF-8
LC_ADDRESS=en_US.UTF-8
LC_TELEPHONE=en_US.UTF-8
LC_MEASUREMENT=en_US.UTF-8
LC_IDENTIFICATION=en_U... |
LC_CTYPEapplies to classification and conversion of characters, and to multibyte and wide characters.
zhis the ISO-Code for Chinese.zh_CNis a subtype ofzhand stands for "simplified Chinese".
|
I'm learning to program in Arduino and, as far as I understand it, it uses the C language (please correct me if I'm wrong).
I'm a senior in JavaScript and PHP, and now I'm having hard time with simple stuff like string handling.
If in JavaScript I have
```
var c = 33;
var myString = "hello" + c;
alert(myString); //... |
In C, you would do something like:
```
char buff[100]; // needs to be large enough.
int c = 33;
sprintf (buff, "hello%d", c); // may want a space after hello
// Now do something with buff.
```
C is a language where you need to manage some low-level details yourself. There's no automatically expanding string type in... |
I want to compile a simple C program with GCC. What do I need to put in the sublime-build file to do so?
|
Mac OS X:
```
{
"cmd" : ["gcc", "$file_name", "-o", "${file_base_name}"],
"selector" : "source.c",
"shell":true,
"working_dir" : "$file_path"
}
```
Windows:
```
{
"cmd" : ["gcc", "$file_name", "-o", "${file_base_name}.exe"],
"selector" : "source.c",
"shell":true,
"working_dir" : "$file_path"
}
```
|
This question already has answers here:how to calculate size of pointer pointed memory?(9 answers)Closed9 years ago.
Say if i want to print out my integer stored inside a "array" , which indeed a pointer in memory.When i use the code:
```
int main(void)
{
int *arr = malloc(3*sizeof(int));
int *p = arr;
*arr++=... |
C does not provide a built-in way to find the size of dynamically allocated chunks of memory. You have to store the size, and pass it "on the side".
One way to address this would be to create astructcombining a pointer and asize_tvalue describing the number of elements allocated in the array.
|
Ok, suppose I want to store the address0xcdddd298in a C string so that it stores the bits for this address in little endian format. How would I do this? Would it be something like\x98d2ddcd?
|
No. It would be"\x98\xd2\xdd\xcd".
But I'm not sure why you'd want to store an address in a string.
|
There was a exercise in my book, which asked me to write a for loop equivalent to :
```
for(i=0;(i<4) && (i<5);i++)
```
but without using&&and||operator.
I came up with a solution like this :
```
for (i=0;;i++)
if((i<4))
if((i<5))
printf("Works!!!\n");
else
... |
Your&&is combining two conditions such that one is a logically weaker one with respect to the other. If an integer is less than 4 it is necessarily less than 5. Thus(i<4) && (i<5)can just be replaced with(i<4).
|
I'm trying include this barcode source codeStefanhafeneger - Barcode github.comto my project because this is the only DataMatrix library for iOS I can find so far. I have no problem compile and run the source code on xcode 4.2 but when i try to use the library in my project. I received quite lots of error as follows.
... |
My assumption is that you did not have the Foundation.framework instanciated in your project...
|
I want to use the actual pointer address (not marked volatile) to an object to uniquely identify the object.
Is this a bad thing to do? In general does system memory management move the objects and hence it's address about or is the pointer stable?
Thanks
|
Your pointer is guaranteed to remain stable for the life of the object to which it points, unless you do something to break it. The OS does indeed move things around in memory, but that's physical memory - the virtual memory space the OS presents to your process will keep things at the same addresses.
|
I would like to make a file that only my program has permissions to write in/read/visualize the file, in windows 7 we have those permissions but I don't know how to make from a user that I create, the user will be only my executable, only it can see, read and write in the file.
I saw a program doing that, but I have ... |
You can't restrict file access to only your app. You can only restrict access to specific user accounts and/or groups. Look at theSetFileSecurity()andSetNamedSecurityInfo()functions for that. If a suitable user account with adequate permissions runs your app (or any app for that matter), or your app (or another app) ... |
I'm starting to learn C now and i'm trying to figure out how I would go about capturing when the user hits "enter." I'm looking particularly at the scanf and getc functions but I'm not quite sure how to go about it. When the user hits enter I want to perform some operations while waiting/watching for him to hit ente... |
You can check the ascii value using fgetc().
```
while(condition) {
int c = fgetc(stdin);
if (c==10) {//Enter key is pressed
//your action
}
}
```
|
I have this code in C (it's for study only):
```
char x;
uint64_t total = 0;
for(x = 20; x < 30; x++){
total = (((((1 << x) * x) / 64) + 1) * sizeof(uint64_t));
printf("%d - %llu\n", x, total);
}
```
What is printed:
```
20 - 2621448
21 - 5505032
22 - 11534344
23 - 24117256
24 -... |
Because1is anint, 32 bits, so(1 << 27)*27overflows. Use1ull.
Regarding your comment, ifxis auint64_t, then1 << xis still anint, but for the multiplication it would be cast touint64_t, so there'd be no overflow. However, ifx >= 31,1 << xwould be undefined behaviour (as the resulting value cannot be represented by a si... |
I saw the projectsshairportandshairport4wwhich stream music from an iDevice (called AirTunes/AirPlay by Apple) to a computer. I wanted to do the same for my media player. Those two projects are in C/C++/Perl and so I can't port them to C#/VB.
Can anyone explain me how the AirTunes protocol works and how do I implemen... |
This is old but may be a good starting point;
JustPort
First version ofAirfoilwas based onthis
|
I have a very big no say 'x' (10^18) and a number 'z' say 6.
I am trying to know/calculate using a c code that how many numbers in the range 1 to x(10^18) are divisible by z.
for that i am using a simple loop
```
While(x)
{
if(x % z == 0)
{
count++;
}
--x;
}
```
But this code is t... |
```
count = floor(x / z);
```
Obviously, you will need a datatype big enough to holdx.
|
To create a daemon I have read somewhere that in order to close all the open file descriptors we can use the following code:-
```
for (fd = 0; fd < _NFILE; fd++)
close(fd); /* close all file descriptors */
```
I have to define _NFILE as
```
#define _NFILE 3
```
or is it already defined in some include files?
I t... |
_NFILEonly applies to original Unix. The portable way to do this issysconf(_SC_OPEN_MAX)(POSIX).
|
I have a server application which I want to protect from being stopped by any signal which I can ignore. Is there a way to ignore all possible signals at once, without setting them one by one?
|
Yes:
```
#include <signal.h>
sigset_t mask;
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, NULL);
```
This does not exactlyignorethe signals, but blocks them; which in practice is the same effect.
I guess there's no need to mention thatSIGKILLandSIGSTOPcannot be blocked nor ignored in any way.
For more detail... |
I'm calling system command
```
system("tftp -m binary 192.168.1.1 -c get myfile > /dev/null") ;
```
it works fine when tftp server is running but it makes my c program crashed when tftp server is off.
Is there a way to check whether the server is available or not in c source code ?
|
I think your problem lies not in the availability of the server, but the fact that tftp (at least on my Ubuntu box) does not support the command-line arguments you've provided. As a matter of fact, the only command-line argument that it does support is the name of the server.
However, you could try piping commands i... |
This is my code in C :
```
#include<stdio.h>
int main()
{
printf("hello","world");
}
```
When I run this code in my system it showed only hello as output.Why is it not showing hello world as output ? What is the significance of usage of , between hello and world ? Can anyone please explain this to me ?
Thanks in a... |
You are callingprintfwith two arguments. The significance of the comma in that statement is that it is used to separate the two arguments.
The first argument toprintfis a format string that can contain placeholders. The remaining arguments are the values that will be substituted into the format string instead of plac... |
How do I find out if the file is not present or the access rights are not present if the file pointer returns NULL in C? I am writing code in Linux. And the file has no access, but the file is present so how do I return different status that file was not present or file has no access.
|
Check the value oferrnoafter the attempt to open the file:
```
if (NULL == (fp = fopen("myfile.txt", "r")))
{
if (ENOENT != errno)
{
fprintf(stderr, "Failed to open file: %s\n", strerror(errno));
}
else
{
fprintf(stderr, "file does not exist\n");
}
}
```
|
If we assume that i align a block of memory with memalign to 4bytes , would it still be safe to do :
```
unsigned int* source = In.Data;
unsigned int* dest = Out.Data;
int loops = In.Size / 4; //size is the same for both in/out
while (loops)
{
*dest++=*source++;
loops--;
}
```
Instead copying 1byte at a t... |
Yes, it is safe as your blocks are properly aligned.
It would also be safe if get your blocks frommallocas the block of memory returned bymallocis guaranteed to be properly aligned for any purpose.
|
Can any user run inline assembly for current linux kernel or does that require special permission?
|
Inline assembly has nothing to do with the kernel. So the answer is no.
Anyone can write inline assembly and compile it into the program. It isn't any different from compiler generated code.
As for your comment, the answer is no it's not possible because ofmemory protection. As soon as you try to access memory that ... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:C++ beginner, execution window disappears quickly
I am beginner at C programming. But when I compile the programm, a problem occurs. The compiler create a .exe for the program, but when I open it, it appears and disappears in a second.
Th... |
That isn't an error. The program will terminate after finishing the code you programmed. If you want to input something tryscanffor instance.
|
I need to make a program which takes as input on text file and output the same string with one replaced word; the main function will take 3 parameters (wordR, wordS, file). So can anyone help me with a good tip how I can scan the words in c?
|
Go with strtok() or strtok_r() function.
|
How do I pass input into the command line using code. For example, I want to start command line, run the executable and the code will have commands like "start" inside it, and as the file runs those commands will be passed to the command line.
|
Use the system() function under windows, i.e. for example you want to pass a command to the command line like pause, use
```
system("pause");
```
and so on..
It is same as opening cmd and writing pause there and executing it!!
|
I would like to conditionally compile certain parts of code based on Compiler Type is there any macro for that?
Like this:
```
#if defined (COMPILER_TYPE e.g. GCC)
// Compile this
#elif defined (COMPILER_TYPE e.g. Visual Studio C Compiler)
// Else this
#endif
```
Thank you
|
You can check if these macros are defined,__GNUC__for GCC and_MSC_VERfor MSVC.
|
If we assume that i align a block of memory with memalign to 4bytes , would it still be safe to do :
```
unsigned int* source = In.Data;
unsigned int* dest = Out.Data;
int loops = In.Size / 4; //size is the same for both in/out
while (loops)
{
*dest++=*source++;
loops--;
}
```
Instead copying 1byte at a t... |
Yes, it is safe as your blocks are properly aligned.
It would also be safe if get your blocks frommallocas the block of memory returned bymallocis guaranteed to be properly aligned for any purpose.
|
Can any user run inline assembly for current linux kernel or does that require special permission?
|
Inline assembly has nothing to do with the kernel. So the answer is no.
Anyone can write inline assembly and compile it into the program. It isn't any different from compiler generated code.
As for your comment, the answer is no it's not possible because ofmemory protection. As soon as you try to access memory that ... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:C++ beginner, execution window disappears quickly
I am beginner at C programming. But when I compile the programm, a problem occurs. The compiler create a .exe for the program, but when I open it, it appears and disappears in a second.
Th... |
That isn't an error. The program will terminate after finishing the code you programmed. If you want to input something tryscanffor instance.
|
I need to make a program which takes as input on text file and output the same string with one replaced word; the main function will take 3 parameters (wordR, wordS, file). So can anyone help me with a good tip how I can scan the words in c?
|
Go with strtok() or strtok_r() function.
|
How do I pass input into the command line using code. For example, I want to start command line, run the executable and the code will have commands like "start" inside it, and as the file runs those commands will be passed to the command line.
|
Use the system() function under windows, i.e. for example you want to pass a command to the command line like pause, use
```
system("pause");
```
and so on..
It is same as opening cmd and writing pause there and executing it!!
|
I would like to conditionally compile certain parts of code based on Compiler Type is there any macro for that?
Like this:
```
#if defined (COMPILER_TYPE e.g. GCC)
// Compile this
#elif defined (COMPILER_TYPE e.g. Visual Studio C Compiler)
// Else this
#endif
```
Thank you
|
You can check if these macros are defined,__GNUC__for GCC and_MSC_VERfor MSVC.
|
Please help me identify the parts of thistypdefand what each part does and how it can be used:
```
typedef struct my_struct
{
int a;
int b;
int c;
} struct_int, *p_s;
struct_int struct_array[5];
```
What I think they are, pleae correct if wrong:
typedef structis creating a new type.my_struc... |
struct my_structis a name of a type,my_structis a tag name and not a type.
typedefdoes not create types in C, but creates alias names for existing types.
|
I am creating an X11 window for a game, but it seems to only do the expose event once in a while (like maximizing and resizing), is there any way to have X11 call expose constantly? Kind of how glut has glutPostRedisplay()
|
The expose event just tells you that a part of the window which was previously obscured is now visible, so you might need to redraw. There is no restriction that you redrawonlyat expose events.
|
The only way I know how to do this is to convert the file into a C source file with a single byte/char array containing the contents of the resource file in hex.
Is there a better or easier way to do this?
|
Here's a nice trick I use with a gcc-arm cross compiler; including a file through an assembly language file. In this example it's the contents of the filepublic_key.pemI'm including.
pubkey.s
```
.section ".rodata"
.globl pubkey
.type pubkey, STT_OBJECT
pubkey:
.incbin "public_key.pem"
.byte 0
.size pubkey, .-p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.