question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
How can I compile my program to run on a computer without having install Visual Studio 8 in the first place? When I start my program on another computer I get a side-by-side configuration message glitch and the program is terminated without executing my code. Could It be that I forgot to disable the debug symbol table... |
You are probaly running the program compiled with the "debug" configuration. The standard "debug" configuration requires the debug version of the runtime library, only available with VS. You should switch to the "Release" configuration (or manually remove the definition of the macro _DEBUG and change the runtime libra... |
UsingWinsock2the code sequence below returns-1(failure) forselect().
```
#include <Winsock2.h>
#include <stdio.h>
...
int rc;
int fdstdin = fileno(stdin); /* returns 0 as expected */
fd_set fds;
FD_ZERO(&fds);
FD_SET(fdstdin, &fds);
rc = select(1, &fds, NULL, NULL, NULL);
...
```
Is this the expected behaviour ... |
This is expected behavior. As mentioned all overthe documentation, winsock'sselectfunction only works on sockets, andstdinis not a socket.
If you had calledWSAGetLastError, you undoubtedly would have found that the cause was
WSAENOTSOCKOne of the descriptor sets contains an entry that is not a socket.
TryWSAEventS... |
In the Windows API, when you monitor a directory, the callback provides what changed. How do I accomplish the same for Mac OS X?
I looked at the File System Events API and the Kernel Events API and it seems like they both watch a file descriptor and return what changes happened to that file descriptor. This is inconv... |
FSEventswatches a directory hierarchy (or multiple hierarchies), not a file descriptor. So you only need one watcher. But you will need to scan the directories to find out which files changed. There is no better way (that doesn't involve a library).
|
TheUbuntu equivalentwould belibc6-dev, but I can't seem to find it for Solaris?
How can I get types.h and related files for building packages on Solaris or Illumos?
|
You need the system/header package.
I found this viahttp://pkg.oracle.com/solaris/release/en/search.shtml?token=types.h&action=Search
|
I created a dynamic array ,and i need to initialize all the members to 0.
How can this be done in C?
```
int* array;
array = (int*) malloc(n*sizeof(int));
```
|
In this case you would usecalloc():
```
array = (int*) calloc(n, sizeof(int));
```
It's safe to assume that all systems now have all zero bits as the representation for zero.
§6.2.6.2 guarantees this to work:
For any integer type, the object representation where all the bits are
zero shall be a representation of... |
I wrote this code to get my hands working on the system calls. I expected the first printf to show result in the console.. but both of them are showing the the given file location..
```
#include<stdio.h>
#include <unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
void main(){
printf("Hello Worl... |
The output tostdoutmay be buffered, and not actually written to the underlying file descriptor until the stream is flushed or closed. Try:
```
fflush(stdout);
```
beforeclose(1).
Note that mixing stdio and system file descriptor operations is not generally a good idea. Use one or the other, otherwise you may get co... |
How to convert integer to char and vice versa in "Dynamic C".
Use VB.NET as bellow:
```
Dim i As Integer
Dim c As Char
' Integer to Character
i = 302
c = ChrW(302)
Debug.Print(c) 'Result: Į
' Character to Integer
Dim j As Integer
j = AscW(c)
Debug.Print(CStr(j)) ' Result: 302
```
Thanks
|
Since both int and char are integer types, you can simply assign an appropriately-valued integer to a char and vice versa:
```
int i = 65; // 'A'
char c = 'B'; // 66;
int cAsInt = (int)c; // 66 = 'B'
char iAsChar = (char)i; // 'A' = "65"
```
|
I have declared and initialized two variables as shown below:
```
int a=5;
char* str;
str = (char*)calloc(255, sizeof(char));
```
I want to convert the int to char* in standard C. I cannot use any conversion function from C++ such itoa.
I am using Ubuntu 11.10
|
First of all,itoais not a C++ thing.
You can simply usesprintf:
```
sprintf(str, "%d", a)
```
In a real application you'll want to usesnprintfthough to remove the risk of a buffer overflow:
```
str = malloc(16);
snprintf(str, 16, "%d", a);
```
And 15 characters are way enough to store an integer.
|
I am going through C++ FAQ by cline. It discusses about how C++ classes are better than "C-style modules". One can refer the texthere.
But it doesn't discuss what a "C module" actually is. I read some texts on the net, but none of them dealt with the topic.
Can anyone explain these concepts further?
|
C does not have a concept of modules, as such. It has the concept of "translation unit", which is (roughly) the.cfile plus the contents of the headers it includes, directly or indirectly. The translation units get compiled independently, and then linked together into an executable program.
A translation unit gives a ... |
I am wondering if:
int a[] = {1, 2};
allocates sizeof(int) * number of constants inside brackets
int a[5] = {1, 2};
assigns constants to array fields from 0 to 1 and then fills with 0
int a[5] = {};
fills with 0
What happens when I do:
int a[] = {};
Thanks.
|
```
int a[5] = {};
```
and
```
int a[] = {};
```
are not valid C definitions.
In GNU C (C with gcc extensions), you can use empty{}and it is considered the same as{0}.
Note thatint []is a incomplete type. When initializing an array of an incomplete type with explicit initializers, the type is completed and the nu... |
For dealing with ASCII we have strlen, strcat etc..
For UTF16(i.e, UCS2) we havewcscatandwcslenfunctions.
For dealing with UTF8 and UCS4 what are the functions available in C?
Assume Linux/gcc
|
I don't think standard C libraries have UTF-8 functions. There are surely libraries for it.
However, normal str functions can be used with UTF-8 in many cases.strlenworks well, returning the number of bytes (not characters).strcatworks (it also overruns your buffer easily, but this is normal for strcat).
The reason ... |
I have the following code of declarations:
```
struct coord {
int x;
int y;
}
void rotateFig(struct coord[10][10]);
```
I need to implementrotateFig.
I tried to start with following:
```
void rotateFig(struct coord[10][10] c)
{
//code
}
```
I can`t compile it - probaly the way I transfer c in the function defin... |
Use this definition:
```
void rotateFig(struct coord c[10][10])
{
//code
}
```
The array is the actual parameter, so the dimensions have to come after its name, not before.
|
```
- (void)methedName{
if(){
_type ^=0x1;
}
}
```
What does this mean?
|
Your question's title and your code do different things.
0x1means "1" interpreted as hexadecimal digits. That happens to be the same as 1 in decimal.
So_type =0x1simply sets_typeto 1.
^means the XOR (exclusive-or) operator.
^=means compute the XOR of the left-hand side with the right-hand side and assign the resu... |
I want to do achieve something like this in Objective-C
```
+(int[10][10])returnArray
{
int array[10][10];
return array;
}
```
However, this gives an "array initializer must be an initializer list" compiler error. Is this at all possible?
|
You can't return an array (of any dimension) in C or in Objective-C. Since arrays aren't lvalues, you wouldn't be able to assign the return value to a variable, so there's no meaningful for such a thing to happen. You can work around it, however. You'll need to return a pointer, or pull a trick like putting your ar... |
I was wondering how can I print colorful text in the console? I use eclipse win64 OS. Does it have to do with the compiler? Can anyone give a simple example in C with just a hello world text in red or whatever?
|
I know that this is incredibly easy to do in C++, but I found this for you to look at in C:
```
#include <stdio.h>
#include <windows.h> // WinApi header
int main()
{
HANDLE hConsole;
int k;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// you can loop k higher to see more color choices
for(k = 1; k < ... |
Well, this must be a silly one. Here below is a can-not-be-simpler code in C. It can not compile saying "undefined reference to sleep". But I think I include all system header I need...
```
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Test starts.\n");
sleep(1);
printf("Test ends.\n");
... |
Try this at the top:
```
#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * (x))
#endif
```
This code will allow you to use two different functions under the same name, that do quite the same thing. And it compiles under different platforms.
Also, parenthes... |
I am new to JSON-C, Please see my sample code and let me know of it will create any memory leak, if yes then how to free JSON-C object.
```
struct json_object *new_obj = NULL;
new_obj = json_tokener_parse(strRawJSON);
new_obj = json_object_object_get(new_obj, "FUU");
if(NULL == new_obj){
S... |
NO, We need to call json_object_put only once for root object as long as we are not explicitly allocating memory to json-object and this worked for me.....!!
|
Sorry for the simple question but I'm on vacation reading a book on core audio, and don't have my C or Objective C books with me...
What are the curly braces doing in this variable definition?
```
MyRecorder recorder = {0};
```
|
Assuming thatMyRecorderis astruct, thissets every member to their respective representation of zero(0for integers,NULLfor pointers etc.).
Actually this also works on all other datatypes likeint,double, pointers, arrays, nested structures, ..., everything you can imagine (thanks to pmg for pointing this out!)
UPDATE:... |
I want to use the unixcryptfunction in an OpenCL program. Does something like that already exist or will I have to translate it on my own?
|
You've probably found an answer by now, but in case anyone else comes here from a search, John The Ripper is open source and has OpenCL acceleration for several hashing algorithms, including the 3DES used in BSD crypt().
https://github.com/magnumripper/JohnTheRipper/tree/bleeding-jumbo/src/opencl
|
I want to remove all my debugging printf statements from my code .How can i do this without using conditional debugging by turning on/off debug statements?
Iam using printf just to check whether a particular value is coming wright or not ...like below... : printf("value read %d\n", a);
|
No way you can do that, without removing them using your editor.
What you can do is:
Allen Holub recommends in hisbookto use the following debug macro:
```
#ifdef DEBUG
# define D(x) x
#else
# define D(x)
#endif
```
and use it like this:
```
D(printf("oh, hai, debug"));
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Address of register variable
I know that getting address of register variable is not allowed in c . But why this code is getting compiled in c++ and not in c.
```
int main()
{
register int a;
printf("%u\n",&a);
}
```
|
The keywordregisteris only a hint to the compiler. In fact, most compilers today ignore it as they contain advanced code to pick the best register variable candidates anyway.
Whenever you take the address of a variable, it is typically placed on the stack, despite the fact that you have used theregisterkeyword.
|
When I complement 1 (~1), I get the output as -2. How is this done internally?
I first assumed that the bits are inverted, so 0001 becomes 1110 and then 1 is added to it, so it becomes 1111 which is stored, how is the number then retrieved?
|
Well, no. When you complement 1, you go just invert the bits:
```
1 == 0b00000001
~1 == 0b11111110
```
And that's -2 in two's complement, which is the way your computer internally represents negative numbers. Seehttp://en.wikipedia.org/wiki/Two's_complementbut here are some examples:
```
-1 == 0b11111111
-2 ... |
Is there any testing tool for c,c++ or c#, other than debugging, which works like copying-pasting an independent function to some text box, and entering parameters on other text boxes?
|
Maybe you think about unit testing. I recommend you Google Test and Google Mock. It is simple and powerful tool (and for free!).
http://code.google.com/p/googletest/
http://code.google.com/p/googlemock/
There are some clear examples and very easy to read documentations.
After you create unit test you have possib... |
in my c application I have this typedef:
```
typedef double mat[2][2];
```
this is my declaration of function:
```
aaa(mat bbb, mat ccc, mat * ddd)
```
in my code I want to compute the sum of each member in math and write the result in ddd.
I did it over loops and this is the main line:
```
*ddd[i][j] = bbb[i][j]... |
You're writing at the wrong address. It should be:
```
(*ddd)[i][j] = bbb[i][j] + ccc[i][j];
```
or simply change the prototype to
```
aaa(mat bbb, mat ccc, mat ddd)
```
since arrays decay to pointers anyway.dddwill be a copy, but the address it points to will be the same as the original.
|
Please help me understand what this typedef is doing??
```
typedef void (xyz) (void *data);
extern struct x* FUNCTION(xyz *ptr);
```
Here is my understanding: in 1st line xyz is a function returning void and taking void pointer as an argument. But I cant interpret 2nd line with this understanding.
Any input is app... |
There is an external function calledFUNCTIONwhich takes a pointer to anxyzfunction as parameter and returns a pointer to astruct x.
|
This question already has answers here:Memory Allocation char* and char[](4 answers)Closed3 years ago.
Can anyone explain me what is a difference between these lines of code
```
char *p = "String";
char p2[] = "String";
char p3[7] = "String";
```
In what case should I use each of the above ?
|
This linkshould satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
|
Is there a C function that doesn't wait for input but if there is one, it detects it?
What I'm trying to do here is continue a loop endlessly until any key is pressed.
I'm a newbie, and all the input functions I've learned so far waits for the user to input something..
I hope I'm clear, although if I'm not I'm happy t... |
WIndows kbhit( ) does exactly thisnon-blocking keyboard char-ready check, and there's a kbhit( ) for Linuxover here
|
I'm using freemp3droid to convert wav files into mp3s. There is a click at the beginning of the file. When I take a look at the file in audacity, the initial 100bytes (beyond the header) have the same pattern. What could be happening??
Here is the waveform of the click (it is the 99% identical,EVERY single time)
h... |
Is your encoder trying to compress the WAV/RIFF 44 byte header as if it were audio?
|
I just started to play C and I bump into this problem. Here's my code:
```
#include<stdio.h>
#include<conio.h>
struct person {
int i;
char name[100];
};
int main() {
struct person p[2];
clrscr();
for(int i=0;i<2;i++) {
printf("Enter i:\n");
scanf("%d",&p[i].i);
printf("... |
You should print a string with%s;%cwill interpret the pointer as achar. (Strictly, I believe the result is undefined behavior.)
|
What is wrong in that code ?
I get error "Semantic Issue: Passing 'cards [3]' to parameter of incompatible type 'cards'"
```
#include <stdio.h>
typedef struct {
char *name;
int sequence
} cards;
void print_deck(cards data);
int main (int argc, const char * argv[])
{
cards deck[] =
{
{"Hea... |
You're trying to passdeck, which is anarrayof cards, to a function with a parameter of typecards. Those are two different types. You probably want to change the type of the parameter in theprint_deckfunction. I'd also suggest renaming thecardstype as it's only actually a single card.
|
I guess this question is somewhat wide but I'm trying to create a C console application (on windows os) that lets the user input the website address and the app will output the source code on the screen.
The second one was for me to traverse to the site source code to extract some contents.
Given that I know how to ... |
cURL. Or, for C++,curlpp.
|
I have the following two files:
file1.c
```
int main(){
foo();
return 0;
}
```
file2.c
```
void foo(){
}
```
Can I compile and link the two files together so thefile1.cwill recognize thefoofunction without addingextern?
Updated the prototype.
gcc file1.c file2.c throws: warning: implicit declaration of fu... |
The correct way is as follows:
file1.c
```
#include <stdio.h>
#include "file2.h"
int main(void){
printf("%s:%s:%d \n", __FILE__, __FUNCTION__, __LINE__);
foo();
return 0;
}
```
file2.h
```
void foo(void);
```
file2.c
```
#include <stdio.h>
#include "file2.h"
void foo(void) {
printf("%s:%s:%d \n... |
When I complement 1 (~1), I get the output as -2. How is this done internally?
I first assumed that the bits are inverted, so 0001 becomes 1110 and then 1 is added to it, so it becomes 1111 which is stored, how is the number then retrieved?
|
Well, no. When you complement 1, you go just invert the bits:
```
1 == 0b00000001
~1 == 0b11111110
```
And that's -2 in two's complement, which is the way your computer internally represents negative numbers. Seehttp://en.wikipedia.org/wiki/Two's_complementbut here are some examples:
```
-1 == 0b11111111
-2 ... |
Is there any testing tool for c,c++ or c#, other than debugging, which works like copying-pasting an independent function to some text box, and entering parameters on other text boxes?
|
Maybe you think about unit testing. I recommend you Google Test and Google Mock. It is simple and powerful tool (and for free!).
http://code.google.com/p/googletest/
http://code.google.com/p/googlemock/
There are some clear examples and very easy to read documentations.
After you create unit test you have possib... |
in my c application I have this typedef:
```
typedef double mat[2][2];
```
this is my declaration of function:
```
aaa(mat bbb, mat ccc, mat * ddd)
```
in my code I want to compute the sum of each member in math and write the result in ddd.
I did it over loops and this is the main line:
```
*ddd[i][j] = bbb[i][j]... |
You're writing at the wrong address. It should be:
```
(*ddd)[i][j] = bbb[i][j] + ccc[i][j];
```
or simply change the prototype to
```
aaa(mat bbb, mat ccc, mat ddd)
```
since arrays decay to pointers anyway.dddwill be a copy, but the address it points to will be the same as the original.
|
Please help me understand what this typedef is doing??
```
typedef void (xyz) (void *data);
extern struct x* FUNCTION(xyz *ptr);
```
Here is my understanding: in 1st line xyz is a function returning void and taking void pointer as an argument. But I cant interpret 2nd line with this understanding.
Any input is app... |
There is an external function calledFUNCTIONwhich takes a pointer to anxyzfunction as parameter and returns a pointer to astruct x.
|
This question already has answers here:Memory Allocation char* and char[](4 answers)Closed3 years ago.
Can anyone explain me what is a difference between these lines of code
```
char *p = "String";
char p2[] = "String";
char p3[7] = "String";
```
In what case should I use each of the above ?
|
This linkshould satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
|
Is there a C function that doesn't wait for input but if there is one, it detects it?
What I'm trying to do here is continue a loop endlessly until any key is pressed.
I'm a newbie, and all the input functions I've learned so far waits for the user to input something..
I hope I'm clear, although if I'm not I'm happy t... |
WIndows kbhit( ) does exactly thisnon-blocking keyboard char-ready check, and there's a kbhit( ) for Linuxover here
|
I'm using freemp3droid to convert wav files into mp3s. There is a click at the beginning of the file. When I take a look at the file in audacity, the initial 100bytes (beyond the header) have the same pattern. What could be happening??
Here is the waveform of the click (it is the 99% identical,EVERY single time)
h... |
Is your encoder trying to compress the WAV/RIFF 44 byte header as if it were audio?
|
I just started to play C and I bump into this problem. Here's my code:
```
#include<stdio.h>
#include<conio.h>
struct person {
int i;
char name[100];
};
int main() {
struct person p[2];
clrscr();
for(int i=0;i<2;i++) {
printf("Enter i:\n");
scanf("%d",&p[i].i);
printf("... |
You should print a string with%s;%cwill interpret the pointer as achar. (Strictly, I believe the result is undefined behavior.)
|
What is wrong in that code ?
I get error "Semantic Issue: Passing 'cards [3]' to parameter of incompatible type 'cards'"
```
#include <stdio.h>
typedef struct {
char *name;
int sequence
} cards;
void print_deck(cards data);
int main (int argc, const char * argv[])
{
cards deck[] =
{
{"Hea... |
You're trying to passdeck, which is anarrayof cards, to a function with a parameter of typecards. Those are two different types. You probably want to change the type of the parameter in theprint_deckfunction. I'd also suggest renaming thecardstype as it's only actually a single card.
|
I guess this question is somewhat wide but I'm trying to create a C console application (on windows os) that lets the user input the website address and the app will output the source code on the screen.
The second one was for me to traverse to the site source code to extract some contents.
Given that I know how to ... |
cURL. Or, for C++,curlpp.
|
in my c application I have this typedef:
```
typedef double mat[2][2];
```
this is my declaration of function:
```
aaa(mat bbb, mat ccc, mat * ddd)
```
in my code I want to compute the sum of each member in math and write the result in ddd.
I did it over loops and this is the main line:
```
*ddd[i][j] = bbb[i][j]... |
You're writing at the wrong address. It should be:
```
(*ddd)[i][j] = bbb[i][j] + ccc[i][j];
```
or simply change the prototype to
```
aaa(mat bbb, mat ccc, mat ddd)
```
since arrays decay to pointers anyway.dddwill be a copy, but the address it points to will be the same as the original.
|
Please help me understand what this typedef is doing??
```
typedef void (xyz) (void *data);
extern struct x* FUNCTION(xyz *ptr);
```
Here is my understanding: in 1st line xyz is a function returning void and taking void pointer as an argument. But I cant interpret 2nd line with this understanding.
Any input is app... |
There is an external function calledFUNCTIONwhich takes a pointer to anxyzfunction as parameter and returns a pointer to astruct x.
|
This question already has answers here:Memory Allocation char* and char[](4 answers)Closed3 years ago.
Can anyone explain me what is a difference between these lines of code
```
char *p = "String";
char p2[] = "String";
char p3[7] = "String";
```
In what case should I use each of the above ?
|
This linkshould satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
|
Is there a C function that doesn't wait for input but if there is one, it detects it?
What I'm trying to do here is continue a loop endlessly until any key is pressed.
I'm a newbie, and all the input functions I've learned so far waits for the user to input something..
I hope I'm clear, although if I'm not I'm happy t... |
WIndows kbhit( ) does exactly thisnon-blocking keyboard char-ready check, and there's a kbhit( ) for Linuxover here
|
I'm using freemp3droid to convert wav files into mp3s. There is a click at the beginning of the file. When I take a look at the file in audacity, the initial 100bytes (beyond the header) have the same pattern. What could be happening??
Here is the waveform of the click (it is the 99% identical,EVERY single time)
h... |
Is your encoder trying to compress the WAV/RIFF 44 byte header as if it were audio?
|
I just started to play C and I bump into this problem. Here's my code:
```
#include<stdio.h>
#include<conio.h>
struct person {
int i;
char name[100];
};
int main() {
struct person p[2];
clrscr();
for(int i=0;i<2;i++) {
printf("Enter i:\n");
scanf("%d",&p[i].i);
printf("... |
You should print a string with%s;%cwill interpret the pointer as achar. (Strictly, I believe the result is undefined behavior.)
|
What is wrong in that code ?
I get error "Semantic Issue: Passing 'cards [3]' to parameter of incompatible type 'cards'"
```
#include <stdio.h>
typedef struct {
char *name;
int sequence
} cards;
void print_deck(cards data);
int main (int argc, const char * argv[])
{
cards deck[] =
{
{"Hea... |
You're trying to passdeck, which is anarrayof cards, to a function with a parameter of typecards. Those are two different types. You probably want to change the type of the parameter in theprint_deckfunction. I'd also suggest renaming thecardstype as it's only actually a single card.
|
I guess this question is somewhat wide but I'm trying to create a C console application (on windows os) that lets the user input the website address and the app will output the source code on the screen.
The second one was for me to traverse to the site source code to extract some contents.
Given that I know how to ... |
cURL. Or, for C++,curlpp.
|
I have the following two files:
file1.c
```
int main(){
foo();
return 0;
}
```
file2.c
```
void foo(){
}
```
Can I compile and link the two files together so thefile1.cwill recognize thefoofunction without addingextern?
Updated the prototype.
gcc file1.c file2.c throws: warning: implicit declaration of fu... |
The correct way is as follows:
file1.c
```
#include <stdio.h>
#include "file2.h"
int main(void){
printf("%s:%s:%d \n", __FILE__, __FUNCTION__, __LINE__);
foo();
return 0;
}
```
file2.h
```
void foo(void);
```
file2.c
```
#include <stdio.h>
#include "file2.h"
void foo(void) {
printf("%s:%s:%d \n... |
Using only stdio.h, string.h and stdlib.h libraries how would I go about implementing this?
I'm quite new to programming so please bear with me!
|
Allocate a newchararray of the same length as your string. Convince yourself that this is enough space. Don't forget the NUL.Loop through the string, copying to the new string only those characters that are alphanumeric. You can't do this portably without also including<ctype.h>and using a function/macro from that hea... |
Say I do initialize an array like this:
```
char a[]="test";
```
What's the purpose of this? We know that the content might immediately get changed, as it isnot allocated, and thus why would someone initialize the array like this?
|
To clarify, this code is wrong for the reasons stated by the OP:
```
char* a;
strcpy(a, "test");
```
As noted by other responses, the syntax "char a[] = "test"" does not actually do this. The actual effect is more like this:
```
char a[5];
strcpy(a, "test");
```
The first statement allocates a fixed-size static ch... |
I am writing in C, not C++ or C#
How can open additional array inside a function and put 0 in all its elements
in one line only?
at the moment i have errors
Error 1 error C2065: 'new' : undeclared identifierError 3 error C2143: syntax error : missing ';' before 'type'Error 4 error C2143: syntax error : missing... |
Try usingcallocinstdlib.h:
```
int *t = calloc(n, sizeof *t);
if (!t) {
perror("calloc");
return;
}
```
|
gcc 4.6.2 c89
I have the following 2D array that I want to pass to a function:
```
char elements[MAX_NUM_ELEMENTS][MAX_STRING_LEN] = {{0}};
```
My function prototype is:
```
int get_elements(char **elements)
```
And I am calling the function like this:
```
get_elements(elements);
```
However, I get the followin... |
"All arrays decay into pointers" is a common misconception about C.
The first few answers in thisFAQclarify the issue.
|
I am wondering what is the maximum number of characters for a host-name in a Unix system. In addition is there any defined variable that can be used in Unix programming to call that number? (i.e. number of characters allowed for a host-name).
I am programming in C.
|
You can usually type:
```
getconf HOST_NAME_MAX
```
In addition, you can generally includelimits.hto your application and read the value of the define.
While the POSIX standard says it is guaranteed not to exceed 255 bytes, that does not necessarily mean that each implementation will adhere to that.
man gethostnam... |
I have this small C program (play.c):
```
#include <stdio.h>
main() {
int t;
for (t=0; t<8000; t++) {
printf ("%c", t%256);
}
}
```
when I redirect it's output (in Linux):
```
./play > /dev/audio
```
it plays a sound as I expect. But if I format the output inprintfas int (%d) instead of char, I get a di... |
No, asman printfwould tell you, or a simple diff on the output redirected into two files. '%c' prints the unsigned char part (the first 8 bits) as one character, and '%d' the whole number in base-10 digit representation.
|
IN LINUX:
Not sure if it is possible. I have 100 source file, and 100 respective executable files.
Now, given the executable file, is it possible to determine, respective source file.
|
I guess you can give this a try.
```
readelf -s a.out | grep FILE
```
I think you can add somegrepandsedmagic to the above command and get the source file name.
|
Can anyone explain me what is the difference between the_Boolandbooldata type in C?
For example:
```
_Bool x = 1;
bool y = true;
printf("%d", x);
printf("%d", y);
```
|
These data types were added in C99. Sinceboolwasn't reserved prior to C99, they use the_Boolkeyword (which was reserved).
boolis an alias for_Boolif you includestdbool.h. Basically, including thestdbool.hheader is an indication that your code is OK with the identifierboolbeing 'reserved', i.e. that your code won't u... |
I have 2 C programs.
Say one isprogram-1.c
```
int main(){
printf("hello world");
}
```
Now in 2nd code namedprogram-2.c, I want the output of 1st code into a variable,
so that I can have the output "hello world" into a variable in the 2nd C code.
How can I do this?
|
You can use thepopenfunction for this:
```
FILE* proc1 = popen("./program1", "r");
// Usual error handling code goes here
// use the usual FILE* read functions
pclose(proc1);
```
|
I just want to create a XML file (I have XML schema for the file) at a given location, and write a structure into it.
For instance
```
struct my_data
{
int no;
char *input ;
char *output;
char * descritpiton;
char *time;
};
```
"Expat" and "Xerces" are two options buti dont want any parsing stuff(As these libs are ... |
XML is text - one option is simply emitting the needed document. There are problems (you must make sure to escape entities, etc), but its the zero-overhead approach.
|
Using socket programming APIs (e.g., socket(), connect(), accept() ...), how can I know if a TCP connection is between two processes on the same machine? Say, I have the socket file descriptor, and the remote ip. Can I simply inspect if the remote ip is 127.0.0.1?
|
There's no really reliable way to determine this - you can connect to local processes using a globally routed IP address (ie, local processes can use IPs other than127.0.0.1). It's also possible for a process to run in a different virtual machine on the same physical hardware, if you're in a virtualized environment.
... |
What is the difference between these three functions ?
|
Those aren't standard functions, but usually it's the return type: signed int, unsigned, and 32-bit respectively.
|
I am allocating memory for array of pointers to structure through malloc and want to initialize it with zero like mentioned below . Assuming the structure contains member of type int and char [] (strings) ? so how can i zero out this struct.
Code : suppose i want to allocate for 100
```
struct A **a = NULL;
a = (st... |
Use of calloc would be most in line with the example above.
|
I am currently trying to get the length of a dynamically generated array. It is an array of structs:
```
typedef struct _my_data_
{
unsigned int id;
double latitude;
double longitude;
unsigned int content_len;
char* name_dyn;
char* descr_dyn;
} mydata;
```
I intialize my array like that:
```
mydata* ar... |
If you need to know the size of a dynamically-allocated array, you have to keep track of it yourself.
Thesizeof(arr) / sizeof(arr[0])technique only works for arrays whose size is known at compile time, and for C99'svariable-length arrays.
|
I am wondering whether it is safe to call a function via a function pointer while inside a event handler on a STM32. The event handler is for I2C and has the highest priority. The function to be called can be assumed to be fast (just some byte reordering).
Thanks for any hints or comments.
Arne
|
If the function pointer is initialized, should work fine. The only issue I can think of the usual one with interrupt-handlers - if the 'byte reordering' involves removing/adding bytes from tx/rx buffers, the buffer-management has to be safely interruptable.
|
This question is for real brainiacs, cause it should be done without an auxiliary array
and has to be most efficient!
C program - needs to recieve an array with X numbers
(suppose X=4 array : 5,4,3,2)
and check if the array has all the numbers from 0 to X-1
(If X is 44 it needs to check if all numbers between 0 to 4... |
If changing order of the array is allowed you can use in-place sort algorithm, then check if for some i:
```
array[i] == array[i+1]
```
Time complexity can be O(n*lg n) then.
|
I have a C/C++ project compiled withgccand usingcmake 2.8+. I knowcmakesupports someOPTION(XXX "Description..." ON/OFF)tag. I would like that these build options result somehow in-DXXXcompile time arguments passed togcc. How to do that most elegantly?
|
If you only care about adding -D compiler flags then the command you want is
add_definitions()
You could wrap that in a if() block to be turned on with the related option():
```
option(MY_FUNCTIONALITY "Cool functionality" ON)
if(MY_FUNCTIONALITY)
add_definitions(-DENABLE_MY_FUNCTIONALITY)
endif()
```
|
I need to pass some values to thefseek()method in C which are greater than the maximum value of the signed long type (2147483647). But if I do like below the value of the result is -1 which is not success. Is there anyway that I can do this?
```
//fp is the pointer to fopen method
unsigned long long index=2147483648;... |
Since you tagged this with "Objective-C", I'm assuming you are also thinking about Macintosh.
Check outfseeko(which takes a 64bit number).
|
```
void mi_start_curr_serv(void){
#if 0
//stmt
#endif
}
```
I'm getting an error as "error: expected declaration or statement at end of input" in my compiler. I could not find any error with the above function. Please help me to understand this error.
|
Normally that error occurs when a}was missed somewhere in the code, for example:
```
void mi_start_curr_serv(void){
#if 0
//stmt
#endif
```
would fail with this error due to the missing}at the end of the function. The code you posted doesn't have this error, so it is likely coming from some other part of... |
When writing code in C/C++ using MPI, if memory is allocated before MPI_Init is called, how do each of the processes view that memory? From a test program, I can see that sometimes it's OK and others it isn't. Does the standard define this? I can't tell if the memory allocation is copied over to the other processes... |
Yes. Each process is spawned at executable load-time. If any memory is allocated before a call to MPI_Init, each process knows that data. However, before MPI_Init is called, processes are not aware of themselves or each other. Calling MPI_Init and MPI_Comm_world initializes MPI environment and returns you MPI_Comm, wh... |
I need to include the contents of a binary file in my C/C++ source code as the text for the declaration of an array initialized to the content of the file. I'm not looking to read the file dynamically at runtime. I want to perform the operation once and then use the generated array declaration text.
How can I convert... |
On Debian and other Linux distros is installed by default (along withvim) thexxdtool, which, given the-ioption, can do what you want:
```
matteo@teodeb:~/Desktop$ echo Hello World\! > temp
matteo@teodeb:~/Desktop$ xxd -i temp
unsigned char temp[] = {
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64... |
The software toolSWIGcan be used to create a programming interface (bindings) to C/C++ software for other languages.
Interfacing to a C library works fine when the original C source code is available, from which one compiles .so files. The sample commands are listed in the SWIG python documentation:http://www.swig.or... |
For SWIG, header files are enough to generate the interface files. Though I haven't worked on MacOS, so not sure on how to link those libraries. But regarding your first question, you dont need the source code of a library to swig it to c/c++.
|
I am having trouble on connecting my C program to mysql. I've done most of the research but seems its quite difficult. Can someone please help? the image below shows the error using the command I typed to compile the code.
Your answers are highly appreciated.
BTW, I am a windows user.
|
It looks like your LD_LIBRARY_PATH isn't set. I believe you need that to be able to find the libraries required by the linker.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Explanation of an algorithm to set, clear and test a single bit
I have anunsigned char. I would like to have bits 2 through 4 (counting from the least significant bit as 0) copied to anotherunsigned charas the first three bits. For example... |
shift it, then mask the rest off:
```
output = ( input >> 2 ) & 0x07;
```
|
Does anyone know where I can find a list of all the native c/c++ methods and functions for use with the android NativeActivity. I cant seem to find a list anywhere on the google/android site and Ive been googling it for the past two days.
|
The documentation forNativeActivitycan be foundhere. That is theJavaside of the API, but the native side's documentation is a bit harder to find.Thisis a link to a doc about the native activity, which can be found in the 'docs' folder of the NDK as well. Additionally, thenative_activity.hcontains all of the C Androi... |
I need to write a program in ANSI C that will display the UTF-8 encoded hexadecimal values of each character of stdin, regardless of the character encoding that stdin uses. For example,
```
AÀĀ
```
yields
```
41
C0
0100
```
Is there a function in C that will convert the character encoding to UTF-8?
|
You can't put UTF-8 out unless youknowwhat is coming in. If you know the encoding of stdin, you can useiconvor even ICU4C to convert to UTF-8, and then dump hex in the usual sort of way. In some cases you could assume that stdin conforms to the locale specified in the LANG environment variable, but nothing stops someo... |
Why this below code gives segmentation fault?
```
int main()
{
char *t = "Working on RedHat Linux";
char *s;
s = malloc (8000 * sizeof(char));
memcpy(s,t,7000);
printf("s = %s\nt = %s\n",s,t);
free(s);
}
```
I have allocated 8000bytes for 's'. And copying only 't' t... |
The segmentation fault is becausetpoints to a region smaller than 7000 bytes.
You are probably trying to read into an area when no readable page is mapped (after the end of string literal"Working on RedHat Linux").
You should limit your memcpy tosizeof("Working on RedHat Linux")bytes.
|
Is installed CUDA capable graphics card necessary (in Linux) for compiling CUDA programs withnvcc? Or one can compile programs everywhere and run only on such systems?
|
No, a graphics card is not necessary for compilation.
You don't even need one to run the program; you can have it emulated in software.
UPDATEOk, apparently, SW emulation hasn't been supported since CUDA 3.0.
|
I've got a byte array containing 8 bytes and would like to convert and use them as a double precision binary floating-point number.
Could someone please tell me how to convert it?
|
Try this:
```
double a;
memcpy(&a, ptr, sizeof(double));
```
whereptris the pointer to your byte array. If you want to avoid copying use a union, e.g.
```
union {
double d;
char bytes[sizeof(double)];
} u;
// Store your data in u.bytes
// Use floating point number from u.d
```
|
The software toolSWIGcan be used to create a programming interface (bindings) to C/C++ software for other languages.
Interfacing to a C library works fine when the original C source code is available, from which one compiles .so files. The sample commands are listed in the SWIG python documentation:http://www.swig.or... |
For SWIG, header files are enough to generate the interface files. Though I haven't worked on MacOS, so not sure on how to link those libraries. But regarding your first question, you dont need the source code of a library to swig it to c/c++.
|
I am having trouble on connecting my C program to mysql. I've done most of the research but seems its quite difficult. Can someone please help? the image below shows the error using the command I typed to compile the code.
Your answers are highly appreciated.
BTW, I am a windows user.
|
It looks like your LD_LIBRARY_PATH isn't set. I believe you need that to be able to find the libraries required by the linker.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Explanation of an algorithm to set, clear and test a single bit
I have anunsigned char. I would like to have bits 2 through 4 (counting from the least significant bit as 0) copied to anotherunsigned charas the first three bits. For example... |
shift it, then mask the rest off:
```
output = ( input >> 2 ) & 0x07;
```
|
Does anyone know where I can find a list of all the native c/c++ methods and functions for use with the android NativeActivity. I cant seem to find a list anywhere on the google/android site and Ive been googling it for the past two days.
|
The documentation forNativeActivitycan be foundhere. That is theJavaside of the API, but the native side's documentation is a bit harder to find.Thisis a link to a doc about the native activity, which can be found in the 'docs' folder of the NDK as well. Additionally, thenative_activity.hcontains all of the C Androi... |
I need to write a program in ANSI C that will display the UTF-8 encoded hexadecimal values of each character of stdin, regardless of the character encoding that stdin uses. For example,
```
AÀĀ
```
yields
```
41
C0
0100
```
Is there a function in C that will convert the character encoding to UTF-8?
|
You can't put UTF-8 out unless youknowwhat is coming in. If you know the encoding of stdin, you can useiconvor even ICU4C to convert to UTF-8, and then dump hex in the usual sort of way. In some cases you could assume that stdin conforms to the locale specified in the LANG environment variable, but nothing stops someo... |
Why this below code gives segmentation fault?
```
int main()
{
char *t = "Working on RedHat Linux";
char *s;
s = malloc (8000 * sizeof(char));
memcpy(s,t,7000);
printf("s = %s\nt = %s\n",s,t);
free(s);
}
```
I have allocated 8000bytes for 's'. And copying only 't' t... |
The segmentation fault is becausetpoints to a region smaller than 7000 bytes.
You are probably trying to read into an area when no readable page is mapped (after the end of string literal"Working on RedHat Linux").
You should limit your memcpy tosizeof("Working on RedHat Linux")bytes.
|
Is installed CUDA capable graphics card necessary (in Linux) for compiling CUDA programs withnvcc? Or one can compile programs everywhere and run only on such systems?
|
No, a graphics card is not necessary for compilation.
You don't even need one to run the program; you can have it emulated in software.
UPDATEOk, apparently, SW emulation hasn't been supported since CUDA 3.0.
|
I've got a byte array containing 8 bytes and would like to convert and use them as a double precision binary floating-point number.
Could someone please tell me how to convert it?
|
Try this:
```
double a;
memcpy(&a, ptr, sizeof(double));
```
whereptris the pointer to your byte array. If you want to avoid copying use a union, e.g.
```
union {
double d;
char bytes[sizeof(double)];
} u;
// Store your data in u.bytes
// Use floating point number from u.d
```
|
Suppose we have two structs:
```
typedef struct Struct1
{
short a_short;
int id;
} Struct1;
typedef struct Struct2
{
short a_short;
int id;
short another_short;
} Struct2;
```
Is it safe to cast fromStruct2 *toStruct1 *? What does the ANSI spec says about this?
I know that some compilers have th... |
It is safe, as far as I know.
But it's far better, if possible, to do:
```
typedef struct {
Struct1 struct1;
short another_short;
} Struct2;
```
Then you've even told the compiler thatStruct2starts with an instance ofStruct1, and since a pointer to a struct always points at its first member, you're safe to ... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why are C character literals ints instead of chars?
http://ideone.com/lHYY8
```
int main(void)
{
printf("%d %d\n", sizeof('c'), sizeof(char));
return 0;
}
```
Why doessizeof('c')return 4 instead of 1?
|
Because in C character constants have the typeint, notchar. Sosizeof('c') == sizeof(int). Refer to thisC FAQ
Perhaps surprisingly,character constants in C are of type int, so
sizeof('a') is sizeof(int) (though this is another area where C++
differs).
|
Is there any library for q-encoding? I need to decode some q-encoded text, such as:
```
**Subject: =?iso-8859-1?Q?=A1Hola,_se=F1or!?=**
```
|
GNU Mailutils libmailutilsis one example of such library.
"Q"-encoding is specified byRFC 2047so using it as a search term gives you other relevant results.
|
I just have a little question with regards to connecting C to MySQL.
Well, I already have an existing MySQL server installed on my system but when I tried to run my code with the#include <mysql.h>in the header, it says that the path does not exist. So, I placed theincludefolder of my MySQL to the "includes" folder of ... |
Append$(mysql_config --libs)and$(mysql_config --cflags)in yourgcccommand.
You need to include the header files and link the libraries. For mysql you can find them usingmysql_configcommand. This command is available if you have installed the library and development header file properly.mysql_config --cflagsandmysql_co... |
we declare main() as
```
int main(int argc, char *argv[])
```
and pass some argument by command line and use it
asargv[1],argv[2]in main() function definition but what if i want to use that in some other function's definition ?
one things i can do it always pass that pointerchar** argvfrom main() to that function ... |
Just pass the pointer?
```
int main(int argc, char** argv) {
do_something_with_params(argv);
}
void do_something_with_params(char** argv) {
// do something
}
```
Or if you mean passing single arguments:
```
int main(int argc, char** argv) {
do_something_with_argv1(argv[1]);
do_something_with_argv2(argv[2])... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why are C character literals ints instead of chars?why sizeof('a') is 4 in C?
```
#include<stdio.h>
int main()
{
char ch;
fflush(stdin);
ch=getchar();
printf("ch= %d a=%d char=%d", sizeof(ch),sizeof('a'),sizeof(char));
}
```
I typ... |
In C, a literal character (e.g.,'a'), is anint, not achar. In C++, however, literal characters are actualchars.
|
I am running Fedora linux and I am trying to simulate key strokes in the browser (specifically the arrow keys). What is the best way to do this in C
|
You can do this with the XTest extesion, a simple example:
```
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/extensions/XTest.h>
#include <unistd.h>
static void SendKey (Display *disp, KeySym keysym)
{
KeyCode keycode = 0;
keycode = XKeysymToKeycode (disp, keysym);
if (keycode == 0) return;
... |
I'm trying to figure out the data structure that is stored in 'buffer' after the following:
sock=socket(PF_PACKET, SOCK_RAW, htons(ETHERTYPE_IP));
recvfrom(sock, buffer, 2048, 0, NULL, NULL);
I'd like to be able to poke into the data structure and read in the link-layer, IP layer, and TCP layer if it is a TCP packe... |
This is the raw bits that go over the wire (OSI layer 2). Theman page for packetexplains it pretty well.
What I would do is to get the output of this and compare it to the output of a Wireshark session looking at the same data. You then should be able to correlate the two and see what's going on.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:how to get bit by bit data from a integer value in c?
I have a 8-bit byte and I want to get a bit from this byte, like
getByte(0b01001100, 3) = 1
|
Firstoff,0bprefix is not C but a GCC extension of C.
To get the value of the bit 3 of anuint8_t a, you can use this expression:
```
((a >> 3) & 0x01)
```
which would be evaluated to 1 if bit 3 is set and 0 if bit 3 is not set.
|
```
iov[0] = (struct iovec) {
.iov_base = &req,
.iov_len = sizeof(req)
};
```
I'm trying to convert a bit of code from the ss network utility to c++, and the above and similar keeps giving these errors:
```
main.cpp|83|error: expected primary- expression before ‘struct’
main.cpp|83|error: expected ‘)’ bef... |
C++ doesn't support that syntax. Try this:
```
iovec iov[2];
iov[0].iov_base = &req;
iov[0].iov_len = sizeof req;
/* ... */
```
Or maybe:
```
iovec iov[] = {
{
&req, sizeof req
},
/* ... */
}
```
What you were trying is a C99 feature called "compound literals". Also, the.iov_basething is called ... |
When I use C programs, many of them defines their own error mechanisms. For that cases, I can follow their definition. How about C base libraries? Is it enough with onlyerrno?
|
You have to look at each function you call and then handle the return value orerrnosetting as appropriate. There is no general error handling (e.g. exceptions) beyond that.
|
I know you have to synchronize your threads to be able to change your global variables content safely in a multithreaded application (where multiple threads are trying to change the variable data at the same time). But is this also necessary if you use a global array, where each thread only uses one of the n elements?... |
If each thread only uses one element, and the array's location in memory is never changed, then it's absolutely safe without synchronization.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.