question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Since, for example,glBufferDatacan report an GL_OUT_OF_MEMORY error, I expectedglTexImageto do so to, but it doesn't.
Presumably itispossible to run out of texture memory, so how do I detect the event?
|
Any OpenGL function can theoretically result in aGL_OUT_OF_MEMORYerror, if as a side effect of some process, memory needs to be allocated but cannot. As stated by GL 4.4 core profile, section 2.3:
The Specification attempts to explicitly describe these implicit error conditions (with the exception of OUT_OF_MEMORY) w... |
i'm trying to use window.h at devc++, i installed devc++ without mingw and installed MinGW32 separeted.
I'm trying to compile an souce code that have#include <window.h>but appear an error.
window.h: No such file or directory.
What can i do to be able to compile with window.h at dev c++?
At compiler options i had a... |
I believe you want to use#include <windows.h>instead, which is the typical include statement for the Windows header file. Note the 's' in thewindows.h.
|
The following code is an interview qusetion and I can't understand the output. Can anyone help? Thanks.
```
#include <stdio.h>
char* string_1()
{
char* p = "ABCD";
return p;
}
char* string_2()
{
char p[] = "ABCD";
return p;
}
int main(void)
{
print... |
The first one is ABCD as expected, the second one is Undefined Behaviour as you are returning a local variable which has gone out of scope.
|
My question is mainly about the fact that a C++ toolchain "understands" both C and C++, so if I feed some code with anextern "C"to a c++ toolchain I assume it can understand what to do with that; but what if I feed code withextern "C++"to a C toolchain ?
What is the expected behaviour ?
|
If the compiler ALSO understands C++, it may accept it. If it's a pure C compiler it will object (just like it will onextern "C"as that syntax is not valid C - this is why it's typically enclosed with#ifdef __cplusplusor some such)
|
Since, for example,glBufferDatacan report an GL_OUT_OF_MEMORY error, I expectedglTexImageto do so to, but it doesn't.
Presumably itispossible to run out of texture memory, so how do I detect the event?
|
Any OpenGL function can theoretically result in aGL_OUT_OF_MEMORYerror, if as a side effect of some process, memory needs to be allocated but cannot. As stated by GL 4.4 core profile, section 2.3:
The Specification attempts to explicitly describe these implicit error conditions (with the exception of OUT_OF_MEMORY) w... |
i'm trying to use window.h at devc++, i installed devc++ without mingw and installed MinGW32 separeted.
I'm trying to compile an souce code that have#include <window.h>but appear an error.
window.h: No such file or directory.
What can i do to be able to compile with window.h at dev c++?
At compiler options i had a... |
I believe you want to use#include <windows.h>instead, which is the typical include statement for the Windows header file. Note the 's' in thewindows.h.
|
The following code is an interview qusetion and I can't understand the output. Can anyone help? Thanks.
```
#include <stdio.h>
char* string_1()
{
char* p = "ABCD";
return p;
}
char* string_2()
{
char p[] = "ABCD";
return p;
}
int main(void)
{
print... |
The first one is ABCD as expected, the second one is Undefined Behaviour as you are returning a local variable which has gone out of scope.
|
My question is mainly about the fact that a C++ toolchain "understands" both C and C++, so if I feed some code with anextern "C"to a c++ toolchain I assume it can understand what to do with that; but what if I feed code withextern "C++"to a C toolchain ?
What is the expected behaviour ?
|
If the compiler ALSO understands C++, it may accept it. If it's a pure C compiler it will object (just like it will onextern "C"as that syntax is not valid C - this is why it's typically enclosed with#ifdef __cplusplusor some such)
|
I wrote a little little program in C, and I expected an error with vectors.
```
#include <stdlib.h>
#include <stdio.h>
main(){
int vet[0];
vet[0] = 1;
vet[1] = 2;
vet[2] = 2;
vet[3] = 2;
vet[4] = 2;
vet[5] = 2;
vet[6] = 2;
vet[7] = 2;
int x;
... |
Because, by writing to memory you never allocated, you are causing undefined behaviour. Sometimes it works, sometimes it doesn't, sometimes it makes your dog explode.
|
I want to convert a float number for example 2.45 to the 4 byte char array.
so the 2.45 should look like this'@' 'FS' 'Ì' 'Í'which is binary the ieee representation of2.45 = 01000000 00011100 11001100 11001101?
I've solved the problem but it has a bad complexity. do you have any good ideas?
Thanks for the good ans... |
Just use memcpy:
```
#include <string.h>
float f = 2.45f;
char a[sizeof(float)];
memcpy(a, &f, sizeof(float));
```
If you require the opposite endianness then it is a trivial matter to reverse the bytes inaafterwards, e.g.
```
int i, j;
for (i = 0, j = sizeof(float) - 1; i < j; ++i, --j)
{
char temp = a[i];
... |
The code compiles and builds properly, but gives no output. Where do i see the ouptput?
```
#include <stdio.h>
#include <std.h>
#include <log.h>
#include "Configuration2cfg.h"
extern far LOG_Obj fastprint;
void main()
{
LOG_printf (&fastprint, "Algorithm 1 is running\n");
}
```
|
Go to menu Tools --> RTA --> Printf Logs and the messages should be updated.
If not, can you try to run one of the supplied examples with BIOS 5.4x and see if you get output on this screen? This may rule out any issues related to your specific project. For details on how to use the example project, please check:
htt... |
I have a moderate C++ project. I'm trying to use autotools for it, but find the complexity overwhelming.
What are guidelines for when to use autotools and when you can do without it? What are (simple) alternatives?
The main reason I want to use autotools is for its fullmake installsupport. Is there a simpler alter... |
For themake installsupport, you only needautomake. And a simpleMakefile.amfile is quite easy to make:
```
LIBS += -lsome-lib -lsome_other_lib
bin_PROGRAMS = hello
noinst_HEADERS = some.h header.h files.h
hello_SOURCES = hello.c some.c other.c source.c file.c
```
That's about it.
Theautoconftool is useful if yo... |
I'm writing a simple http program which downloads a file,maybe .html, .jpg or any othersand how can i open the file using the system default application in C codeThis program is on ubuntu12.10 and based on gtk3.xsorry for my English and thanks in advance.
|
I know that
```
GFile *g_file_new_for_path(const gchar *path);
GAppInfo *g_file_query_default_handler(GFile *file,GCancellable *cancellable,GError **error);
gboolean g_app_info_launch(GAppInfo *appinfo,GList *files,GAppLaunchContext *launch_context,GError **error);
```
Create a GFile and get its default handler,th... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10... |
Unsigned char's (assuming char is only eight bits) can only represent 28numbers, from 0 to 255. You'll need to use another type such asintto represent this.
|
I would like to compile MuPdf for Android followingtheseSteps. I stuck at building the native code libraries. Following error appears:
```
"Compile thumb : mupdfcore <= pdf_cmap_table.c
jni/../../pdf/pdf_cmap_table.c:5:35: fatal error:
../generated/cmap_cns.h: No such file or directory compilation terminated. make: *... |
Try this:
```
make generate NOX11=yes
```
And/Or:
http://nondroid.blogspot.com/2012/06/mupdf-android-library-build.html
|
In C I might say
```
printf("%p",0x11194);
*((int *) 0x11194) = 30240;
```
(In this example I know that there is an integer at that memory location)
Please tell me, how would I do the same in Java? Btw I may have completely misunderstood how memory works
|
Youcando this in Java usingsun.misc.UnsafeandByteBuffer.
However for normal Java usage you don't do this at all. Java will give you an object reference, which is handle to an object. It doesn't point to one place in memory (the JVM can move objects in memory without you knowing/caring) and you can't perform arithmeti... |
I have:
```
int a = 2147483647;
short b = (short)a;
```
and I getb = -1whereas I expectint32to be converted toint16(short). I expect to see some value andnot-1.
Please someone help me with this.
|
The value 2147483647, or 231-1 overflows a 16-bit integer. Its binary representation is zero in the MSB followed by 31 ones in the remaining bits.
It looks like in your implementation the last 16 bits are taken in the conversion toshort. When this happens, all of them are set to1, resulting in a2's complementrepresen... |
This question already has answers here:How to achieve function overloading in C?(16 answers)Closed9 years ago.
I need to develop a function in C that will be called with the same definition with or without parameters like this:
```
char *fnc(???)
{
char *str;
....
return str;
}
char *c1 = fnc();
char *c... |
This is calledFunction OverloadingYou can't do it in C
|
I wrote a little little program in C, and I expected an error with vectors.
```
#include <stdlib.h>
#include <stdio.h>
main(){
int vet[0];
vet[0] = 1;
vet[1] = 2;
vet[2] = 2;
vet[3] = 2;
vet[4] = 2;
vet[5] = 2;
vet[6] = 2;
vet[7] = 2;
int x;
... |
Because, by writing to memory you never allocated, you are causing undefined behaviour. Sometimes it works, sometimes it doesn't, sometimes it makes your dog explode.
|
I want to convert a float number for example 2.45 to the 4 byte char array.
so the 2.45 should look like this'@' 'FS' 'Ì' 'Í'which is binary the ieee representation of2.45 = 01000000 00011100 11001100 11001101?
I've solved the problem but it has a bad complexity. do you have any good ideas?
Thanks for the good ans... |
Just use memcpy:
```
#include <string.h>
float f = 2.45f;
char a[sizeof(float)];
memcpy(a, &f, sizeof(float));
```
If you require the opposite endianness then it is a trivial matter to reverse the bytes inaafterwards, e.g.
```
int i, j;
for (i = 0, j = sizeof(float) - 1; i < j; ++i, --j)
{
char temp = a[i];
... |
I am coding an app that captures video from a webcam. I am doing it in C and for Windows. But here is an error that I don't know how to solve it. It's in the variable declaration:
```
CvCapture* capture = cvCreateCameraCapture(0);
```
As you can see I am using OpenCV to code my app and this line is to create de conn... |
try this :
```
CvCapture* cam = cvCaptureFromCAM(CV_CAP_ANY);
```
|
for example,
```
#include <stdio.h>
int main (void) {
int x = 5;
double y = 6;
int z = x+y;
printf("size of z = %d bytes",sizeof(z));
return 0;
}
```
The output is4bytes, why doesn't it converted to double and takes8bytes of memory as a double.
|
No,sizeof zwill always besizeof(int)
When you do:
```
int z = x+y;
```
The value ofxwill be converted todoublesinceyis double, but this won't changex. And the result ofx+y(typedouble) will be converted toint, and assigned toz.
|
I am new to OpenSSL, so forgive me if I ask anything stupid.
I need to convert an existing server project which uses axTLS to OpenSSL. As the server requires client authentication, I need to load the server cert file, private key file and the CA cert file. All 3 files are in DER format.
For server cert file and priv... |
I will answer my own question. As what Yu Hao said, there seems to be no API available in OpenSSL to load a CA cert in DER(ANS1) format. I had to get the PEM format version of CA cert to use in the end.
|
I've read in 4 bytes binary string from a file. The 4 bytes binary string is big endian, and represents a 32-bit integer. But My machine is little endian (intel). So I need to convert the 4 bytes binary string of big endian into 32-bit little endian integer.
Is there any native function in mysql could handle this? An... |
For C you can usentohl()to convert 32bit (that is 4 bytes) integers to host byte order.
Its prototype should reside in<arpa/inet.h>.
Update
Thentoh/htonfamily of functions is defined by the POSIX standard.
It converts network byte order to host bytes order and verse visa.
Network byte order is defined to be Big E... |
This is the snippet where I call the main of another class by including its header file...
As the title says, I want to invoke the main() of a program with parameters from another C program.
Example:
Suppose there are two programs:imain.candanother.c
I wish to call the main() ofimain.cfrom the body of main inanother.... |
Create a header file with a function that exposes the functionality of the target main function. Then you can call that function by including that header file. A good example can be foundhttp://www.tutorialspoint.com/cprogramming/c_header_files.htm.
|
```
void HowToPutParameters( XXXXXX) // how to put parameters in XXXXXX
{
array[0][0]=5;
}
void main()
{
int array[2][2]={{1,2},{3,4}};
HowToPutParameters(&array[0][0]); // &array[0][0] is correct or &array[0]
}
```
// I wana put this array to HowToPutParameters;
// 1.I am not sure "&array[0... |
If you want use pass two dimensions array params,use:
```
void func(int (*a)[2]);// tell the function the first dimension size!
func(array);
```
It is the same as:
```
void func(int a[][2]);
func(array);
```
If you pass&array[0][0], it means you pass a pointer point to a int.
```
void func(int *element);
```
|
I am using the BIGNUM library from OpenSSL and I need to do a calculation in an if statement as follows:
```
if (expo & 1)
```
I know for bit shifting there are functions. Is there a function corresponding to this kind of operation (whereexpois aBIGNUM*)? If not, is there a way to carry this out?
|
The function you are looking for is:
```
bool BN_is_bit_set( const BIGNUM *a, int n );
```
... it behaves exactly like the bitwise operatorAND. For example, to see if the right-most bit is on I would call the function as follows:
```
bool is_set = BN_is_bit_set( ptr_my_bignum, 0x1 );
```
... notice my mask is0x1(w... |
As part of a small app I am working on, I need to find a way to return the coordinates of the mouse on the screen when I click. I am looking for a solution that would run the same across operating systems, or at least the same on Unix systems. I'm wondering if there's a low-level solution for this. I have seen solutio... |
I would suggest using Qt. The problem is that, you will have different windowing systems on different platforms, potentially even on Linux.
As a fallback, you could check how Qt gets this bit right across the platforms, and copy/paste that into your software. It might bring further dependencies into your software.
g... |
I want to avoid dividing by zero so I have anifstatement:
```
float number;
//........
if (number > 0.000000000000001)
number = 1/number;
```
How small of a value can I safely use in place of0.000000000000001?
|
Just use:
```
if(number > 0)
number = 1/number;
```
Note the difference between>and>=. Ifnumber > 0, then it definitely is not0.
If number can be negative you can also use:
```
if(number != 0)
number = 1/number;
```
Note that, as others have mentioned in the comments, checking thatnumberis not0will not pr... |
I have some C++ code (exposing a C-only interface through a header) which I will use for an iOS project.
I can either create a static library and link to this from my app project, or add the source files directly to the app project - which option is best?
All answers appreciated!
|
Add the sources if you expect them to change often. Otherwise a library will be more suitable and will make your project cleaner (however, you will have to put only the header files in your project)
|
According to theCERT standardsObject-like macros can be dangerous because their uses are not subject to the language scope rules. Can any one please explain with an example How it is problematic. say for example I have an Object-like macro#define BUFFER_SIZE 1024
|
```
// file a.hpp
#define SOME_MACRO 42
// file some/nested/dir/really/far/in/x.hpp
#define SOME_MACRO 13
```
Kaboom. This would have easily been avoided using any kind of scope, e.g.
```
struct X { static unsigned const value = 42; };
struct Y { static unsigned const value = 13; };
```
Now you can accessX::valuea... |
I have a webpage, say atwww.mypage.com, which uses$_GETto fetch data and then saves the fetched data into theMySQLdatabase.
I need to send thisHTTP Requestfrom a Cpp File.
How can I send aHTTP Requestfrom Cpp file?
|
Yes, libcurl should be helpful. You can send some data by GET parameters or by POST and read responses. (Maybe necessary to verify a successful transmission) Here are some examples:http://curl.haxx.se/libcurl/c/example.html
|
When function arguments are of the same type, is following code well-defined and portable?
```
void foo(int* p, int size);
void pass_on_args_by_pointer(int a, int b, int c)
{
foo(&a, 3);
}
```
To clearify: the 'size' argument should contain the number of elements in the array p. So, I want to pass all three ints... |
No, this is neither portable nor well-defined. Compilers are not required to allocate function parameters in adjacent locations in memory. In fact, they are not required to place parametersbandcin memory at all, since you are not taking their address. Any access beyond the bounds of theintthroughpinfoois undefined be... |
I want to avoid dividing by zero so I have anifstatement:
```
float number;
//........
if (number > 0.000000000000001)
number = 1/number;
```
How small of a value can I safely use in place of0.000000000000001?
|
Just use:
```
if(number > 0)
number = 1/number;
```
Note the difference between>and>=. Ifnumber > 0, then it definitely is not0.
If number can be negative you can also use:
```
if(number != 0)
number = 1/number;
```
Note that, as others have mentioned in the comments, checking thatnumberis not0will not pr... |
I have some C++ code (exposing a C-only interface through a header) which I will use for an iOS project.
I can either create a static library and link to this from my app project, or add the source files directly to the app project - which option is best?
All answers appreciated!
|
Add the sources if you expect them to change often. Otherwise a library will be more suitable and will make your project cleaner (however, you will have to put only the header files in your project)
|
According to theCERT standardsObject-like macros can be dangerous because their uses are not subject to the language scope rules. Can any one please explain with an example How it is problematic. say for example I have an Object-like macro#define BUFFER_SIZE 1024
|
```
// file a.hpp
#define SOME_MACRO 42
// file some/nested/dir/really/far/in/x.hpp
#define SOME_MACRO 13
```
Kaboom. This would have easily been avoided using any kind of scope, e.g.
```
struct X { static unsigned const value = 42; };
struct Y { static unsigned const value = 13; };
```
Now you can accessX::valuea... |
I have a webpage, say atwww.mypage.com, which uses$_GETto fetch data and then saves the fetched data into theMySQLdatabase.
I need to send thisHTTP Requestfrom a Cpp File.
How can I send aHTTP Requestfrom Cpp file?
|
Yes, libcurl should be helpful. You can send some data by GET parameters or by POST and read responses. (Maybe necessary to verify a successful transmission) Here are some examples:http://curl.haxx.se/libcurl/c/example.html
|
When function arguments are of the same type, is following code well-defined and portable?
```
void foo(int* p, int size);
void pass_on_args_by_pointer(int a, int b, int c)
{
foo(&a, 3);
}
```
To clearify: the 'size' argument should contain the number of elements in the array p. So, I want to pass all three ints... |
No, this is neither portable nor well-defined. Compilers are not required to allocate function parameters in adjacent locations in memory. In fact, they are not required to place parametersbandcin memory at all, since you are not taking their address. Any access beyond the bounds of theintthroughpinfoois undefined be... |
My code requires me to open up a file.
the first line of the file contains 2 integers between 1 and 1000.
I must read these 2 numbers, use them to create a 2D array corresponding to those numbers
(e.g. 50,200 is - array[50][200]).
After i have created this array, i have to read the rest of the file and store the data... |
Is the file binary or text? If binary, use fread, it will let you read the raw bytes easily. if its text use fscanf
|
This question already has answers here:What does dot (.) mean in a struct initializer?(4 answers)Closed10 years ago.
I wonder the meaning of attribute definitions with dot (.) for struct attributes inRedissource code :
```
struct config cfg = {
.tcp = {
.host = "127.0.0.1",
.port = 6379
}... |
It is a way to do named initialization of thestructmembers.
The default way to initialize astructrequires you to provide the arguments in the order the members were defined. This lets you you reorder that, and makes it more readable as well. This syntax also lets you initialize only a few members of thestruct, esp. i... |
So I have a situation where I am trying to write to an Embedded Linux file (Nitrogen6x board). I can do this manually withecho 1 > /sys/class/gpio/gpio16/value. However, when I try and do this same thing via C code:
```
FILE *fs;
fs = fopen("/sys/class/gpio/gpio16/value","w")
fputc(1,fs);
fclose(fs);
```
it doesn'... |
That's because you are writing "CTRL-A" (character code 1, not the digit '1' that echo sends) to the gpio16/value.
Try:
```
fputc('1', fs);
```
If that still doesn't work, it may be that you need a newline as well:
```
fputs("1\n", fs);
```
|
In the spec for asm.js (athttp://asmjs.org/spec/latest/) in the introduction section it says
"The asm.js language provides an abstraction similar to the C/C++ virtual machine"
..but I can't find any information on 'the C/C++ virtual machine' by googling. Can someone enlighten me or point me in the direction of a boo... |
TheC standardtalks about an abstract machine it makes assumptions about. I suppose that is what the author ofasm.jstalks about.
|
My code requires me to open up a file.
the first line of the file contains 2 integers between 1 and 1000.
I must read these 2 numbers, use them to create a 2D array corresponding to those numbers
(e.g. 50,200 is - array[50][200]).
After i have created this array, i have to read the rest of the file and store the data... |
Is the file binary or text? If binary, use fread, it will let you read the raw bytes easily. if its text use fscanf
|
This question already has answers here:What does dot (.) mean in a struct initializer?(4 answers)Closed10 years ago.
I wonder the meaning of attribute definitions with dot (.) for struct attributes inRedissource code :
```
struct config cfg = {
.tcp = {
.host = "127.0.0.1",
.port = 6379
}... |
It is a way to do named initialization of thestructmembers.
The default way to initialize astructrequires you to provide the arguments in the order the members were defined. This lets you you reorder that, and makes it more readable as well. This syntax also lets you initialize only a few members of thestruct, esp. i... |
So I have a situation where I am trying to write to an Embedded Linux file (Nitrogen6x board). I can do this manually withecho 1 > /sys/class/gpio/gpio16/value. However, when I try and do this same thing via C code:
```
FILE *fs;
fs = fopen("/sys/class/gpio/gpio16/value","w")
fputc(1,fs);
fclose(fs);
```
it doesn'... |
That's because you are writing "CTRL-A" (character code 1, not the digit '1' that echo sends) to the gpio16/value.
Try:
```
fputc('1', fs);
```
If that still doesn't work, it may be that you need a newline as well:
```
fputs("1\n", fs);
```
|
In the spec for asm.js (athttp://asmjs.org/spec/latest/) in the introduction section it says
"The asm.js language provides an abstraction similar to the C/C++ virtual machine"
..but I can't find any information on 'the C/C++ virtual machine' by googling. Can someone enlighten me or point me in the direction of a boo... |
TheC standardtalks about an abstract machine it makes assumptions about. I suppose that is what the author ofasm.jstalks about.
|
Are the types of these two declarations compatible types?
```
void f(char *, char *);
void f(char *restrict, char *restrict);
```
or similarly:
```
void g(char *);
void g(char *const);
```
I'm having a hard time finding anything in the standard which covers the issue. I'm mostly interested in the topic of whether ... |
They are compatible:
(C99, 6.7.5.3 Function declarators (including prototypes) p15) "[...] (In the determination of type
compatibility and of a composite type, each parameter declared with function or array
type is taken as having the adjusted type and each parameter declared with qualified type
is taken as hav... |
```
void * (*proto_type(long int, char *b)) (const char *b, unsigned short int d);
```
The return type is void* and proto_type is the name of the function? Or is this a pointer to function? Which are the parameters:
(long int, char *b)or this(const char *b, unsigned short int d)
Please, explain how this function wo... |
```
void * (*proto_type(long int, char *b)) (const char *b, unsigned short int d);
```
This is a function declaration. The function name isproto_type, which takes two parameters of types:
long intchar *
and returns a pointer to a function which takes
const char*unsigned short int
and returnsvoid*.
Now if you use... |
When we usually input the string, we do this:
```
#include <stdio.h>
int main()
{
char str[256];
scanf("%s",str);
//Other Operation
}
```
But, today, in programming class, one of my friends wrotescanfline like this:
```
scanf("%s",&str);
```
and it pass the compilation, and works.
The question is, I'd... |
It's undefined behavior (because the typescanf()expects ischar *, but you pass in achar (*)[256]), but it usually "works" (appears to be working) since the address of an array is often the same (regarding the numeric value of the pointer) as the address of its first element.
From theofficial documentation:
If this o... |
I need to calculate no of possible substrings containing "00" as a substring.
I know the length of the binary string.
Eg: for a string of length 4, possible substrings are:
0000
0001
0010
0011
0100
1000
1001
1100
I just need the number of possible combinations, not enumerate all of them
PS: max length 10^6
|
This is calculated using fibonacci n-step number sequences.
The number of string permutations containing k 0's from a string of length n is 2^n-fibk( n + 2 ).
In your case you have k=2 so you use the normal fibonacci sequence giving you the solution to your example with a string length of n=4: 2^4 - fib( 6 )= 16 - 8... |
I was wondering if there was a way to convert a string that has its first letter pointed at by a char* to a char[], so it is no longer a pointer, but a literal char[].
For example, if my string is "hi my name is bob\0", andchar* pointerhad this string copied to it via memcpy, is there a way to turn this back to a cha... |
there is no need to convert, You can index a pointer as if it was an array. you can just to
```
char * a;
```
ant then do
```
char ch = a[4];
```
here is a similar questionhere
ther other way is also as easy
```
void f(int* p);
int x[5];
f(x); // this is the same as f(&x[0])
```
|
Where am I going wrong and why?
```
#include<stdio.h>
#include<string.h>
int main()
{
char *str;
int length, i, j, flag = 0;
printf("\n\nEnter string: ");
fgets(str, 20, stdin);
printf("You entered: %s", str);
return 0;
}
```
There's a problem with the linefgets(str, 20, stdin);line. I cannot figure it out. Af... |
You need to allocate memory forstr
Any size say 128.
char *str = malloc(128*sizeof(char));
or
char str[128];
|
While compiling Apache source, I've been able to define one macro just fine:
```
# export CFLAGS=" -DSINGLE_LISTEN_UNSERIALIZED_ACCEPT" // OR even:
# export CFLAGS=" -DSINGLE_LISTEN_UNSERIALIZED_ACCEPT=1"
```
... works like a charm,howeverevery time I try to set:
```
# export CFLAGS=" -DDEFAULT_PIDLOG=/var/run/ap... |
Seems that DEFAULT_PIDLOG is expected to define a constant C string. Try with
```
export CFLAGS="-DDEFAULT_PIDLOG=\\\"/var/run/apache/apache.pid\\\""
```
(Thanks @mathk)
|
Simple question:
If i have a line in an input file that looks looks like:
```
Hello#Great#Day#Today
```
how can I scan in each word individually as its own array, in other words tell C to stop scanning when it reaches the # character and then go in the next iteration of the loop to scan the next word as a separate ... |
This is assuming you are reading throughstdin. Definitely take a look at @Whoz kick start approach as well (very similar to this).
What you would want to do is create a dynamic array and populate it with every byte read throughstdin. You would then want to create an array of character pointers that will point to th... |
I've created a table and assigned a method withlua_pushcfunctionnamedmytable:myfunction(). In a different (callback) context it's necessarily thatmyfunctionwill be overriden inside the Lua script. For some reasons, if i callmyfunctionfrom the C host, I need to know, ifmyfunctionis still the c function or was replaced ... |
Yes, you can uselua_iscfunction.
|
A short example excerpted from wdm.h
```
typedef struct _KMUTANT {
DISPATCHER_HEADER Header;
LIST_ENTRY MutantListEntry;
struct _KTHREAD *OwnerThread;
BOOLEAN Abandoned;
UCHAR ApcDisable;
} KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX;
```
I know 'P' means 'Pointer', but I don't kn... |
TheRidentifies the pointer as arestricted pointer.
|
I just started using Netbeans 7.3.1, and I am experiencing some trouble compiling my project. In terminal, I successfully compiled with the following code:
```
gcc -Wall one.c two.c three.c four.c -o gateway -lpthread
```
When I compile in Netbeans, I get errors like 'undefined reference to 'pthread_create'. So I ne... |
Found it!
Adding library dependencies to GCC in Netbeans:
```
File->Project Properties->Build->Linker->Libraries->add Library/add standard Library.
```
For example for the -lpthread or -pthread option:
```
add standard Library --> Posix Threads
```
|
I trying to emulatemain()function like behavior for normal functions using string tokenizing and storing tokens in a NULL terminatedchar*array.
Every thing is fine exceptgetopt(). It won't rearrangeargv[0]coz it expects the first argument to be program name. But for my function theargv[0]isn't the program name. I wan... |
getopt(3)uses a global variableoptind(option index) to track its progress throughargvand initializes it to 1. Try settingoptind = 0before reading the options.
|
I was going through the source code of Linux version 0.0.1. In the kernel source directory saw a file tty_io.c. What is the role of this file/tty in Linux kernel?
|
In Unix systems, atty(which is short for "teletypewriter") is the standard representation of aterminal device, with at least input and output capabilities and usually much more. These were originally connected to serial ports, but most today arevirtual terminals, connected to either a text-mode console (DOS-like) or a... |
Where am I going wrong and why?
```
#include<stdio.h>
#include<string.h>
int main()
{
char *str;
int length, i, j, flag = 0;
printf("\n\nEnter string: ");
fgets(str, 20, stdin);
printf("You entered: %s", str);
return 0;
}
```
There's a problem with the linefgets(str, 20, stdin);line. I cannot figure it out. Af... |
You need to allocate memory forstr
Any size say 128.
char *str = malloc(128*sizeof(char));
or
char str[128];
|
While compiling Apache source, I've been able to define one macro just fine:
```
# export CFLAGS=" -DSINGLE_LISTEN_UNSERIALIZED_ACCEPT" // OR even:
# export CFLAGS=" -DSINGLE_LISTEN_UNSERIALIZED_ACCEPT=1"
```
... works like a charm,howeverevery time I try to set:
```
# export CFLAGS=" -DDEFAULT_PIDLOG=/var/run/ap... |
Seems that DEFAULT_PIDLOG is expected to define a constant C string. Try with
```
export CFLAGS="-DDEFAULT_PIDLOG=\\\"/var/run/apache/apache.pid\\\""
```
(Thanks @mathk)
|
Simple question:
If i have a line in an input file that looks looks like:
```
Hello#Great#Day#Today
```
how can I scan in each word individually as its own array, in other words tell C to stop scanning when it reaches the # character and then go in the next iteration of the loop to scan the next word as a separate ... |
This is assuming you are reading throughstdin. Definitely take a look at @Whoz kick start approach as well (very similar to this).
What you would want to do is create a dynamic array and populate it with every byte read throughstdin. You would then want to create an array of character pointers that will point to th... |
I've created a table and assigned a method withlua_pushcfunctionnamedmytable:myfunction(). In a different (callback) context it's necessarily thatmyfunctionwill be overriden inside the Lua script. For some reasons, if i callmyfunctionfrom the C host, I need to know, ifmyfunctionis still the c function or was replaced ... |
Yes, you can uselua_iscfunction.
|
A short example excerpted from wdm.h
```
typedef struct _KMUTANT {
DISPATCHER_HEADER Header;
LIST_ENTRY MutantListEntry;
struct _KTHREAD *OwnerThread;
BOOLEAN Abandoned;
UCHAR ApcDisable;
} KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX;
```
I know 'P' means 'Pointer', but I don't kn... |
TheRidentifies the pointer as arestricted pointer.
|
I just started using Netbeans 7.3.1, and I am experiencing some trouble compiling my project. In terminal, I successfully compiled with the following code:
```
gcc -Wall one.c two.c three.c four.c -o gateway -lpthread
```
When I compile in Netbeans, I get errors like 'undefined reference to 'pthread_create'. So I ne... |
Found it!
Adding library dependencies to GCC in Netbeans:
```
File->Project Properties->Build->Linker->Libraries->add Library/add standard Library.
```
For example for the -lpthread or -pthread option:
```
add standard Library --> Posix Threads
```
|
I trying to emulatemain()function like behavior for normal functions using string tokenizing and storing tokens in a NULL terminatedchar*array.
Every thing is fine exceptgetopt(). It won't rearrangeargv[0]coz it expects the first argument to be program name. But for my function theargv[0]isn't the program name. I wan... |
getopt(3)uses a global variableoptind(option index) to track its progress throughargvand initializes it to 1. Try settingoptind = 0before reading the options.
|
I was going through the source code of Linux version 0.0.1. In the kernel source directory saw a file tty_io.c. What is the role of this file/tty in Linux kernel?
|
In Unix systems, atty(which is short for "teletypewriter") is the standard representation of aterminal device, with at least input and output capabilities and usually much more. These were originally connected to serial ports, but most today arevirtual terminals, connected to either a text-mode console (DOS-like) or a... |
While compiling Apache source, I've been able to define one macro just fine:
```
# export CFLAGS=" -DSINGLE_LISTEN_UNSERIALIZED_ACCEPT" // OR even:
# export CFLAGS=" -DSINGLE_LISTEN_UNSERIALIZED_ACCEPT=1"
```
... works like a charm,howeverevery time I try to set:
```
# export CFLAGS=" -DDEFAULT_PIDLOG=/var/run/ap... |
Seems that DEFAULT_PIDLOG is expected to define a constant C string. Try with
```
export CFLAGS="-DDEFAULT_PIDLOG=\\\"/var/run/apache/apache.pid\\\""
```
(Thanks @mathk)
|
Simple question:
If i have a line in an input file that looks looks like:
```
Hello#Great#Day#Today
```
how can I scan in each word individually as its own array, in other words tell C to stop scanning when it reaches the # character and then go in the next iteration of the loop to scan the next word as a separate ... |
This is assuming you are reading throughstdin. Definitely take a look at @Whoz kick start approach as well (very similar to this).
What you would want to do is create a dynamic array and populate it with every byte read throughstdin. You would then want to create an array of character pointers that will point to th... |
I've created a table and assigned a method withlua_pushcfunctionnamedmytable:myfunction(). In a different (callback) context it's necessarily thatmyfunctionwill be overriden inside the Lua script. For some reasons, if i callmyfunctionfrom the C host, I need to know, ifmyfunctionis still the c function or was replaced ... |
Yes, you can uselua_iscfunction.
|
A short example excerpted from wdm.h
```
typedef struct _KMUTANT {
DISPATCHER_HEADER Header;
LIST_ENTRY MutantListEntry;
struct _KTHREAD *OwnerThread;
BOOLEAN Abandoned;
UCHAR ApcDisable;
} KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX;
```
I know 'P' means 'Pointer', but I don't kn... |
TheRidentifies the pointer as arestricted pointer.
|
I just started using Netbeans 7.3.1, and I am experiencing some trouble compiling my project. In terminal, I successfully compiled with the following code:
```
gcc -Wall one.c two.c three.c four.c -o gateway -lpthread
```
When I compile in Netbeans, I get errors like 'undefined reference to 'pthread_create'. So I ne... |
Found it!
Adding library dependencies to GCC in Netbeans:
```
File->Project Properties->Build->Linker->Libraries->add Library/add standard Library.
```
For example for the -lpthread or -pthread option:
```
add standard Library --> Posix Threads
```
|
I trying to emulatemain()function like behavior for normal functions using string tokenizing and storing tokens in a NULL terminatedchar*array.
Every thing is fine exceptgetopt(). It won't rearrangeargv[0]coz it expects the first argument to be program name. But for my function theargv[0]isn't the program name. I wan... |
getopt(3)uses a global variableoptind(option index) to track its progress throughargvand initializes it to 1. Try settingoptind = 0before reading the options.
|
I was going through the source code of Linux version 0.0.1. In the kernel source directory saw a file tty_io.c. What is the role of this file/tty in Linux kernel?
|
In Unix systems, atty(which is short for "teletypewriter") is the standard representation of aterminal device, with at least input and output capabilities and usually much more. These were originally connected to serial ports, but most today arevirtual terminals, connected to either a text-mode console (DOS-like) or a... |
This question already has answers here:Checking the return value of a C program in a bash script?(3 answers)Closed10 years ago.
I want to run a exe having command line arguments in a script. Based on the return of this exe, I need to execute further steps. Is it possible to get the return of this exe?
```
#!/bin/bas... |
You can either test the result to see if it is 0 (success) directly using "if", like this:
```
if ./getDisplayWidth "FullHD"; then
```
Or you can run the script and then use $? to refer to it's return value:
```
./getDisplayWidth
if [ "$?" == "0" ]; then
```
|
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Closed10 years ago.
I am trying to replace'G'with'R'but I am getting unhandled exception.
```
int main()
{
char *pszStr1 = "EFGH";
(++pszStr1... |
Your string lies in a read-only area.
Instead, do
```
int main()
{
static char pszStr1arr[] = "EFGH";
char *pszStr1 = pszStr1arr;
(++pszStr1)[1] = 'R';
printf("%s", pszStr1);
return 0;
}
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
In order to write a xmpp bot in linux, you need to use an XMPP library like libstrophe (http://strophe.im/libstrophe) for C language or any other language see XMPP clients in xmpp.org. As far as remote shell is concerned you can useforkptysystem call to start a shell and communicate with it using its standard input an... |
Following the stackoverflow question: "Variadic macros with zero arguments, and commas", I tried:
```
#define MAKE_TEMPLATE(...) template <typename T, ## __VA_ARGS__ >
MAKE_TEMPLATE()
struct Testing{};
```
Compiler gives:error: expected identifier before '>' token
Butg++ -E main.cpp(to get macro expansion) show:
... |
http://en.wikipedia.org/wiki/Variadic_macro:
GCC supports the following (non-portable) extension:## __VA_ARGS__
|
How can I remove the unnecessary parts of an uploaded file content? I am using an HTML form file upload to get the file. But after submitting the file and usingCONTENT_LENGTH, it seems to have extra information displayed like "WebKitBoundary[random characters]"". How can I remove those headers? Thanks!
|
I solved this by usingfgetsin awhileloop until it reads all of the input fromstdin. Then, I loaded them in abuffer, remove those unnecessary strings by setting them toNULL.
|
The g_poll() function returns-1"on error or if the call was interrupted". (See:https://developer.gnome.org/glib/2.28/glib-The-Main-Event-Loop.html#g-poll).
Ifg_pollreturns-1how do I determine if this was because the call was interrupted vs. if there was an error?
If it was an error, how do I determine the cause of t... |
Yes. Checkerrnoifg_poll()returns-1. The documentation also says
gpoll()polls fds, as with the poll() system call, but portably.On systems that don't have poll(), it is emulated using select().
i.e.g_poll()usespoll()andselect()internally.Hence, check the various scenarios thaterrnois set to various values bypoll()and... |
I have looked at thelibspotifydocumentation and have not been able to find a function that allows me to get a list of handles to artists that the current user is following. Is there something I have missed or is it just not part of the public API yet?
|
At the moment,No.
However, you may want to take a look at these other Q&As that manage to overcome the limitations of the API by implementing their own workarounds with the info available.
Obtaining a list of artists from the user's favorite tracks.Parsing the localplaylist.bnkfile.
|
I have a daemon process namedmydaemon. Now I want to have an other process to send something for me , and when I fork a child process , it has the same name with the parent process. How can I have a different process name withoutexecfunction?
|
Under Linux you can use theprctl()function to set the process name:
```
#include <sys/prctl.h>
prctl(PR_SET_NAME, "foobar");
```
|
I am calling a shell script from a 'c' program and have some variables in c which I would like to pass as arguments to the shell script. I tried using the system() to call the shell script but the variable I pass as argument is considered as a string rather than a variable.
|
shell script (a.sh):
```
# iterates over argument list and prints
for (( i=1;$i<=$#;i=$i+1 ))
do
echo ${!i}
done
```
C code:
```
#include <stdio.h>
int main() {
char arr[] = {'a', 'b', 'c', 'd', 'e'};
char cmd[1024] = {0}; // change this for more length
char *base = "bash a.sh "; // note trailine ' ... |
I saw other questions about having two main()'s in C program:
I'm using CodeBlocks
But please consider this program:
```
void main()
{
void main()
{
printf("hello!");
}
printf("World!");
}
```
prints only "World!".
I'm actually writing these kind of code pieces to check what's happening u... |
C: Can there be two main() functions in a program?
No.
And the code you posted is not valid C anyway, there are no nesting functions in C.
|
Hi guys I am new to Dll Hijacking. I have few problems and I hope that you would help me clarify my doubts.
Suppose I used msfpayload to generate a calc dll
```
msfpayload windows/exec CMD=calc.exe D > abc.dll
```
The dll file generated by msfpayload works fine, and the calculator prompts along with the software.
... |
The software won't execute. [W]hy is that?
Almost certainly becauseowned()callsexit(). This terminates the process.
|
I have the following program
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char string[30],ch,*chp;
printf("Enter Text below:");
gets(string);
printf("\n Character to find:");
ch=getchar();
chp=strchr(string,ch);
if(chp)
printf("Character %c found in string",ch);
els... |
if (pointer)is equivalent toif (pointer != NULL).
|
I am a beginner C coder and I want to know how the make it so the program will do this.
```
printf("which direction would you like to go?\n");
/*they type an arrow key*/
printf ("you went left/right/up/down\n");
```
I have a Mac
|
Try these suggestions. You can get the ASCII codes by
getch()
|
I'm developing a program in C using Xcode.To be practical let's take the following code
```
#include <stdio.h>
int main () {
printf("%c",3);
}
```
It's supposed to display the hearts character but it doesn't,instead just a interrogation icon show's up!And,at least for me,this is happening for many other 'spec... |
The ASCII character 3 is a control character called "end of text." It does not stand for a hearts symbols. You may think that it does because the PC console generated a heart-suit symbol when a program tried to print that character. There's no reason why a modern system should follow the same convention, although the ... |
```
#include<stdio.h>
#include<string.h>
int main()
{
char a[1000000];
int i,j;
int arr[1000000];
gets(a);
unsigned long int len=strlen(a);
if(len<1000000){
for(i=0,j=len-1;i<len&&j>=0;i++,j--)
arr[j]=a[i]-'0';
}
return 0;
}
```
I am using this code to store th... |
The alternative to gets it's fgets:
```
fgets(a, sizeof(a), stdin);
```
|
I am developing an NDIS 6 filter driver of Win7 and Win8 for WinPcap and Nmap. As you know, Nmap is a network scanner. A requirement of Nmap is to capture localhost packets like "ping 127.0.0.1", so that Nmap can test the local machine itself, too. However, it seems that the localhost packets will just return in the T... |
You'll need a WFP callout to capture layer-3 loopback packets. TCPIP has a fast-path for loopback that never reaches layer-2 in NDIS.
|
What should I be using if (on a multicore system) I wanted to make a kernel module function be ran only by one core at a time? Said in other words, avoid two cores running the same function at the same time; aka, one of the cores should wait for the other one to finish running the function.
Mutex? Spinlock? Something... |
You need to use variants of spinlock() i.e raw_spin_lock_irqsave(), raw_spin_lock_irqrestore() (https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/linux/spinlock.h#n188), not mutex() cause they're sleep-able, so they might wake up on some other CPUs. And spinlock will make sure your code won'... |
Let's say I epoll_create1() and only interest in EPOLLIN | EPOLLET for 1 socket.
Is it possible that I will get epoll_wait() > 1 (assuming timeout=-1) for that socket and the event is EPOLLIN?
Or will epoll_wait() return 1 even there are multiple packets (let's say spread over few sec that I pause the program on pur... |
epoll_waitreturns the number ofevents, which according to the documentation equals the "number of file descriptors ready for I/O". So you cannot get more events than the number of file descriptors you have registered.
|
What is the error in this code ??!!
HINT : thesp_to_dash()function in the following program prints a dash for each space in its string argument. That is, the string"this is a test"will be printed as"this-is-a-test".
```
#include <stdio.h>
void sp_to_dash( char *str);
int main(void)
{
sp_to_dash("this is a te... |
String literals are not modifiable. Change it this way:
```
int main(void)
{
char str[] = "this is a test";
sp_to_dash(str);
return 0;
}
```
|
If you have a pointer that is not initialized and, by mistake, try to free it, is this going to result in undefined behavior?
Like:
```
int main(void){
char *string;
free(string);
return 0;
}
```
|
Does freeing an uninitialized pointer result in undefined behavior?
Yes.
However, freeing a null pointer is well-defined.
From the C99 standard:
Thefreefunction causes the space pointed to byptrto be deallocated, that is, made available for further allocation. Ifptris a null pointer, no action occurs. Otherwise, i... |
I'm developing a program in C using Xcode.To be practical let's take the following code
```
#include <stdio.h>
int main () {
printf("%c",3);
}
```
It's supposed to display the hearts character but it doesn't,instead just a interrogation icon show's up!And,at least for me,this is happening for many other 'spec... |
The ASCII character 3 is a control character called "end of text." It does not stand for a hearts symbols. You may think that it does because the PC console generated a heart-suit symbol when a program tried to print that character. There's no reason why a modern system should follow the same convention, although the ... |
```
#include<stdio.h>
#include<string.h>
int main()
{
char a[1000000];
int i,j;
int arr[1000000];
gets(a);
unsigned long int len=strlen(a);
if(len<1000000){
for(i=0,j=len-1;i<len&&j>=0;i++,j--)
arr[j]=a[i]-'0';
}
return 0;
}
```
I am using this code to store th... |
The alternative to gets it's fgets:
```
fgets(a, sizeof(a), stdin);
```
|
I am developing an NDIS 6 filter driver of Win7 and Win8 for WinPcap and Nmap. As you know, Nmap is a network scanner. A requirement of Nmap is to capture localhost packets like "ping 127.0.0.1", so that Nmap can test the local machine itself, too. However, it seems that the localhost packets will just return in the T... |
You'll need a WFP callout to capture layer-3 loopback packets. TCPIP has a fast-path for loopback that never reaches layer-2 in NDIS.
|
What should I be using if (on a multicore system) I wanted to make a kernel module function be ran only by one core at a time? Said in other words, avoid two cores running the same function at the same time; aka, one of the cores should wait for the other one to finish running the function.
Mutex? Spinlock? Something... |
You need to use variants of spinlock() i.e raw_spin_lock_irqsave(), raw_spin_lock_irqrestore() (https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/linux/spinlock.h#n188), not mutex() cause they're sleep-able, so they might wake up on some other CPUs. And spinlock will make sure your code won'... |
Let's say I epoll_create1() and only interest in EPOLLIN | EPOLLET for 1 socket.
Is it possible that I will get epoll_wait() > 1 (assuming timeout=-1) for that socket and the event is EPOLLIN?
Or will epoll_wait() return 1 even there are multiple packets (let's say spread over few sec that I pause the program on pur... |
epoll_waitreturns the number ofevents, which according to the documentation equals the "number of file descriptors ready for I/O". So you cannot get more events than the number of file descriptors you have registered.
|
What is the error in this code ??!!
HINT : thesp_to_dash()function in the following program prints a dash for each space in its string argument. That is, the string"this is a test"will be printed as"this-is-a-test".
```
#include <stdio.h>
void sp_to_dash( char *str);
int main(void)
{
sp_to_dash("this is a te... |
String literals are not modifiable. Change it this way:
```
int main(void)
{
char str[] = "this is a test";
sp_to_dash(str);
return 0;
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.