question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
This question already has answers here:Pointer arithmetic getting wrong output [duplicate](3 answers)Closed8 years ago.
I see the below code snippet always return 1 instead of 4 Not able to really make out what is wrong
```
#include <stdio.h>
int main(void) {
int a[4] = {1,2,3,4};
int *p = a;
p++;
printf("%ld\n",(long int)(p-a));
return 0;
}
```
|
This is the basics of pointer arithmetic. When you have:
```
int a[4] = {0};
int *p = a;
```
when you dop++- compiler automatically increasespwith four bytes (in case size of integer is four).
Same happens with subtraction if you subtract 1
frompcompiler will automatically subtract four bytes.
But to more precisely answer your question it seems-operator when applied to pointer types
divides result on size of element type to which
pointer points to.
|
This question already has answers here:How to format a function pointer?(6 answers)Closed8 years ago.
I've been trying a way to figure out how to print the address of the function, This is what I came up with
```
#include<stdio.h>
int test(int a, int b)
{
return a+b;
}
int main(void)
{
int (*ptr)(int,int);
ptr=&test;
printf("The address of the function is =%p\n",ptr);
printf("The address of the function pointer is =%p\n",&ptr);
return 0;
}
```
It o/p something like this without any warning and errors
```
address of function is =0x4006fa
address of function pointer is =0x7fffae4f73d8
```
My question whether using%pformat specifier is the correct way to print the address of the function or is there any other way to do so?
|
This is not correct.%pis only for object pointer types (in fact,void *specifically). There is no format specifier for a function pointer.
|
I've written a function for calculating the standard deviation and the result is always '1.#QNAN0', I've tried formatting it in different ways but I can't find a solution. It was working on a different computer yesterday, is there anything I can do?
```
void CalcStandardDeviation(int count, int* nums, double mean, FILE* output){
int k;
double std=0,a;
for (k=0; k<count; k++){
a=nums[k]-mean;
std=std+(a*a);
}
std/=(count);
std=sqrt(std);
fprintf(output,"Standard deviation: %f\r\n",std);
fprintf(output,"\r\n");
}
```
|
ANaNcan only have three origins in your code:
meanis aNaN.Instd/=(count);ifcountis0.Instd=sqrt(std);ifstdat this point is a negative number (seems impossible in your case).
You should debug your code and watchcountandmeanvalues (or print/export it) to find the why.
|
I am trying to do this (is this possible?) with GCC compiler:
Specifiy a function but this function if is not implemented point to a NULL. Example:
```
extern void something(uint some);
```
And if this is unimplemented point to a NULL value.
So it's possible check like this:
```
something != NULL ? something(222) : etc.;
```
I would like solution with trough GCC (this could be solvable with function pointers).
|
This is definitely not portable, but gcc can do this with weak symbols on some platforms. I know this works on Linux and *BSD, but doesn't work on MacOS.
```
$ cat weak.c
#include <stdio.h>
extern int foo(void) __attribute__((__weak__));
int
main(int argc, char **argv)
{
int x = foo ? foo() : 42;
printf("%d\n", x);
return 0;
}
$ cat weak2.c
int
foo(void)
{
return 17;
}
$ cc -o weak weak.c && ./weak
42
$ cc -o weak weak.c weak2.c && ./weak
17
$
```
|
This question already has answers here:Pointer arithmetic getting wrong output [duplicate](3 answers)Closed8 years ago.
I see the below code snippet always return 1 instead of 4 Not able to really make out what is wrong
```
#include <stdio.h>
int main(void) {
int a[4] = {1,2,3,4};
int *p = a;
p++;
printf("%ld\n",(long int)(p-a));
return 0;
}
```
|
This is the basics of pointer arithmetic. When you have:
```
int a[4] = {0};
int *p = a;
```
when you dop++- compiler automatically increasespwith four bytes (in case size of integer is four).
Same happens with subtraction if you subtract 1
frompcompiler will automatically subtract four bytes.
But to more precisely answer your question it seems-operator when applied to pointer types
divides result on size of element type to which
pointer points to.
|
This question already has answers here:How to format a function pointer?(6 answers)Closed8 years ago.
I've been trying a way to figure out how to print the address of the function, This is what I came up with
```
#include<stdio.h>
int test(int a, int b)
{
return a+b;
}
int main(void)
{
int (*ptr)(int,int);
ptr=&test;
printf("The address of the function is =%p\n",ptr);
printf("The address of the function pointer is =%p\n",&ptr);
return 0;
}
```
It o/p something like this without any warning and errors
```
address of function is =0x4006fa
address of function pointer is =0x7fffae4f73d8
```
My question whether using%pformat specifier is the correct way to print the address of the function or is there any other way to do so?
|
This is not correct.%pis only for object pointer types (in fact,void *specifically). There is no format specifier for a function pointer.
|
This question already has answers here:How to format a function pointer?(6 answers)Closed8 years ago.
I've been trying a way to figure out how to print the address of the function, This is what I came up with
```
#include<stdio.h>
int test(int a, int b)
{
return a+b;
}
int main(void)
{
int (*ptr)(int,int);
ptr=&test;
printf("The address of the function is =%p\n",ptr);
printf("The address of the function pointer is =%p\n",&ptr);
return 0;
}
```
It o/p something like this without any warning and errors
```
address of function is =0x4006fa
address of function pointer is =0x7fffae4f73d8
```
My question whether using%pformat specifier is the correct way to print the address of the function or is there any other way to do so?
|
This is not correct.%pis only for object pointer types (in fact,void *specifically). There is no format specifier for a function pointer.
|
I have a binary file that I can execute in C by using the system() command or popen(). when running the binary in the linux filesystem I can use ctrl + z to pause the execution of the program and the fg to resume the execution. Is there any possible way in which I could do this in C?
|
Send a SIGSTOP signal to it. See the signals manpage on how to do it. You can continue the process by sending it a SIGCONT signal. You'll need the process ID for this, so you'll have to use fork+exec instead of plain system.
|
I want to quickly make a static linked list, with as little code as possible, which is very readable and without clutter. How do i accomplish this elegantly?
something like
1 -> 2 -> 3 -> 4 -> NULL
|
```
struct node {int x; struct node *next;};
#define cons(x,next) (struct node[]){{x,next}}
struct node *head = cons(1, cons(2, cons(3, cons(4, NULL))));
```
|
So I read in a line using fgets
```
line = fgets(l, BUFSIZ, stdin);
```
And I from what I understand control+d is EOF so I tried
```
if(line[0] == EOF)
continue;
```
to get back to the top of the loop. But this led to segfaults... Is there another way?
|
Since the machine generatesEOFonCtrl + D, you should be checkingfgets()forNULL, asfgets()is obliged to returnNULLon end of file.
```
line = fgets(l, BUFFSIZ, stdin)
if (line == NULL)
continue;
```
In your code, you are trying to dereference a pointer that'sNULLleading to segfault.
|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed8 years ago.
```
#include <stdio.h>
int main(int argc, char *argv[]){
int *ia[5]={0,1,2,3,4};
iap=ia;
printf("ia[3]:%d\n",3[ia]);
return 0;
```
}
Why is that line working in C?
|
The amazing world of C pointer arithmetic:
ia[3]is computed as*(ia + 3), which is the same as*(3 + ia)or3[ia].
You can also write1[ia+2], or3[ia-+!ia], or even2[1+ia, ia+1]...
None of these should appear in regular code unless you are trying to obfuscate and confuse the casual reader/maintainer/code reviewer.
|
I wrote a program that has you input numbers and output the average. It isn't outputting the exact answer sometimes and I'm not sure why. For example when I input 1, 2, 10, -3, it outputs 2, but it should output 2.50. Also, is there a way to get it to break out of the loop by inputting a letter such as N instead of 0? Here is my code:
```
#include<stdio.h>
int main(){
int nA = 1;
int nSum = 0;
int input = 0;
double dAvg = 0;
int nums = 0;
printf("enter numbers to find the average\n");
printf("enter 0 to quit.\n");
while (nA !=0) {
scanf("%d", &input);
nA = input;
nSum+=nA;
if (nA !=0) {
nums = nums + 1;
}
dAvg = nSum / nums;
}
printf("your average is %lf\n", dAvg);
return 0;
}
```
|
You divide integers, you should do a double division:
```
dAvg = nSum / (double)nums;
```
|
How does the following work?
```
char *str="string";
printf("str is %s\n",str);
```
but the below one gives segmentation fault
```
int *i=3;
printf("int is %d\n",*i);
```
|
A string literal such as"string"is achar[7]stored in a read-only memory location. Array names can decay to pointers to their first element, so it is possible to initialize achar*to such a literal expression.
An integer literal such as3is just an int rvalue which is not stored anywhere. The initializationint* i = 3initializesito point to a memory location with value3. This is unlikely to be a valid location, which is why de-referencingigives you a segmentation violation.
|
Is there a way to compute the result of((UINT_MAX+1)/x)*x-1in C without resorting tounsigned long(wherexisunsigned int)?
(respective "without resorting tounsigned long long" depending on architecture.)
|
It is rather simple arithmetic:
```
((UINT_MAX + 1) / x) * x - 1 =
((UINT_MAX - x + x + 1) / x) * x - 1 =
((UINT_MAX - x + 1) / x + 1) * x - 1 =
(UINT_MAX - x + 1) / x) * x + (x - 1)
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed8 years ago.Improve this question
I have tried to search this question in stackoverflow but did not find it. Feel free to delete this post (please link me too...) if this is posted elsewhere.
I just started programming with C and learnt that
```
while(true)
{
}
```
forms an infinite loop.
To my understanding, this means the function executes with the condition of being "true". But what does this mean? Is the condition always set as "true" in the first place?
May some one please explain!
|
Given:
```
while (a)
{
// b
}
```
Ifais true, then blockbwill execute. This will keep repeating untilais not true.
Ifais replaced with the constant valuetrue, thenawill never be false so the loop will never quit.
|
How to open then man page of mkdir from terminal . I want the manual entry given in the followinglink.
|
Simply give like this.
```
man 2 mkdir
```
From themanpage ofman
1 Executable programs or shell commands2 System calls (functions provided by the kernel)3 Library calls (functions within program libraries)4 Special files (usually found in /dev)5 File formats and conventions eg /etc/passwd6 Games7 Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7)8 System administration commands (usually only for root)9 Kernel routines [Non standard]
You need to open the system call , so you have to mention that as 2. If you give like this,man mkdirthen it will open themanpage ofmkdircommand.
|
This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed8 years ago.
What is the difference between
```
int *p1[M][N]
```
and
```
int (*p2)[M][N]
```
Also if we define another such pointer
```
int (*p3)[M][N][K]
```
what does this represent?
If anyone can explain the differences between the above three, it will be very helpful.
|
int *p1[M][N]is a 2D array of pointers.
int (*p2)[M][N]is a pointer to a 2D array.
int (*p3)[M][N][K]is a pointer to a 3D array.
|
I wrote a program that has you input numbers and output the average. It isn't outputting the exact answer sometimes and I'm not sure why. For example when I input 1, 2, 10, -3, it outputs 2, but it should output 2.50. Also, is there a way to get it to break out of the loop by inputting a letter such as N instead of 0? Here is my code:
```
#include<stdio.h>
int main(){
int nA = 1;
int nSum = 0;
int input = 0;
double dAvg = 0;
int nums = 0;
printf("enter numbers to find the average\n");
printf("enter 0 to quit.\n");
while (nA !=0) {
scanf("%d", &input);
nA = input;
nSum+=nA;
if (nA !=0) {
nums = nums + 1;
}
dAvg = nSum / nums;
}
printf("your average is %lf\n", dAvg);
return 0;
}
```
|
You divide integers, you should do a double division:
```
dAvg = nSum / (double)nums;
```
|
How does the following work?
```
char *str="string";
printf("str is %s\n",str);
```
but the below one gives segmentation fault
```
int *i=3;
printf("int is %d\n",*i);
```
|
A string literal such as"string"is achar[7]stored in a read-only memory location. Array names can decay to pointers to their first element, so it is possible to initialize achar*to such a literal expression.
An integer literal such as3is just an int rvalue which is not stored anywhere. The initializationint* i = 3initializesito point to a memory location with value3. This is unlikely to be a valid location, which is why de-referencingigives you a segmentation violation.
|
Is there a way to compute the result of((UINT_MAX+1)/x)*x-1in C without resorting tounsigned long(wherexisunsigned int)?
(respective "without resorting tounsigned long long" depending on architecture.)
|
It is rather simple arithmetic:
```
((UINT_MAX + 1) / x) * x - 1 =
((UINT_MAX - x + x + 1) / x) * x - 1 =
((UINT_MAX - x + 1) / x + 1) * x - 1 =
(UINT_MAX - x + 1) / x) * x + (x - 1)
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed8 years ago.Improve this question
I have tried to search this question in stackoverflow but did not find it. Feel free to delete this post (please link me too...) if this is posted elsewhere.
I just started programming with C and learnt that
```
while(true)
{
}
```
forms an infinite loop.
To my understanding, this means the function executes with the condition of being "true". But what does this mean? Is the condition always set as "true" in the first place?
May some one please explain!
|
Given:
```
while (a)
{
// b
}
```
Ifais true, then blockbwill execute. This will keep repeating untilais not true.
Ifais replaced with the constant valuetrue, thenawill never be false so the loop will never quit.
|
The following code
```
printf("!%d = %d\n", 0, !0);
printf("!%d = %d\n", 1, !1);
printf("!%d = %d\n", -1, !-1);
```
gives
```
!0 = 1
!1 = 0
!-1 = 0
```
Now, considering that0 = 0x00000000, shouldn't!0 = 0xFFFFFFFF = -1(for signed representation)?
This messes up usingint/longin a bitfield and inverting everything at once.
What is the reason behind this? Is it only to avoid!1to be considered as the booleantrue?
|
The reason is that in standard C, it has been specified that all operators returning a boolean return either 1 or 0. !0 calculates the logical not of 0, i.e. 1. The logical not of 1 would be then 0.
What you want to use is the bitwise NOT operator, i.e.~0which should be0xFFFFFFFF == -1.
|
What is the value of this bool within a struct when we try to access it as n->myBool? I'm interested to know what the "default" value of the bool is after allocating memory for it but not assigning it a true of false value.
```
#include <stdbool.h>
typedef struct node
{
bool myBool;
} Node;
void main()
{
Node* n = malloc(sizeof(Node));
return;
}
```
edit: corrected a typo in code (should be sizeof(Node) not sizeof(node)
|
There is no default value. Space allocated bymallocis uninitialized, and trying to read fromn->myBoolbefore writing a value to it will cause undefined behaviour.
|
If I am using fgets(line, MAXLINE, stdin) function in a loop, should I zero-out line each time before a new iteration? Meaning is I have smth like
```
char *line = calloc(MAXLINE+1, 1);
while (fgets(line, MAXLINE+1, stdin)) {
...
}
```
is it required to reallocate or zero-out the line char string before next call of fgets?
Thank you
|
No.fgetsguarantees zero termination on a successful read. Your loop condition handles the unsuccessful case. For completeness, you should check that the calloc worked though.
|
I have a C# program that needs to read tens to hundreds of millions of records from a flat text file. Is there is a significant performance gain from using a p/invoke call to an unmanaged C/C++ dll that handles all of the file input on a separate thread, or is it an insignificant gain in performance, such that it would be better to just handle my file IO in C#?
|
There is probably not a significant performance gain in using a C/C++ dll. The C# runs in an environment with a quite efficient JIT compiler, so my guess is that the code performance is limited by a hard disk read speed of approximately 100 MB/s. Of course, if you have an SSD, your mileage may vary.
Do note that if one record is e.g. 1000 bytes and you are reading 100 million records, that means 100 gigabytes. Reading it takes 1000 seconds, i.e. more than 15 minutes, just due to the slow speed of the hard disk drive.
|
I'm trying to write structures fromtempGroupFileintoGroupFile.fwrite()returns 1, when writing, but actually no data is written in the fileGroupFile. FunctionprintRec()prints out the structure on the screen.datais a variable of structure. FileGroupFileis empty after these operations.
Code:
```
GWTemp = fopen(tempGroupFile, "rb");
GW = fopen(GroupFile, "wb");
if((GW == NULL) || (GWTemp == NULL))
{
puts("Failed to open file.");
fflush(stdin);
getchar();
return 0;
}
while(fread(&data, sizeof data, 1, GWTemp))
{
if(fwrite(&data, sizeof data, 1, GW))
{
printRec(data);
}
}
```
|
You need to close the file using fclose(GW) after the while loop. This makes sure all buffers are flushed so the file is written.
|
I have the following code (its for an threads library to a class):
```
int tcb_context_create(TCB *thread, void (*start)(void*), void *arg) {
if (!makecontext( &(thread->context), (void (*) (void)) start, 1, arg)) {
errno = EAGAIN;
return -1;
}
return 0;
}
```
But i the compiler keep giving 'error: invalid use of void expression' i have searched everywhere and cant find the corrent way to use the makecontext function.
corrected:
```
int tcb_context_create(TCB *thread, void (*start)(void*), void *arg) {
makecontext( &(thread->context), (void (*) (void)) start, 1, arg);
return 0;
}
```
|
The return type ofmakecontextisvoid. Using!on avoidis not correct.
In addition, you don't have areturnstatement outside theifblock. Since the function's return type isint, you need to add a proper return statement. Otherwise, you will run into undefined behavior.
|
```
@property (nonatomic, strong) UILabel *versionLabel;
```
I am trying write like this:
```
void sipmessagecallback(char* pMsg)
{
printf("pMsg=%s\n", pMsg);
self.versionLabel.text = [NSString stringWithFormat:@"%s", pMsg];
}
```
error : Use of undeclared identifier 'self'
|
C functions aren't methods, so don't have direct access to instance variables of the class that you are in, includingself. You could write a C function which would work like this:
```
void sipmessagecallback(char *pMsg, MyClass *self) {
printf("pMsg=%s\n", pMsg);
self.versionLabel.text = [NSString stringWithFormat:@"%s", pMsg];
}
```
Obviously when you call this you need to passselfto the function.
|
I'm trying to generate some random names but I came across a problem. Here's how I try to choose a letter:
```
char alf[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char letter = alf[rand()%26];
printf("%s\n", alf);
printf("%s\n", letter);
```
It compiles but when I try to run it I get segmentation fault after first printf, and warning:
format '%s'expects argument of type 'char*', but argument 2 has type 'int'
What do I do wrong?
|
letteris a single char and as such, you should format it correctly by using%cinstead of%s.
For more information on printf formats, visit this page:http://www.cplusplus.com/reference/cstdio/printf/?kw=printf
|
I am developing an application with GLUT in C.
I have a basic GLUT canvas where I draw OpenGL stuff.
I have a problem when other X11 windows are overlapping the GLUT canvas and then removed. The GLUT canvas is polluted with the content of the overlapping windows, and there is not refreshing.
How can I manage to refresh the GLUT canvas, when the transcient windows are removed ? Shall I use a system call or something like that to detect this situation, so that I could trigger aglutSwapBuffers()
|
Register a display callback and do all the drawing from there. GLUT will call the display callback whenever a window requires refreshing. Actually you should not draw from anywhere else but the display callback.
|
This line will not compile in Visual C++
```
printf("x=%"PRIszu")\n",
```
Even though the symbol is defined:
```
#define PRIszu "Iu"
```
I get the following error:
Error C3688 invalid literal suffix 'PRIszu'; literal operator or
template 'operator ""PRIszu' not found
So how do I fix this print line to make use of the defined symbol?
|
Perhaps...?
```
printf("x=%" PRIszu "\n", yourVar);
```
I suspect you are using a C++11 compiler, which permitsuser-defined literals. See the answer here:Using macro with string fails on VC 2015
|
I'm programming in C in the last few years and I developed an habit to put the typedef of the struct in the header file, and to leave its definition in the source file, so others can use my files without letting them mess things up.
```
// header file
typedef struct s_example EXAMPLE
```
```
// source file
struct s_example {
// something
};
```
is there something wrong it doing this, should i let others know what i do with my structs?
im just asking this because i see a lot of people showing everything in the header file.
|
The downside of only having the declaration in the header file is that all other source files that do not include the definition of thestructcannot instantiate an instance of thatstruct, but only a pointer to it. This is because, to those other source files, yourstructis anincomplete type. If that is fine for your application, then there is nothing wrong with just a declaration in the header.
|
I have found out that you can run a program from memory in Windows. But is this functionality considered to be a hack (that could one day not work anymore), or does Windows supports this functionality?
This is one thread that talks about this subject:CreateProcess from memory buffer
|
Windows does not support running processes from memory, only from file. Running processes from memory is a hack that relies on undocumented implementation details which are subject to change. In other words, MS could perfectly well change the system design in a future OS release such that existing run from memory code stopped working.
|
So I declared a variable as an integer and initialized it to 0. When I tried printing the value of that variable, it gave me an incredibly high number. int
```
x=0;
printf("%d", &x);
```
This is what I did. Am I doing anything wrong? Thanks in advance.
|
The operator '&' represent the address of that variable. we need, the actual value of that variable use like this...
```
printf("%d",x);
```
|
I was expecting 1 as the output..
```
#include<stdio.h>
int main(){
struct A{
int a:1;
};
struct A bb;
bb.a=1;
printf("%d",bb.a);
return 0;
}
```
|
By doingint a:1, you are settingaas a1 bit signed int. It's represented by 1 bit and assuming two's complement representation in your implementation, it has a range of{0,-1}. So setting1toawill represent a value of-1.
Addendum:
Take notice that byC90standard, a plainintis asigned int; but when it comes to bit-fields, the following holds true:
A bit-field may have type int , unsigned int , or signed int . Whether the high-order bit position of a plainintbit-field is treated as a sign bit is implementation-defined
|
I'm trying to generate some random names but I came across a problem. Here's how I try to choose a letter:
```
char alf[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char letter = alf[rand()%26];
printf("%s\n", alf);
printf("%s\n", letter);
```
It compiles but when I try to run it I get segmentation fault after first printf, and warning:
format '%s'expects argument of type 'char*', but argument 2 has type 'int'
What do I do wrong?
|
letteris a single char and as such, you should format it correctly by using%cinstead of%s.
For more information on printf formats, visit this page:http://www.cplusplus.com/reference/cstdio/printf/?kw=printf
|
I am developing an application with GLUT in C.
I have a basic GLUT canvas where I draw OpenGL stuff.
I have a problem when other X11 windows are overlapping the GLUT canvas and then removed. The GLUT canvas is polluted with the content of the overlapping windows, and there is not refreshing.
How can I manage to refresh the GLUT canvas, when the transcient windows are removed ? Shall I use a system call or something like that to detect this situation, so that I could trigger aglutSwapBuffers()
|
Register a display callback and do all the drawing from there. GLUT will call the display callback whenever a window requires refreshing. Actually you should not draw from anywhere else but the display callback.
|
This line will not compile in Visual C++
```
printf("x=%"PRIszu")\n",
```
Even though the symbol is defined:
```
#define PRIszu "Iu"
```
I get the following error:
Error C3688 invalid literal suffix 'PRIszu'; literal operator or
template 'operator ""PRIszu' not found
So how do I fix this print line to make use of the defined symbol?
|
Perhaps...?
```
printf("x=%" PRIszu "\n", yourVar);
```
I suspect you are using a C++11 compiler, which permitsuser-defined literals. See the answer here:Using macro with string fails on VC 2015
|
I'm programming in C in the last few years and I developed an habit to put the typedef of the struct in the header file, and to leave its definition in the source file, so others can use my files without letting them mess things up.
```
// header file
typedef struct s_example EXAMPLE
```
```
// source file
struct s_example {
// something
};
```
is there something wrong it doing this, should i let others know what i do with my structs?
im just asking this because i see a lot of people showing everything in the header file.
|
The downside of only having the declaration in the header file is that all other source files that do not include the definition of thestructcannot instantiate an instance of thatstruct, but only a pointer to it. This is because, to those other source files, yourstructis anincomplete type. If that is fine for your application, then there is nothing wrong with just a declaration in the header.
|
Whenever I seemallocin someone else's code, it typically usessizeof(short)orsizeof(double)etc. to help define the size of memory to be allocated. Why do they not just replace those expressions with2or8, in those two examples?
|
It makes the code easier to port.
In general there are compiler options which allow you to say how data is to be alligned in a struct. The size of a double may vary between platforms.
By consistantly using the data type, you reduce the occurance of some types of size mismatch errors.
I think it is a better practice to use the variable name instead of the data type for the size of piece.
```
float Pi = 3.14f;
float *pieArray = (float *) malloc(sizeof (Pi) * 1000);
```
Personally I would prefer this method.
```
typedef float Pi;
Pi *piArray = new Pi[1000];
// use it
delete[] piArray;
```
new/deleteshould be preferred overmalloc/freein most cases.
|
In this problem I basically store the inverse of given linked list into another linked list.
Here is the function
```
void copy(struct node** aref,struct node** bref) {
struct node* first = *aref;
struct node* second = *bref;
while(first!=NULL) {
struct node* tmp = (struct node*)malloc(sizeof(struct node));
tmp->data = first->data;
tmp->next = second;
second = tmp;
first = first->next;
}
}
```
This doesn't work. However, if I replace second by *bref it works.
Why is it so?
|
After the while loop add the below code
```
while(first!=NULL)
{
struct node* tmp=(struct node*)malloc(sizeof(struct node));
tmp->data=first->data;
tmp->next=second;
second=tmp;
first=first->next;
}
/* CHANGE HERE */
*bref = second;
```
The reason is that you will have to point "*bref" to the head of the inversed linked list.
|
I am aware that you can run a command after building, but how do I run a command after running the .exe I just built? I saw a tutorial that had a "Post test" option, but I can't find in my project configuration.
|
Since you are using Visual Studio, you can use the MSbuild to create a build script.
https://msdn.microsoft.com/en-us/library/dd393574.aspx
Above the is the documentation. Here you can create a build script so it will compile the project you are working on and then action some separate tests.
https://msdn.microsoft.com/en-us/library/dd393573.aspx
here is a tutorial for the build system. Then you could integreate this with jenkins for more testing and configuration purposes.
http://www.infoq.com/articles/MSBuild-1
This might help as well.
|
while this Code works:
```
char * k = "asd";
char * j = malloc(sizeof(char) * 3);
memmove(j,k,3);
printf("%s",j);
```
while code gives error:
```
char * k = "asd";
char * j = malloc(sizeof(char) * 3);
memmove(k,k+1,3);
printf("%s",k); // output should be "sd"
```
I am thinking wrong? Why it gives an erorr? I'm planning to use it for deleting the multiple whitespaces ("aaa.......bbb"(dots are spaces) -> "aaa bbb")
Thank you.
|
A declaration like
```
char *k = "asd";
```
causes the string literal to be stored in the read-only data segment. (C compilers tend to not warn for this case even though declaring the pointer asconst char *k = "asd"would be safer, for historical reasons.)
If you want the string contents to be modifiable, you will need to use an array instead, like
```
char k[] = "asd";
```
|
I'm getting anchar const too longerror on if statement. I searched this error in Google, they suggested to change the single quotes('') to double quotes ("") i.e charRead != "/0".
After compiling the code I'm getting a different error that"operands of "!=" not same type".
How to resolve this?
```
if( (charRead != '/0') && (isalnum(charRead) || isspace(charRead) || ispunct(charRead)) ) ...
```
|
/0are two chars. This is why you get the error message that it is too big to be stored in a char.\0is one char which has the byte value 0. This one can be stored in a char.
|
I have created a kernel module to have a proc file into which I can read and write data. After usinginsmod mymodule.ko, I am able to write simple text into my proc file as:
```
echo "Hello world" > /proc/myprocfile
```
I am also able to read data from my proc file properly using:
```
cat /proc/myprocfile
```
My question is if I want to write the contents of a command say,ls /procrather than simply echoing a message, then how to send the output of such command tomyprocfile.
|
```
ls /proc > /proc/myprocfile
```
Since this seems to be what you were looking for,here is the wikipedia page on IO redirectionwhich gives more examples and explains some of the other IO redirection operations.
|
Is it possible to makeSetTimer()only send oneWM_TIMERmessage and not send a new message every time the specified time elapses? I am currently usingKillTimer()when I receive aWM_TIMERmessage to stop the timer. Should I continue doing this or there is another way to specify this automatically?
|
SetTimer()creates a periodic timer only. The only way to make it a one-shot timer is to kill the timer on the firstWM_TIMERmessage, as you are already doing.
Otherwise, change your timer logic so you can useCreateWaitableTimer()ortimeSetEvent()instead, both of which can create a true one-shot timer.
|
I am trying to insert data into mysql table through mysql C client, through the step written below.
Thecommandis of the Form : (A variable string generated at run time)
```
INSERT INTO department values('Statistics','Taylor',395051.74)
```
which is correct for MySQL.
```
if (mysql_query(con, command))
{
printf("Done\n");
}
printf("\n%s\n",command);
```
But my database shows no change. No rows get inserted, is there any way the above steps could not work?
|
Note that mysql_query returns a zero if it is successful, and an error code if it's unsucessfulMySQL Docs. I think you might be treating it backward. So I think it's issuing an error you're not catching.
As a guess of what might be wrong, try telling it what columns you're inserting into:
```
INSERT INTO department (`column1`,`column2`,`column3`)
values ('Statistics','Taylor',395051.74)
```
|
When removing an element from a linked list by just moving the pointer. Will free get rid of the memory after the element in the linked list is no longer connected to the list?
|
free will release whatever you point it at. Nothing happens by magic. YOu must call free on the unlinked element
What you hoping for (automatic release of memory when no longer in use) is provided by either reference counted pointers (like shared_ptr in c++) or garbage collection (in C#, Java, javascript,...)
|
So I am basically making a stack which takes in an element(10000) for example and then a priority to later sort it. So "10000 5", 5 is the priority and 10000 the element. I keep inserting the values in till a pop is called, which takes the highest priority element of the top of the stack. For some reason i get am error: "Request for member ‘priority’ in something not a structure or union." From researching the error it seems to be some kind of problem with my referencing? But i don't see where.
|
refAandrefBare pointers to structs, not structs, so you have to use->for referencing fields, not.. Like this:
```
if(refA->priority != refB->priority){
return refB->priority - refA->priority;
} else {
return refB->followNr - refA->followNr;
}
```
Of course you knew this, because earlier in your function, you use->correctly.
|
Anyone else encountered a problem like this?
```
swprintf_s(v, len, L"%ws", var);
MessageBox(NULL, v, NULL' NULL);
```
Message box prints out "%ws" not the contents of var.
Thanks.
|
C++Builder does not support all of the size prefixes that Visual Studio supports (and vice versa). In this case, C++Builder does not support thewprefix for%s, but Visual Studio does.
Visual Studio:
Format Specification Syntax: printf and wprintf Functions
A format specification, which consists of optional and required fields, has the following form:%[flags] [width] [.precision] [{h | l | ll | w | I | I32 | I64}] type
C++Builder:
printf Format Specifiers
Print format specifiers have the following form:% [flags] [width] [.prec] [F|N|h|l|L] type_char
Ifvaris a wide string, you can use%sor%lsin both compilers.
|
This question already has answers here:Assigning strings to arrays of characters(10 answers)Closed8 years ago.
I need to create a structure whose member is an character array like below:
```
struct Person{
char name [100];
};
```
Why the below results in a incompatible types error? And how to fix it?
```
struct Person john;
john.name = "John";
```
what is the difference between the assignment above and bellow, which works well:
```
char str[100] = "this is a string";
```
|
john.name = "John";is an assignment (which is not possible in this case) while
```
char str[100] = "this is a string";
```
is definition with initialization.
john.name = "John";is an invalid statement in C because an array can't be a left operand of=operator. You needstrcpyorstrncpyto copy a string.
|
What is the reason to invoke theprepare handle callbackand thecheck handle callbackin the libuv event loop?
|
The i/o operations happen between those 2, so you may want to perform some operation before blocking for i/o (prepare handles), and after i/o (check handles).
This diagram illustrates how the libuv event loop operates internally:http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop
|
I am trying to upgrade old Visual Studio 6 projects. They use "default" memory-boundary alignment. However, it seems that defaults for Visual Studio 6 and 2013 are not the same.
Anyone know what the old default was?align(1)?
(I need to know this since during the migration we will have a mix of programs. They communicate by serializing C-structs to byte-arrays and passing the array between programs. If the alignments are different that will fail horribly.)
|
According to MSDN "Structure Alignment" documentation:
The default pack size for Windows 3.x is 2, whereas the default for
Win32 is 8.
Be aware that compiler options can be overridden with#pragma pack.
|
When I create atapinterface in Linux withip tuntap add mode taportunctlcommands, then it seems to get a random MAC address. For example:
```
root@fw-test:~# tunctl
Set 'tap5' persistent and owned by uid 0
root@fw-test:~# ip link show dev tap5
11: tap5: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT qlen 500
link/ether 76:df:78:5e:d6:9f brd ff:ff:ff:ff:ff:ff
root@fw-test:~#
```
If I look thetunctl.csource-file, then I quite don't understand where this MAC address is generated. Where and based on which rules the random MAC address is generated for tap interfaces?
|
The functioneth_random_addrdeclared in the kernel headerLinux/include/linux/etherdevice.h
|
I have a C code I need to understand. There is a
```
typedef struct someStruct {
int i;
char c;
someStruct() {
i = 0;
c = 'c';
}
someStruct(char inpChar) {
i = 1;
c = inpChar;
}
} t_someStruct;
```
(The code doesn't really make sense or serve a purpose, I know. I just simplified it.)
So there is this structure and it has two members (int i and char c). The interesting part is that it has basically two constructors, which is a new concept to me.
It works normally, but can we write constructors for structures? I couldn't find anything on Google, maybe I am not searching right.
|
Your code is not valid C code (i.e. validC11) code but it is valid C++ (i.e.C++14) code.
In C++, astructis like aclassexcept that all members are by defaultpublic; see e.g.here.
|
I am constantly receiving:
error: called object is not a function or function pointer
When using ternary operator like that:
puts("\nx: " (0 == 1) ? "y1\n" : "y2\n");
What am I doing wrong?
|
You are attempting to call an object which is neither a function nor a function pointer! In particular, the compiler is seeing the open paren after the string and thinks (as much as a compiler can be said to "think") that you are trying to invoke a function call. You cannot concatenate a string with the ternary operator as you are trying to do. Try:
```
printf("\nx: %s", (0 == 1) ? "y1\n" : "y2\n");
```
|
I've been trying to compile my application using tcmalloc. Therefore I append, as recommended in the usage instructions,-ltcmallocto my compiler flags. After rerunning my application I could not see any performance differences.
How can I check if the calls to malloc have been replaced like the author ofthis questionmentions. I had a look at the compiled assembler code but there were still calls to malloc.
Thanks in advance
|
The simplest way is to check ifheap checkeris working or not, by setting envHEAPCHECK, e.g.HEAPCHECK=normal
Seehttps://gperftools.googlecode.com/git/doc/heap_checker.htmlfor details
|
I am new to codelite and have set up a new g++ Project:
```
#include <stdio.h>
int main(int argc, char **argv)
{
printf("hello world\n");
return 0;
}
```
However, if I click 'Build Active Project' the Build ouput says:
/bin/sh -c ' -j 1 -e -f Makefile'/bin/sh: 1: -j: not found0 errors, 0 warnings
I tried the by default generated Makefile as well as a custom one. What is wrong here that the build operation fails without any error?
I'm using following software:OS:Ubuntu 14.04.01 LTS 64bit, as a virtual machine with Windows 7 as HostIDE:CodeLite 7.0 for Trusty Tahr(=Ubuntu 14.04)Compiler, Tools:I installed g++ and gdb from the command line, in case I forgot something, I listed theoutput ofapt list
|
In 'Settings... -> Build Settings... -> Compiler : Make'
You should have:
```
make -j 1
```
And make sure that make is installed on your machine.
|
What is the reason to invoke theprepare handle callbackand thecheck handle callbackin the libuv event loop?
|
The i/o operations happen between those 2, so you may want to perform some operation before blocking for i/o (prepare handles), and after i/o (check handles).
This diagram illustrates how the libuv event loop operates internally:http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop
|
I am trying to upgrade old Visual Studio 6 projects. They use "default" memory-boundary alignment. However, it seems that defaults for Visual Studio 6 and 2013 are not the same.
Anyone know what the old default was?align(1)?
(I need to know this since during the migration we will have a mix of programs. They communicate by serializing C-structs to byte-arrays and passing the array between programs. If the alignments are different that will fail horribly.)
|
According to MSDN "Structure Alignment" documentation:
The default pack size for Windows 3.x is 2, whereas the default for
Win32 is 8.
Be aware that compiler options can be overridden with#pragma pack.
|
When I create atapinterface in Linux withip tuntap add mode taportunctlcommands, then it seems to get a random MAC address. For example:
```
root@fw-test:~# tunctl
Set 'tap5' persistent and owned by uid 0
root@fw-test:~# ip link show dev tap5
11: tap5: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT qlen 500
link/ether 76:df:78:5e:d6:9f brd ff:ff:ff:ff:ff:ff
root@fw-test:~#
```
If I look thetunctl.csource-file, then I quite don't understand where this MAC address is generated. Where and based on which rules the random MAC address is generated for tap interfaces?
|
The functioneth_random_addrdeclared in the kernel headerLinux/include/linux/etherdevice.h
|
I have a C code I need to understand. There is a
```
typedef struct someStruct {
int i;
char c;
someStruct() {
i = 0;
c = 'c';
}
someStruct(char inpChar) {
i = 1;
c = inpChar;
}
} t_someStruct;
```
(The code doesn't really make sense or serve a purpose, I know. I just simplified it.)
So there is this structure and it has two members (int i and char c). The interesting part is that it has basically two constructors, which is a new concept to me.
It works normally, but can we write constructors for structures? I couldn't find anything on Google, maybe I am not searching right.
|
Your code is not valid C code (i.e. validC11) code but it is valid C++ (i.e.C++14) code.
In C++, astructis like aclassexcept that all members are by defaultpublic; see e.g.here.
|
I am constantly receiving:
error: called object is not a function or function pointer
When using ternary operator like that:
puts("\nx: " (0 == 1) ? "y1\n" : "y2\n");
What am I doing wrong?
|
You are attempting to call an object which is neither a function nor a function pointer! In particular, the compiler is seeing the open paren after the string and thinks (as much as a compiler can be said to "think") that you are trying to invoke a function call. You cannot concatenate a string with the ternary operator as you are trying to do. Try:
```
printf("\nx: %s", (0 == 1) ? "y1\n" : "y2\n");
```
|
I've been trying to compile my application using tcmalloc. Therefore I append, as recommended in the usage instructions,-ltcmallocto my compiler flags. After rerunning my application I could not see any performance differences.
How can I check if the calls to malloc have been replaced like the author ofthis questionmentions. I had a look at the compiled assembler code but there were still calls to malloc.
Thanks in advance
|
The simplest way is to check ifheap checkeris working or not, by setting envHEAPCHECK, e.g.HEAPCHECK=normal
Seehttps://gperftools.googlecode.com/git/doc/heap_checker.htmlfor details
|
I am new to codelite and have set up a new g++ Project:
```
#include <stdio.h>
int main(int argc, char **argv)
{
printf("hello world\n");
return 0;
}
```
However, if I click 'Build Active Project' the Build ouput says:
/bin/sh -c ' -j 1 -e -f Makefile'/bin/sh: 1: -j: not found0 errors, 0 warnings
I tried the by default generated Makefile as well as a custom one. What is wrong here that the build operation fails without any error?
I'm using following software:OS:Ubuntu 14.04.01 LTS 64bit, as a virtual machine with Windows 7 as HostIDE:CodeLite 7.0 for Trusty Tahr(=Ubuntu 14.04)Compiler, Tools:I installed g++ and gdb from the command line, in case I forgot something, I listed theoutput ofapt list
|
In 'Settings... -> Build Settings... -> Compiler : Make'
You should have:
```
make -j 1
```
And make sure that make is installed on your machine.
|
I understand why the first print statement outputs-3 5 8 2. But the second print outputs4 5 8 0. I know that the5and the8are what they are because their respective values remain unchanged, but I don't know howw's value is4andz's value becomes0. I think my understanding of pointers in C might be a little fuzzy.
```
#include <stdio.h>
void mysterious(int *a, int *b, int *c) {
*a = *c;
*b = *b + *a;
*c = *a - *b;
}
int main() {
int w = 5;
int x = 1;
int y = 3;
int z = 2;
mysterious(&x, &y, &w);
printf("%d %d %d %d\n", w, x, y, z);
mysterious(&w, &w, &z);
printf("%d %d %d %d\n", w, x, y, z);
return 0;
}
```
|
If you translate the steps insidemysteriousbased on*a,*b,*cbeingw,w,zrespectively then it comes out to:
```
w = z;
w = w + w;
z = w - w;
```
Stepping through this:zwas2; sowbecomes2, then4; and finallyzbecomes4 - 4which is0.
|
From what I am reading the below code is invalid c99, however I seem to be able to compile it using gcc -std=c99 which, to my knowledge should disable the GNU extension that allows for embedded functions. I cannot seem to figure out why this is the case.
```
int main() {
int e() {
printf("testing");
return 0;
};
e();
return 0;
}
```
|
In order to get warnings on non-conformant code you need to use the-pedanticflag as well, then you will see the following (see it live):
```
warning: ISO C forbids nested functions [-Wpedantic]
int e() {
^
```
To turn this into an error you can use-Werrorto turn warnings into errors or-pedantic-errors.
From the gcc docs onstandards support:
to obtain all the diagnostics required by the standard, you should also specify -pedantic (or -pedantic-errors if you want them to be errors rather than warnings)
|
I am having serious troubles to discover how to add another directory to the default Compiler Directories to be searched for when #including something with angle brackets.
I would like to know how to install whole new libraries too if possible.
Thanks in Advance.
|
As weird as it seems but I am going to answer my own question as I found the answer myself, and I want to share this simple information with other people.
Well it is done like this:
go to Settings.choose Compiler Options.go to the ( Search Directories ) tab.in the ( Compiler ) tab add the Directories you want to be searched automatically.
of course, this applies on a global level, if you want to make it for specific projects than replace the first option with ( build options ) of the project.
That's it, I know it's easy but it took me a while to find it out :)
|
I wrote a program in C that selects random words from a book in txt file format and prints them out one by one using goto statements. When I run the program it takes about 2 to 3 minutes to start running. Could it be that goto statements break locality of reference and drastically decrease performance? Also does jmp in assembly act as goto breaking locality of reference as well?
|
Eventually all flow control results in some form of jump. Most only jump locally so will not break locality. If your program is taking minutes to start, you probably have it doing something like reading that (large?) text file before it does anything else. Try it with a small file and see how it runs then.
|
void f() {int *c=(int*)malloc(10);}void f() {int c[10];}
I think that on in first casec+9will be pointing at elementc[9]in array that is allocated on heap.
And for the second case I think thatc+9will be pointing at the same elementc[9]of the array that is located on stack.
I am new to programming and I am not sure if it is correct answer. thanks for any help.
|
In both cases the behaviour is undefined. In case 1 it points beyond the allocated piece of memory. In case two it points into an array which was allocated on the stack and which has now been popped.
|
I am writing FTP client in C. I am not making any changes to Server program.I want to get specific amount of data from a file on server.Suppose I have a file on server and I want to read last 100 bytes from the file. I don't want to read whole file.
I am able to get whole file usingRETR filenamebut I didn't find any way to read specific amount of bytes.
Is there any way to do this for a standard FTP server?
|
Is there any way to do this for a standard FTP server?
No. You can tell the server the position where it should start with theREST(restart) command, but you cannot tell it how much data it should send. All you can do is close the data channel after you've received the amount of data you want. The FTP server will probably complain about this because it received a RST (writing against a closed socket) but in most cases this should not cause problems.
|
C program is compiled and converted into .dll using cygwin compiler.In python scripting it can be loaded using ctypes and call the functions successfully.But I import that python scripting as libraray into Robot Framework Automation tool,it cant load that .dll file and the test case also failed.
is the cygwin created dll file not be supported by RTF?
Can anyone suggest any other method for that?
|
Given our discussion in the comments. You can't mix and match like this. The format that Cygwin builds a DLL in is different that the format Windows expects a DLL in. You need to build and run all in one environment.
|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed8 years ago.
I am trying to understand why the following piece of code produces the output of7.
```
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int b[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int c = 5;
int *p = a;
printf("%d", (c[b])[p]);
return 0;
}
```
|
This is pure pointer arithmatic. Read more about pointer arithmatichereandhere
Just FYI,a[5]==5[a]==*(5 + a)==*(a + 5).Related Reading.
So, in your code,c[b]==b[c]==b[5]==6.
Then,pbeing equal toa, the base address of theaarray,(c[b])[p]==6[p]==6[a]==a[6]== 7.
|
This question already has answers here:What is an undefined reference/unresolved external symbol error and how do I fix it?(39 answers)Closed4 years ago.
I have a simple program asdemo_use.c
```
#include "libhello.h"
int main(void) {
hello();
return 0;
}
```
libhello.h
```
void hello(void);
```
libhello.c
```
#include <stdio.h>
void hello(void) {
printf("Hello, library world.\n");
}
```
I have used the command in terminal as
```
gcc demo_use.c -o test
```
errorUndefined symbols for architecture x86_64: "_hello",
referenced from: _main in ccZdSQP3.o
ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status
|
You need to compile both the source files together to generate the binary. use
```
gcc demo_use.c libhello.c -o test
```
Otherwise, the definition ofhello()function will be absent. So, at linking time, linker will throwundefined symbolerror.
|
I recently came across the C function with return type asvoidandpackagekeyword added in front of it.
Could anyone please tell me what the meaning ofpackagein the below mentioned C function prototype represents?
```
package void function (void)
```
The macro definition for the package:
```
/* function and variable scope modifiers */
#define package //accessible within package only,used for functions only
```
|
packageis not akeywordin any C standard.
Perhaps it's being#defined by some header file you're not showing us.
Edit:packageis being defined to nothing, so it has exactly zero effect in your program. Maybe if you told us what this header file was, and what this other code is you're trying to use, we might understand why it exists.
|
I've downloaded a program which seems to have an error at the line:
```
for(i=0; i<SIZE_OF_DATA; i--){
```
in main.c, however as a newbie programmer I'm not too sure how to resolve it.
Here's main.c :
```
#include <stdio.h>
#include "util.h"
#define SIZE_OF_DATA 10
int main(void) {
int data[SIZE_OF_DATA];
generateRandomData(data, SIZE_OF_DATA);
int i;
for(i=0; i<SIZE_OF_DATA; i--){
printf("%d: %d\n",i,data[i]);
}
return 0;
}
```
|
Your problem is that you usei--. So the loop will count backwards, i.e. 0, -1, -2, -3 and so on and willalwaysbe smaller thanSIZE OF DATA
The correct code would be
```
for(i=0; i<SIZE_OF_DATA; i++) {
```
Otherwise you'll have a perfect infinite loop :)
|
I recently came across the C function with return type asvoidandpackagekeyword added in front of it.
Could anyone please tell me what the meaning ofpackagein the below mentioned C function prototype represents?
```
package void function (void)
```
The macro definition for the package:
```
/* function and variable scope modifiers */
#define package //accessible within package only,used for functions only
```
|
packageis not akeywordin any C standard.
Perhaps it's being#defined by some header file you're not showing us.
Edit:packageis being defined to nothing, so it has exactly zero effect in your program. Maybe if you told us what this header file was, and what this other code is you're trying to use, we might understand why it exists.
|
I've downloaded a program which seems to have an error at the line:
```
for(i=0; i<SIZE_OF_DATA; i--){
```
in main.c, however as a newbie programmer I'm not too sure how to resolve it.
Here's main.c :
```
#include <stdio.h>
#include "util.h"
#define SIZE_OF_DATA 10
int main(void) {
int data[SIZE_OF_DATA];
generateRandomData(data, SIZE_OF_DATA);
int i;
for(i=0; i<SIZE_OF_DATA; i--){
printf("%d: %d\n",i,data[i]);
}
return 0;
}
```
|
Your problem is that you usei--. So the loop will count backwards, i.e. 0, -1, -2, -3 and so on and willalwaysbe smaller thanSIZE OF DATA
The correct code would be
```
for(i=0; i<SIZE_OF_DATA; i++) {
```
Otherwise you'll have a perfect infinite loop :)
|
I need to use private variable of a class inside a C function.
I was doing something like this
```
class Helper
{
private:
std::string name;
public:
std::getName(){return name;}
friend extern "C" void initializeHelper();
};
```
but this code segment gives errorunqualified-id before string constant
extern "C" {
I am not able to identify what I am doing wrong here.
|
Just forward-declare this function before your class:
```
extern "C" void foo();
```
Then you can use it in friend-declaration:
```
class A {
public:
A() {}
private:
friend void foo();
int a;
};
```
|
I wrote a program
```
include<stdio.h>
struct record
{
int i;
char ch[20];
};
int main()
{
struct record a,*b;
b=&a;
printf("intial pointer is %p and final is %p",b++,b);
return 0;
}
```
The size of a should be 20+4=24 but the output is
```
intial pointer is 0x7fffb0455e40 and final is 0x7fffb0455e58
```
The arithmetic is 18 bytes. Why is the output like this?
|
the arithmetic is 18 bytes. why is the output like this?
Because it is hex.0x7fffb0455e58-0x7fffb0455e40is0x18, or 2410, which is the result that you expect.
Note that your code has undefined behavior, because++bandbare used in the same expression without a sequence point separating them. You also need to cast the value prepared for%ptovoid*, i.e.
```
printf("initial pointer is %p and final is %p", (void*)b, (void*)(b+1));
```
|
I currently have a file that appends new entries to the current file. I would like to fetch the 5 most recent entries. How can I read the last line first in C? I would like to use the fgets command to read in line by line if that's possible.
Thank you for your help!
Edit:
For instance:
Original File:
```
The cat is fast.
Dogs are cool.
I like pie.
```
Desired Output:
```
I like pie.
Dogs are cool.
The cat is fast.
```
|
```
while(fgets(buffer,sizeof(buffer),fp); //go on scanning lines
//Now `buffer` holds the last line of `fp`
```
|
Is there any way to check if there are no pending connection requests to the server?
In my case, I have this code, from C:
```
listen(mysocket, 3);
//while(no pending connections) do this
int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
```
And what I need, is that while there are no pending connections, do something else, instead of getting stuck waiting, by calling accept().
|
You can set a socket in non-blocking mode withfcntl.
```
fcntl(sockfd, F_SETFD, O_NONBLOCK);
```
After that, a call toaccept(sockfd)will either immediately return a newly accepted connection or immediately fail withEWOULDBLOCKwhich you can use to decide to do “something else”.
Another option would be to useselect, maybe with a finite timeout, to gain finer grained control over blocking.
|
I'm supposed to make a program which allows me to do this calculation:
-5+10-20+40-80+160
I've done this so far:
```
const int START = -5, LIMIT = 160;
int somme = 0;
int terme = START;
do {
somme += terme;
terme = terme * 2;
terme = -terme;
} while(terme <= LIMIT);
printf ("equals %d\n\n", somme);
```
But when I run it it shows -215 and of course it's not the correct answer. I'd really appreciate your help.
|
You should use absulute value oftermein condition of your loop, that better have to be PRE-CONDITION while:
```
#include <stdio.h>
#define ABS(X) (X>=0)?(X):(-X)
int main()
{
const int START = -5, LIMIT = 160;
int somme = 0;
int terme = START;
while( ABS(terme) <= LIMIT )
{
somme += terme;
terme = terme * 2;
terme = -terme;
}
printf ("equals %d\n\n", somme);
}
```
|
As the title suggests, what are names ofletoh16,letoh32,betoh16, andbetoh32on Linux? I have foundhtonl, but that doesn't let me choose 16 bit or 32 bit, and it is also only to big endianess.
|
The functions are called the following on Linux:
letoh16is calledle16tohletoh32is calledle32tohbetoh16is calledbe16tohbetoh32is calledbe32toh
|
```
#include<stdio.h>
main()
{
unsigned int a=1,b=2;
printf("%d\n",a-b>=0);
getch();
}
```
Why does this program output "1" ?
|
Compile with warnings enabled, and it will become quite obvious:
```
unsigned.c:5:22: warning: comparison of unsigned expression >= 0 is always true
[-Wtautological-compare]
printf("%d\n",a-b>=0);
~~~^ ~
```
You are subtracting two unsigned integers. Even though the subtraction would equal-1, since they are unsigned it wraps around and you get some very large value. There is no way that an unsigned integer could ever not be greater than or equal to zero.
|
how do I add Arduino libraries to Eclipse Project? I just started playing with Intel Edison and have a Grove developer kit with an LCD that I can't use, because the library is missing.
|
If you go to Project->Properties->C/C++ Build->Settings
You can add a library under the appropriate compiler with -l and you can include directories for headers with -I under C/C++ General->Paths and Symbols under the includes tab.
|
i have a txt file and i want to read from it. I know that i will have to read 20 lines(each line contain 3 number variables,for instance 10 5 6 and so on)
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x,y,z;
int counter = 0;
FILE *fid;
fid = fopen(argv[1],"r");
while(counter<20){
sscanf(fid,"%d%d%d",&x,&y&z);
//some operations made on x,y,z
counter=counter+1;
}
fclose(fid) ;
return 0;
}
```
Unfortunately it is not working.
I want to go through file and usesscanf(fid,"%d%d%d",&x,&y,&z)20 times.
Maybe i should scanf?I would be grateful if somebody could tell me how to make this working.
|
sscanftakes first argument of typeconst char *.You are passing the first argument asFILE *.
You can use:
fscanf
OR
fgetswithsscanf
|
I am new to C++ and I am currently on a project to create a maze that generates out using the DFS algorithm.
I've already successfully managed to generate out a single path, which is for example
```
0 , 0 , 0 , 0, 0
0 , 1 , 1 , S, 0
0 , 1 , 0 , 0, 0
0 , 1 , 0 , 0, 0
0 , D , 0 , 0, 0
0 , 0 , 0 , 0, 0
```
As above,
Source is the initial cell, and 1 is the path that I created based on random neighbor, the thing is, D is "dead end". So, if possible I will like to backtrack to S and start from the other direction. How am I supposed to do that with queue and stack? Can anyone shed some light on this? Thank you so much?
|
It's better if we used basic AI knowledge. Define a set of valid operations for this specific problem, an initial state, a final state and let your program use asearch tree of stateswith the defined operations to find the solution.
|
When I try to use the following;
#include <mysql.h>
I get an error that it is not found in this library.
I've tried to rewrite it as:
#include <mysql/mysql.h>
But I keep getting the same error.
This is problem image
|
Search your filesystem to locate the mysql.h file, then use the -I flag with gcc to tell it to look for include files in this directory. For example, if your mysql.h file is in /usr/include/mysql, your would do:
```
gcc -I/usr/include/mysql ...
```
|
how do I add Arduino libraries to Eclipse Project? I just started playing with Intel Edison and have a Grove developer kit with an LCD that I can't use, because the library is missing.
|
If you go to Project->Properties->C/C++ Build->Settings
You can add a library under the appropriate compiler with -l and you can include directories for headers with -I under C/C++ General->Paths and Symbols under the includes tab.
|
i have a txt file and i want to read from it. I know that i will have to read 20 lines(each line contain 3 number variables,for instance 10 5 6 and so on)
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x,y,z;
int counter = 0;
FILE *fid;
fid = fopen(argv[1],"r");
while(counter<20){
sscanf(fid,"%d%d%d",&x,&y&z);
//some operations made on x,y,z
counter=counter+1;
}
fclose(fid) ;
return 0;
}
```
Unfortunately it is not working.
I want to go through file and usesscanf(fid,"%d%d%d",&x,&y,&z)20 times.
Maybe i should scanf?I would be grateful if somebody could tell me how to make this working.
|
sscanftakes first argument of typeconst char *.You are passing the first argument asFILE *.
You can use:
fscanf
OR
fgetswithsscanf
|
I am new to C++ and I am currently on a project to create a maze that generates out using the DFS algorithm.
I've already successfully managed to generate out a single path, which is for example
```
0 , 0 , 0 , 0, 0
0 , 1 , 1 , S, 0
0 , 1 , 0 , 0, 0
0 , 1 , 0 , 0, 0
0 , D , 0 , 0, 0
0 , 0 , 0 , 0, 0
```
As above,
Source is the initial cell, and 1 is the path that I created based on random neighbor, the thing is, D is "dead end". So, if possible I will like to backtrack to S and start from the other direction. How am I supposed to do that with queue and stack? Can anyone shed some light on this? Thank you so much?
|
It's better if we used basic AI knowledge. Define a set of valid operations for this specific problem, an initial state, a final state and let your program use asearch tree of stateswith the defined operations to find the solution.
|
When I try to use the following;
#include <mysql.h>
I get an error that it is not found in this library.
I've tried to rewrite it as:
#include <mysql/mysql.h>
But I keep getting the same error.
This is problem image
|
Search your filesystem to locate the mysql.h file, then use the -I flag with gcc to tell it to look for include files in this directory. For example, if your mysql.h file is in /usr/include/mysql, your would do:
```
gcc -I/usr/include/mysql ...
```
|
How can I compare a pointer value with a constant memory address?
```
#define ADR 0x2000
unsigned int * po;
if(po<ADR) { };
```
Above code works but it gives a warning "comparison between pointer and integer"
|
The issue is that you are actually doing this:
```
unsigned int * p;
if(p<0x2000) {};
```
Where0x2000is an integer. You can resolve this by using a cast:
```
#define ADR 0x2000
unsigned int * p;
if(p<(unsigned int*)ADR) {};
```
Although a better option might be to actually add the cast into the #define like so:
```
#define ADR ((unsigned int*) 0x2000)
```
As @Alter Mann (cryptically) points out, technically you should actually cast the pointer to an integer. Seethis answerfor details.
|
I need to read a row of symbols from input stream without going to new line after reading each symbol. More precisely, I need to change hitting the "Enter" button to "Space" after reading each new symbol. Is there a way to do it without reading all row to a string and parsing string after that? Any options are acceptable, like scanf, cin.
|
If you can use conio.h then you can do that by reading input in a character array with getch() function. Or if you are in visual studio you can use _getch() function for the same result.
conio.h defines function named getch() and getche() which reads a character then terminates without any enter key. Both these functions have specific meanings while they do the same task. I don't use those any more so I don't remember much. It's upto you if you wanna use them or not...
|
I get the ascii code from a char like this (using C langage):
```
char * text = "5°";
int sizeText = strlen(text);
int i = 0;
float asciiCode;
for(i=0; i<sizeText; i++) {
asciiCode = (GLfloat)text[i];
}
```
It's working well for the ASCII table (chars number 0 to 127) but it's not working with characters from the extended ASCII table.
For example I get -62 from this symbol "°" (it should be 248).
I tried with several encoding like UTF-8 and ISO 8859-1 (I'm using eclipse cdt btw), I got a different ASCII code each time but not the good one :/
Do you have any idea why it is not working? How can I get it work?
Thanks.
|
Because char is from -127 to 127. You can't use extended ASCII table like that.
I suggest you usewcharinstead. Checkwchar.handwctype.hmanual.
|
I have a make project with two real targets, a testsuite and the project's executable.
To build these I want rules something like:
```
testsuite: *.c (except executable.c) *.h
clang ... *.c (except executable.c) -o testsuite
executable: *.c (except testsuite.c) *.h
clang ... *.c (except testsuite.c) -o executable
```
What's the correct syntax for this, if it's possible?
|
Something like this should do what you want.
```
# Explicitly list the sources specific to each target.
EXECUTABLE_SOURCES := executable.c
TESTSUITE_SOURCES := testsuite.c
# Filter out all specific sources from the common wildcard-ed sources.
COMMON_SOURCES := $(filter-out $(TESTSUITE_SOURCES) $(EXECUTABLE_SOURCES),$(wildcard *.c))
testsuite: $(TESTSUITE_SOURCES) $(COMMON_SOURCES)
clang ....
executable: $(EXECUTABLE_SOURCES) $(COMMON_SOURCES)
clang ....
```
|
I am writing a library for producing charts from numerical data, it usescairoand is meant to use code conventions similar to that library.
The problem was: ACfunction appears to return the value I expected, I saw it by means ofprintfjust beforereturn. But the destination variable gets assigned a different value, that is constant, event though the funtion return different values.
I would appreciate you if you are insterested in this question, and you can see the code for the two problematic functions in:
https://github.com/exocode/slope/blob/master/slope/xymetrics.clines 40 and 48.and the are called inhttps://github.com/exocode/slope/blob/master/slope/xydata.cline 65.
|
The problem, seems to be due to the implicit declaration of those functions.
You need to includeslope/xymetrics.hinxydata.cto get the forward declarations for those functionsslope_xymetrics_map_x()andslope_xymetrics_map_y().
|
I want to accept asingle wordand print each character of that singleinput word on a new line.
```
This is my input:Maria
Output:M
a
r
i
a
```
But here condition is I dont want to use Length function and nor any array.
I have done this with length function but i am not getting how to do this without using length function and array too.
Could anybody help me with this ??
|
```
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar()) != '\n' && c !=EOF)
printf("\t%c\n", c);
return 0;
}
```
Output:
```
maria
m
a
r
i
a
```
|
printf stops printing at the first \0 it meets.
Is there a way to force it to continue, for example if my string contains more characters after \0.
|
If you know the length of your string asncharacters, you can output it usingfwrite:
```
if (n && fwrite(str, 1, n, stdout) != n) {
/* Error handling. */
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.