question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I learnedenumswhen I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is due to the fact I never use it in my programming,my programming interest concentrate around algorithmic problem solving so I am not sure where could ... |
Imagine that you are programming a depth first search and you want to tag your edges with whether they are tree, back, forward, or cross. You could create an enum EDGE_TYPE with the four possibilities and use it to tag your edges.
|
I have doubts about many things related with the different C specifications.
If I program a library in C99, can I use it from C89 code? (using only the functions with C89 compliant definitions).
example, this code would be usable in C89?
Header of a shared library:
```
#ifdef C99
void func (double complex a, doub... |
The C language does not say anything about binary compatibility of C89 and C99 code. That is entirely up to the compilers you use for the different parts of the executable.
If you can make the external headers of your library palatable for a C89 compiler, I don't see any obvious reason why it would not work, except f... |
C history question here. Why does the C functionputcrequire a second parameter like
```
putc( 'c', stdout ) ;
```
While puts is oh so more convenient
```
puts( "a string" ) ;
```
There is a function in msvc++
```
putchar( 'c' ) ;
```
Which works the way one might expectputcto work. I thought the second paramet... |
```
int putc ( int character, FILE * stream );
```
Writes a character to the stream and advances the position indicator.So it is a more generic function thanputcharOther functions can be based on this e.g.
```
#define putchar(c) putc((c),stdout)
```
According to Kernighan's bookputcis equivalent withfputcbutputccou... |
in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)
|
There is no static device name, you should usewaveOut*functions,hereis a nice example of using those APIs.
|
I am writing C89, C90, Ansi-C Code. One of my functions requires a struct as a parameter. I want to call the function with the initialization of that struct rather than creating a struct first then passing it to the function.
Here are some snippets which work.
```
typedef struct {
char* EventName;
char* Mess... |
Use the compound literal(Event){"infomessage", "Testmessage"}, ie
```
Notify((Event){"infomessage", "Testmessage"});
```
|
I'm having a trouble in opening FIFOs in C.. first I created them using mkfifo() function with permission : 0777, and when I tried to open them, it succeeded in opening the first FIFO only, then the process will stuck in opening the second FIFO, and this is my code :
```
fd1 = open("FIFO1_PATH", O_WRONLY );
fd2 = ope... |
I just got it right :)
I have to let the opening process wait until some other process opens the FIFO for reading (and it will be a blocked reading).. by doing sleep on the writing process I will ensure that the other process will opens for reading ..
|
I'm trying to find all subfolders in a file's path that have 'others exec' permission.
I've tried to usestrtok(path_str,"/")to break the path string, but when usingstat()for the sub-directories of the root of the process I run, I get the "not a file or folder" error.
Any suggestions on how I can overcome this error?... |
If the path is"long/path/to/the/file.txt", then you will need to callstat()on"long","long/path","long/path/to"and"long/path/to/the". If you don't care in what order you check these, the easiest way is probably to repeatedly usestrrchr():
```
char *s;
while (s = strrchr(path, '/'))
{
*s = 0;
if (strlen(path)... |
I want to define a function in C language which can take an unlimited number of arguments of any datatype.
For example:printf(),scanf(), etc.
Any idea on this?
|
To use variable number of arguments in C you need to include the header
```
#include <stdarg.h>
```
printf()in C is an example of function that takes variable number of arguments.
```
int printf(const char *fmt, ...)
```
More infohere
|
How can i get the last digit of an integer (or NSInteger) outputted to integer?
example:
```
int time = CFAbsoluteGetCurrent();
int lastDigit;
```
|
Usemodulo:
```
int lastDigit = time % 10;
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
If you mean systems level then perhapsD Language.
|
```
char program[3] = { 0x6a, 0x0a, 0xC3 }; //push 10; ret;
char (*p)(void) = program;
printf("char = %c \n", p());
```
This code crashes. Why?
The following code works ok:
```
char program[3] = { 0x90, 0x90, 0xC3 }; //nop; nop; ret
void (*p)(void) = program;
p();
```
|
Because you need to cleanup your stack by popping from it. Read more on theretinstruction - it will load cs:ip with values from the stack!
|
I have a text file and would like to check if it contains a string.
The text file is stored in a char array:char buffer[512][128];.
Q1: Is it easier if I buffer it in one long array instead of a multidimensional array?
Q2: How could I check whether the buffer contains the stringchar *s1 = "Hello world!";?
I will ... |
It will be much easier to use a single 1D array.strstr(buffer, s1)!= null(once you've changedbufferinto a 1D array)
|
the problem is i dunno how long the string will be, so i dunno how much should i allocate for my data...
```
char *Data = malloc(1024*1024); //???????
sprintf(Data, "%s %s", Data1, Data2);
```
Data1 and Data2 varies in Size from time to time.... from very very long to very small
i was wondering if there is away to ... |
Many C runtime libraries (for instance, GNU's glibc and FreeBSD's (and NetBSD's and OpenBSD's and OS X's) libc) provideasprintf, which combinesmallocandsprintfinto a single call.
```
char *Data = NULL;
asprintf(&data, "%s %s", Data1, Data2);
```
Assuming the return value indicates success, enough space has been dyna... |
in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)
|
There is no static device name, you should usewaveOut*functions,hereis a nice example of using those APIs.
|
I am writing C89, C90, Ansi-C Code. One of my functions requires a struct as a parameter. I want to call the function with the initialization of that struct rather than creating a struct first then passing it to the function.
Here are some snippets which work.
```
typedef struct {
char* EventName;
char* Mess... |
Use the compound literal(Event){"infomessage", "Testmessage"}, ie
```
Notify((Event){"infomessage", "Testmessage"});
```
|
I'm having a trouble in opening FIFOs in C.. first I created them using mkfifo() function with permission : 0777, and when I tried to open them, it succeeded in opening the first FIFO only, then the process will stuck in opening the second FIFO, and this is my code :
```
fd1 = open("FIFO1_PATH", O_WRONLY );
fd2 = ope... |
I just got it right :)
I have to let the opening process wait until some other process opens the FIFO for reading (and it will be a blocked reading).. by doing sleep on the writing process I will ensure that the other process will opens for reading ..
|
I'm trying to find all subfolders in a file's path that have 'others exec' permission.
I've tried to usestrtok(path_str,"/")to break the path string, but when usingstat()for the sub-directories of the root of the process I run, I get the "not a file or folder" error.
Any suggestions on how I can overcome this error?... |
If the path is"long/path/to/the/file.txt", then you will need to callstat()on"long","long/path","long/path/to"and"long/path/to/the". If you don't care in what order you check these, the easiest way is probably to repeatedly usestrrchr():
```
char *s;
while (s = strrchr(path, '/'))
{
*s = 0;
if (strlen(path)... |
I want to define a function in C language which can take an unlimited number of arguments of any datatype.
For example:printf(),scanf(), etc.
Any idea on this?
|
To use variable number of arguments in C you need to include the header
```
#include <stdarg.h>
```
printf()in C is an example of function that takes variable number of arguments.
```
int printf(const char *fmt, ...)
```
More infohere
|
How can i get the last digit of an integer (or NSInteger) outputted to integer?
example:
```
int time = CFAbsoluteGetCurrent();
int lastDigit;
```
|
Usemodulo:
```
int lastDigit = time % 10;
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
If you mean systems level then perhapsD Language.
|
```
char program[3] = { 0x6a, 0x0a, 0xC3 }; //push 10; ret;
char (*p)(void) = program;
printf("char = %c \n", p());
```
This code crashes. Why?
The following code works ok:
```
char program[3] = { 0x90, 0x90, 0xC3 }; //nop; nop; ret
void (*p)(void) = program;
p();
```
|
Because you need to cleanup your stack by popping from it. Read more on theretinstruction - it will load cs:ip with values from the stack!
|
I have a text file and would like to check if it contains a string.
The text file is stored in a char array:char buffer[512][128];.
Q1: Is it easier if I buffer it in one long array instead of a multidimensional array?
Q2: How could I check whether the buffer contains the stringchar *s1 = "Hello world!";?
I will ... |
It will be much easier to use a single 1D array.strstr(buffer, s1)!= null(once you've changedbufferinto a 1D array)
|
the problem is i dunno how long the string will be, so i dunno how much should i allocate for my data...
```
char *Data = malloc(1024*1024); //???????
sprintf(Data, "%s %s", Data1, Data2);
```
Data1 and Data2 varies in Size from time to time.... from very very long to very small
i was wondering if there is away to ... |
Many C runtime libraries (for instance, GNU's glibc and FreeBSD's (and NetBSD's and OpenBSD's and OS X's) libc) provideasprintf, which combinesmallocandsprintfinto a single call.
```
char *Data = NULL;
asprintf(&data, "%s %s", Data1, Data2);
```
Assuming the return value indicates success, enough space has been dyna... |
Why condition rand() % 3 is true approximatelу EVERY 3 time ? rand is REALY random isn't it ?
|
You realize, of course, that even a fair coin can give you ten heads in a row. There's a probability that can be assigned to that combination.
A fair coin will give half heads and half tails overmanytrials, but it's not guaranteed to be 50/50 over a shorter run.
Your own experience of the physical world tells you t... |
Is there a compression algorithm that is faster than JPEG yet well supported? I know about jpeg2000 but from what I've heard it's not really that much faster.
Edit: for compressing.
Edit2: It should run on Linux 32 bit and ideally it should be in C or C++.
|
Jpeg encoding and decoding should beextremelyfast. You'll have a hard time finding a faster algorithm. If it's slow, your problem is probably not the format but a bad implementation of the encoder. Try the encoder fromlibavcodecin theffmpegproject.
|
I'm writing a CGI program in C to get an uploaded file through HTTP multipart/form-data.
How is that Apache handles file uploads? How can I get the data?
|
You could use an established CGI library, such ascgic, which hascgiFormFileNamemethod for handling uploaded files.
|
Is it possible to useSGen garbage collector(from the mono runtime) in coventionnal C/C++ programs ?
I think mono used also theBoehm-Demers-Weiserconservative garbage collector that can be used in C/C++ programs.
|
There are very few dependencies on the rest of the Mono code in SGen, so it should be easy to extract it out and adapt to other uses.
The major difference from the Boehm collector is that it currently doesn't support a non-precise mode for heap objects, so you can't use it to replace malloc easily.
It would work great... |
From a compiled file, can I see which compiler has been used to generate the file?
|
There's also the good old 'strings' utility. Dumps all ascii-ish looking strings it finds in the binary. Different compilers embed different amounts of information in the binaries they produce, but many will actually include obviously identifying strings.
|
I need to write a C program to find the Perfect Number..
```
main()
{
int n=1000,sum = 0;
for(int num = 1; num <= n; num++)
{
sum = 0;
for(int i = 1; i < num; i++)
{
if(!(num%i))
{
sum+=i;
}
}
if(sum == num)
... |
if(!(num%i))simply meansif( (num%i) == 0 )
|
Does anyone have an idea how to convert char* to string. Actually, I have a function which returns value as char* and now i need to store/copy std::string.
I have tried something like
char *sResult = (char*)malloc(1024);
std:string line;
line= line+ sResult
Thanks and regards,
Sam
|
How about
```
std::string line(szResult);
```
|
I want to add a simple function to a central place so that I can use it without having to include the header files over and over again. How do I accomplish it?
Consider the function
```
void foo() {
printf("Bar");
}
```
I tried adding this to a foo.h file and then including it in the prefix.pch file. But a comp... |
You need to use inclusion guards, like this:
```
#ifndef FOO_H
#define FOO_H
void foo(); //declaration
#endif
```
And inFoo.m:
```
void foo() {
printf("Bar");
}
```
Or, even easier, you can simply use the#importdirective:
```
#import "Foo.h"
```
If you did all of the above, then the only way this could've h... |
I was doing some rounding calculations and happened upon a question. How can I express the highest quantity less than 1 for a given floating point type?
That is, how I write/represent valuexsuch thatx < 1, x + y >= 1for anyy > 0.
In fractions this would bex = (q-1)/qwhereqis theprecisionof the type. For example, if ... |
C99 definesnextafter()function. Use it like
```
#include <math.h>
double under_one = nextafter(1, 0);
```
|
For example I have a string<abc="xyz">
abc can change and so does the value xyz. I need a way to find out value which is between two double quotes. How do I do that in C?
Any standard lib function I can use? without doing explicit pointer dance?
|
You have to browse the string.
Everything you need is there :http://www.cppreference.com/stdstring/index.html
|
Here's how I open a file for writing+ :
```
if( fopen_s( &f, fileName, "w+" ) !=0 ) {
printf("Open file failed\n");
return;
}
fprintf_s(f, "content");
```
If the file doesn't exist the open operation fails. What's the right way tofopenif I want to create the file automatically if the file doesn't already exi... |
To overwrite any existing file, use thecreatcall:
```
#include <fcntl.h>
#include <stdio.h>
int fd = creat (fileName, 0666); // creates file if not exist, overwrite existing
FILE *f = fdopen (fd, "w"); // optional, if FILE * type desired
```
|
I wrote a C command line tool which usesGLUTto visualize a genetic algorithm and I want to distribute it in a Mac OS X .app Bundle.
How do I do that? Are there any helper tools available for this?
Thank you very much!
Thomas
Edit:
Thank you very much for your help, I didn't think of it being that easy!
|
Create new xcode project, with "application" template. Add your source code to that project, compile and... You have app bundle. You need only to deploy it (add frameworks). Thats all.
|
I define a function
```
void add(char *key, char *value) {
}
```
And I have a string
```
char * message = "hello world"
```
I want to call add("hello", "world"), so I write
```
add(message[0,4], message[6, 10])
```
It does not work, I am refused with the "char *" and "char array", who can explain for me?
|
You can't substring a string that way in C. Here's a decent, accessible description of how to do what you want:http://www.eskimo.com/~scs/cclass/notes/sx8.html
|
I want to decompile CHM file to HTML format . Is it possible using c or c++ ? Is there any c or c++ library to do this.
|
It is possible using C++. If you use Windows, you can do it using COM. An example you can findhere. This article is about C#, but it is done using COM interfaces and you can easily do the same in C++.
|
```
gcc 4.4.1 c89
```
I have 2 different structures called origin_t and session_t.
I would to pass the instance of one of these structure to my function. However, before I can perform an operation on these I need to cast it to the correct type. My problem is that I don't know how to check for the correct type. Is th... |
Is there any way to modify the types? Seems like the easiest way it to put a small member that indicates the type if there's no other way to tell.
|
I wanna get string like 34,34;34,21;45,12;45,12(length is not certain.)
I wanna dynamic memory allocation with realloc but i can't do it.
How i can get like this characters to string??
it will be string={34,34,34,21,45,12,45,12}
|
You will have to know the length beforehand, and when you know that your buffer is too small for data that is going to be newly entered, use:
```
realloc(ptr, newLength);
```
|
I have a simple question.Why is it necessary to consider the terminating null in an
array of chars (or simply a string) and not in an array of integers. So when i want a string to hold 20 characters i need to declarechar string[21];. When i want to declare an array of integers holding 5 digits thenint digits[5];is eno... |
You don't have to terminate achararray withNULLif you don't want to, but when using them to represent a string, then you need to do it because C usesnull-terminated stringsto represent its strings. When you use functions that operate on strings (likestrlenfor string-length or usingprintfto output a string), then those... |
I was wondering how I could do this. I'm mostly puzzled by the N arguments part:
```
printf("Hello, I'm %i years old and my mom is %i .",me.age(),mom.age());
```
I want to make a function that will take a formatted string like this and return a std string.
How is the N arguments part done?
|
printfis a variadic function; you can implement your own variadic functions using the facilities provided by<stdarg.h>.
In C++, you should avoid variadic functions wherever possible. They are quite limited in what types they can accept as arguments and they are not type safe. C++0x adds variadic templates to C++; o... |
Example code:
```
#include <stdio.h>
int main (){
int *p;
{
int v = 1;
p = &v;
}
printf("%d\n", *p);
return 0;
}
```
This code works fine, but I'm not sure if there's a guarantee that the address of v will be preserved.
|
There is no guarantee.
Oncevgoes out of scope, doing anything with it at all (even via a pointer) is consideredUndefined Behavior.
As with any other undefined behavior, just because it works on one operating system, compiler, compiler version, time of day, etc, doesn't mean it will work for another.
|
I am trying to compare to a defined constants in C, and I have simplified my program to the following:
```
#include "stdio.h"
#include "stdlib.h"
#define INVALID_VALUE -999;
int main(void)
{
int test=0;
if(test==INVALID_VALUE) //The error line..
return INVALID_VALUE;
return 0;
}
```
And when I u... |
Remove the semicolon from your INVALID_VALUE definition.
Macros are replaced lexically (character-by-character) with no understanding of the syntax around them. Your macro INVALID_VALUE is set to-999;, so your if line expands the macro to:
```
if (test==-999;)
```
which is invalid C syntax.
|
What is the function of these operators ( =& , ~ ), i found this code posted as a joke and titled
"Found in early Unix sources:"
```
if(rp->p_flag & SSWAP) {
rp->p_flag =& ~SSWAP;
aretu(u.u_ssav);
}
```
EDIT:
Source:http://www.bsdlover.cn/study/UnixTree/V6/usr/sys/ken/slp.c.html
|
You young whippersnappers were born too late :)
This code comes from a very early version of Unix (pre V7). The joke is that the comment just above it is"You are not supposed to understand this", which has becomea bit of a legend.
|
```
int i;
int data[5] = {0};
data[0] = i;
```
What's the value in data[0]?
Also, what's the meaning of this line?
```
if (!data[0]) { ... }
```
|
In most cases, there is no "default" value for anintobject.
If you declareint i;as a (non-static) local variable inside of a function, it has an indeterminate value. It is uninitialized and you can't use it until you write a valid value to it.
It's a good habit to get into to explicitly initialize any object when y... |
I have a string like this:
```
char *message = "12#34#56#78#90"
```
I want to get:
```
a = "12"
b = "34"
c = "56"
d = "78"
d = "90"
```
Who can give me a good method?
|
Usestrtok(). Note that even though that is C++ documentation, the function is also present in C. Take special note to useNULLin subsequent calls to get the next token.
```
char label = 'a';
char *token = strtok(message, "#");
while (token != NULL) {
printf("%c = \"%s\"\n", label++, token);
token = strtok(NULL, "#... |
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.Closed10 years ago.The community reviewed whether to reo... |
Wikipedia has a goodarticle on quadtrees. The quadtree section inthese slidesis very good.
Here are some C implementations (found viaGoogling for quadtree c -"c++" -"c#"):
http://hyantes.gforge.inria.fr/doc/quadtree_8c-source.htmlhttp://xw2k.nist.gov/dads/html/quadtree.htmlhttp://www.informatik.uni-ulm.de/acm/Locals... |
For example:
In A.c :
```
Head init(){
Head treeHead;
treeHead = malloc(sizeof (struct TreeHead));
treeHead->Root = malloc(sizeof (struct TreeNode));
return treeHead;}
```
In B.c :
```
Head treeHead;
treeHead = init();
```
Should I call free in init() method in A.c or in B.c ? |
I would define a function in A.c:
```
void freeHead(Head head){
free(head->Root);
free(head);
return;
}
```
Then call it in appropriate places in B.c:
```
freeHead(head);
```
|
I am currently working on a wireless solution for my Arduino and computer. I am trying to connect a transmitter to my computer and a receiver to my Arduino. I have seen a lot of examples with Arduino to Arduino communication but none for computer to Arduino. What would I need to interface the transmitter with my co... |
Thejeenodeis a good low-cost solution. It really depends on your needs, though.
|
How do you setup eclipse so that it parses and underlines errors for C as you type like it does for Java?
|
Install theCDTextension.
Sadly, CDT is more limited than JDT... it can only find the absolute basic syntax errors itself (missing semicolons etc.), in part because a C or C++ build can be so heavily altered by flags to the tool chain, preprocessor variables etc. It can only highlight most errors and warnings after ... |
I implemented a virtual filesystem using Dokan. I tried to set the drive letter to C but it errors every time. I was wondering if there is a different virtual filesystem which will allow me to do that or if there is a way of fixing it. Is there some windows api call which will allow me to remount the filesystem in a f... |
Use DoaknMountPoint to create a mount point in a existing C drive. Firat make sure Dokan.dll has that API supported.
Drive can be mounted from D thru Z.
hope this helps
|
I have written a program in C which communicates through udp with an Arduino.
My question is, how can I "ping" an ip address and only get a 1 or 0 (available or not) in C (unix).
Thesystem("ping xxx.xxx.xxx.xxx");call doesn't work because it outputs a list...?
|
```
system("ping -c 1 127.0.0.1 > /dev/null");
```
Should do the trick.-c 1sends only a single packet. We pipe to/dev/nullas we don't care about the output to stdout (is that the list you refer to?). If you also want to discard stderr, add a2>&1to the end. You might also want to limit the response time using-W.
The ... |
I want my program to create a file located at the path of the command parameter, i.e.program /home/user/directory/that/doesnt/exist/file. If the directory doesn't exist,fopenwill fail to open the file, so the program would have to create the directories. Would I have to program my own loop to detect each slash andmkdi... |
Someone coded it for you:mkpath()
Or if you're satisfied usingsystem(), then you can usesystem("mkdir -p /your/path/here");
|
```
int i=0;
void push(int *ptr)
{
if(i==0)
{
ptr= (int *)calloc(1,sizeof(int));
}
else
{
ptr=(int *)realloc(ptr,sizeof(int)*(i+1));
}
i++;
}
```
when i add two or more number , realloc giving an error(main.exe)
|
I assume you have a pointer somewhere else, which you send as an argument to the function "push"?
You need to send a pointer to that pointer, so the "push" function can change its value.
|
I would like to programmatically move and click the mouse using the windows API in C. I have searched google high and low and can't find any sendInput tutorials for plain C. All I can find is C#/C++. I have little experience with the windows API and would love a great tutorial that would cover sendInput! Thanks!
|
Hans Passant was right with C++ code being almost identical. Here's what I ended up with:
```
INPUT input;
input.type = INPUT_MOUSE;
input.mi.mouseData = 0;
input.mi.dx = x * (65536 / GetSystemMetrics(SM_CXSCREEN)); //x being coord in pixels
input.mi.dy = y * (65536 / GetSystemMetrics(SM_CYSCREEN)); //y being coord ... |
Here's how I open a file for writing+ :
```
if( fopen_s( &f, fileName, "w+" ) !=0 ) {
printf("Open file failed\n");
return;
}
fprintf_s(f, "content");
```
If the file doesn't exist the open operation fails. What's the right way tofopenif I want to create the file automatically if the file doesn't already exi... |
To overwrite any existing file, use thecreatcall:
```
#include <fcntl.h>
#include <stdio.h>
int fd = creat (fileName, 0666); // creates file if not exist, overwrite existing
FILE *f = fdopen (fd, "w"); // optional, if FILE * type desired
```
|
I wrote a C command line tool which usesGLUTto visualize a genetic algorithm and I want to distribute it in a Mac OS X .app Bundle.
How do I do that? Are there any helper tools available for this?
Thank you very much!
Thomas
Edit:
Thank you very much for your help, I didn't think of it being that easy!
|
Create new xcode project, with "application" template. Add your source code to that project, compile and... You have app bundle. You need only to deploy it (add frameworks). Thats all.
|
I define a function
```
void add(char *key, char *value) {
}
```
And I have a string
```
char * message = "hello world"
```
I want to call add("hello", "world"), so I write
```
add(message[0,4], message[6, 10])
```
It does not work, I am refused with the "char *" and "char array", who can explain for me?
|
You can't substring a string that way in C. Here's a decent, accessible description of how to do what you want:http://www.eskimo.com/~scs/cclass/notes/sx8.html
|
I want to decompile CHM file to HTML format . Is it possible using c or c++ ? Is there any c or c++ library to do this.
|
It is possible using C++. If you use Windows, you can do it using COM. An example you can findhere. This article is about C#, but it is done using COM interfaces and you can easily do the same in C++.
|
I want to return several values from a C function, and IMHO, a hash is a good option.
I first usedrb_intern('A_KEY')to create the keys, but the extension crashed. Now, I am usingrb_str_new2, but I prefer symbols.
How do I create a new symbol, and use it without referring to a class or a method?
|
You need to use theID2SYMmacro to convert the identifier that you get fromrb_interninto a ruby symbol. Try changing
```
rb_intern('A_KEY')
```
to
```
ID2SYM(rb_intern('A_KEY'))
```
|
I'm currently working on some C program, and I'd like to know if there's any chance to block writing in the writer process (until the read is done) ? i.e. I have 3 pipes between the parent process and the children processes (the parent writes and the children read), I'd like to let the parent to write only to the proc... |
bmargulies is correct. An alternative to creating a more complex protocol, however, would be to use multiple threads in the parent process -- one thread per child process. One thread might block due to a slow child, but the other threads could continue with their children. Depending on the details of your problem, thi... |
Hi
i am trying to do a project using windows API in C language. The small part in my project is to get process ID of lsass.exe.
i have tried the program below but it wont work.
i have read about the CreateToolhelp32Snapshot, Process32First, Process32Next functions can anyone help me explaining how to use them in the ... |
Because there might be several instances of a process name running, there is no one-to-one correlation between a process's image name and a PID. You'll have to enumerate the processes and check the base module names for each one as Burgos describes, by using EnumProcesses.
FWIW, .Net approaches this problem by provid... |
Is it required to release the memory allocated to string "str", in the below program ?If so, free(str) works ? In which segment, the memory is allocated to "str" ?
```
int main()
{
function()
}
function()
{
char *str="hello";
--
--
return
}
```
|
char *str= "hello";
String literal"Hello"is stored inconstregion of memory(on most common implementations) and has static storage duration. Any attempt to modify the content would invoke UB i.estr[0]='c'would cause segfault on most implementations.
ISO C992.13.4/1says
An ordinary string literal has type "array of n... |
I have to define a 24-bit data type.I am usingchar[3]to represent the type. Can I typedefchar[3]totype24? I tried it in a code sample. I puttypedef char[3] type24;in my header file. The compiler did not complain about it. But when I defined a functionvoid foo(type24 val) {}in my C file, it did complain. I would like t... |
The typedef would be
```
typedef char type24[3];
```
However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and thesizeoffor it will then be wrong.
A bett... |
This question already has answers here:Closed12 years ago.
Possible Duplicate:Why no switch on pointers?
```
int main(int argc, char** argv)
{
void* not_a_pointer = 42;
switch(not_a_pointer)
{
case 42:
break;
}
return 0;
}
```
.
```
error: switch quantity not an integer
```
How can I portably... |
try casting tointptr_t, which is an integer type:
```
switch((intptr_t)not_a_pointer)
```
etc...
|
```
void foo(void* arg)
{
}
int main(int argc, char** argv)
{
foo((void*)1);
return 0;
}
```
Is there any standard that compilers are to meet that defines the default size (as in bytes) of the integral literal constant passed to foo?
|
You're not passing an integer literal constant tofoo; you're passing avoid *, which is defined to have sizesizeof(void *).
More generally, if you do pass an integer constant expression as an argument to a function, then there are two possibilities:
you have a prototype for the function; in this case, the integer con... |
I want to create a virtual folder of run-time generated links. What i mean by run-time is that the location of the link is determined by the result of a query. I want all programs to be able to access the folder, however. Therfore, i think that a namespace extension is not adequate enough. However, a full on filesyste... |
Well, if you decided that you need to expose the links as a filesystem, then user-mode filesystem is the obvious choice. But the question iswhat foryou need the links to be represented as files. Do you need to expose content behind the URLs as files? Or do you just need to have some hierarchy of links?
|
I have
```
programConfig = fopen("program.conf", "a+");
```
However I need to prepend my system drive letter which is a char* and a couple more directories. I've always been puzzled by this. In PHP for example, you dostring1 . string2.
How can I resolve this problem?
Thanks!
Edit: One of the variables might be va... |
```
char pathname[PATH_MAX];
if (snprintf(pathname, sizeof pathname, "%s/%s", dir, file) >= sizeof pathname)
goto error;
```
|
I am trying to pass a 2D array of variable size to a function to print it. I know how it's done when one has fixed sized arrays. But how does one do this with variable sized arrays? Here is some code that'll give you an idea what I am trying to do:
```
void print_grid(char (*g)[9], int size) // the array subscript (9... |
```
void print_grid(int rows, int cols, char g[][cols]) { ... }
```
|
This is a bit written from memory so I apologize if I made a mistake in this posting. I created a struct and wanted to assign a name to it, but I get this error:
error: incompatible types in assignment ofconst char[3]' tochar[15]'
For the life of me I tried to understand what exactly is wrong here, I thought a const... |
name is a fixed-size static buffer. You need to use strcpy or similar functions to assign it a string value. If you change it to beconst char* nameinstead, then your code should work as-is.
|
I want to return several values from a C function, and IMHO, a hash is a good option.
I first usedrb_intern('A_KEY')to create the keys, but the extension crashed. Now, I am usingrb_str_new2, but I prefer symbols.
How do I create a new symbol, and use it without referring to a class or a method?
|
You need to use theID2SYMmacro to convert the identifier that you get fromrb_interninto a ruby symbol. Try changing
```
rb_intern('A_KEY')
```
to
```
ID2SYM(rb_intern('A_KEY'))
```
|
I'm currently working on some C program, and I'd like to know if there's any chance to block writing in the writer process (until the read is done) ? i.e. I have 3 pipes between the parent process and the children processes (the parent writes and the children read), I'd like to let the parent to write only to the proc... |
bmargulies is correct. An alternative to creating a more complex protocol, however, would be to use multiple threads in the parent process -- one thread per child process. One thread might block due to a slow child, but the other threads could continue with their children. Depending on the details of your problem, thi... |
Hi
i am trying to do a project using windows API in C language. The small part in my project is to get process ID of lsass.exe.
i have tried the program below but it wont work.
i have read about the CreateToolhelp32Snapshot, Process32First, Process32Next functions can anyone help me explaining how to use them in the ... |
Because there might be several instances of a process name running, there is no one-to-one correlation between a process's image name and a PID. You'll have to enumerate the processes and check the base module names for each one as Burgos describes, by using EnumProcesses.
FWIW, .Net approaches this problem by provid... |
Is it required to release the memory allocated to string "str", in the below program ?If so, free(str) works ? In which segment, the memory is allocated to "str" ?
```
int main()
{
function()
}
function()
{
char *str="hello";
--
--
return
}
```
|
char *str= "hello";
String literal"Hello"is stored inconstregion of memory(on most common implementations) and has static storage duration. Any attempt to modify the content would invoke UB i.estr[0]='c'would cause segfault on most implementations.
ISO C992.13.4/1says
An ordinary string literal has type "array of n... |
I have to define a 24-bit data type.I am usingchar[3]to represent the type. Can I typedefchar[3]totype24? I tried it in a code sample. I puttypedef char[3] type24;in my header file. The compiler did not complain about it. But when I defined a functionvoid foo(type24 val) {}in my C file, it did complain. I would like t... |
The typedef would be
```
typedef char type24[3];
```
However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and thesizeoffor it will then be wrong.
A bett... |
This question already has answers here:Closed12 years ago.
Possible Duplicate:Why no switch on pointers?
```
int main(int argc, char** argv)
{
void* not_a_pointer = 42;
switch(not_a_pointer)
{
case 42:
break;
}
return 0;
}
```
.
```
error: switch quantity not an integer
```
How can I portably... |
try casting tointptr_t, which is an integer type:
```
switch((intptr_t)not_a_pointer)
```
etc...
|
```
void foo(void* arg)
{
}
int main(int argc, char** argv)
{
foo((void*)1);
return 0;
}
```
Is there any standard that compilers are to meet that defines the default size (as in bytes) of the integral literal constant passed to foo?
|
You're not passing an integer literal constant tofoo; you're passing avoid *, which is defined to have sizesizeof(void *).
More generally, if you do pass an integer constant expression as an argument to a function, then there are two possibilities:
you have a prototype for the function; in this case, the integer con... |
I want to create a virtual folder of run-time generated links. What i mean by run-time is that the location of the link is determined by the result of a query. I want all programs to be able to access the folder, however. Therfore, i think that a namespace extension is not adequate enough. However, a full on filesyste... |
Well, if you decided that you need to expose the links as a filesystem, then user-mode filesystem is the obvious choice. But the question iswhat foryou need the links to be represented as files. Do you need to expose content behind the URLs as files? Or do you just need to have some hierarchy of links?
|
I have
```
programConfig = fopen("program.conf", "a+");
```
However I need to prepend my system drive letter which is a char* and a couple more directories. I've always been puzzled by this. In PHP for example, you dostring1 . string2.
How can I resolve this problem?
Thanks!
Edit: One of the variables might be va... |
```
char pathname[PATH_MAX];
if (snprintf(pathname, sizeof pathname, "%s/%s", dir, file) >= sizeof pathname)
goto error;
```
|
Kind of trivial thing but ...
I want to print japanese characters using plain C from Hexadecimals
Fromthis table, I know that, the first char in the table, あ's Entity is &# 12353 and its Hex Entity is x3041, etc.
But how do I use this two numbers in order to get printed all characters in the command line?
|
If your terminal is set to UTF-8 and locale is set correctly, you may write:
```
char s[]="あ";
```
you can also try
```
char s[]={0xe3,0x81,0x82,0x0}
```
(the last is the Unicode UTF-8 encoding for "あ"), and then justprintf("%s",s);
|
What would be the best way to copy unsigned char array to another?
For example:
```
unsigned char q[1000];
unsigned char p[1000];
strcpy (q,&p);
```
The above code does not work, it gives me error saying "cannot convert parameter 1 from unsigned char [1000] to char *".
|
As indicated by its name,strcpyworks on C string (which a unsigned char array is not).
You should considermemcpy.
|
Ie, how to get keystrokes send directly to my program without waiting for the user to press enter. Basicly I'm trying get something like curses'scbreak()call. (But I can't use curses due a couple of bugs/misfeatures that I haven't been able to work around.) This seems like something that should just be a trival esc... |
Lookuptermiosand thetcsetattrfunction.
|
I have made the following #defines
```
#define GOLD 1;
#define SILVER 2;
```
later in my program I set up some variables
```
int source, target;
```
They are then set to the values:
```
source = GOLD;
target = SILVER;
```
I now want to compare in an if statement:
```
if(source == GOLD) {...}
```
But the compil... |
Because you have an errant;after the#define GOLD 1and#define SILVER 2. Remove them, your problem will go away.
|
I have a pointer that's holding 100 bytes of data.
i would like to add 5 to every 2nd byte.
example:
```
1 2 3 4 5 6
```
will become:
```
1 7 3 9 5 11
```
Now i know i can do a for loop, is there a quicker way? something like memset that will increase the value of every 2nd byte ?
thanks
|
A loop would be the best way. memset() is efficient for setting a contiguous block of memory. Wouldn't be much help for you here.
|
Excuse the beginner level of this question. I have the following simple code, but it does not seem to run. It gets a segmentation fault. If I replace the pointer with a simple call to the actual variable, it runs fine... I'm not sure why.
```
struct node
{
int x;
struct node *left;
struct node *right;
};
int m... |
```
struct node *root;
root->x = 42;
```
You're dereferencing an uninitialized pointer. To allocate storage for the node:
```
struct node *root = malloc(sizeof(struct node));
```
You could also allocate a node on the stack:
```
struct node root;
root.x = 42;
```
|
From what Platform SDK?
Which version?
Where can be downloaded? link
Thanks.
|
T_SafeVector.h is provided by Microsoft as part of what used to be called Platform SDK. Now Platform SDK has been superseded by the Windows SDK
http://msdn.microsoft.com/en-us/windows/bb980924
Windows SDK = Platform SDK + .NET Framework SDK
|
I am getting sick of seeing the warning
"Declaration of 'index' shadows a global declaration"
index is defined in string.h. I don't think that it's required for anything I am using and I really don't want to change all the local vars from index to something else.
Anyone know of a way to find out how (by what path) ... |
Theindexfunction is actually declared in/usr/include/strings.h, and is marked as removed as of POSIX issue 7. You can hide its declaration by setting the appropriate POSIX version with the compiler flag-D_POSIX_C_SOURCE=200809. This will also hide other functions deprecated in issue 7, likebcopyandbzero.
|
I have an array that looks like this:
```
struct table_elt
{
int id;
char name[];
}
struct table_elt map[] =
{
{123,"elementt1"},
{234,"elt2"},
{345,"elt3"}
};
```
I'm trying to access these elements through map[1].name, etc. However, it doesn't seem to be able to fetch the elements correctly, a... |
You probably want :
```
struct table_elt
{
int id;
const char *name;
}
struct table_elt map[] =
{
{123,"elementt1"},
{234,"elt2"},
{345,"elt3"}
};
```
On a side note,table_eltdoesn't even need a name if it's used in this context only.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
You did not mention whether you wanted an open-source or a commercial software, so here is a list containing both:
GNU Scientific Library(GSL)Basic Linear Algebra Subprograms(BLAS)MeschachNumerical Algorithms Group(NAG)
There was also thisprevious questionon the subject.
|
I need to include a header file which needsHAVE_SYS_UIO_Hto be defined. My system do actually havesys/uio.h, but the macro isn't defined automatically. For the moment, I can define it before including the header, but this is obviously a bad idea.
What do I need to do to getHAVE_SYS_UIO_H(and other macros like it) to ... |
Usually things like "HAVE_SOMETHING" are defined in Makefiles generated by "./configure" script which actually makes test programs and tries to compile and run them to figure out whether a particular system has a particular thing or not.
|
I hadstruct point {(...)};defined. But with C90 it seems I have to do it with typedef. How do I do this correctly?typedef struct point {} point;?typedef struct {} point;?typedef struct point {};?
|
You can do:
```
typedef struct Point { ... } MyPoint;
```
and then use both kinds of declarations:
```
struct Point p1;
MyPoint p2;
```
|
I'm writing a Python module in C and I intend to mmap largeish blocks of memory (perhaps 500 MB). Is there anything about working in the same process space as the Python interpreter that I should be careful of?
|
No, you're fine.
On 32-bit systems, you could run out of virtual memory, or with virtual memory fragmentation not have a single chunk big enough to map as many huge files as you want. But that pitfall isn't particular to CPython.
|
I am having a situation for which I am looking for some suggestion.
Suppose I write a program which prints the directory names of the directories.
Is it possible to convert this program into a command (just on my system).
Not be alias but via C only.
|
As long as the file isexecutable(has the execxaccess for the user starting it) and can be seen from the command interpreter (usuallybashorsh), you can consider it to be a command.
There will be no difference in running your own file from your path than thelscommand for instance.
Also, the C (or C++ ...) language is ... |
How do you count the number of zero group bits in a number? group bits
is any consecutive zero or one bits, for example, 2 is represented
as ....0000000000000000010 has two zero bits groups the least
significant bit and the group starts after one.
Also, I am in a bad need for algorithms on bits manipulation if any... |
Here are some hints for you:
if (x & 1) {...}checks if the least-significant bit ofxis set;x >>= 1shifts the value ofxone bit to the right;mind the negative numbers when you do bit manipulation.
|
I have an arraychar input[11] = {'0','2','7', '-','1','1','2', ,'0','0','9','5'};
How do I convert input[0,1,2] toint one = 27, input[3,4,5,6] toint two = -112and input[7,8,9,10] toint three = 95?
thx, JNK
|
You can use a combination ofstrncpy()to extract the character range andatoi()to convert it to an integer (or readthis questionfor more ways to convert a string to an int).
```
int extract(char *input, int from, int length) {
char temp[length+1] = { 0 };
strncpy(temp, input+from, length);
return atoi(temp);
}
i... |
I just browsed throughMark Probst's diploma thesisand stumpled over the following code:
```
typedef void* cont(void);
for (;;)
{
cp = (cont*)(*cp)();
}
```
I'm pretty sure the cast should read(cont), not(cont*), because he explains:
The function wishing to do a proper tail call returnsthe address of the functi... |
No,typedef void* cont(void);contdefines a function type returning avoid *. I think you are confusing it withtypedef void (*cont)(void);ortypedef void *(*cont)(void);.
I don't believe that it's possible to eliminate the need for a cast in this scenario but I'm open to be convinced otherwise.
|
I'm sorry if this was covered before, but I can't find it anywhere on StackOverflow.
Basically I'm trying to run things that you usually run at a Windows command prompt:
msiexec /i file.msi /q
and other sort of commands from my C program. Is this possible?
Thanks.
|
In windows using the Win APIShellExecutewill give you best control of your child process. However the other two methods mentioned by Dave18 and Pablo work as well.
|
I'm wanting to remove a space between any two words and add anything that I want. For example, I'll have a string that has two words in it with a space between the two. I want to be able to remove the space and replace the space with something that I declare. Also, this needs to be written in objective-c or c.
```
NS... |
UseNSString'sstringByReplacingOccurrencesOfString:withString:method:
```
NSString *spaceReplacement = @"whatever";
NSString *replaced = [string stringByReplacingOccurrencesOfString:@" " withString:spaceReplacement];
```
|
On writing an extension for php (5.3) i want to access thezend_class_entrypointer on a static method.
On non static methods i can use thegetThis()macro and withinZ_OBJCE_Pmacro like this:
```
zend_class_entry ce* = Z_OBJCE_P(getThis());
```
Now the problem:
on static methods thegetThis()macro returns anullpointer, ... |
it is really interesting:
on static methods you can access the scope like this
```
zend_class_entry* ce = 0L;
if (EG(called_scope)) {
ce = EG(called_scope);
} else if (!EG(scope)) {
ce = EG(scope);
}
```
the EG Macro access a lot of global and context specific variables, also the calling scope, the calling... |
I'm wondering if it's possible to paste a character as a token in C at runtime. Something like,
```
a = OPERATION(3, 4, '+')
```
will be processed to,
```
a = 3 + 4
```
Is there a way to do this?
Edit:I wanted to add some more information. Obviously this can't be done with the preprocessor. I'm wondering if there... |
How about this:
```
#define OPERATION( A, B, OP ) ((A) OP (B))
```
However, as delnan notes below, you would have to modify your call to:
```
a = OPERATION(3, 4, +)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.