question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I know this is possible, because I have a binary I wrote a couple years ago to do exactly this. Unfortunately, I didn't save the source code.
I know that it was written in pure C, and I called against an OS X API and was able to lock the screen. Googling for "pure C OS X lock screen" and similar strings isn't getting... |
One way to do this is by using a call tosystem():
```
#include <stdlib.h>
int main(void) {
system("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend");
return 0;
}
```
|
I get this error.
```
error: warning: incompatible implicit declaration of built-in function ‘memcpy’ [enabled by default]
```
This is the code:
```
int arr[ 12] = {1,0,0,0,0,0,0,0,0,0,9370, 0};
void *a = &arr;
memcpy(machine->mem, a,12*4);
```
What I am doing wrong?
|
You likely forgot to include<string.h>.
Add#include <string.h>to the top of your file.
|
What does this code means? Specifically, what are the curly braces doing? They're not in the middle of a function.
```
yyerror(s) char * s;
{
fputs(s,stderr), putc('\n',stderr);
}
```
|
That looks like K&R syntax. In standard C, it would look like:
```
int yyerror(char *s)
{
fputs(s,stderr), putc('\n',stderr);
}
```
The comma operator in the function body is really a no-op in this case, too. You could easily replace it with a semicolon and get this more familiar looking (and equivalent) code:... |
```
struct contact list[3];
int checknullarray()
{
for(int x=0;x<10;x++)
{
if(strlen(contact[x].name)==0)
{
return x;
break;
}
}
}
```
I am having problem with the checknullarray. It say that my type name(contact[x].name)is not allowed. What should I do now?
|
Supposing contact haves a member likechar name[n];
```
struct contact list[3];
int checknullarray(void) /* void is a better option when no params */
{
for (int x = 0; x < 10; x++) /* 3 or 10 ? I think you want x < 3 */
{
/*
if(strlen(contact[x].name)==0) No need to strlen, you can check if na... |
I am learning cmocka unit testing framework. I am a bit puzzled at use of mock() function. Can somebody explain it clearly why and how it is used with suitable examples? Also please explain when it should be used.
|
You should readhttps://lwn.net/Articles/558106/to understand the mock() feature.
|
```
#include <stdio.h>
int main(void)
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int*)(&a + 1); // what happens here ?
printf("%d %d\n", *(a + 1), *(ptr - 1));
return 0;
}
```
I expected the answer to be 1 but 'm getting 5 ..
Why ?
|
```
int *ptr = (int*)(&a + 1); // what happen here ?
```
The address of the array is taken, and then 1 is added to it, which produces a pointer pointingsizeof abytes past the beginning ofa. That pointer is then cast to anint*, and that is assigned toptr. The same could be achieved with
```
int *ptr = &a[5];
```
in... |
```
void mystery2 (int n)
{
int i;
for (i = 1; i <= n; i++) {
double x = i;
double delta = 1 / (double)i;
while ( x > 0 )
x -= delta;
}
return 0;
}
```
How to determine the time complexity of this program using tracking tables like herehttp://pages.cs.wisc.edu/~vernon/cs367/notes/3.COMPLEXITY.ht... |
For each iteration, initially you havex=i, thenxis decremented by1/ieach time. So this will be repeatedi/(1/i)==i^2times.
So, for each iteration offor(i=1;i<n;++i), the inner part has a complexity ofO(i^2). Asigrows from 1 to n it's just like adding(1^2+2^2+3^2+...+n^2), which is roughlyn^3/6. Thus it'sO(n^3).
```... |
Hi I have a question about double pointers. For example in this code:
```
int a, b=2;
int *iPtr1, **iPtr2;
iPtr1 = &a;
iPtr2 = &iPtr1;
*iPtr1 = b+3;
*iPtr2 = iPtr1;
```
On the last line*iPtr2 = iPtr1;It that just tellingiPtr1to point back to itself since dereferencing a double pointer just once is like usingiPt... |
It makes*iPtr2point to whateveriPtr1points to. And asiPtr2points toiPtr1it's the same asiPtr1 = iPtr1.
|
I have a piece of C code I need to deobfuscate. It contains a bunch of tricky macros. I ran the code through C preprocessor and indent and now it looks similar to this:
```
switch (9263 + 1505) {
case 1505 + 41131 + 6729 + 2347:
...
case 1505 + 41131 + 6729 + 2347 + 1:
...
case 1505 + 41131 + ... |
Use clang to compile it, and use its c backend to generate c code.
Something like this should work:
```
clang -emit-llvm source.cpp -o - | llc -march=c
```
|
How to use perf to examine which parts of code run slowly? I came about theseLinksbut still I could not understand the data generated which is something like this!So how do i understand the reports of perf and data generated by perf annotate?picture
|
ThisTutorialmay help. As osgf said, you want to look for the "hottest" functions and instructions, that are where your program spent most of the time. Then think on how you can improve those areas. Make sure you have debug symbols so perf report gives you a more understandable output.
|
I'm having some troubles with this "simple" program that im trying to build.
My goal is to create a C program which executes an mp3 sound file saying "Hello" and runs at Windows startup.
```
#include<stdio.h>
main(int argc, char *argv[]){
FILE *fp;
char s[100];
int i;
if((fp=fopen("Hello.mp3","rb"))==NULL) /... |
I think we cannot open an mp3 file this way , like any regular text file.
```
fp=fopen("Hello.mp3","rb")
```
We have to use a codec , to actually play the mp3 file , or atleast use a library which has one.
Do take a look at these places.
How to play MP3 files in C?
SDL Sound Mix Tutorial
|
I've written some code to right justify all the bits in a char's byte.
However, the application is stuck in a loop because it never executes the linepositionmask<<1;
Why is this happening?
```
void rjustify(char thisChar)
{
unsigned char c = thisChar;
unsigned char positionmask = 1;
unsigned char inserti... |
When the line is executed, it has no effect. Turn up your compiler warnings and change it to:
```
positionmask <<= 1;
```
|
I have two structs name *head and *tail.
I use head for start of linked list and tail for the end.
Lets say I have a linked list with an arbitrary amount of elements
```
typedef struct queue
{
int stuff;
struct queue *nextNode;
}q;
```
In one of my nodes, stuff = 164 (this is hypothetical)
How would I go ... |
Grab a pointer to the head of the linked list. Assuming that the last item in the list is marked with itsnextNodepointer beingNULL, you can iterate through the list one by one:
```
struct queue *tmp = head;
while (tmp != NULL) {
if (tmp->stuff == 164) {
// found it!
break;
}
tmp = tmp->nex... |
In this project, I need to get the size of a struct in a header file from within a C file.
I can't include the header file in the C file because the struct contains classes which will not compile in C.
Any ideas?
|
You could declare in the.hfile:
```
extern const size_t SIZE_OF_MY_STRUCT;
```
And defineSIZE_OF_MY_STRUCTin the.cppfile as:
```
extern const size_t SIZE_OF_MY_STRUCT = sizeof(MyStruct);
```
So you would not have the overhead of a function call.
|
I am wondering if there is some sort of string prefix so that the cstring is taken as is without the need of my escaping all the characters. I am not 100% sure. I remember something about prefixing the string with the@symbol (char str[] = @"some\text\here";) and you would not need to escape any of your characters such... |
No. In C there are only two types of "string", the string literal surrounded by double quotes and the char literal surrounded by single quotes.
In both cases you must backslash escape characters that have special meaning.
|
I was asked this about a month back. It is not exactly my line of work, yet I'm curious. They basically had some music libraries in C and wanted to make them available for ios code.
If I have some .c or .cpp files. How can I use them in an ios project. Again this can be confusing as I'm not giving you any context. Bu... |
Just add them to the project, you don't have to do anything special. XCode (and clang) will know what language they are from the extension and compile them appropriately.
Youmightneed to tell xcode to link tolibstdc++, but that would be it.
|
I'm having some troubles with this "simple" program that im trying to build.
My goal is to create a C program which executes an mp3 sound file saying "Hello" and runs at Windows startup.
```
#include<stdio.h>
main(int argc, char *argv[]){
FILE *fp;
char s[100];
int i;
if((fp=fopen("Hello.mp3","rb"))==NULL) /... |
I think we cannot open an mp3 file this way , like any regular text file.
```
fp=fopen("Hello.mp3","rb")
```
We have to use a codec , to actually play the mp3 file , or atleast use a library which has one.
Do take a look at these places.
How to play MP3 files in C?
SDL Sound Mix Tutorial
|
I've written some code to right justify all the bits in a char's byte.
However, the application is stuck in a loop because it never executes the linepositionmask<<1;
Why is this happening?
```
void rjustify(char thisChar)
{
unsigned char c = thisChar;
unsigned char positionmask = 1;
unsigned char inserti... |
When the line is executed, it has no effect. Turn up your compiler warnings and change it to:
```
positionmask <<= 1;
```
|
I have two structs name *head and *tail.
I use head for start of linked list and tail for the end.
Lets say I have a linked list with an arbitrary amount of elements
```
typedef struct queue
{
int stuff;
struct queue *nextNode;
}q;
```
In one of my nodes, stuff = 164 (this is hypothetical)
How would I go ... |
Grab a pointer to the head of the linked list. Assuming that the last item in the list is marked with itsnextNodepointer beingNULL, you can iterate through the list one by one:
```
struct queue *tmp = head;
while (tmp != NULL) {
if (tmp->stuff == 164) {
// found it!
break;
}
tmp = tmp->nex... |
In this project, I need to get the size of a struct in a header file from within a C file.
I can't include the header file in the C file because the struct contains classes which will not compile in C.
Any ideas?
|
You could declare in the.hfile:
```
extern const size_t SIZE_OF_MY_STRUCT;
```
And defineSIZE_OF_MY_STRUCTin the.cppfile as:
```
extern const size_t SIZE_OF_MY_STRUCT = sizeof(MyStruct);
```
So you would not have the overhead of a function call.
|
I am wondering if there is some sort of string prefix so that the cstring is taken as is without the need of my escaping all the characters. I am not 100% sure. I remember something about prefixing the string with the@symbol (char str[] = @"some\text\here";) and you would not need to escape any of your characters such... |
No. In C there are only two types of "string", the string literal surrounded by double quotes and the char literal surrounded by single quotes.
In both cases you must backslash escape characters that have special meaning.
|
I was asked this about a month back. It is not exactly my line of work, yet I'm curious. They basically had some music libraries in C and wanted to make them available for ios code.
If I have some .c or .cpp files. How can I use them in an ios project. Again this can be confusing as I'm not giving you any context. Bu... |
Just add them to the project, you don't have to do anything special. XCode (and clang) will know what language they are from the extension and compile them appropriately.
Youmightneed to tell xcode to link tolibstdc++, but that would be it.
|
what is the problem here? scanf doesnt seems to working in while loop. i was trying to find out vowel & consonent until user wants.
Here's the code:
```
#include <stdio.h>
main()
{
char x,c;
do
{
printf("enter\n");
scanf("%c",&x);
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
... |
You are trying to read a character using%dwhich is wrong. Use%cinstead.
|
Can anyone help with converting the following inline assemly in a header file to corresponding x86-64 .asm file or c style function without assembly?
```
extern const char hexlu[];
void _inline hextoascii(char* a_src , char* a_dest ) {
_asm {
mov esi, a_src;
mov edi, a_dest;
sub ebx,ebx
mo... |
```
void hextoascii(char* src, char* dest)
{
dest[0] = hexlu[ 2*(unsigned)src[0]];
dest[1] = hexlu[1+2*(unsigned)src[0]];
}
```
|
I have the code:
```
#DEFINE NEW = 1;
```
And a Struct:
```
typedef struct PCB
{
/*Process state:new, ready, running, waiting, terminated*/
int state;
}PCB;
```
How can I assign NEW, such that state=1?
More info, I get the error:
```
expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
```
|
Remove both semicolon and the=
#DEFINE NEW 1
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
Neither...
```
void GoodPractice()
{
bool flag = right;
// though I would return it ;)
}
```
|
So my question is the following.
```
int n=0;
while(n<=0)
scanf("%d",&n);
```
This code enters in an infinite loop, and I don't have a clue why. When the user inputs a number > 0, the loop was supposed to stop.
And thanks:)
|
Over and over and over and over...
stdinis (generally) line-buffered - one has to press<enter>to make the terminal transfer the characters to your program. So now there's a dangling newline character in the buffer, andscanf()will try to read it during the next iteration, but it's not an integer, so it fails and doesn... |
I'm still a beginner in coding so I had this problem
I'm trying to convert an integer into its binary representation
```
#include <stdio.h>
int main () {
int x;
printf("input the number\n");
scanf("%d",&x);
while(x!=0) {
if (x%2)
printf("1");
else
printf("0");
}
return 0;
... |
The Program Logic for the operation is wrong , try this
```
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
... |
I am usingstfp serverbut it requires RSA key authentication, Here i want to upload files on mysftpserver.
So please any body can tell me how can i authenticate my SFTP server using private key ofRSAprogrammatically in C. I want to do this thing in C
i am using thislinkfor refernce
But Here its not mentioned how to ... |
For public key authentication I add the following options:
```
const char* path_to_my_public_key = "~/.ssh/id_rsa.pub";
const char* path_to_my_private_key = "~/.ssh/id_rsa";
curl_easy_setopt(m_curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PUBLICKEY);
curl_easy_setopt(m_curl, CURLOPT_SSH_PUBLIC_KEYFILE, path_to_my_publi... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
It seems that with normal integers ... |
You only seem interested in 2 values of k: 0 and -1.
For k=0:(n^0)-0=(n+0)^0, ok.
For k=-1, sincen^-1==~n, this rewrites as~n+1=~(n-1), try adding n-1 on both sides and notice that n+~n==-1.
|
i created a text file in d: drive named abc. I am unable to open it. Please tell me how to do so.
```
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
clrscr();
fp = fopen("D:/abc.txt","r");
if(fp == NULL)
{
printf("\nCannot open");
getch();
ex... |
You have a typo, try
```
fp = fopen("D:\\abc.txt","r");
```
instead.Or if the file is in the same folder as the program:
```
fp = fopen("abc.txt","r");
```
|
What is the practical difference, if any, betweenstdinandSTDIN_FILENOin C?
|
The interface. Like everyone else has said,stdinis aFILE *as defined by the standard c library. You can use some of the higher level interfaces likefread,fwrite, andfprintf. On the other hand,STDIN_FILENOis just a file descriptor (almost certainly 0). This uses a slight lower level interface through the likes ofre... |
```
#include <stdio.h>
#include <cstdlib>
rec();
main()
{
int a, fact;
char q, n, y;
printf("\nEnter any number ");
scanf("%d", & a);
fact = rec(a);
printf("Factorial value = %d\n", fact);
printf("do you want to exit.....(y/n):");
scanf("%s" ,&q);
if (q == 'n')
{
syst... |
Change
```
#include <cstdlib>
```
to
```
#include <stdlib.h>
```
cstdlibis aC++ header file, and thus will beunusable in C.
|
I have a feeling this may be too broad of a question but I'm hoping some may be a u-boot expert so I'm going to give it a shot...
When compiling for a powerpc based setup similar to redwood, I'm getting an error: nand.c:91: undefined reference to `board_nand_init'
The function is in ndfc.c, which does not have a .h ... |
This kind of error is usually caused by not defining all the compilation variables required.
See theU-Boot README file. Some are set with the Makefile: for examplemake TQM823L_configwhich defines all the variables normally used for the TQM823L board.
Other configuration settings need to be done by hand editing the... |
I need to support an old hardware, which user land library doesn't have source code, but I have the source code for the device driver. Therefore, I have to rewrite the device driver to support IA-32 mode user land binaries.
For the ioctl calls, compat_ioctl is added to support IA-32 in user land. But the 32 bit libra... |
You don't need to worry about it. When yourf_op->mmap()function is called, it's passed astruct vm_area_structwhich is already correctly positioned for the calling task.
(On x86-64, thearch_get_unmapped_area()function takes care of this - it ensures that the area returned is less thanTASK_SIZE, andTASK_SIZEdepends on... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
Is there a way to implement bitwise... |
```
a xor b == (a and (not b)) or ((not a) and b)
```
|
This question already has answers here:Check substring exists in a string in C(12 answers)Closed9 years ago.
I'm pretty new to the language. Let's say I have a string from an HTTP request, such as
```
char * request = "GET /favicon.ico HTTP/1.1";
```
And I specifically want to know iffaviconis in that request, perh... |
```
if (strstr(request, "favicon") != NULL) {
// contains
}
```
|
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed10 years ago.
Is there a difference between:
```
char string = "name";
const char* point = string;
```
vs
```
const char string[] = "name";
```
Will you please explain the difference too?
|
Yes.
The first simply points to a read only section of memory, the declaration really should be:
```
const char* string = "name";
```
The second creates an array long enough to hold the string"name"(so, four characters plus one for the null terminator) and copies the string inside the allocated space.
|
```
void setup_map (int *map); <--- prototype
int row, col; <-- global variables
some main
{
//get number of rows and cols from user
int map[rows][cols]; //create map here because another function uses it
setup_map (map[row][col]);
}
void setup_map (int map[row][col])
{
loop through and set up map
}
```
... |
Correct prototypes include:
```
void setup_map(int map[ROWS][COLS]);
void setup_map(int map[][COLS]);
void setup_map(int (*map)[COLS]);
```
And to call it:
```
setup_map(map);
```
Note that, however, that the number of rows and columns needs to be a compile-time constant for this to work.
|
Is there a difference between
```
const char* name = "name";
```
and
```
const char *name = "name";
```
Thank you.
|
no.
But there is a difference between
```
const char* name = "hello", something = "else";
```
which will not work, while
```
const char *name = "hello", *something = "else";
```
should
|
I have a small question. I know that the %x format specifier can be used to read values from the stack in a format string attack.
I found the following code:
```
%08x%08x%08x%08x
```
What does the 08 mean? What is it doing exactly? Thanks :)
|
Break-down:
8says that you want to show 8 digits0that you want to prefix with0's instead of just blank spacesxthat you want to print in lower-case hexadecimal.
Quick example (thanks to Grijesh Chauhan):
```
#include <stdio.h>
int main() {
int data = 29;
printf("%x\n", data); // just print data
printf... |
I heard of FlasCC which is a C/C++ compiler targets AVM2. And also I heard it is based on an older version of GCC. (4.2??)
What kind/versions of C and C++ standards are supported on FlasCC?
|
As perhttp://www.adobe.com/devnet-docs/flascc/docs/Reference.htmlit use standard GCC 4.2http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/, which should answer your query!
You can look at "Introduction" section of above GCC link to know what is supported in this compiler.
|
I am doing assignment in which I am using POSIX named semaphore, but it is not showing me list when I enteripcs -scommand.
Please help me to get entry of named semaphore. Where will I get that?
|
ipcsis for System V semaphores, you are using POSIX semaphores. For the differences, seehere.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
How to implement printf style funct... |
You usevariable argument liststo do this.
An initial argument that somehow contains the information needed to properly decode the type and order of the other arguments is needed, this is the formatting string forprintf().
|
followed the steps mentioned in the following thread,
Attaching a process to a debug session: empty process list
Now I am able to get the process list. But Process list is missing "javaw.exe" which is shown in the task manager.
any help?
|
Enter the process id of the process you want to attach to.
You can get the process id by looking for the process's image name in the task manager.
|
What is the practical difference, if any, betweenstdinandSTDIN_FILENOin C?
|
The interface. Like everyone else has said,stdinis aFILE *as defined by the standard c library. You can use some of the higher level interfaces likefread,fwrite, andfprintf. On the other hand,STDIN_FILENOis just a file descriptor (almost certainly 0). This uses a slight lower level interface through the likes ofre... |
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed10 years ago.
Is there a difference between:
```
char string = "name";
const char* point = string;
```
vs
```
const char string[] = "name";
```
Will you please explain the difference too?
|
Yes.
The first simply points to a read only section of memory, the declaration really should be:
```
const char* string = "name";
```
The second creates an array long enough to hold the string"name"(so, four characters plus one for the null terminator) and copies the string inside the allocated space.
|
```
void setup_map (int *map); <--- prototype
int row, col; <-- global variables
some main
{
//get number of rows and cols from user
int map[rows][cols]; //create map here because another function uses it
setup_map (map[row][col]);
}
void setup_map (int map[row][col])
{
loop through and set up map
}
```
... |
Correct prototypes include:
```
void setup_map(int map[ROWS][COLS]);
void setup_map(int map[][COLS]);
void setup_map(int (*map)[COLS]);
```
And to call it:
```
setup_map(map);
```
Note that, however, that the number of rows and columns needs to be a compile-time constant for this to work.
|
Is there a difference between
```
const char* name = "name";
```
and
```
const char *name = "name";
```
Thank you.
|
no.
But there is a difference between
```
const char* name = "hello", something = "else";
```
which will not work, while
```
const char *name = "hello", *something = "else";
```
should
|
Uncrustify is great, and does an excellent job of tidying code.
However, I have some C code within a file that I don't want Uncrustify to change. Is there any way I can prevent Uncrustify from touching this, maybe by putting specific tags in comments around the code or something?
|
```
/* *INDENT-OFF* */
int i = 0; // No uncrustify action here
/* *INDENT-ON* */
```
|
I came accros this line of code:
```
#define CPARSER_FLAGS_DEBUG (1 << 0)
```
What does it do? Its the same as:
```
#define CPARSER_FLAGS_DEBUG (1)
```
Right?
|
Yes, it is. Maybe it is used for symmetry when setting values for flags:
```
#define FLAG_1 (1 << 0)
#define FLAG_2 (1 << 2)
#define FLAG_3 (1 << 3)
/* ... */
```
Don't worry about performances, a good compiler will be able to optimize such operations.
You can combine these values as follow:
```
/* Flags FLAG_1... |
It is possible to imitate namespaces in C like this:
```
#include <stdio.h>
#include <math.h>
struct math_namespace {
double (*sin)(double);
};
const struct math_namespace math = {sin};
int main() {
printf("%f\n", math.sin(3));
return 0;
}
```
Are there any disadvantages to this, or just situation... |
This method is already used in real projects such as theC Containers Libraryby Jacob Navia. C is not designed for object-oriented programming. This is not really efficient, since you have to (1) access to the structure and (2) dereference the function pointer. If you really want prefixes, I think changing your identif... |
I want to know how to check if a value or a object exists in an array, like in python:
```
a = [1,2,3,4,5]
b = 4
if b in a:
print("True!")
else:
print("False")
```
I want to know if something similar already exists in cython. I have a struct object array of pointers; I want to know if the object exists in th... |
You pretty much have to iterate through the array and check each element.
```
#include <stdbool.h>
bool isvalueinarray(int val, int *arr, int size){
int i;
for (i=0; i < size; i++) {
if (arr[i] == val)
return true;
}
return false;
}
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
I think it's "return code". Mostly used to refer to integer return codes of0/NULL or 1form.
|
I have the following input:
```
AG23,VU,Blablublablu,8
IE22,VU,FooBlaFooBlaFoo,3
and so on...
```
I want it to "parse" withscanf()using some code like this:
```
char sem[5];
char type[5];
char title[80];
int value;
while(scanf("%s,%s,%s,%d", sem, type, title, &value) == 4) {
//do something with the read line valu... |
The comma is not considered a whitespace character so the format specifier"%s"will consume the,and everything else on the line writing beyond the bounds of the arraysemcausing undefined behaviour. To correct this you need to use a scanset:
```
while (scanf("%4[^,],%4[^,],%79[^,],%d", sem, type, title, &value) == 4)
`... |
What is the behavior of calling a null function pointer?
```
void (*pFunc)(void) = NULL;
pFunc();
```
Why is it advisable to initialize yet unused function pointers to NULL?
|
In C and C++, this is calledundefined behaviour, meaning that this can lead to aSegmentation fault, nothing or whatever such a case will cause based on your compiler, the operating system you're running this code on, the environment (etc...) means.
Initializing a pointer to a function, or a pointer in general to NULL... |
I am writing a C code to parse a XML file for which I use libxml2 library. The xml is stored in file. Now, I need to call a WebService from the same C (client)program and then fetch that XML and parse it.
I am a bit confused and want to know if libxml2 library can do this?
Or do I need some other library to handle ... |
Libxml2 can only parse, generate or modify an XML tree, stored in a file or in memory. If you want to do an HTTP(S) request and get a response, you need to use another library, for example libcurl (http://curl.haxx.se/libcurl/).
Note also that libxml2 doesn't know anything about SOAP, as I assume from your question t... |
I have the following code:
```
struct prefix rnp;
char prefix[IPV6_PREFIX_STR_MAX_LEN];
...
strncat(prefix, "/", 1); <----- WORKS OK
strncat(prefix, rnp.prefixlen, MAX_PREFIX_LEN); <------ SEG FAULT
...
```
Wherernp.prefixlenis of typeu_int8_t.
```
IPV6_PREFIX_STR_MAX_LEN = 45
MAX_PREFIX_LEN = 2
```
Content o... |
Ifrnp.prefixlenis aninteger(as indicated by the typeu_int8_t), then you cannotstrncatit (the integer will be cast to a pointer and then dereferenced, which will cause undefined behaviour).
If your goal is to write some formatted text to a string, usesprintforsnprintfinstead:
```
sprintf(prefix, "/%d", rnp.prefixlen)... |
I want to implement a functionality such that a loop keeps on iterating and simultaneously takes input from user if available.
I have implemented following code but the value of scanned variable "a" does not get reflected while printing.
```
pid_t pid;
pid=fork();
if(pid == 0 )
{
while(1)
{
printf("%... |
That is because you have two separate processes using fork(). You will need to use threads if you want to follow this approach.
|
```
#include<stdio.h>
int main(){
int * ptr=(int *)malloc(40);
printf("%d",sizeof(ptr));
}
```
When I'm running this, output is coming as 8...what is happening here...why is output 8?
|
malloc()returns a pointer to 40 bytes of memory (probably 10 ints) and assigns it toptr. The reasonsizeof(ptr)is 8 is because you are using a 64 bit machine and pointers are 8 bytes in size.
You should usesizeof()inside themalloc()because it's good form and avoids problems if the type ever changes size (crossing pla... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I implemented introsort using quick... |
Both gcc and Microsoft's VisualC++ provide source code for std::sort (in header file algorithm). So, you can take a look yourself. I have investigated similar issues before. My conclusion was that the code was optimized for the general code path even to the extent of making the code more complex and difficult to maint... |
Hello I use following code to print tabulated out put of my database queries
```
printf("+----------+------------+\n");
printf("| Col1 | Col2 |\n);
printf("+----------+------------+\n");
for(i=0;i<n;i++)
printf("|%8s|%8s|\n",str1,str2);
printf("+----------+------------+\n");
```
It just makes my db tabl... |
Unicode does include some characters intended for this. Wikipedia has a list:
http://en.wikipedia.org/wiki/Box-drawing_character
|
I have a bunch of different datatypes I want to pass to char but when I do the usual format for passing ints:
```
char number=(char)one;
```
It only works for integers. With other datatypes it gives me the numerical vales when I want the string representation. What is the easiest way to do this?
P.S. please explain ... |
If you are looking for the string representation of the datatypes, I think what you want is thesprintffunction. For example, for a float type you would do:
```
float example = 3.6;
char temp[64]; // Allocate a string of size 64.
sprintf(temp, "%f", example);
```
This will store a string representation ofexamplein te... |
I need to write a one liner program that prints out the program's arguments without using any other counter variables except for argc. However:
Problem 1. It prints the arguments in descending order, rather than ascending.
Problem 2. gcc and cl produce different results, so which one is right?
```
while(argc>0) pri... |
If you are looking for a oneliner then this will do without the help ofargc:
```
while(*argv) printf("Argument is %s\n",*argv++);
```
argv[argc]is guaranteed to be NULL.
This is also a problem in your code. When you passargv[argc]with%s, it causes undefined behaviour. Another being the modification ofargcwithout an... |
I have a project where I want to read a file with data which lies in a specific folder. I have a script file to execute the program, and this script file can lie anywhere on the computer, hence I cannot use the function getcwd in the program to get the path for my data file. My question is, is there any possibility in... |
In the script you could docd <specific dir>and then start the binary using an absolute path.
```
cd <specific dir>
/home/user/project/main
```
Then inmainyou very well could do agetcwd()to have<specific dir>be returned tomain.
And no, there is no portable way to get the path wheremainis located from out ofmain.
|
I am building an APP over TCP and to detect the other end is down, I need to implement a heartbeat mechanism where the client keeps sending pseudo ping packets. I did some testing and saw that when the other end is down, the number of bytes read is 0.
So I can I not so something like this?:
```
If FD is set, then
... |
The cause of read return 0 is that the peer sends FIN. If there is some network issue between you and peer (the network cable is plugged out), how do your application detect it without keepalive? The read will block for a long time (depend on your OS environment).
|
When i compiles a program with this code:
```
int main()
{
float a;
scanf("%f", &a);
printf("%.1f\n", a); //Here
return 0;
}
```
There is no difference with this other:
```
int main()
{
float a;
scanf("%f", &a);
printf("%.01f\n", a); //Here
return 0;
}
```
Anybody can tell me why?
|
The number behind the period is the precision that specifies the number of digits after the decimal point of a floating-point value. The leading zero has no meanings.
The number before the period is the number that specifies the minimum field width. The leading zero will change the padding character from white space ... |
I am compiling a C code in linux with the following command:
```
gcc -o myprogram myprogram.c
```
If I hadn't given a name to it, I could have simply written the command./a.outto execute it. But now, to execute the program I just write "myprogram" to the command line, but it says "command not found". What can I do ... |
It's possible that the current directory (".") isn't on yourPATH. (You can check this by typingecho $PATH, this is a list of directories delimited with":". "." should be in the list if you want to run something in the current directory.)
If the current directory isn't on yourPATH, you'll need to type./myprogram(or wh... |
```
int main()
{
// system("start cd i:"); //1. changing to I: but again going back to c:
system(" dir i: >>d:\txt.txt"); //2. "Access denied."
getch();
return 0;
}
```
Could someone please explain the output generated by this code in the statements one and two.
And please suggest how to conc... |
```
system(" dir i: >>d:\txt.txt");
```
should be
```
system(" dir i: >>d:\\txt.txt");
```
otherwise you try to create a file "tab" followed by "xt.txt" which is not allowed.
|
Two constants (1+2) share the same case statement. I don´t want to double the code.
What is the right syntax to do this?
```
switch (expression) {
case 0:
[self taskA];
break;
case 1:
[self taskB];
break;
case 2:
[self taskB]
... |
Use :
```
switch (expression) {
case 0:
[self taskA];
break;
case 1:
case 2:
[self taskB];
break;
default:
break;
}
```
Edit 1:
Inswitchwe say a term calledfall-through. Whenever control reaches to a label saycase 0:it falls tillbreakis found. Onbreakcontrol i... |
I need to optimize an expression of the form:
```
(a > b) || (a > c)
```
I tried several optimized forms one of which is as follows:
```
(a * 2) > (b + c)
```
Optimization is not from the compiler's point of view. I would like to reduce the two >s to one.
This is based on the assumption that 1 <= (a, b, c) <= 26
... |
The answer is probably: you do not want to optimize that. Moreover, I doubt that there's any way to write this more efficiently. If you say that a, b and c are values between 1 and 26, you shouldn't be using integers (you don't need that precision) if you wanted to be optimal (in size) anyway.
If a > b, the expressi... |
I'm trying to read a text file line by line and printing the first 17 characters.
```
FILE *devices;
devices = NULL;
devices = fopen("devices.txt", "r");
char deviceaddr[17];
char addr[17];
char line[1024];
while (fgets(line,1024,devices) != NULL)
{
fscanf(devices,"%s", deviceaddr);
printf("%s\n", devicea... |
Thewhileloop is reading a line of text, then thefscanfwill read the next set of text (and possibly overrun that buffer incidentally). It seems as if you should just be printing the desired data inside the loop from the bufferline.
For example, suppose there are three lines of text.
```
00:07:80:4C:0E:EE --> ends... |
I need to write a one liner program that prints out the program's arguments without using any other counter variables except for argc. However:
Problem 1. It prints the arguments in descending order, rather than ascending.
Problem 2. gcc and cl produce different results, so which one is right?
```
while(argc>0) pri... |
If you are looking for a oneliner then this will do without the help ofargc:
```
while(*argv) printf("Argument is %s\n",*argv++);
```
argv[argc]is guaranteed to be NULL.
This is also a problem in your code. When you passargv[argc]with%s, it causes undefined behaviour. Another being the modification ofargcwithout an... |
I'm trying to get my head around structs. It seems ok in theory (e.g. a very concise and clear explanation:http://www.stanford.edu/class/cs110/hws/structs.html)
But then I find this in a code I'm messing with:
```
static struct pci_driver ik220_driver = {
name: DRV_NAME,
id_table: ik220_tbl,
... |
The=initializes a struct of typepci_driver, namedik220_driver, with the specified values for fields.
You are just assigning a variable, but it's a compound type.
|
Is there a way for abashshell program, that takes a command-line argumentx, that will makex(C program) processes start?
.
|
It's fairly simple:
```
#!/bin/bash
$1
```
If you want to pass the rest of the parameters as parameters to the function, do this:
```
$@
```
(i.e.foo.sh echo hiexecutesecho hi)
If you want to steal some parameters and pass others, useshift:
```
param1=$1
shift
echo $@ # contains parameters 2+
```
|
My ThreadData struct:
```
typedef struct threadData {
pthread_t *ths;
} threadData;
```
Where *ths is an array ofpthread_t.
Now, I create a thread that uses as action the following function, which creates a new thread in ths[1]
```
void *rootThread(threadData *d) {
pthread_t *b = (*d).ths;
pthread_crea... |
It looks like (for example) you are not allocating. You have to do something like this:
```
void* Thread(void* theCUstom);
pthread_t* threadHandle = malloc(sizeof(pthread_t));
pthread_mutex_t mutex; // mutex lock
pthread_attr_t attr; // thread attributes
pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&attr);
... |
With the latest Xamarin Studio (relabeled from MonoDevelop 4.0), I cannot open.cprojprojects anymore that worked in MonoDevelop 3.0.4.7.
Thefeature listsays it's not supported on Windows but it also says "Page last modified 09:53, 27 Oct 2010"…
Is there a way to re-add the language binding? Do I need to recompile my... |
C/C++ has never been supported in MonoDevelop on Windows, though reportedly some users were able to get it working with a mingw32 environment. Unfortunately the addin was accidentally included in some of the MonoDevelop 3.0.x releases for Windows.
You could in theory just copy the C/C++ addin dll from a Mac/Linux mac... |
I can't find relevant information about this. For lua, if you want to execute a test.lua file from the main() C function, you calllua_dofile("test.lua").
What is the python equivalent?
|
If you are embedding Python, usePyRun_SimpleFile:
```
FILE *fp = fopen("test.py", "r");
int ret = PyRun_SimpleFile(fp, "test.py");
if(ret < 0) {
/* exception occurred */
}
```
|
quite a simple problem I have here.
I have a little Macro for a global Variable which is defined in my Header like this:
```
extern bool uart_message_received;
#define get_uart_message_rec() uart_message_received;
```
In my C-File I want to access the file like this:
```
bool uart_message_received = 0;
void foo(v... |
```
#define get_uart_message_rec() uart_message_received
// ^ no semicolon
```
Macro replacement will substitute the text as is, including the;in your case. Which will lead to syntax errors in theifcase.
|
I'm setting up i2c for an Application written in C, but I've not been able to find any how-to's for it. I'm running a model-b Raspberry Pi on Debian 6 with LXDE. Can anybody show me how to set up i2c so I can use it in a C Application?
Thanks for any help in advance
|
I've been looking for similar information and I found a couple of i2c tutorials, one inadafruit tutorialsand the other inGuy Carpenter's Gaugette blog. I'm not yet at the stage of actually using it so I can't vouch for their completeness but they seem to be a good start.
Configuring Your Pi for I2CAnalog Gauges Usin... |
Given the following snippet of code:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 15
typedef struct{
int touchdowns;
int interceptions;
int tackles[MAX_SIZE + 1]; //this is the line in question
}stats;
```
The question posed to me was, "Why does this line [denoted above] add 1 to the pos... |
As Armin pointed out, the tokenMAX_SIZEis replaced by the preprocessor. But for clarification, that's not why it works/compiles in the end. The actual requirement for this to compile is, that the array size is aconstant integral expression, which applies to the code in question.
|
I'm really raw with C, and am having trouble with a cast. Here are the lines of my code that I think are relevant:
```
#define BUF 1025
char hostname[BUF];
hostname = *(char *) qpop(&queue);
```
And this is the error that I am getting from the compiler:
error: incompatible types when assigning to type 'char[1025]'... |
Arrays are not first-class types. You cannot assign to an array. You have to copy the memory/elements into the array:
```
memcpy(hostname, qpop(&queue), BUF)
```
|
I need to do some socket programming on Mac OS X but I'm missing the library for it?
This is what happens when I compile:
```
gcc ser.c -o ser -lsocket -lnsl
ser.c: In function ‘main’:
ser.c:41: warning: format ‘%.24s’ expects type ‘char *’, but argument 6 has type ‘int’
ld: library not found for -lsocket
collect2: l... |
You don't need-lsocketon OS X.
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago.
Cannot explain the output of the following program. According to my knowledge the output should be 19, but running it gives me output of 20. I used gcc to compile this progra... |
Your program exploits undefined behavior as you modifyymultiple times between two sequence points (in your case, the end of the statement). If you turn on warnings with-Wall, your compiler is probably even going to warn you about that.
|
```
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) {
(void) state; /* unused */
}
int main(void) {
const UnitTest tests[] = {
unit_test(null_test_success),
};
return ru... |
can you check if you have permission to access the folder /usr/local/lib/
Do a ls -lart /usr/local/lib/libcmocka.so and check for the access permission and check if you have read permission
|
For any c application (let's say apache in this case) I want to return a list of all the methods and the file they are found in. For example, I want would to see something like:
```
int add (int a, int b)..... math.c
int subtract (int a, int b)..... math.c
int Multiply (int a, int b)..... math.c
int foo ()..... foo.c... |
man nm(1)
But, the symbols source files are only available if the debugging information was compiled in (-g).
|
I wish to change this popup for every program calling
```
public class OpenFileDialog : FileChooserDialog {
```
Ideally it would involve removing desktop and changing search etc. I was just hoping somebody knew where the underlying files are?
|
The UI layout for the file chooser dialog is in gtk/gtkfilechooserwidget.c
http://git.gnome.org/browse/gtk+/tree/gtk/gtkfilechooserwidget.c
|
I sat down and readApache's MPM prefork.cand this code is using a variable calledaccept_mutexto prevent multiple threads from callingaccept(). This is strange because as far as I knowaccept()is thread-safe.
Is accept() thread safe? Is this a platform compatibility issue? If so what platform implements a non-thread... |
This is explained in theApache performance tuning documentation, under "accept()Serialization - multiple sockets". In brief, under at least some operating systems, an incoming connection will wakeallApache processes that are waiting for incoming connections inselect()orpoll(), but will cause theaccept()to fail on all ... |
```
$arr['key1'] = "";
$arr['key2'] = "";
echo json_encode($arr);
```
I get{"key1":"","key2":""}. How could I add just a key element without a value? So it would be{"key1","key2"}?
|
Your desired output is notvalid JSON. If you want to create a list, then use:
```
$arr[0] = 'key1';
$arr[1] = 'key2';
echo json_encode($arr);
```
Output:
```
["key1","key2"]
```
|
I'm trying to populate several arrays with the same randomly selected integer but I keep getting the error in the subject line. Here is my code:
```
while(i++ < arraySize){
randInt = (int)random()%100;
originalArray++ = randInt;
ascendingOrderArray++ = randInt;
descendingOrderArray++ =... |
Here, you are trying to assign a value to a number -- to the address of an array. A number is an rvalue, not an lvalue, so it fails.
```
originalArray++ = randInt;
```
Here, you are assigning a value to a memory location -- the address obtained by dereferencing a pointer. This is a lvalue, and so it succeeds:
```
*... |
i can do a recursive function to compute the nth Fibonacci term as follows:
```
int rec (int i)
{
if(i == 1 || i == 2)
return i;
else return rec(i-1)+rec(i-2);
```
}
But i want to use the golden number which is 1.618 to compute the Fibonacci; but my attempt fails, i get wrong numbers:
```
int rec (int i)
{
... |
The golden ratiois an irrational number, so you shouldn't necessarily expect to be able to plug an approximation of it into a formula to get an exact result.
If you want to know how to calculate thenth fibonacci number quickly, here is a page that lists a variety of methods in decreasing order of runtime (but increas... |
I have the following code:
```
void main()
{
// Ask user for input file name
char file_name[100];
printf("File Name?: \n");
fgets(file_name, 100, stdin);
printf("Your input: %s", file_name);
processFile(file_name);
}
```
Which is used to get the value of the input file that needs to be read. Then in ... |
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
http://www.cplusplus.com/reference/cstdio/fgets/
Try with
```
scanf("%s", file_name);
```
|
I'm setting up i2c for an Application written in C, but I've not been able to find any how-to's for it. I'm running a model-b Raspberry Pi on Debian 6 with LXDE. Can anybody show me how to set up i2c so I can use it in a C Application?
Thanks for any help in advance
|
I've been looking for similar information and I found a couple of i2c tutorials, one inadafruit tutorialsand the other inGuy Carpenter's Gaugette blog. I'm not yet at the stage of actually using it so I can't vouch for their completeness but they seem to be a good start.
Configuring Your Pi for I2CAnalog Gauges Usin... |
Given the following snippet of code:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 15
typedef struct{
int touchdowns;
int interceptions;
int tackles[MAX_SIZE + 1]; //this is the line in question
}stats;
```
The question posed to me was, "Why does this line [denoted above] add 1 to the pos... |
As Armin pointed out, the tokenMAX_SIZEis replaced by the preprocessor. But for clarification, that's not why it works/compiles in the end. The actual requirement for this to compile is, that the array size is aconstant integral expression, which applies to the code in question.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
GraphVizis open source, so it's parser is available...
|
My understanding is that when evaluating an assignment statement in C, the value assigned is also returned.However, when I run the code below, this does not seem to be the case. When source_next_level (a GLib queue) is empty, the g_queue_pop_head() function returns NULL, which is then assigned to current_q_node.The !=... |
```
while((current_q_node = g_queue_pop_head(source_next_level)) != NULL);
^^^
```
you have an extra;above.
|
After readingWikipedia pageof Raw image format which is the digital negative of any image.
To be viewed or printed, the output from a camera's image sensor has
to be processed, that is, converted to a photographic rendering of the
scene, and then stored in a standard raster graphics format such as
JPEG. This pr... |
```
ffmpeg -f rawvideo -s 640x480 -pix_fmt yuyv422 -i frame-1.raw frame-1.jpg
```
The options were set based on thev4l2code linked, and the resulting image is the one you would expect to get.
|
Is there a way of adding two memory addresses or multiplying a memory address with a number, in C?
If so, how? For example let's say I have address:
```
void * p = (void *) 0x80000000;
```
And I want to multiply by 2 or add another address, to change current address of the variable!
|
The value0x28ff44is not the "address of the variable"p, it's merely the value of the variable. Since the variable is a pointer, the value is an address. You can certainly modify the valueas ifit were an integer, by converting to/from integer, but why would you ever want to do that?
Here's a silly function to double t... |
I am sure I am going crazy, but consider the following C code:
```
// file1.c
int first;
void f(void)
{ first = 2; }
```
```
// file2.c
#include <stdio.h>
int first;
void f();
int main(void)
{
first = 1;
f();
printf("%d", first);
}
```
These two files, for some reason will compile and link together,... |
It only compiles becausefirstis onlydeclaredtwice, there are not actually two places in memory but only one. Just initialize the one first withint first=4;and the other withint first=5;and your linker will show you the error, e.g. GCC:
```
b.o:b.c:(.data+0x0): multiple definition of `_first'
a.o:a.c:(.data+0x0): firs... |
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
GraphVizis open source, so it's parser is available...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.