question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
You know thatWaitForMultipleObjectsfuntction from windows library in c is getting parameter as an array for objects. But in my homework, assistant wants to keep all the threads in a stack not in an array how can i use this function with a stack?
|
You can only call this function with an array. That is not something you have any control over. So you need to use a stack that is capable of exposing its contents as an array. Or an array that is capable of operating like a stack.
However, it is perfectly plausible that the use of a stack container for your threads ... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Is array name a pointer in C?
```
char arr[1024];
arr++ //move arr to arr+1, error!
```
I have heard the the name of a char array is a char pointer, is it?
|
The name of an array decays to an pointer to its first element sometimes.An expression with array type will convert to a pointer anytime an array type is not legal, but a pointer type is.
You cannot do:
```
arr++;
```
Because array is an non modifiable l-value.
|
We have installed GDB on AIX 6.1 (gdb-6.0-1.aix5.1.ppc_AIX.rpm) and I notice that there is no "TUI" (terminal user interface) mode for "interactive source code debugging"?
Is that a known thing for GDB on AIX? Is there another way I can debug my application through the source code like using TUI mode on AIX? Perhaps ... |
Perhaps you need a more recent GDB.GDBis now at version7.3.1and gdb 7.2 has a--tuioption.
Did you try to build GDB from its source code?
|
I am trying to understand when a developer needs to define aCvariable with preceding '_'. What is the reason for it?
For example:
```
uint32_t __xyz_ = 0;
```
|
Maybe this helps, from C99, 7.1.3 ("Reserved Identifiers"):
All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.All identifiers that begin with an underscore are always reserved for use as identifiers
with file scope in both the ordina... |
I'm trying to get all .c files in a directory tree usingnftwwith the following code:
```
static int gf(const char *path, const struct stat *st, int t, struct FTW *ftw) {
if (t != FTW_F)
return 0;
if (strcmp(ext(path), ".c") == 0)
addl(&files, dup(abspath(path)));
return 0;
}
void getfiles... |
What is the return value ofnftw? If it's-1and theerrno isset toEINVALit's quite likely that you're exceeding the value ofOPEN_MAX. Try passing a smaller value as third parameter tonftwand ensure it's smaller thanOPEN_MAX.
|
What API is available to use Facebook from C or C++, and is there a library to do the grunt work for me? (So that you for instance can use Facebook from a desktop program written in C++.)
Thankssehe.
|
Yes you are able to develop Facebook application using C/C++.
Here's a good APIhttp://projects.seligstein.com/facebook/
|
If we want to write a module in C and have to compile it as C++ withg++, is it OK to develop a piece of code in C++ without any own classes, only using "global / static functions" as in C? So, simply said, to code C in C++ (with only few system header changes etc.)
|
Yes. In fact, it's generally a good idea because C++ enforces stronger type-checking than C.
|
In problems like this,
If I were solving a problem in C using recursion where I'd have to find all TRUE or FALSE values for X1, X2 AND X3 satisfying the expression, how would I compare the alignment (whether or not a variable is NOT like X2 in the first clause)against actual true and false values? I could use 0 and 1... |
I'm not entirely sure about your question, but you have 4 boolean values which can be represented by 4 bits. By exploiting the internal respresentation for integrals, you can make that in aforloop to check for all possible combinations:
```
for( int i = 0; i < 16; ++i ) // That's 2^4
{
int x1 = i & 1;
int x2 ... |
I am trying to setup a 'shared' memory location using
```
caddr_t mmap_ptr;
```
But am getting an error. Any help? Thanks!
Also
```
mmap_ptr = mmap((caddr_t) 0, /* Memory Location, 0 lets O/S choose */
MAX_BUFFER_SIZE,/* How many bytes to mmap */
PROT_READ | PROT_WRITE, /* Read and write permissions */
... |
caddr_tis a BSD-ism, and an old one at that. Under Linux (and POSIX),mmapreturns a void pointer.
```
#include <sys/mman.h>
void *mmap (void *addr,
size_t length,
int prot,
int flags,
int fd,
off_t offset);
int munmap (void *addr,
size_t length);
... |
I'm looking for a tool that can statically discover invariants in C programs. I checked outDaikonbut it discovers invariants only dynamically.
Is there a tool available for what I'm looking for? Thanks!
|
SeeThe SLAM project: debugging system software via static analysis. It claims to infer invariants statically, for just what you asked for, the C language. The author, Tom Ball, is widely known for stellar work in program analysis.
|
void (*(*f[])())()definesfas an array of unspecified size, of pointers to functions that return pointers to functions that returnvoid.
What does this means in a very very very simple explanation
|
Imagine you have a function - let's call ita()- that returns void.
a()has an address in memory.
Now imagine you have a functionpa()that returns a pointer toa(), i.e.pa()returns the address ofa().
Now, you don't have just one pair of functions like this but several:
b()returns void,pb()returns the address ofb()c()r... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Objective C for Windows
I know there are several posts about this but I don't feel that any of them fit my scenario. I have been asked to learn Objective-C and write a report over its differences from C/C++ along with develop a presentati... |
TryGnuStepwhich has an IDE called ProjectCenter. It is aimed at reproducing the NextStep/OpenStep programming experience on multiple platforms, including Windows.
|
If I have an array and want to assign pointer to id'th element of the array are these equivalent?
```
int* hello = &Array[id];
int* hello = &(Array[id]);
```
|
No, parentheses are not necessary, and yes these two are equivalent. Array subscripthas higher precedencethan Address operator.
|
I am tasked with writing a simple shell along with these three commands: "nl", "head", "chroot"(with no parameters). I've written nl.c and head.c but I don't know where to start with the chroot.c. I've read what chroot does, googled some documentation and to me as a beginner this is complicated.
Any advice on this m... |
chrootwithout an argument just prints an error message. You can useprintffor that.
Otherwise, chroot callschroot,chdir("/")and then executes a shell with one of theexec*functions.
|
I am trying to understand when a developer needs to define aCvariable with preceding '_'. What is the reason for it?
For example:
```
uint32_t __xyz_ = 0;
```
|
Maybe this helps, from C99, 7.1.3 ("Reserved Identifiers"):
All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.All identifiers that begin with an underscore are always reserved for use as identifiers
with file scope in both the ordina... |
I'm trying to get all .c files in a directory tree usingnftwwith the following code:
```
static int gf(const char *path, const struct stat *st, int t, struct FTW *ftw) {
if (t != FTW_F)
return 0;
if (strcmp(ext(path), ".c") == 0)
addl(&files, dup(abspath(path)));
return 0;
}
void getfiles... |
What is the return value ofnftw? If it's-1and theerrno isset toEINVALit's quite likely that you're exceeding the value ofOPEN_MAX. Try passing a smaller value as third parameter tonftwand ensure it's smaller thanOPEN_MAX.
|
What API is available to use Facebook from C or C++, and is there a library to do the grunt work for me? (So that you for instance can use Facebook from a desktop program written in C++.)
Thankssehe.
|
Yes you are able to develop Facebook application using C/C++.
Here's a good APIhttp://projects.seligstein.com/facebook/
|
If we want to write a module in C and have to compile it as C++ withg++, is it OK to develop a piece of code in C++ without any own classes, only using "global / static functions" as in C? So, simply said, to code C in C++ (with only few system header changes etc.)
|
Yes. In fact, it's generally a good idea because C++ enforces stronger type-checking than C.
|
In problems like this,
If I were solving a problem in C using recursion where I'd have to find all TRUE or FALSE values for X1, X2 AND X3 satisfying the expression, how would I compare the alignment (whether or not a variable is NOT like X2 in the first clause)against actual true and false values? I could use 0 and 1... |
I'm not entirely sure about your question, but you have 4 boolean values which can be represented by 4 bits. By exploiting the internal respresentation for integrals, you can make that in aforloop to check for all possible combinations:
```
for( int i = 0; i < 16; ++i ) // That's 2^4
{
int x1 = i & 1;
int x2 ... |
I am trying to setup a 'shared' memory location using
```
caddr_t mmap_ptr;
```
But am getting an error. Any help? Thanks!
Also
```
mmap_ptr = mmap((caddr_t) 0, /* Memory Location, 0 lets O/S choose */
MAX_BUFFER_SIZE,/* How many bytes to mmap */
PROT_READ | PROT_WRITE, /* Read and write permissions */
... |
caddr_tis a BSD-ism, and an old one at that. Under Linux (and POSIX),mmapreturns a void pointer.
```
#include <sys/mman.h>
void *mmap (void *addr,
size_t length,
int prot,
int flags,
int fd,
off_t offset);
int munmap (void *addr,
size_t length);
... |
I'm looking for a tool that can statically discover invariants in C programs. I checked outDaikonbut it discovers invariants only dynamically.
Is there a tool available for what I'm looking for? Thanks!
|
SeeThe SLAM project: debugging system software via static analysis. It claims to infer invariants statically, for just what you asked for, the C language. The author, Tom Ball, is widely known for stellar work in program analysis.
|
void (*(*f[])())()definesfas an array of unspecified size, of pointers to functions that return pointers to functions that returnvoid.
What does this means in a very very very simple explanation
|
Imagine you have a function - let's call ita()- that returns void.
a()has an address in memory.
Now imagine you have a functionpa()that returns a pointer toa(), i.e.pa()returns the address ofa().
Now, you don't have just one pair of functions like this but several:
b()returns void,pb()returns the address ofb()c()r... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Objective C for Windows
I know there are several posts about this but I don't feel that any of them fit my scenario. I have been asked to learn Objective-C and write a report over its differences from C/C++ along with develop a presentati... |
TryGnuStepwhich has an IDE called ProjectCenter. It is aimed at reproducing the NextStep/OpenStep programming experience on multiple platforms, including Windows.
|
If I have an array and want to assign pointer to id'th element of the array are these equivalent?
```
int* hello = &Array[id];
int* hello = &(Array[id]);
```
|
No, parentheses are not necessary, and yes these two are equivalent. Array subscripthas higher precedencethan Address operator.
|
If I want to bit shift the integer5by 3, soint a = 5; int b = a << 3;, the result would be40in decimal as5is101and40is101000.
What if however, I have the followingchararray:00000 00101and by bit shifting three to the left, I want the result to be00001 01000. So I want to accommodate for the0's padding. What do you ... |
If you meant an actualchararray, you can usememmove()andmemset():
```
char str[] = "0000000101";
int shift = 3;
int length = strlen(str);
memmove(str, str + shift,length - shift);
memset(str + length - shift,'0',shift);
// Result:
// "0000101000"
```
|
theBeej's Guide to Network Programmingexplains the accept() as follows:
What's going to happen is this: someone far far away will try to connect() to your machine on a port that you are listen()ing on. Their connection will be queued up waiting to be accept()ed. You call accept() and you tell it to get the pending co... |
Pass the acceptedSOCKETtogetsockname()to retreive its local IP/Port, and togetpeername()to retreive its remote IP/Port.
|
I made a distributed shell program that has a client and server. The client sends a command request to the server and the server executes that command locally and is supposed to output the results of that command to the client. I am having trouble figuring out how to redirect stdout/stderr to the client. I use execvp ... |
You just need to usedup2()to duplicate the socket's file descriptor onto the stderr and stdout file descriptors. It's pretty much the same thing as redirecting to pipes.
```
cpid = fork();
if (cpid == 0) {
dup2(sockfd, STDOUT_FILENO);
dup2(sockfd, STDERR_FILENO);
execvp(...);
/*... etc. etc. */
```
|
This question already has answers here:Return value range of the main function(7 answers)Closed6 years ago.
I have a C program which returns an integer value. I was surprised to find out that when examining the return value from the shell prompt I get the value modulo 256.
```
/* prog.c */
int main(...) { return 257... |
When a program exits, it can return to the parent process a small amount of information about the cause of termination, using the exit status. This is a value between 0 and 255 that the exiting process passes as an argument to exit.
http://www.gnu.org/s/hello/manual/libc/Exit-Status.html
alternatively:
http://en.wi... |
I have a structure to represent strings in memory looking like this:
```
typedef struct {
size_t l;
char *s;
} str_t;
```
I believe using size_t makes sense for specifying the length of a char string. I'd also like to print this string usingprintf("%.*s\n", str.l, str.s). However, the*precision expects ani... |
```
printf("%.*s\n", (int)str.l, str.s)
// ^^^^^ use a type cast
```
Edit
OK, I didn't read the question properly. You don't want to use a type cast, but I think, in this case: tough.
Either that or simply use fwrite
```
fwrite(str.s, str.l, 1, stdout);
printf("\n");
```
|
I need to send a variable of type mode_t through a socket. How do i do it? I mean I could convert it to a string using snprintf()..but is it ok?
Thanks
|
mode_tis an integer.
Indeed, having textual protocols on sockets is practically useful (easier to debug and to evolve).
|
I am working on a project where I have to define a new processor hardware architecture.
I need a compiler to generate assembly code for this target (it has its own instruction set).
Programs for this processor will be written in C.
My idea to do this is to parse the C code and generate an Abstract Syntax Tree (AST),... |
Take a look atLLVM.
It consists of seperate modules which can be created individually and communicate through an intermediate language. In you're case you'll have to write the assembly back-end and reuse other people's C compiler.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
There's a PerlNet::EPPpackage on CPAN that implements low-level and high-level EPP clients.
|
I have been googling a bit, but did not find what i was looking for.
I want to start a process with arguments(in C) using the win32 API.
Does anybody have some examples or pointers which i can use/see?
|
The win32CreateProcessfunction does what you need.
|
so usually this typedef makes code cleaner:
```
typedef struct {
int x;
} X;
```
What if I want to have a list that needs pointers in the struct how do I reference them?
```
struct X{
int x;
struct X * next;
}
```
This works, but now I don't have a typedef for this?
|
You can do the typedef just like for any other structure:
```
typedef struct X {
int x;
struct X * next;
} X;
```
Or you can do the typedef before the structure:
```
typedef struct X X;
struct X {
int x;
X * next;
};
```
In the first case above, we have to reference thestructinside itself, since th... |
In a "C" code I would like to list all the files in a directory and delete the oldest one. How do I do that?
Can I use popen for that or we have any other solutions??
Thanks,
|
From the tag, I assume that you want to do this in a POSIX compliant system. In this case a code snippet for listing files in a folder would look like this:
```
#include <dirent.h>
#include <sys/types.h>
#include <stdio.h>
DIR* dp;
struct dirent* ep;
char* path = "/home/mydir";
dp = opendir(path);
if (dp != NULL)
... |
Am trying to guess-timate how much stack to allocate on per thread basis.
Found hints that suggest program should scribble a known pattern (ex:0xEF) in memory, to get upper/lower bounds of stack.
Can someone provide quick C program to do so? Is this truly the way to go?
Any other suggestions?
Thank you for assistin... |
If you have complete control of your program( code ), it's a nonsense trying to find the size becauseyouwould be the one who's telling the OS to allocate the specific amount of stack size when you're creating a thread usingCreateThreadorpthread_create. However, if you don't, depending on your OS, you can either callpt... |
I'm relatively inexperienced to C and C++ programming, but if it is possible to load and call symbols from shared libraries (as I understand are compiled and linked much like binaries), is it also possible to load symbols from another [executable] binary during run time?
I'm particularly interested in doing this with... |
If you are programming on Windows
LoadLibraryto load the shared library into current processGetProcAddressto get the address of the function that you want to call
On unix like Oses. something likedlopenanddlsym
An example of dlsymlook for 6.6. File demo_dynamic.c
|
I want to make an array static and also want to reference it in the other translation unit. Then I define it asstatic int array[100] = {...}, and declare it in other translation unit asextern int array[]. But the compiler tells me that the storage class of static and extern conflict with each other, how could I pass i... |
Remove thestatic. Just have theint array[100] = {...};in one .cpp file, and haveextern int array[100];in the header file.
staticin this context means that other translation units can't see it. That obviously conflicts with theexterndirective.
|
This question already has answers here:Changing working directories in Linux shell in a C program(2 answers)Closed8 years ago.
I'm having a problem with chdir() in my C program - only when running on Linux (works fine on Mac). I've stripped down my code.
Something like this works fine:
```
chdir("/Documents");
```
... |
Since you are readinghome_directoryfrom a file, have you forgotten to remove a trailing newline and any other spurious characters before you use it as a parameter tochdir?
|
I've got a lot of requests that avoid caching because all of their list permutations are listed, ie:
```
http://.....&var=a,b,c
http://.....&var=a,c,b
http://.....&var=b,a,c
http://.....&var=b,c,a
http://.....&var=c,a,b
http://.....&var=c,b,a
```
Is there a clever way to hash these to the same value? Is the easiest ... |
I've written a module for Varnish which reorders the query parameters alphabetically.
Blog post with some explanation:http://cyberroadie.wordpress.com/2012/01/05/varnish-reordering-query-string/
Code can be found here:https://github.com/cyberroadie/varnish-urlsort
|
The file is named with .cu extension. It is complaining about my device function definitions... What other information do you need?
```
d.cu(96): error C2054: expected '(' to follow '__device__'
d.cu(96): error C2085: 'distance' : not in formal parameter list
d.cu(96): error C2143: syntax error : missing ';' before ... |
Found the problem: For some reason (a while back) I had included the.cufile in the.cfile. Don't know why/how maybe I was drunk. So this was an ID:107 error.
|
I'm new to valgrind and I was wondering if I can invoke valgrind in such a way that it causes my mallocs to fail for lack of available memory.
Something like:
$valgrind helloworld --heapsize=10
|
No, valgrind tries to not interfere with the operation of your program. You should be able to useulimit -dto restrict the amount of memory available to your program, though, independent of valgrind.
|
I want to do a function to get a pointer on a struct.
I done this :
```
void *getTokenList() {
static t_token *list;
return &list;
}
```
At compilation, I have this warning :warning: variable ‘list’ set but not used [-Wunused-but-set-variable]
Is it possible to disable this warning for this function (only ... |
You can use this to shut it off:
```
(void)list;
```
Alternatively and less portably you can use__attribute__((unused)).
|
Can this cast fail and when?
```
long x=-1;
long y = (long)(void*)x;
assert(x==y);
```
More specifically, how to detect if the above cast is OK at compile time.
|
A more portable way (on the C99 standard variant) is to#include <stdint.h>and then cast pointers tointptr_t(and back). This integer type is guaranteed to be the size of a pointer.
|
here's a really simple C program, and I just can't figure out why it crashes:
```
int main () {
size_t argc = 2;
char **argv = malloc(argc * sizeof(char *));
for (int i = 0; i < 20; i++) {
if (i >= argc) {
argc *= 2;
argv = realloc(argv, argc);
}
argv[i] = ... |
```
argv = realloc(argv, argc);
```
The size is wrong; you wantargc * sizeof(*argv)instead.
|
I want to get both the beginning and ending line numbers of all functions in a file in C. Does any one know that whether there is a easy-to-use tool in Linux for this purpose?
|
```
$ ctags -x --c-kinds=f filename.c
```
This only gives the starting line of each function, but perhaps that is good enough.
If the code was written using fairly common conventions, the function should end with a single line containing}in the first column, so it is fairly easy to get the last line given the first:... |
I wrote a timer following some examples from the web:
```
void fun(int i)
{
struct itimerval to;
//do something
signal(SIGALRM, fun);
to.it_interval.tv_sec = 0;
to.it_interval.tv_usec = 0;
to.it_value.tv_sec = 60;
to.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &to, 0);
}
```
in the m... |
You probably want to use anevent loop, so that your program sleeps and consumes no CPU when there is nothing to do. An easy way would be to uselibevent.
Otherwise, useselect()orpselect().
|
I'm looking for a solution to begin my journey in the ARM world's, i want to use the C as my main language and i'd like to create a basic program using the standard I/O library for this environment.
Also, there is an emulator or something like that which runs on an X86 based PC? I can try some operative systems on t... |
If you don't have any specific hardware platform in mind already, thenQEMUmight be working for the emulation part.
|
Please highlight the difference between the following function declarations:
void (*p) (void *a[], int n)void *(*p[]) (void *a, int n)
|
void (*p) (void *a[], int n)definesa pointer to a function that takes avoid*array and anintas parametervoid *(*p[]) (void *a, int n)definesan array of pointers to functions that return avoid*, and take avoid*and anintas parameter.
|
```
#include<stdio.h>
#define A(int x) printf("%d\n",x)
#define AS(A) A(20)
typedef struct{
int *m;
int n;
int k;
}st;
//static st sb[10] = {AS(A)}
int main()
{
AS(A);
return 0;
}
```
I'm getting an error as below .
```
Line 14: error: macro parameters must be comma-separated
```
Please help.
|
This has nothing to do with nesting macros. The problem is
```
#define A(int x) printf("%d\n",x)
```
you must remove theintpart. Like this:
```
#define A(x) printf("%d\n",x)
```
If you leave theint, the preprocessor interprets it as another parameter, that's why it tells you
```
Line 14: error: macro parameters... |
Can someone help me to understand the output of these program.
```
int* fun1();
void fun2();
int main()
{
int *p=fun1();
fun2();
printf("%d\n",*p);
return 0;
}
int* fun1()
{
int i=10;
return &i;
}
void fun2()
{
int a=100;
printf("%d\n",a);
}
```
It is 100 100 on windows and 100 10... |
Returning a pointer to a stack-allocated variable that went out of scope and using that pointer is undefined behavior, pure and simple.
But I'm guessing the answer "anything can happen" won't cut it for you.
What happens is that on *nix the memory isn't recycled so it's not overwritten yet, and on win it is. But tha... |
My MacBookPro, running BootCamp, has an Intel i7-640M processor, which has 2 cores. Like all the other i7 chips, each core is hyperthreaded, so you can have up to 4 threads. Using Visual Studio 2010 c/c++ to determine these:
```
coresAvailable = omp_get_num_procs ( );
threadsAvailable = omp_get_max_th... |
omp_get_num_procsreturns the number of CPUs the OS reports, and since a hyperthreaded core reports itself as 2 CPUs, a dual-core hyperthreaded chip will report itself as 4 processors.
omp_get_max_threadsreturns the most threads that will be used in a parallel region of code, so it makes sense that the most threads it... |
In C that's legal and will compile:
```
char names[5] = "Hello";
```
but this one is not:
```
char names[5];
names = "Hello";
```
How do I put assignment in array of characters word "Hello" ? Can I do that withoutstrcpy?
|
You cannot. In Can array is not an lvalueso you can't assign to it.
The only ways to do it:
Use a copying function (likememcpyorstrcpyfor example)Assign all the elements one at a time (eew)Use a pointer instead of an array. There is some folk knowledge that "an array is just a pointer".It'snottrue(yes, those are 3 l... |
I have 2 programs (written by me). The first one called "MAN" will invoke "D" (the second one) which is a process that will run in background until terminated in some ways.
I would like to terminate MAN without terminating D.
I try to terminate MAN using ctrl + c and it terminates man correctly (I intercepted the si... |
The child process (D) should disassociate from the controlling terminal by callingsetsid(2).
|
My head is getting bad trying to find a solution for this assignment because my ideas didn't work...
I have to interlace twocharstrings using pointers. See the following example (this example is not code):
```
char s1 = "My House Black"
char s2 = "Are very near"
```
Result:"MAyr eH ovuesrey Bnleaacrk"
How can I d... |
Try:
```
int total = strlen(char1) + strlen(char2);
int i1 = 0, i2 = 0;
for(i = 0; i < total; i++)
{
if(i % 2 == 0)
{
result[i] = char1[i1];
i1++;
}
else
{
result[i] = char2[i2];
i2++;
}
}
```
|
I'm trying to create a window control where you can toggle the state from hidden to shown, that hides/shows some stuff when not hidden.Something like this:Is there any built in control to handle this? Or do I have to implement it myself?
And what would be the best method to implement something like this?
Thanks in ad... |
You'll have to implement it yourself, but it's just a button with an icon on it that changes when you click it! Should be a breeze :-) Another way to do it is have 2 buttons in the same position and they hide one another when clicked - can be simpler to do.
|
This may sounds a little trivial but I really dont get it.
TheProjectView(Left side of the screen) displays all files of your project. You are able to create and delete files but you can't move files to different folders (I'm familar with MSVC).
Is there a way of moving source files in Kdevelop?
|
I wonder the same thing-- I always manually create a new 'src' folder and manually move the source files into the new folder. Then I edit the cmake file to compile the sources in the src folder.
|
I am programming a small unix shell written in c. I want it to do only some basic commands for now. e.g. ls, pwd, ch
My problem is how do I set the Home directory and Path directory? I want to read the configuration from a text file so it can be easily changed whenever.
I am going to be using execv() to call unix fu... |
They are all simply environment variables that you manipulate e. g. throughsetenv(3)(runman 3 setenvfor details). The variables areHOMEandPATH. See alsoman 7 environ.
Note that setting/changing an environment variable only influences thecurrentprocess and all processes forked from itafterthe setting/changing (unlike ... |
when we use #include < stdio.h > in linux platform, the compiler will search the stdio.h in /usr/include. How to change the path of using #include<>?
thank you.
I asked the question because of this : when I use the C standard function isdigit(), if "#include< ctype.h >" is not added, the program generates a warning b... |
```
-I dir
Add the directory dir to the list of directories to be
searched for header files. Directories named by -I are
searched before the standard system include directories.
```
|
Im building an iphone app for video analyzing and i need to know the exact amount of frames in the movie clip.
I got the frame rate and the duration and for some reason i get 2880 frames but i know that the movie clip has actually 2840.
how can i get an exact number of frames?
|
Well this will depend on the video format.
If it's raw video then PAL and SECAM dictate 25 frames per secon(fps), NTSC 29.97 actual film is 24fps. Is it interlaced or progressive scan?
Is it already compressed and hence uses an approximation of frame numbers?
edit
Ah so you're video is in H.264/MPEG4 standard with... |
When programming in C, is it possible to set aconstwith a value of a user-input?
If so, how?
|
Why not?
```
void some_function(int user_input)
{
const int const_user_input = user_input;
...
return;
}
int main (void)
{
int user_input;
scanf("%d", &user_input);
some_function(user_input);
return 0;
}
```
|
I have a structure defined as
```
struct xyz {
char *str;
int x;
int y;
};
```
Which I am getting as input parameter to the executable from some other program1.(other program didexecveof theprogram2with input parameter as this structure).
I wish to know, can I do the typecast of this input parameter as... |
You can't pass arbitrary data to a command in that way. You'll have to serialize it to a string, or perform some IPC (e.g. through pipe/socket).
The reason for this is that the strings are null terminated. Yourchar*member will have a\0on the end, and even if it doesn't, any int less than 16843009 (0x01010101) will ha... |
As I understand assigning arrays is a Memory copy operation, will this work?
```
struct x{
int i;
int j;
} A[5];
struct y{
int i;
int j;
struct y * next;
} B[5];
```
Then can I do:
```
B[0] = A[0];
```
and expect i and j copied over for index [0]?
EDIT: What I really want to know is how to ma... |
My suggestion is to embedstruct xinstruct y, like so:
```
struct x{
int i;
int j;
} A[5];
struct y{
struct x x;
struct y * next;
} B[5];
```
That way, it's easy to assign, and the memory layout of the firstsizeof(struct x)bytes of both structs are guaranteed to be the same, even in C89.
You can now... |
```
static struct fuse_oprations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
```
I don't understand this C syntax well. I can't even search because I don't know the syntax's name. What's that?
|
This is a C99 feature that allows you to set specific fields of the struct by name in an initializer. Before this, the initializer needed to contain just the values, for all fields, in order -- which still works, of course.
So for the following struct:
```
struct demo_s {
int first;
int second;
int ... |
Using Valgrind or any other debugger in Linux, how can one see places where a variable is modified. I am using gcc. Note that I don't want to step into the code using gdb. I just want to run the program and have the debugger report me in the end, places where the variable is modified in the code.
|
Hm, thinking about it it's notexactduplicate ofCan I set a breakpoint on 'memory access' in GDB?, because it asks a little bit more. So:
Use gdbFind the address you want to watch (hardware watchpoints only work for watchingaddress, so you have to run it to the point where the variable or object are instantiated, take... |
I'm currently learning C through "Learning C the Hard Way"
I am a bit confused in some sample code as to why some arrays must be initialized with a pointer.
```
int ages[] = {23, 43, 12, 89, 2};
char *names[] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
```
In the above example, why does the name... |
A string literal such as"Alan"is of typechar[5], and to point to the start of a string you use achar *."Alan"itself is made up of:
```
{ 'A', 'L', 'A', 'N', '\0' }
```
As you can see it's made up of multiplechars. Thischar *pointsto the start of the string, the letter'A'.
Since you want anarrayof thesestrings, you ... |
Ok, here is the piece of code where I found it strange:
```
printf("di consumerthread : mulai isi data, itmsg = %d\n",itmsg);
msgq->data[itmsg]=rec_data;
printf("di consumerthread : selesai isi data, itmsg = %d\n",itmsg);
```
What I found strange is the output:
```
di consumerthread :... |
Perhaps msgq->data[itmsg] is an alias for itmsg. It could happen. If you inherited this code run a bounds checker on it.
|
The above program i have typed in linux. It basically has to connect a client and server in separate terminals. But when i run them in the correct order, i.e
Compile server -> run serverCompile client - > run client
The terminals just dont do anything. It doesnt even print the"Trying to connect"part of the firstpr... |
You made deadlock. Server wait open("fifo1",O_RDONLY) and client wait open("fifo2",O_RDONLY).
Edit client.c:
```
int writefd = open("fifo1",O_WRONLY);
int readfd = open("fifo2",O_RDONLY);
```
|
I declare the following array:
```
char* array [2] = { "One", "Two"};
```
I pass this array to a function. How can I find the length of this array in the function?
|
You can't find the length of an array after you pass it to a function without extra effort. You'll need to:
Use a container that stores the size, such asvector(recommended).Pass the size along with it. This will probably require the least modification to your existing code and be the quickest fix.Use a sentinel value... |
Hi I wanted to learn using MPI in C. I am using Codeblocks on Windows 7
I ran this program:
```
#include <stdio.h>
#include <mpi.h>
void main (int argc, char *argv[]) {
int err;
err = MPI_Init(&argc, &argv);
printf("Hello world!\n");
err = MPI_Finalize();
}
```
but for some reason, i get an error at "m... |
First, install an implementation of MPI. In the past I've used MPICH, but there are other implementations available. I know another is LAM/MPI. Check out the Wikipedia page for additional information at:
http://en.wikipedia.org/wiki/Message_Passing_Interface#Implementations
After you install MPI, use the sample c... |
I have to write a simple piece of code that acts on a file; my software have to scans the file searching for a pattern with a regex (I never had to use the regex in C, but generally speaking, I know them) and it always have to pretends to decode and encode in UTF8.
The file has also a UNIX file format and it could be... |
I use thepcrelibrary for using regex in C/C++. Originally because we were porting perl code to C, and its a good simple library with UTF-8 support.http://www.pcre.org/
And when we have to deal with non UTF-8 encodings we use theiconvlibrary to convert to UTF-8 first.http://www.gnu.org/s/libiconv/
|
```
char* x = malloc(512);
memset(x, 0, 513);
free(x);
```
Why is this crashing the program? It is sayingfree(): invalid pointer: 0x0000000000614010That doesn't make any sense, if anything it should be ruining some other random part of the program because it writes into undefined memory space.
|
You've caused undefined behaviour, soanythingcan happen. In this case, it's possible that yourfree()implementation might be checking for some information in the space immediately after your buffer. Since you overwrote it, it's game over.
|
I'm trying to detect the input of fgets from stdin as empty (when I press enter without entering in anything). Here is my program:
```
int main()
{
char input[1000];
printf("Enter :");
fgets(input, 1000, stdin);
input[strlen(input) - 1] = '\0';
if(input != '\0'){
printf("hi");
}
... |
I think this is the most readable (but not performant):
```
if (strlen(input) != 0) {
printf("hi");
}
```
But for the sake of teaching here is your style, but then fixed:
```
if (input[0] != '\0') {
printf("hi");
}
```
Whyinput[0]? Becauseinputacts like a pointer to the first element of the array if you co... |
I`m just wondering....
If it was the case that I was thinking in creating different reseases for each custumer that I sold my software, could I check each one with MD5 just changing a comment inside the source code and recompiling? I mean, will a ##comment inside a C++, C# or java code change the binnary MD5?
|
Comments are removed early in (or before) the compilation process, so inserting a comment will not change the hash of the compiled binary.
The only exception (that I can think of) is if your binaries include line numbers, which can change based on comments. Typically this happens when you're compiling in debug mode, ... |
Canepoll(on Linux) be somehow useful for regular files? I know it's primarily used with sockets but just wonder.
|
Not really.epollonly makes sense for file descriptors which would normally exhibit blocking behavior on read/write, like pipes and sockets. Normal file descriptors will always either return a result or end-of-file more or less immediately, soepollwouldn't do anything useful for them.
|
I have an array that's declared as char buff[8]. That should only be 8 bytes, but looking as the assembly and testing the code, I get a segmentation fault when I input something larger than 32 characters into that buff, whereas I would expect it to be for larger than 8 characters. Why is this?
|
What you're saying is not a contradiction:
You have space for 8 characters.You get an error when you input more than 32 characters.
So what?
The point is that nobody told you that you would be guaranteed to get an error if you input more than 8 characters. That's simplyundefined behaviour, and anything can (and wil... |
What is the meaning of the>>=symbol in C or C++? Does it have any particular name?
I have thisforloop in some CUDA code which looks like this
```
for(int offset=blockDim.x; offset>0; offset >>=1)
{
//Some code
}
```
How does the offset variable get modfied with the>>=operator?
|
The>>=symbol is the assignment form of right-shift, that isx >>= y;is short forx = x >> y;(unless overloaded to mean something different).
Right shifting by 1 is equivalent to divide by 2. That code looks like someone doesn't trust the compiler to do the most basic optimizations, and should be equivalent to:
```
for... |
My MacBookPro, running BootCamp, has an Intel i7-640M processor, which has 2 cores. Like all the other i7 chips, each core is hyperthreaded, so you can have up to 4 threads. Using Visual Studio 2010 c/c++ to determine these:
```
coresAvailable = omp_get_num_procs ( );
threadsAvailable = omp_get_max_th... |
omp_get_num_procsreturns the number of CPUs the OS reports, and since a hyperthreaded core reports itself as 2 CPUs, a dual-core hyperthreaded chip will report itself as 4 processors.
omp_get_max_threadsreturns the most threads that will be used in a parallel region of code, so it makes sense that the most threads it... |
In C that's legal and will compile:
```
char names[5] = "Hello";
```
but this one is not:
```
char names[5];
names = "Hello";
```
How do I put assignment in array of characters word "Hello" ? Can I do that withoutstrcpy?
|
You cannot. In Can array is not an lvalueso you can't assign to it.
The only ways to do it:
Use a copying function (likememcpyorstrcpyfor example)Assign all the elements one at a time (eew)Use a pointer instead of an array. There is some folk knowledge that "an array is just a pointer".It'snottrue(yes, those are 3 l... |
I have 2 programs (written by me). The first one called "MAN" will invoke "D" (the second one) which is a process that will run in background until terminated in some ways.
I would like to terminate MAN without terminating D.
I try to terminate MAN using ctrl + c and it terminates man correctly (I intercepted the si... |
The child process (D) should disassociate from the controlling terminal by callingsetsid(2).
|
My head is getting bad trying to find a solution for this assignment because my ideas didn't work...
I have to interlace twocharstrings using pointers. See the following example (this example is not code):
```
char s1 = "My House Black"
char s2 = "Are very near"
```
Result:"MAyr eH ovuesrey Bnleaacrk"
How can I d... |
Try:
```
int total = strlen(char1) + strlen(char2);
int i1 = 0, i2 = 0;
for(i = 0; i < total; i++)
{
if(i % 2 == 0)
{
result[i] = char1[i1];
i1++;
}
else
{
result[i] = char2[i2];
i2++;
}
}
```
|
I'm trying to create a window control where you can toggle the state from hidden to shown, that hides/shows some stuff when not hidden.Something like this:Is there any built in control to handle this? Or do I have to implement it myself?
And what would be the best method to implement something like this?
Thanks in ad... |
You'll have to implement it yourself, but it's just a button with an icon on it that changes when you click it! Should be a breeze :-) Another way to do it is have 2 buttons in the same position and they hide one another when clicked - can be simpler to do.
|
This may sounds a little trivial but I really dont get it.
TheProjectView(Left side of the screen) displays all files of your project. You are able to create and delete files but you can't move files to different folders (I'm familar with MSVC).
Is there a way of moving source files in Kdevelop?
|
I wonder the same thing-- I always manually create a new 'src' folder and manually move the source files into the new folder. Then I edit the cmake file to compile the sources in the src folder.
|
I am programming a small unix shell written in c. I want it to do only some basic commands for now. e.g. ls, pwd, ch
My problem is how do I set the Home directory and Path directory? I want to read the configuration from a text file so it can be easily changed whenever.
I am going to be using execv() to call unix fu... |
They are all simply environment variables that you manipulate e. g. throughsetenv(3)(runman 3 setenvfor details). The variables areHOMEandPATH. See alsoman 7 environ.
Note that setting/changing an environment variable only influences thecurrentprocess and all processes forked from itafterthe setting/changing (unlike ... |
when we use #include < stdio.h > in linux platform, the compiler will search the stdio.h in /usr/include. How to change the path of using #include<>?
thank you.
I asked the question because of this : when I use the C standard function isdigit(), if "#include< ctype.h >" is not added, the program generates a warning b... |
```
-I dir
Add the directory dir to the list of directories to be
searched for header files. Directories named by -I are
searched before the standard system include directories.
```
|
Im building an iphone app for video analyzing and i need to know the exact amount of frames in the movie clip.
I got the frame rate and the duration and for some reason i get 2880 frames but i know that the movie clip has actually 2840.
how can i get an exact number of frames?
|
Well this will depend on the video format.
If it's raw video then PAL and SECAM dictate 25 frames per secon(fps), NTSC 29.97 actual film is 24fps. Is it interlaced or progressive scan?
Is it already compressed and hence uses an approximation of frame numbers?
edit
Ah so you're video is in H.264/MPEG4 standard with... |
When programming in C, is it possible to set aconstwith a value of a user-input?
If so, how?
|
Why not?
```
void some_function(int user_input)
{
const int const_user_input = user_input;
...
return;
}
int main (void)
{
int user_input;
scanf("%d", &user_input);
some_function(user_input);
return 0;
}
```
|
I have a structure defined as
```
struct xyz {
char *str;
int x;
int y;
};
```
Which I am getting as input parameter to the executable from some other program1.(other program didexecveof theprogram2with input parameter as this structure).
I wish to know, can I do the typecast of this input parameter as... |
You can't pass arbitrary data to a command in that way. You'll have to serialize it to a string, or perform some IPC (e.g. through pipe/socket).
The reason for this is that the strings are null terminated. Yourchar*member will have a\0on the end, and even if it doesn't, any int less than 16843009 (0x01010101) will ha... |
As I understand assigning arrays is a Memory copy operation, will this work?
```
struct x{
int i;
int j;
} A[5];
struct y{
int i;
int j;
struct y * next;
} B[5];
```
Then can I do:
```
B[0] = A[0];
```
and expect i and j copied over for index [0]?
EDIT: What I really want to know is how to ma... |
My suggestion is to embedstruct xinstruct y, like so:
```
struct x{
int i;
int j;
} A[5];
struct y{
struct x x;
struct y * next;
} B[5];
```
That way, it's easy to assign, and the memory layout of the firstsizeof(struct x)bytes of both structs are guaranteed to be the same, even in C89.
You can now... |
```
static struct fuse_oprations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
```
I don't understand this C syntax well. I can't even search because I don't know the syntax's name. What's that?
|
This is a C99 feature that allows you to set specific fields of the struct by name in an initializer. Before this, the initializer needed to contain just the values, for all fields, in order -- which still works, of course.
So for the following struct:
```
struct demo_s {
int first;
int second;
int ... |
Using Valgrind or any other debugger in Linux, how can one see places where a variable is modified. I am using gcc. Note that I don't want to step into the code using gdb. I just want to run the program and have the debugger report me in the end, places where the variable is modified in the code.
|
Hm, thinking about it it's notexactduplicate ofCan I set a breakpoint on 'memory access' in GDB?, because it asks a little bit more. So:
Use gdbFind the address you want to watch (hardware watchpoints only work for watchingaddress, so you have to run it to the point where the variable or object are instantiated, take... |
I'm currently learning C through "Learning C the Hard Way"
I am a bit confused in some sample code as to why some arrays must be initialized with a pointer.
```
int ages[] = {23, 43, 12, 89, 2};
char *names[] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
```
In the above example, why does the name... |
A string literal such as"Alan"is of typechar[5], and to point to the start of a string you use achar *."Alan"itself is made up of:
```
{ 'A', 'L', 'A', 'N', '\0' }
```
As you can see it's made up of multiplechars. Thischar *pointsto the start of the string, the letter'A'.
Since you want anarrayof thesestrings, you ... |
Ok, here is the piece of code where I found it strange:
```
printf("di consumerthread : mulai isi data, itmsg = %d\n",itmsg);
msgq->data[itmsg]=rec_data;
printf("di consumerthread : selesai isi data, itmsg = %d\n",itmsg);
```
What I found strange is the output:
```
di consumerthread :... |
Perhaps msgq->data[itmsg] is an alias for itmsg. It could happen. If you inherited this code run a bounds checker on it.
|
The above program i have typed in linux. It basically has to connect a client and server in separate terminals. But when i run them in the correct order, i.e
Compile server -> run serverCompile client - > run client
The terminals just dont do anything. It doesnt even print the"Trying to connect"part of the firstpr... |
You made deadlock. Server wait open("fifo1",O_RDONLY) and client wait open("fifo2",O_RDONLY).
Edit client.c:
```
int writefd = open("fifo1",O_WRONLY);
int readfd = open("fifo2",O_RDONLY);
```
|
I declare the following array:
```
char* array [2] = { "One", "Two"};
```
I pass this array to a function. How can I find the length of this array in the function?
|
You can't find the length of an array after you pass it to a function without extra effort. You'll need to:
Use a container that stores the size, such asvector(recommended).Pass the size along with it. This will probably require the least modification to your existing code and be the quickest fix.Use a sentinel value... |
If we want mainly anepollbased loop over file-descriptors, what else features does thelibeventoffer (not interested inhttpordnsstuff)??
I know it's quite a big project, but it looks quite simple to me to write anepollwrapper API.
|
epollis only available on Linux;libeventcontains some abstractions such that it'll use other similar APIs on other operating systems (for instance:kqueueon OpenBSD).
|
How do I check that the message fromrecvfrom()is the correct size in C or C++ on windows?
Thank you.
|
recvfromreturns the number of bytes in the datagram actually received.
All you need is
```
if (iResult < 0) { /* network error */ }
if (iResult != BufLen) { /* wrong size */ }
```
Old answer, off topic
You should declare a variable to hold the size, and pass its address as thefromlenparameter.
recvfromwill fill... |
I want to have chars and ints inside one array. What i am trying to do is have 1 to 9 in my array and the user selects which number to replace with the letter X. How can i have this done? I assume i cant pass chars into an array that is called asint array[8];So is there a way to have both ints and chars in an array?
|
In c++ints andchars arealmostthe same thing. They are both stored as numbers, just with different resolutions.
```
int array[2];
array[0] = 100;
array[1] = 'c';
printf("%d", array[0]) //Prints the number at index zero.
//Is it %c to print a char?
printf("%c", array[1]) //Prints the number at index zero as it's equi... |
I want the user to enter two numbers with a space between them, then take the two numbers and place them in a 2-element array. For example it would look like:
```
Please enter two values:
>> 1 6
```
Wherearray[0] = 1andarray[1] = 6
How would I do this in C?
|
Probably usingscanf():
```
if (scanf("%d %d\n", &i1, &i2) != 2)
...oops...
```
|
Consider this simple code:
```
int foo = 4;
double d1 = sin (foo);
double d2 = foo * 0.1;
```
When i compile this with gcc, the results are as expected (i.e. mathematically correct), even thoughsin()expects adoubleas its argument. It appears gcc has implicitly castedfootodouble.
How portable is this kind of implici... |
The C99 standard allows this kind of implicit conversion (see section 6.5.2.2, paragraph 7).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.