question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I'm trying to define an array of typechar
```
char data[][]
```
I want to use it to store some data from another array usingstrcpy()
The problem is I don't know exactly what is the length and I can't specify the length in the array, and I'm getting this error:
Error array type has incomplete element type
Here's t... |
You either declare it with maximum size possible and acceptable for your case, or usemalloc(3)to ask the runtime to dynamically allocate exact amount of memory for you (then release that memory withfree(3)when done).
|
Is the stack allocated at runtime or compile time?Example:
```
void main()
{
int x;
scanf("%d", &x);
int arr[x];
}
```
|
Stack isallocatedat runtime; layout of each stack frame, however, is decided at compile time, except for variable-size arrays.
|
I have a problem where I have to run a command prompt command from inside a C program. Here is what I did
```
#include<stdio.h>
#include<stdlib.h>
int main(){
system("cd \Users");
system("Dir");
}
```
The problem is I want to cd into Users first and then execute the command Dir where as currently the program o... |
system()starts a new process. This new process changesitscurrent directory, then ends. The current directory of your program's process does not change.
You wantchdir()(or_chdir()).
|
I know the general usage of theperror().
But right now, I want to export its result into a file, not the console. By the way, i run it in under the android emulator's adb shell.
|
Usestrerror()instead:
```
fprintf(logfile, "Something went wrong: %s\n", strerror(errno));
```
Or, you could redirectstderrto a file usingdup2()and then carry on usingperror().
EDIT: It was early when I answered this originally and my brain wasn't firing on all cylinders. There is no need to usesprintf()followed by... |
When I want to work with big and small digits how must I sum / compare values in C?
```
#include <stdio.h>
#include <math.h>
int main(void) {
if (1.0 + (1/pow (10,50)) == 1.0)
printf("true");
else
printf("false");
return 0;
}
```
how to make it to return false?
|
You can't make it return false with standard C types. You'll need to use a high-precision floating point library.
|
In function main() {...}
1) #include header file string.h
2) I prototype my own file, call it strcpy:
```
**char *strcpy(char *strSource , const char *dest);**
```
3) I also wish to use the "real"strlenfunction in string.h in main().
4) In another compilation file I have my version of strcpy.
Question: How can ... |
You can't do that in C. That's one of the reasons why C++ introducesnamespaces.
The only thing you can do is use a non-conflicting name for your own functions.
|
I'm curious because the man page of connect(2) is pretty short and it takes a struct sockaddr* which is normally cast anyways..
|
sockaddr_inandin_addraren't even similar. There's no way that would work. There different because more than an address is usually needed. For example, a port number is needed to establish connect a IP socket.
|
I have come across some legacy code that has the following type of line:
sscanf(szBuff,"%Fd %Ff %Fd %Ff"
Has anyone seeen a modifier like Fd or Ff? If so, what does it mean?
I cant seem to find any information on it. The code compiles and runs fine.
|
C says forfscanffunctions:
(C991, 7.19.6.2p14) The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.
So in%Fd, the conversion specification is%Fwhich is equivalent to%f. Note that thedis not part of the conversion specification.
For example (forfprintffu... |
I am trying to do the following:
```
typedef struct tagSTRUCT
{
MYPROC lpfnMyProc;
} STRUCT, *HSTRUCT;
typedef void (*MYPROC)(HSTRUCT);
void version1(HSTRUCT ); // version of delegate MYPROC
void version2(HSTRUCT ); // another version
...
```
, which gives me a compilation error. I have tried to make the typed... |
Try this:
```
struct tagSTRUCT;
typedef void (*MYPROC)(struct tagSTRUCT *);
typedef struct tagSTRUCT {
MYPROC p;
} STRUCT, * HSTRUCT;
```
|
How can I check if a CLI program, that I just started with CreateProcess(), is waiting for input from stdin with the Windows C API?
|
as some of the comments above have said, you cannot check if your program is waiting for stdin once it has already started waiting. You could use an event handler or you could simply have a read from stdin with a timeout, where on occurrence of the timeout you flag that you are waiting for input and start waiting wit... |
I need a very simple makefile to compile a shared object library file (*.so). I also need to know how to pass optimization parameters like -O2 and -O3. I tried to search for simple examples using google, but all examples are twisted.
I don't need to create any version like *.so.1.0 but only a simple *.so file. My pro... |
The simplest makefile that I can think of that does what you want:
```
CXXFLAGS += -fPIC
CXXFLAGS += -O3
x.so: x.o y.o
g++ -shared $^ -o $@
```
In the alternative, you may want to use more of make's built-in rules and variables:
```
CXXFLAGS += -fPIC
CXXFLAGS += -O3
x.so: x.o y.o
$(LINK.cc) -shared $^ $(LOA... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:What is __gxx_personality_v0 for?
I've seen this question circulating around here in the context of compiling C++ code. However I am to compile apureC code and keep on getting this error. I am forbidden to use "-lstdc++" as a workaround to... |
Use eitherg++- since your file is suffixed.cppor rename the file to.cand keep the command line as is. Tested on Debian 6.0.5 withgcc4.4.5.
|
I wish to have a file name as an argument to the C program. I tried all the possible ways infopensomething like the below.
```
fp = fopen(*argv[2], "r");
```
Also used"*argv[2]"but did not work. I want to know where I am going wrong so that I can use this correctly. Thanks!
|
It should be
```
fp = fopen(argv[2], "r");
```
Please be aware thatargv[0]will contain your exe name(with path), other arguments which you pass will start fromargv[1].
Refer tothisfor more details on using command line arguments in C.
In your main function if you are gettingchar **argvas the argument, the array su... |
DigiFlow is used for image processing for fluid dynamics experiments -DigiFlow website. There is a console within the program which is used for writing macros.
Some example code:
```
function do_this(variable) {variable += 2};
output := do_this(5);
```
(output = 7 after running this.)
|
From assignment and function declaration I'd say it looks like Google'sgo language. Pascal might be another choice.
|
I ran into a bit of a problem writing a wrapper for a third party library today. They've usedgenericas a variable name in a couple of structs. When I try to compile this in Visual Studio as a C++/CLI library project the compiler complains.
Example of the code below.
```
typedef struct
{
UINT8 generic;
UINT8 id[3... |
Since you're already wrapping this third-party library, your wrapper could do something like:
```
#define generic generic_
#include "original.h"
#undef generic
```
|
I'm using MPLab C18 C compiler and getting a syntax error with this code:
```
hundreds = unsigned char((tick / 100));
tens = unsigned char((tick - (hundreds * 100)) / 10);
ones = unsigned char((tick - (hundreds * 100) - (tens * 10)));
```
tickis anunsigned int.
What I'm attempting is to convert a three digit value o... |
Casting is done in parentheses:
```
hundreds = (unsigned char)(tick/100);
```
|
As the title suggests, how to return pointer like this:
```
xxxxxxx foo() {
static int arr[5][5];
return arr;
}
```
BTW. I know that I must specify the size of one dimension at least, but how?
|
The return type would beint (*)[5](pointer to 5-element array ofint), as follows
```
int (*foo(void))[5]
{
static int arr[5][5];
...
return arr;
}
```
It breaks down as
```
foo -- foo
foo( ) -- is a function
foo(void) -- taking no parameters
*foo(void) -- re... |
I have an xml file in below format and I decided to use libxml2 after experts suggested I go for this in this forum. I started with little knowledge.
```
<ACCOUNT NO="123>
<STATE> FL </STATE>
<PERCENT>10.2</PERCENT>
</ACCOUNT>
```
Now my question is , since value of PERCENT tag is floating, how do I read PERCE... |
libxml gives you a string which you can convert to an int or float using whatever method you wish... in C strtol or strtod, using a stringstream in c++, etc etc...
|
Found the function on "Computer Systems":
```
int fun_a(unsigned x){
int val = 0;
while(x){
val ^= x;
x >>= 1;
}
return val & 0x1;
}
```
it return 1 if x contains odd "1", return 0 if x contains even "1".
I know "val & 0x1" check val is odd or even, but I don't know how it count the b... |
It doesn't exactly count the bits, but the XOR will flip the low bit invalonce for each bit inx. That will make it a1if it is flipped an odd number of times.
It also flips a lot of other bits inval, but that is irrelevant as they are masked off in the return statement.
|
Last week I had an interview. I was asked to write a macro to read a memory location (say0x2000).
I wrote the code in normal programming, but I could not write the macro.Please help me figure out how to write the macro for the code below:
```
char *address = (char*)0x2000; // address is a pointer to address 3000 char... |
Something like this?
```
#define READ_CHAR_AT(address) *((char *) (address))
```
|
CreateFilevsfopenvsofsteam-advantage & disadvantage?
I heard that CreateFile powerful but only for windows.Can you tell what should I use ( on windows) and why?
|
It depends on what you're doing. For sequentially reading and writing text files, iostream is definitely the way to go. For anything involving transactional security or non-standard devices, you'll have to access the system directly (CreateFileoropen). Even then, for sequential reading and writing of text, the best... |
I have to assign memory to a 3D array using a triple pointer.
```
#include <stdio.h>
int main()
{
int m=10,n=20,p=30;
char ***z;
z = (char***) malloc(sizeof(char**)*m*n*p);
return 0;
}
```
Is this correct way of doing this?(I think what i am doing is incorrect.)
|
To completely allocate a 3D dynamic array you need to do something like the following:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m=10,n=20,p=30;
char ***z;
z = malloc(m * sizeof(char **));
assert(z != NULL);
for (i = 0; i < m; ++i)
{
z[i] = malloc(n * sizeof(char *)... |
I came across a piece of code which is as below
qsort(array, 10, sizeof(int), sort);
Here sort is again a function. But I was always under the impression that any function which is called should have()after the function name or was I missing something.
I just wanted to know how will this work and what are the diffe... |
```
qsort(array, 10, sizeof(int), sort);
```
this passes a pointer to the function "sort" so that the function "qsort" can call this function.
|
I got this from a site which was explaining sorting. But i could not understand*(int*)x. How to read the variable x when used like this in C program? Is it pointer to pointer of x or is it different? Any help is appreciated. Thanks!
|
You can get there if you split it up, first:
```
(int*)x
```
This castsxto anint*, pointer to anint. I assume in this case,xis anint, so the number inxgets interpreted as a pointer.
In the next step:
```
*(int*)x
```
*dereferences a pointer, in this case the just castedint. The result is anint.
In short: Interpr... |
I've an address in memory and I want to find out the permissions (r/w/x) of that memory address.
E.g.
```
char *s = "hello";
```
Here, the string literal "hello" is stored in read-only memory. When running the program through gdb, is there a possibility to check out the permissions for that memory address (whether ... |
You can first find wheresis pointing to:
```
(gdb) print s
$6 = 0x400dbc "foo"
```
and then find the section in which it's in:
```
(gdb) maintenance info sections
Exec file:
`/home/mfukar/tmp', file type elf64-x86-64.
...sections...
0x00400db8->0x00400dfb at 0x00000db8: .rodata ALLOC LOAD READONLY DATA ... |
I have to usesudoto run my program:
```
sudo ./my_program
```
I am trying to rungit clonefrom my program, but it tries to use the root user's SSH keys instead of mine.
Is there a way to execute this single command as the user who originally invoked my program?
I guess I can do:
```
su - original_user -c "git --ve... |
Thesudomanual shows that$SUDO_USERshould give you the original user's username and$SUDO_UIDgives the original user's UID.
|
I would like to know how to "subtract letters" in C:I mean, I have 2 letters, 'a' and 'c' and i want to execute 'c'-'a'='b' which is 3-1=2.How is it possible to obtain the same behaviour in C?I can conversionLetters->Numbersbut how to manage thelimited lenghtof the alphabet?Thank you.
|
you can treat the letters as numbers and then add the letter'a'back to normalize it
so
```
char c1 = 'a';
char c2 = 'c';
int diff = c2 - c1; //'c' - 'a' = 2
char ans = diff + 'a' - 1; //add 'a' and subtract 1 to normalize it
```
If you want the number difference just usedifffrom my answer (answill give you the lett... |
This question already has an answer here:Closed11 years ago.
Possible Duplicate:What is the C Equivalent of Python's pack(“<I”, 0)
How can I replicate the code in Python:
```
from struct import pack
string = pack("<I", 0x11111111)
print string
```
in C? From what I understand \x11 is a nonprintable character so...... |
```
const char *string = "\x11\x11\x11\x11";
puts(string);
```
|
I'm currently having a bit of trouble with arrays of structs (specifically, my array is so big that it takes up seven megabytes of memory), and I'm beginning to question whether I really need to declare all the structs at one time and hog the memory like that, rather than increment it proportionally as new structs are... |
Linked lists?Or any other more advanced data structures, depending on your purpose, but in any case some reading seems to be in order :) Or if you're doing C++, just use std::list.
|
I want to run an application on closing/Disconnecting Remote Desktop Connection. Is there's any way to keep record of Remote desktop session start-stop timing in winndows xp/win 7.
|
You can write a Windows service and listen for SERVICE_CONTROL_SESSIONCHANGE. One of the parameters for that event is the session state, which in this case you would be interested in either WTS_SESSION_LOGON/WTS_SESSION_LOGOFF or WTS_REMOTE_CONNECT/WTS_REMOTE_DISCONNECT depending on your needs.
|
I have an xml file in below format and I decided to use libxml2 after experts suggested I go for this in this forum. I started with little knowledge.
```
<ACCOUNT NO="123>
<STATE> FL </STATE>
<PERCENT>10.2</PERCENT>
</ACCOUNT>
```
Now my question is , since value of PERCENT tag is floating, how do I read PERCE... |
libxml gives you a string which you can convert to an int or float using whatever method you wish... in C strtol or strtod, using a stringstream in c++, etc etc...
|
Found the function on "Computer Systems":
```
int fun_a(unsigned x){
int val = 0;
while(x){
val ^= x;
x >>= 1;
}
return val & 0x1;
}
```
it return 1 if x contains odd "1", return 0 if x contains even "1".
I know "val & 0x1" check val is odd or even, but I don't know how it count the b... |
It doesn't exactly count the bits, but the XOR will flip the low bit invalonce for each bit inx. That will make it a1if it is flipped an odd number of times.
It also flips a lot of other bits inval, but that is irrelevant as they are masked off in the return statement.
|
Last week I had an interview. I was asked to write a macro to read a memory location (say0x2000).
I wrote the code in normal programming, but I could not write the macro.Please help me figure out how to write the macro for the code below:
```
char *address = (char*)0x2000; // address is a pointer to address 3000 char... |
Something like this?
```
#define READ_CHAR_AT(address) *((char *) (address))
```
|
CreateFilevsfopenvsofsteam-advantage & disadvantage?
I heard that CreateFile powerful but only for windows.Can you tell what should I use ( on windows) and why?
|
It depends on what you're doing. For sequentially reading and writing text files, iostream is definitely the way to go. For anything involving transactional security or non-standard devices, you'll have to access the system directly (CreateFileoropen). Even then, for sequential reading and writing of text, the best... |
I have to assign memory to a 3D array using a triple pointer.
```
#include <stdio.h>
int main()
{
int m=10,n=20,p=30;
char ***z;
z = (char***) malloc(sizeof(char**)*m*n*p);
return 0;
}
```
Is this correct way of doing this?(I think what i am doing is incorrect.)
|
To completely allocate a 3D dynamic array you need to do something like the following:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m=10,n=20,p=30;
char ***z;
z = malloc(m * sizeof(char **));
assert(z != NULL);
for (i = 0; i < m; ++i)
{
z[i] = malloc(n * sizeof(char *)... |
I came across a piece of code which is as below
qsort(array, 10, sizeof(int), sort);
Here sort is again a function. But I was always under the impression that any function which is called should have()after the function name or was I missing something.
I just wanted to know how will this work and what are the diffe... |
```
qsort(array, 10, sizeof(int), sort);
```
this passes a pointer to the function "sort" so that the function "qsort" can call this function.
|
I got this from a site which was explaining sorting. But i could not understand*(int*)x. How to read the variable x when used like this in C program? Is it pointer to pointer of x or is it different? Any help is appreciated. Thanks!
|
You can get there if you split it up, first:
```
(int*)x
```
This castsxto anint*, pointer to anint. I assume in this case,xis anint, so the number inxgets interpreted as a pointer.
In the next step:
```
*(int*)x
```
*dereferences a pointer, in this case the just castedint. The result is anint.
In short: Interpr... |
I've an address in memory and I want to find out the permissions (r/w/x) of that memory address.
E.g.
```
char *s = "hello";
```
Here, the string literal "hello" is stored in read-only memory. When running the program through gdb, is there a possibility to check out the permissions for that memory address (whether ... |
You can first find wheresis pointing to:
```
(gdb) print s
$6 = 0x400dbc "foo"
```
and then find the section in which it's in:
```
(gdb) maintenance info sections
Exec file:
`/home/mfukar/tmp', file type elf64-x86-64.
...sections...
0x00400db8->0x00400dfb at 0x00000db8: .rodata ALLOC LOAD READONLY DATA ... |
I have to usesudoto run my program:
```
sudo ./my_program
```
I am trying to rungit clonefrom my program, but it tries to use the root user's SSH keys instead of mine.
Is there a way to execute this single command as the user who originally invoked my program?
I guess I can do:
```
su - original_user -c "git --ve... |
Thesudomanual shows that$SUDO_USERshould give you the original user's username and$SUDO_UIDgives the original user's UID.
|
I would like to know how to "subtract letters" in C:I mean, I have 2 letters, 'a' and 'c' and i want to execute 'c'-'a'='b' which is 3-1=2.How is it possible to obtain the same behaviour in C?I can conversionLetters->Numbersbut how to manage thelimited lenghtof the alphabet?Thank you.
|
you can treat the letters as numbers and then add the letter'a'back to normalize it
so
```
char c1 = 'a';
char c2 = 'c';
int diff = c2 - c1; //'c' - 'a' = 2
char ans = diff + 'a' - 1; //add 'a' and subtract 1 to normalize it
```
If you want the number difference just usedifffrom my answer (answill give you the lett... |
This question already has an answer here:Closed11 years ago.
Possible Duplicate:What is the C Equivalent of Python's pack(“<I”, 0)
How can I replicate the code in Python:
```
from struct import pack
string = pack("<I", 0x11111111)
print string
```
in C? From what I understand \x11 is a nonprintable character so...... |
```
const char *string = "\x11\x11\x11\x11";
puts(string);
```
|
I'm currently having a bit of trouble with arrays of structs (specifically, my array is so big that it takes up seven megabytes of memory), and I'm beginning to question whether I really need to declare all the structs at one time and hog the memory like that, rather than increment it proportionally as new structs are... |
Linked lists?Or any other more advanced data structures, depending on your purpose, but in any case some reading seems to be in order :) Or if you're doing C++, just use std::list.
|
I was reading some source code, and this came up;
```
struct Cookie *
Curl_cookie_add(struct SessionHandle *data, /* rest of params were here */)
{
/* unrelated things were here */
#ifdef CURL_DISABLE_VERBOSE_STRINGS
(void)data;
#endif
/* rest of function goes here */
}
```
As you can see, void casted pointer, isn... |
This cast suppresses a compiler warning that would arise ifdatais not used.
GCC produces this warning if the-Wunused-parameterflag (implied by-Wextra) is enabled.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Python import dll
I am trying to load a c dll located at the same path where my .py script is, still I can not load the dll.
```
module = PyImport_ImportModule("<module-name.dll>");
```
Any suggestion.
|
You must call the line below to set your current directory in path, that is because by default, the current directory is not in the search path:
```
PySys_SetPath(".");
mymod = PyImport_ImportModule("your_DLL_name or Py_module_name");
```
Once you have above code the C DLL or Python module will be loaded.
|
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... |
Just found theIGCC(Interactive GCC) REPL. I like it.
Example:
```
./igcc
g++> int a = 1, b = 2;
g++> printf("%d\n", a + b);
3
g++>
```
And it gives you compile errors like this:
```
g++> c = 3;
[Compile error - type .e to see it.]
g++> .e
<stdin>:14:1: error: use of undeclared identifier 'c'
c = 3;
^
```
(SF do... |
I have this kind of code. What I'm interested in is to find the data dependencies between the loops, so that I can guess If I can run the loops in parallel. Is there any tool which can help me with this.
```
void some_func()
{
for( ... )
{
...
}
for( ... )
{
...
}
for( ... )
{
...
}
}
```
|
Seefor data flow results computedby ourDMS Software Reengineering Toolkitand itsC Front End.
(Our C++ front won't quite do this yet).
Probably an expensive way to see those dependencies if you only want do to this for one or two loops. You obviously can do this by hand, and yes it is painful.
|
Given:
```
int a[N];
int *p;
```
why doesa-pwork yeta+pdoes not with error: "invalid operands to binary +".
|
Thedifferencebetween two pointers is meaningful, i.e. it is the number of elements between the two pointers (provided that they both lie within the same array).
Addingtwo pointers makes no sense though (how would you interpret it ?).
|
I'm writing a C program where I fork() read a file in parent and pass to child via a pipe, then in child redirect the file receive from the pipe to the program I want to execv,
For example, if I exec /bin/less with doc.txt, I will read doc.txt in parent and pass to child, then execute less with the string receive fro... |
Since any forked child share the parents file descriptors, you can simply redirect stdin to a file descriptor withdup2()then just fork and exec away in your child process.
When the child process reads data from stdin, it'll read from the file descriptor you opened (which could be a descriptor to your doc.txt).
|
I have a repository. I don't want to checkout the whole repository but just one folder inside it. I don't remember the folder names, so I want to see them. Is there a command in svn which can show all the folder names in the root directory of the repository.
|
Have you triedsvn ls http://repo.url/here?
|
My program receives an executable binary file through a TCP socket.
I need to save this file in to the harddisk as a executable program. File is successfully received but the problem is the default file attribute is being set to non executable.
How to change the file's attribute as executable in C in Ubuntu?
Thank ... |
How aboutint chmod(const char *path, mode_t mode)andint fchmod(int fd, mode_t mode) ?
```
apropos chmod
man 2 chmod
```
The most basic example:
```
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
char * fpath = "/path/to/binary";
int ret=0;
if(ret = chmod(fp... |
I listed some example code below and the question is if there is a way for the function_name to access the value of number from struct_name?
```
typedef struct struct_name {
int number
void (*func)();
} * struct_name_ptr;
void function_name() {
//access number from struct
}
main() {
struct_name_ptr ... |
Uh - no.
A struct can certainlycontaina function pointer. But the function you call wouldn't have any knowledge of the struct. Unless you passed a pointer as a function argument, or made the struct global.
|
I am trying to figure out the correct way to write the EBNF description for a C float literal.
This is the one problem that I am stuck on. I am not sure how to write it because isn't float just a type? So far I am thinking it may just be
float < literal >
But that seems way too simple.
|
Yes, from a viewpoint of a parser, a floating point ltieral would generally just be another token.
Figuring out that a particular sequence of input characters was a floating point literal would normally be done by the lexer. It's not as trivial as you'd like, but still pretty much a one-liner using a regex.
|
I don't know much python but from what I can tell from the documentation the code:
```
str = "AAAA"
str += pack("<I", 0)
```
would append the result of the pack function to str, which would be the integer value of 0 in little-endian style. My question is what the C equivalent of this would be. Would it just be:
... |
strcat()stops at the first NUL, so no.
```
char str[20] = "AAAA";
int val = 0;
int nval = htole32(val);
memcpy(str + 4, (char*)&nval, 4);
```
|
When I code and run the statement:
```
print "\x00\x00\x00"
```
in Python it outputs three blank spaces followed by a newline. But in C, when I code and run the statement:
```
char hex[] = "\x00\x00\x00";
printf("%s\n", hex);
```
it interprets the NULL bytes like I thought it would: it doesn't do anything. So w... |
So why in Python are NULL bytes treated as spaces?
It's not. Your terminal/console is treating them like spaces. C just happens to stop at the first NUL, whereas Python outputs them. Try writing three NULs to stdout instead.
|
it's possible to write something like this?
```
#define ISWINDOWS() (#if defined(_WIN32) || defined(_WIN64) \
1 \
#elif \
0 \
#endif)
```
and then:
```
void foo() {
if(ISWINDOWS()) {
// ..
} else {
// ...
}
}
```
|
You cannot define a macro within a macro. You can do this, but its probably not what you want:
```
#if defined(_WIN32) || defined(_WIN64)
#define ISWINDOWS() 1
#elif
#define ISWINDOWS() 0
#endif
```
|
I know the initial value of an array is 0 when defined as static and undefined otherwise, but I'm not entirely sure if this is the same way when the array is typedef'd. I think so, but I want to confirm it.
Just to make it clear, I mean something like this:
```
typedef float vector3[3];
int main (int argc, char* ar... |
Yes, the values invecwould be undefined; the values invec2would be all zeroes.
The use of atypedefmakes no difference to the behaviour of the type when variables are defined or declared.
|
My question is how I would go about converting something like:
```
int i = 0x11111111;
```
to a character pointer? I tried using the itoa() function but it gave me a floating-point exception.
|
itoais non-standard. Stay away.
One possibility is to usesprintfand the proper format specifier for hexa i.e.xand do:
```
char str[ BIG_ENOUGH + 1 ];
sprintf(str,"%x",value);
```
However, the problem with this computing the size of thevaluearray. You have to do with some guesses andFAQ 12.21is a good starting point... |
The following code shows a segmentation error. How to solve the problem? What is the problem with the code?
```
#include <stdio.h>
void stcp (char *, char *);
int
main ()
{
char *s = "This is first string";
char *t = "string to be copied";
stcp (s, t);
printf ("%s", s);
getch ();
}
void
stcp (char *s, c... |
A string literal isconstby default. To make it un-const, you must make it an array:
```
char s[] = "this is my string";
char t[] = "another string";
```
|
i recently moved to a C project and i want to use eclipse CDT as my IDE. The project layout is a bit annoying. the header files are located
main_component/sub_comonent/include/ folder
However, in the c source file. they are referenced as#inlcude<main/subcomonent/sample.h>.
In eclipse, if i put include folder into m... |
It seems there is no better way. I finally decided to copy all the header files out to one folder by a bash.
|
I was reading some source code, and this came up;
```
struct Cookie *
Curl_cookie_add(struct SessionHandle *data, /* rest of params were here */)
{
/* unrelated things were here */
#ifdef CURL_DISABLE_VERBOSE_STRINGS
(void)data;
#endif
/* rest of function goes here */
}
```
As you can see, void casted pointer, isn... |
This cast suppresses a compiler warning that would arise ifdatais not used.
GCC produces this warning if the-Wunused-parameterflag (implied by-Wextra) is enabled.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Python import dll
I am trying to load a c dll located at the same path where my .py script is, still I can not load the dll.
```
module = PyImport_ImportModule("<module-name.dll>");
```
Any suggestion.
|
You must call the line below to set your current directory in path, that is because by default, the current directory is not in the search path:
```
PySys_SetPath(".");
mymod = PyImport_ImportModule("your_DLL_name or Py_module_name");
```
Once you have above code the C DLL or Python module will be loaded.
|
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... |
Just found theIGCC(Interactive GCC) REPL. I like it.
Example:
```
./igcc
g++> int a = 1, b = 2;
g++> printf("%d\n", a + b);
3
g++>
```
And it gives you compile errors like this:
```
g++> c = 3;
[Compile error - type .e to see it.]
g++> .e
<stdin>:14:1: error: use of undeclared identifier 'c'
c = 3;
^
```
(SF do... |
I have this kind of code. What I'm interested in is to find the data dependencies between the loops, so that I can guess If I can run the loops in parallel. Is there any tool which can help me with this.
```
void some_func()
{
for( ... )
{
...
}
for( ... )
{
...
}
for( ... )
{
...
}
}
```
|
Seefor data flow results computedby ourDMS Software Reengineering Toolkitand itsC Front End.
(Our C++ front won't quite do this yet).
Probably an expensive way to see those dependencies if you only want do to this for one or two loops. You obviously can do this by hand, and yes it is painful.
|
Given:
```
int a[N];
int *p;
```
why doesa-pwork yeta+pdoes not with error: "invalid operands to binary +".
|
Thedifferencebetween two pointers is meaningful, i.e. it is the number of elements between the two pointers (provided that they both lie within the same array).
Addingtwo pointers makes no sense though (how would you interpret it ?).
|
I'm writing a C program where I fork() read a file in parent and pass to child via a pipe, then in child redirect the file receive from the pipe to the program I want to execv,
For example, if I exec /bin/less with doc.txt, I will read doc.txt in parent and pass to child, then execute less with the string receive fro... |
Since any forked child share the parents file descriptors, you can simply redirect stdin to a file descriptor withdup2()then just fork and exec away in your child process.
When the child process reads data from stdin, it'll read from the file descriptor you opened (which could be a descriptor to your doc.txt).
|
I have a repository. I don't want to checkout the whole repository but just one folder inside it. I don't remember the folder names, so I want to see them. Is there a command in svn which can show all the folder names in the root directory of the repository.
|
Have you triedsvn ls http://repo.url/here?
|
My program receives an executable binary file through a TCP socket.
I need to save this file in to the harddisk as a executable program. File is successfully received but the problem is the default file attribute is being set to non executable.
How to change the file's attribute as executable in C in Ubuntu?
Thank ... |
How aboutint chmod(const char *path, mode_t mode)andint fchmod(int fd, mode_t mode) ?
```
apropos chmod
man 2 chmod
```
The most basic example:
```
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
char * fpath = "/path/to/binary";
int ret=0;
if(ret = chmod(fp... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
What is the meaning of "f" in C's p... |
Thefinprintfstands forformatted, its used for printing with formatted output.
|
I have a problem with python to C code translation and further compilation.
First, I installed MinGW, wrote `setup.py? script and translated python code (simplest helloworld) to C with Cython:
python setup.py build_ext --inplace
Then I tried to compile generated .c file:
gcc.exe helloworld.c -mdll -IC:\Python27\in... |
See Cython wiki onEmbedding Cythonfor creating standalone executable with Cython
|
```
#include <stdio.h>
int main(int argc, const char * argv[])
{
long nc;
nc=0;
while (getchar()!=EOF) {
++nc;
printf("%ld\n", nc);
}
}
```
This is the code, and when I typed a character, it will print 1 then print 2, even if I have only typed once.
I am using Xcode.
|
This is the code, and when I typed a character, it will print 1 then
print 2, even if I have only typed once.
But you did pressreturn, didn't you ? Try pressingCTRL+Dor watch out for the newline in the loop. Maybe something like this ?
```
int ch;
while ((ch = getchar()) != EOF) {
if (ch == '\n')
conti... |
I have made a code that read data from flash Nand (without filesystem).
```
fd = open("/dev/mtd0", O_RDONLY)
```
It works, then I want to try to read write it..
So I change the code to:
```
fd = open("/dev/mtd0", O_RDWR)
```
But It returns-1, means can not open. But for others MTD, it works.
Then I seecat /proc/m... |
The operation is likely being forbidden by the kernel driver for your device. It's likely that your device is actually read-only or marked as such by the driver.
|
Here's my aim - to take the ASCII roguelike Angband and create an online console where users can play the game server-side. From my superficial viewpoint this seems like itshouldbe doable - as there are REPL consoles that can be displayed online for a multitude of languages, so interpreting the language shouldn't be a... |
Probably the simplest -- and coolest -- solution to this sort of thing isEmscripten. It's literally a LLVM -> JavaScript translator. You can generate LLVM bytecode using a C compiler (using llvm-gcc or Clang), so this is a reasonably short path from C to JavaScript.
You will, of course, still need some JavaScript "gl... |
How could I go about writing a Haskell library to provide input functionality similar to that provided by SDL or GLFW? Specifically, how would I go about grabbing device events (e.g. mouse, keyboard, joystick) and system events (e.g. quit, resize, window move, focus).
|
Make FFI bindings to the primitives provided by the platform (or library) you're building on.Use these primitives to implement higher level abstractions.
|
This appears to be a simple problem but I haven't had any luck searching for any answers so here goes. I have a struct Person with char* name and int age. I have the following method:
```
void Person_messup(struct Person &who) {
who.name="asdfasdf";
who.age = 9001;
}
```
compiling this code gives me the foll... |
There are no references in c - pass the struct as a pointer.
```
void Person_messup(Person *who) {
who->name="asdfasdf"; // or really strcpy!
who->age = 9001;
}
```
(or use c++ !)
|
It seems that forprintf-style debugging people always use preprocessor macros. Is there anything wrong with a solution similar to this one?
```
void debug(char *msg) {
#ifdef DEBUG
printf("%s", msg);
#endif
}
```
|
Usually so that they can do something like this:
```
#define DEBUG(MSG) printf("[%s:%i] %s\n", __FILE__, __LINE__, (MSG))
```
Since it's so useful to have the exact source of a debug message right there in the log, this is a pretty common pattern. But if you used a function, like so:
```
void DEBUG(const char *MSG)... |
Although I have compiled my C program with-g -O0, the backtrace I get from gdb is useless:
```
(gdb) bt
#0 0x6113759d in wordfree () from /cygdrive/c/cygwin/bin/cygwin1.dll
#1 0x75141375 in OutputDebugStringA () from /cygdrive/c/Windows/system32/KERNELBASE.dll
#2 0x40010006 in ?? ()
#3 0x00000000 in ?? ()
```
Is... |
"bt full" should give you better results.
|
I need to enable core dumps in cygwin. I have usedulimit -c unlimitedbut when the program I want to debug crashes, there still is no coredump in the directory. Is this actually the correct way to enable core dumps and where can I find the dump then?
|
This should be working. What shell are you using?
Don't forget that the dump is not named "core" ... rather on a Windows machine with Cygwin it will likely be named something like "mybadprog.exe.stackdump"
|
The output of this program is 28. I don't understand how?
According to me this should be 32(4+4+4+4+12)+4(to maintain the alignment)=32.
Please explain the reason for displaying the output 28??
```
struct test{
char c;
int d;
int x;
int y;
long double p;
}t1;
printf("%d",sizeof(t1));
```
|
Maybe your "long double" is actually the same as a double (8 bytes), and if you're on a 32bit processor the alignment is 4-byte.
4+4+4+4+8 = 24
What issizeof(long double)?
EDIT:
I used GCC's__builtin_offset_of()and__alignof__to investigate. The actual answer that explains the size of the struct is:
4+4+4+4+12 = ... |
I have a question about this code:
```
typedef struct pop {
unsigned long int *np; // matrix
unsigned long int f;
long double fp;
unsigned long int *R; // matrix
unsigned long int *C; // matrix
unsigned long int Dp;
unsigned long int Ds;
unsigned long int count;
struct popolazione *ptrTempLst; // pointer
struct popo... |
Yes.
Every call tomallocmust have a matching call tofree.
|
I am trying to read a file in C. But when I read, and write it to stdout it prints @ also which there is no in my file. What is the reason?
```
#include <stdio.h>
int main() {
FILE *fp;
int br;
char buffer[10];
int i;
fp = fopen("a.txt","r");
while(1) {
br = fread(buffer,1,10,fp);
printf("%s",buffer... |
Yourfreadcall reads up to 10 bytes correctly, butprintfwith%srequires string to be null terminated. You can fix it by increasing size of the buffer to be 11 bytes and after every call tofreadwrite zero at the end of data, i.e.buffer[br] = 0;.
The other way to go is to tellprintfwhat is the size of your data by callin... |
```
#ifndef UNICODE
#define UNICODE
#endif
#include <Windows.h>
#include <cstring>
#include <cstdio>
int main()
{
TCHAR* greeting = L"HELL\0O W\0ORLD!";
wprintf(L"%s\n",greeting);
_wsystem(L"pause");
return 0;
}
```
How to remove all null characters(except of trailing) in "greeting"? I would lik... |
Unfortunately, after
```
TCHAR* greeting = L"HELL\0O W\0ORLD!";
```
the length of the string is lost. The runtime will only see
```
greeting == L"HELL"; //HA!
```
You need to store the length of the string and manually shift the characters.
|
This appears to be a simple problem but I haven't had any luck searching for any answers so here goes. I have a struct Person with char* name and int age. I have the following method:
```
void Person_messup(struct Person &who) {
who.name="asdfasdf";
who.age = 9001;
}
```
compiling this code gives me the foll... |
There are no references in c - pass the struct as a pointer.
```
void Person_messup(Person *who) {
who->name="asdfasdf"; // or really strcpy!
who->age = 9001;
}
```
(or use c++ !)
|
It seems that forprintf-style debugging people always use preprocessor macros. Is there anything wrong with a solution similar to this one?
```
void debug(char *msg) {
#ifdef DEBUG
printf("%s", msg);
#endif
}
```
|
Usually so that they can do something like this:
```
#define DEBUG(MSG) printf("[%s:%i] %s\n", __FILE__, __LINE__, (MSG))
```
Since it's so useful to have the exact source of a debug message right there in the log, this is a pretty common pattern. But if you used a function, like so:
```
void DEBUG(const char *MSG)... |
Although I have compiled my C program with-g -O0, the backtrace I get from gdb is useless:
```
(gdb) bt
#0 0x6113759d in wordfree () from /cygdrive/c/cygwin/bin/cygwin1.dll
#1 0x75141375 in OutputDebugStringA () from /cygdrive/c/Windows/system32/KERNELBASE.dll
#2 0x40010006 in ?? ()
#3 0x00000000 in ?? ()
```
Is... |
"bt full" should give you better results.
|
I need to enable core dumps in cygwin. I have usedulimit -c unlimitedbut when the program I want to debug crashes, there still is no coredump in the directory. Is this actually the correct way to enable core dumps and where can I find the dump then?
|
This should be working. What shell are you using?
Don't forget that the dump is not named "core" ... rather on a Windows machine with Cygwin it will likely be named something like "mybadprog.exe.stackdump"
|
The output of this program is 28. I don't understand how?
According to me this should be 32(4+4+4+4+12)+4(to maintain the alignment)=32.
Please explain the reason for displaying the output 28??
```
struct test{
char c;
int d;
int x;
int y;
long double p;
}t1;
printf("%d",sizeof(t1));
```
|
Maybe your "long double" is actually the same as a double (8 bytes), and if you're on a 32bit processor the alignment is 4-byte.
4+4+4+4+8 = 24
What issizeof(long double)?
EDIT:
I used GCC's__builtin_offset_of()and__alignof__to investigate. The actual answer that explains the size of the struct is:
4+4+4+4+12 = ... |
I have a question about this code:
```
typedef struct pop {
unsigned long int *np; // matrix
unsigned long int f;
long double fp;
unsigned long int *R; // matrix
unsigned long int *C; // matrix
unsigned long int Dp;
unsigned long int Ds;
unsigned long int count;
struct popolazione *ptrTempLst; // pointer
struct popo... |
Yes.
Every call tomallocmust have a matching call tofree.
|
I am trying to read a file in C. But when I read, and write it to stdout it prints @ also which there is no in my file. What is the reason?
```
#include <stdio.h>
int main() {
FILE *fp;
int br;
char buffer[10];
int i;
fp = fopen("a.txt","r");
while(1) {
br = fread(buffer,1,10,fp);
printf("%s",buffer... |
Yourfreadcall reads up to 10 bytes correctly, butprintfwith%srequires string to be null terminated. You can fix it by increasing size of the buffer to be 11 bytes and after every call tofreadwrite zero at the end of data, i.e.buffer[br] = 0;.
The other way to go is to tellprintfwhat is the size of your data by callin... |
```
#ifndef UNICODE
#define UNICODE
#endif
#include <Windows.h>
#include <cstring>
#include <cstdio>
int main()
{
TCHAR* greeting = L"HELL\0O W\0ORLD!";
wprintf(L"%s\n",greeting);
_wsystem(L"pause");
return 0;
}
```
How to remove all null characters(except of trailing) in "greeting"? I would lik... |
Unfortunately, after
```
TCHAR* greeting = L"HELL\0O W\0ORLD!";
```
the length of the string is lost. The runtime will only see
```
greeting == L"HELL"; //HA!
```
You need to store the length of the string and manually shift the characters.
|
I want creat a C program for Unix that can porcess the Regular Expression,like a simple Perl interpreter. Do I have to personally write an regexp engine?
|
http://www.gnu.org/software/libc/manual/html_node/Regular-Expressions.html
You might like to look for a library with it already coded. C uses librarys to allow you to include other peoples code into your work. I assume there are many regular expression librarys for you to use already to go!
|
I develop a program on Solaris 10.
I want it to print stack trace on crash. I found this example:
```
static void pstack()
{
char buf[256];
sprintf(buf, "/usr/proc/bin/pstack %d |/bin/tee traceback.txt\n", (int)getpid());
/* undefine LD_PRELOAD to avoid 64-bit problems */
(void)putenv("LD_PRELOAD=");
syste... |
No, a handledSIGSEGVdoes not affect any other threads (although if it resulted from memory corruption or other UB, that UB could of course affect other threads). An unhandledSIGSEGVon the other hand terminates the whole process.
|
I want to insert GtkEntry widget to GtkToolbar. Following line
```
gtk_toolbar_insert(GTK_TOOLBAR(searchPanel_Toolbar),
GTK_TOOL_ITEM(searchPanel_Entry), -1);
```
gives me this error:
```
Gtk-CRITICAL **: gtk_toolbar_insert: assertion `GTK_IS_TOOL_ITEM (item)' failed
```
How can I add widgets... |
```
GtkToolbar *toolbar = gtk_toolbar_new();
GtkToolItem *item = gtk_tool_item_new();
GtkEntry *entry = gtk_entry_new();
gtk_container_add( GTK_CONTAINER(item), GTK_WIDGET(entry) );
gtk_toolbar_insert( GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(item), -1 );
```
|
I want to write an X-Chat plugin where users will be able to perform a CTCP request to my client, whereby the plugin/X-Chat will respond with my current active window title.
This would be really cool for fellow IRC users to see what I'm up to to allow them to determine what I'm doing if I'm full screen (playing a gam... |
Ithinkyou can useGetForegroundWindow()to get a handle to the window the user is using and then useGetWindowText()to get the title:
```
HWND foreground = GetForegroundWindow();
if (foreground)
{
char window_title[256];
GetWindowText(foreground, window_title, 256);
}
```
|
I want to make stack which work with dynamic memory allocation, but I need to know about which it is more efficient :to have an initial size like 10 for example , and then I double it if I need more.or I can have an initial size = 1 and for every new input adding one place . !?!
```
int *tmp = malloc(sizeof(int) * 2 ... |
Doubling when needed is way more efficient.
If you allocate a new array for every push operation, then you do an amount of work proportional to thesquareof the number of stack elements (when you push elementN+1, you must copy the previousNelements to the new array).
If you double the array when needed, then the numb... |
I have seen code for summation of an array using threads. In this code a thread is created and anintdata type is returned:
```
int iret1, iret2;
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
```... |
According toman pthread_create:
Return ValueOn success, pthread_create() returns 0; on error, it returns an error
number, and the contents of *thread are undefined.
That value simply indicates whether the thread creation was successful or not.
It is not a memory allocation call likemalloc, therefore I don't see w... |
Embarrassingly basic question.sudo apt-get install libmemcached6- where do the .h's and .o's or .so's live in a typical install on a Linux machine (Ubuntu)? And, how do I make sure g++ can pick them up?
|
They go to /usr/include and /usr/lib. If you use the -l option (for the libraries) it should find them from these standard places. If you include using<file.h>it should also get it from the right place.
|
I am pointing to the address of a 2D array, and I am confused as to how to dereference the pointer to free up the memory again. (I don't use "->" or "*". Is that wrong?)
My code:
```
double array[12][12];
//filled with numbers
double *arrayPtr; //pointer
arrayPtr = &array[0][0]; //pointing to address
multiply(a... |
In this case, the answer is no -- since you simply definedarray(didn't use something likemallocto allocate it) you don't have to do anything to free it either. If it was local (defined inside a function) it'll be freed automatically when you exit the function. If you defined it outside any function, it's a global, so ... |
I was wondering why does the following code not throw an error during compilation? :
```
#include <stdio.h>
char * func (char *);
int main()
{
func("TINFO");
func("INFO");
}
char * func(char * str)
{
if (str[0] == 'T')
return str + 1;
}
```
You see there is a return path from the function that does... |
All you have to do is raise the "warning" level on your compiler.
EXAMPLE:
```
$ gcc -o x x.c
<= DEFAULT: No warnings, no errors
$ gcc -Wall -pedantic -o x x.c
x.c: In function `main':
x.c:14: warning: control reaches end of non-void function
x.c: In function `func':
x.c:24: warning: control reaches end of non-vo... |
I have the following calculation to make:
```
float value = MY_VALUE;
float percentage = (value - MIN)/(MAX - MIN);
if (percentage < 0)
percentage = 0;
if (percentage > 1)
percentage = 1
```
I was just wondering if there is some method that exists in Objective-C or C to help accomplish this, like for example ... |
There is no such method in standard C libraries (I don't know about Objective C).
|
```
void echoFileA(const char* iPath,const char* oPath)
{
FILE* iFile;
FILE* oFile;
iFile = fopen(iPath,"rb");
oFile = fopen(oPath,"wb");
while(iFile)
fputc(fgetc(iFile),oFile);
fclose(iFile);
fclose(oFile);
}
```
The procedure was written purely for fun, I know that there a... |
The body of your loop ...
```
fputc(fgetc(iFile),oFile);
```
... does nothing to change the condition of the loop, so it will run forever.
Instead try something like ...
```
int c;
while((c = fgetc(iFile)) != EOF)
fputc(c, oFile);
```
The loop will end once you hit the end of the input file.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.