question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Could anyone explain the following syntax of code for structures in C ?
```
struct {
Fn *pmq;
}
service_MQ[] =
{
NULL
#define BUILd_SVC_MQ(name , func) , (Fn*) Func
#include<mqsvctable.h>
};
```
|
There is a structure with only member as a pointer (possibly to a
function)There is an x-header filemqsvctable.hcontaining list of functions
underBUILd_SVC_MQmacro. Something like
```
BUILd_SVC_MQ("clear", clear_screen)
BUILd_SVC_MQ("delete", delete_something)
```
You use thisx-macro headerto prepare an array of your struct.
|
I use a shorthand form for the basic C/C++ types and I want Vim to syntax highlight them. I added
syn keyword cType u8 s8 u16 s16 u32 s32 u64 s64 f32 f64 byte
to my.vimrc, but that doesn't work. What am I doing wrong?
UPDATE 1It has been suggested elsewhere that the problem is when Vim loads the syntax files for C or C++ it overrides my custom syntax in .vimrc. Is that the problem?
UPDATE 2Duskwuff's answer hinted to me to look at Vim'sruntimepathvariable, which I am setting to a shared network drive,S:\vim\_vim, but Vim was still looking for theafterdirectory in~\vimfiles\after, which didn't exist! I addedS:\vim\_vim\afterto theruntimepathvariable and it seems to have fixed the problem of the syntax files not loading.
|
If you want to extend the behavior of an existing vim syntax file (e.g,c.vim), create the file$HOME/.vim/after/syntax/c.vim, and add the extrasyncommand there. It'll be loaded after the mainc.vimsyntax file.
|
I m trying to build json-c with the following configuration:
```
./configure --target=arm-linux-androideabi --host=arm-linux-androideabi \
--build=x86_64-unknown-linux-gnu
```
but I got the following error:
```
cc1: error: command line option '-std=c++11' is valid for C++/ObjC++ but not for C [-Werror]
```
I tried to add--disable-std-c++11and--disable-std-cpp11to the configure but I got always the same problem.
How to fix that?
|
Since there is no one answered me, I will answer to myself
In fact the-std=c++11is injected by the global variableCPPFLAGS.
I just added the following line before the./configureand the-std=c++11disappear
```
export CPPFLAGS=""
```
|
I have astructsimilar to:
```
typedef struct _pair_t{
uint16_t keylen; // 2
uint32_t vallen; // 4
} __attribute__((__packed__)) pair_t;
```
I will be usingmmapto read from a file, so I want to store the numbers as big endian.
Do I need to dohtobe16/betoh16or there is some__attribute__that can do this for me?
|
You need to use htobe16 or htons or similar. There's no way in most compilers to declare a variable as having a different endianness.
I'm aware of a (paid, commercial) compiler which had a switch to turn the entire program into the "opposite" endianness, but that's not quite what you want, and I'm sure you don't want to pay for it.
|
I have a text file containing multiple columns of integers. Sample file is as:
```
Col1 Col2 Col3 Col4
Col1 Col2 Col3 Col4
.
.
.
Col1 Col2 Col3 Col4
```
I am able to read the file line by line. Now if I want to read Col3 from each line read, how would I be able to do this and store it in some int variable?
|
```
int a[5];
```
Use
```
for(i=0;i<5;i++)
fscanf(fp,"%*d %*d %d %*d",&a[i]);
```
Else
Read a line usingfgets()Break the line usingstrtok()using proper delimiter.Useatoi()on the 3rd token to convert it to an integer.Store the value
|
This question already has answers here:C pointers : pointing to an array of fixed size(10 answers)Closed8 years ago.
I Have read some where about this type declaration.
Declaration is:
```
int (*arr)[5];
```
i'm little bit confused with this type declaration.Actually what is the meaning of this declaration and when do we use it.
|
```
int *arr[5]
```
arris array of 5 pointers
```
int (*arr)[5]
```
arris a pointer to an array of 5 integer elements
Check the code below:
```
int a[5] = { 1,2,3,4,5};
int (*arr)[5] = &a;
printf("%d",(*arr)[2]);
```
Now the array element can be accessed like
(*arr)[i]not*arr[i]
|
I compile and run this simple program in console of Linux 3.12, GCC 4.8:
```
#include <stdio.h>
main() {
setvbuf(stdin, NULL, _IONBF, 0);
printf("%c\n", getchar());
}
```
Run the program and press any letter, the program does not exit unless I press enter key.
What is stopping getchar() from functioning? Is there a hidden buffer somewhere?
|
The problem is that yourterminalis buffering the input. Until your terminal sends passes the input that it receives along, your program can't see it -- and by default, it doesn't pass it through until it sees a newline.
If you're running bash on Linux, runningstty -icanonshould change your terminal settings to pass all input through directly without requiring newlines.
|
```
#include<stdio.h>
int main()
{
printf("%c\n",~('C'*-1));
return 0;
}
```
I have tried the above source code and executed without any warnings.
The output isB.
I am excited how the above code is processed and what is the meaning for printf("%c\n",~('C'*-1))
|
In C,'C'is anint, it's a small integer with a value of67(assuming ASCII). You can get each step from:
```
#include<stdio.h>
int main()
{
printf("%d\n", 'C'); //67
printf("%d\n", 'C' * -1); //-67
printf("%d\n", ~('C' * - 1)); //66
printf("%c\n",~('C' * -1)); //B
return 0;
}
```
In 2's complement, the value of~(-67)is66.
|
Can I receive a new virtual address for a page that is already allocated?
If so what are the system calls? (Preferably on linux)
|
Not entirely sure what you are asking here but:
A little research (first answerhere) suggests you can do this in the general case bymmap'ing/proc/PID/mem. Not tried that, but assuming it works it will let you access the memory of the calling process or (subject to security) other processes.There are (to my knowledge) no direct system calls which allow you to create a new virtual address in a process's address space in respect of a page already allocated to adifferentprocess.There are (to my knowledge) no direct system calls which allow you to create a new virtual address in a process's address space in respect of a page already allocated tothe sameprocess, other than as a result ofmmap.In respect of pages allocated withmmapto the same process, you might want to look atmremapandremap_file_pages.
|
I m trying to build json-c with the following configuration:
```
./configure --target=arm-linux-androideabi --host=arm-linux-androideabi \
--build=x86_64-unknown-linux-gnu
```
but I got the following error:
```
cc1: error: command line option '-std=c++11' is valid for C++/ObjC++ but not for C [-Werror]
```
I tried to add--disable-std-c++11and--disable-std-cpp11to the configure but I got always the same problem.
How to fix that?
|
Since there is no one answered me, I will answer to myself
In fact the-std=c++11is injected by the global variableCPPFLAGS.
I just added the following line before the./configureand the-std=c++11disappear
```
export CPPFLAGS=""
```
|
I have astructsimilar to:
```
typedef struct _pair_t{
uint16_t keylen; // 2
uint32_t vallen; // 4
} __attribute__((__packed__)) pair_t;
```
I will be usingmmapto read from a file, so I want to store the numbers as big endian.
Do I need to dohtobe16/betoh16or there is some__attribute__that can do this for me?
|
You need to use htobe16 or htons or similar. There's no way in most compilers to declare a variable as having a different endianness.
I'm aware of a (paid, commercial) compiler which had a switch to turn the entire program into the "opposite" endianness, but that's not quite what you want, and I'm sure you don't want to pay for it.
|
I have a text file containing multiple columns of integers. Sample file is as:
```
Col1 Col2 Col3 Col4
Col1 Col2 Col3 Col4
.
.
.
Col1 Col2 Col3 Col4
```
I am able to read the file line by line. Now if I want to read Col3 from each line read, how would I be able to do this and store it in some int variable?
|
```
int a[5];
```
Use
```
for(i=0;i<5;i++)
fscanf(fp,"%*d %*d %d %*d",&a[i]);
```
Else
Read a line usingfgets()Break the line usingstrtok()using proper delimiter.Useatoi()on the 3rd token to convert it to an integer.Store the value
|
This question already has answers here:C pointers : pointing to an array of fixed size(10 answers)Closed8 years ago.
I Have read some where about this type declaration.
Declaration is:
```
int (*arr)[5];
```
i'm little bit confused with this type declaration.Actually what is the meaning of this declaration and when do we use it.
|
```
int *arr[5]
```
arris array of 5 pointers
```
int (*arr)[5]
```
arris a pointer to an array of 5 integer elements
Check the code below:
```
int a[5] = { 1,2,3,4,5};
int (*arr)[5] = &a;
printf("%d",(*arr)[2]);
```
Now the array element can be accessed like
(*arr)[i]not*arr[i]
|
I compile and run this simple program in console of Linux 3.12, GCC 4.8:
```
#include <stdio.h>
main() {
setvbuf(stdin, NULL, _IONBF, 0);
printf("%c\n", getchar());
}
```
Run the program and press any letter, the program does not exit unless I press enter key.
What is stopping getchar() from functioning? Is there a hidden buffer somewhere?
|
The problem is that yourterminalis buffering the input. Until your terminal sends passes the input that it receives along, your program can't see it -- and by default, it doesn't pass it through until it sees a newline.
If you're running bash on Linux, runningstty -icanonshould change your terminal settings to pass all input through directly without requiring newlines.
|
```
#include<stdio.h>
int main()
{
printf("%c\n",~('C'*-1));
return 0;
}
```
I have tried the above source code and executed without any warnings.
The output isB.
I am excited how the above code is processed and what is the meaning for printf("%c\n",~('C'*-1))
|
In C,'C'is anint, it's a small integer with a value of67(assuming ASCII). You can get each step from:
```
#include<stdio.h>
int main()
{
printf("%d\n", 'C'); //67
printf("%d\n", 'C' * -1); //-67
printf("%d\n", ~('C' * - 1)); //66
printf("%c\n",~('C' * -1)); //B
return 0;
}
```
In 2's complement, the value of~(-67)is66.
|
Can I receive a new virtual address for a page that is already allocated?
If so what are the system calls? (Preferably on linux)
|
Not entirely sure what you are asking here but:
A little research (first answerhere) suggests you can do this in the general case bymmap'ing/proc/PID/mem. Not tried that, but assuming it works it will let you access the memory of the calling process or (subject to security) other processes.There are (to my knowledge) no direct system calls which allow you to create a new virtual address in a process's address space in respect of a page already allocated to adifferentprocess.There are (to my knowledge) no direct system calls which allow you to create a new virtual address in a process's address space in respect of a page already allocated tothe sameprocess, other than as a result ofmmap.In respect of pages allocated withmmapto the same process, you might want to look atmremapandremap_file_pages.
|
I have a text file containing multiple columns of integers. Sample file is as:
```
Col1 Col2 Col3 Col4
Col1 Col2 Col3 Col4
.
.
.
Col1 Col2 Col3 Col4
```
I am able to read the file line by line. Now if I want to read Col3 from each line read, how would I be able to do this and store it in some int variable?
|
```
int a[5];
```
Use
```
for(i=0;i<5;i++)
fscanf(fp,"%*d %*d %d %*d",&a[i]);
```
Else
Read a line usingfgets()Break the line usingstrtok()using proper delimiter.Useatoi()on the 3rd token to convert it to an integer.Store the value
|
This question already has answers here:C pointers : pointing to an array of fixed size(10 answers)Closed8 years ago.
I Have read some where about this type declaration.
Declaration is:
```
int (*arr)[5];
```
i'm little bit confused with this type declaration.Actually what is the meaning of this declaration and when do we use it.
|
```
int *arr[5]
```
arris array of 5 pointers
```
int (*arr)[5]
```
arris a pointer to an array of 5 integer elements
Check the code below:
```
int a[5] = { 1,2,3,4,5};
int (*arr)[5] = &a;
printf("%d",(*arr)[2]);
```
Now the array element can be accessed like
(*arr)[i]not*arr[i]
|
I compile and run this simple program in console of Linux 3.12, GCC 4.8:
```
#include <stdio.h>
main() {
setvbuf(stdin, NULL, _IONBF, 0);
printf("%c\n", getchar());
}
```
Run the program and press any letter, the program does not exit unless I press enter key.
What is stopping getchar() from functioning? Is there a hidden buffer somewhere?
|
The problem is that yourterminalis buffering the input. Until your terminal sends passes the input that it receives along, your program can't see it -- and by default, it doesn't pass it through until it sees a newline.
If you're running bash on Linux, runningstty -icanonshould change your terminal settings to pass all input through directly without requiring newlines.
|
```
#include<stdio.h>
int main()
{
printf("%c\n",~('C'*-1));
return 0;
}
```
I have tried the above source code and executed without any warnings.
The output isB.
I am excited how the above code is processed and what is the meaning for printf("%c\n",~('C'*-1))
|
In C,'C'is anint, it's a small integer with a value of67(assuming ASCII). You can get each step from:
```
#include<stdio.h>
int main()
{
printf("%d\n", 'C'); //67
printf("%d\n", 'C' * -1); //-67
printf("%d\n", ~('C' * - 1)); //66
printf("%c\n",~('C' * -1)); //B
return 0;
}
```
In 2's complement, the value of~(-67)is66.
|
Can I receive a new virtual address for a page that is already allocated?
If so what are the system calls? (Preferably on linux)
|
Not entirely sure what you are asking here but:
A little research (first answerhere) suggests you can do this in the general case bymmap'ing/proc/PID/mem. Not tried that, but assuming it works it will let you access the memory of the calling process or (subject to security) other processes.There are (to my knowledge) no direct system calls which allow you to create a new virtual address in a process's address space in respect of a page already allocated to adifferentprocess.There are (to my knowledge) no direct system calls which allow you to create a new virtual address in a process's address space in respect of a page already allocated tothe sameprocess, other than as a result ofmmap.In respect of pages allocated withmmapto the same process, you might want to look atmremapandremap_file_pages.
|
In C, I have the following function for creating a 2D array.
```
int** createMatrix(int xdim, int ydim){
int** mat = malloc(xdim*sizeof(int*));
int i;
for(i=0; i<xdim; i++){
mat[i] = malloc(ydim*sizeof(int));
}
return mat;
}
```
In the caller function (int main() in this case):
```
int **matA = createMatrix(10, 10);
free(matA);
```
I seemingly have a problem with freeing memory, and I am wondering if this is because the variable "mat" is never freed.
Is it enough to free(matA), as I have done? Or is the issue that I cannot free(mat)?
|
You need to free each of the rows individually first (essentially the reverse process of your create)
```
for(i=0; i < xdim; i++)
free(matA[i]);
free(matA)
```
I would recommend creating afreeMatfunction to do this
|
```
int n = 00000011;
printf("n is: %d\n", n);
```
x is: 9
Shouldn't it be 3 in decimal?
|
00000011is the octal value of9, you can't use the binary representation directly.
```
Octal 011 -> Decimal 9
```
Only, decimal, octal and hexadecimal representations can be specified, for the decimal representation it's straight forward, for the octal representation you prefix the value with a0so09would not be valid, and for hex representation you prefix the value with0x.
note: as commented byabligh, you can use the0bprefix withgccandclangand probably other compilers.
|
I'm trying to create my own data type of string, could anyone tell me what I'm doing wrong with typedef and initialization.
```
#include<stdio.h>
#include<conio.h>
typedef char string[10];
int main(){
string myName;
myName = "Tayyab";
printf("This is %s", myName);
getch();
}
```
|
You cannot assign to an array but you can initialize it:
```
string myName = "Tayyab";
```
|
Is there some gcc portable pragma, so I can do C structnotto be memory aligned?
I want my program to be portable (Linux, FreeBSD, MacOS, Cygwin), but I will stay with gcc.
|
If you don't want to align members of a structure (that is not have any padding between members), withgccyou can usepackedattribute:
```
struct bla
{
int x;
char y;
} __attribute__((__packed__));
```
or usepackpragma:
```
#pragma pack(1)
struct bla
{
int x;
char y;
};
#pragma pack()
```
or compile using-fpack-structoption.
You can also force a minimum alignment for the whole structure withalignedattribute, but as far as I know you cannot disable the alignment of the whole structure withgcc.
|
```
char cwd[256];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
return -1;
}
```
First comes to mind thatgetcwd()could returnNULL, when cwd is not large enough. Is there any other cases?
|
Its documentationstates:
ERRORS
The getcwd() function shall fail if:
[EINVAL]
The size argument is 0.
[ERANGE]
The size argument is greater than 0, but is smaller than the length of the pathname +1.
The getcwd() function may fail if:
[EACCES]
Read or search permission was denied for a component of the pathname.
[ENOMEM]
Insufficient storage space is available.
|
```
long long int a;
scanf("%lld",&a);
printf("n : %lld\n",a);
```
input is9223372036854775808 (LLONG_MAX + 1)
but output is9223372036854775807 (LLONG_MAX)
x64 GNU/Linux and I use GCC compiler
|
Overflow inscanftriggers undefined behavior.
However, many popular implementations ofscanfuse functions fromstrto...group internally to convert strings into actual numbers. (Or, maybe more precisely, they use the same lower-level implementation primitives asstrto...functions.)strto...functions generate max value of the target type on overflow. The side effect of that implementation is what you observe in your test.strtollwas apparently used, which producesLLONG_MAXon positive overflow.
But you should not rely on that, since the behavior is undefined.
|
I have a little basic issue.
In C there is nobytetype so I defined it asunsigned charto hold buffer to system file I need to read and handle.
My C program now needs to work with C# which hasbytebuilt-in type but defined as 'unsigned int'.
Would it cause any issues in casting back and forth between the two systems ?
I think no matter what "word" it is used the underlying storage remains unchanged, right. So doing something like
```
//C#
//byte[] b=new byte[2];
//b[0]=11;
//b[1]=12;
C
byte b[2];//unsigned char
b[0]=(byte)(11);
b[1]=(byte)(12);
```
is indifferent among the two.
|
The C standard has definedint8_tsince C99. Use that for an 8 bit type, oruint8_tfor the unsigned analogue.
Take care when using such a type in a structure though, there's no guarantee that adjacent members will be contiguous in memory. You'll be fine with arrays though.
|
In C, what is the best way to parse a string with multiple delimiters? Say I have a stringA,B,C*Dand want to store these values of A B C D. I'm not sure how to deal with the*elegantly, other than to store the last stringC*Dand then parse that separately with a*delimiter.
If it was justA,B,C,*DI'd use strtok() and ignore the first index of the*Dto get just D, but there is no comma before the*so I don't know that*is coming.
|
You can usemultipledelimiters withstrtok, the second argument is a C string with thelistof delimiters in it, not just a single delimiter:
```
#include <stdio.h>
#include <string.h>
int main (void) {
char myStr[] = "A,B,C*D";
char *pChr = strtok (myStr, ",*");
while (pChr != NULL) {
printf ("%s ", pChr);
pChr = strtok (NULL, ",*");
}
putchar ('\n');
return 0;
}
```
The output of that code is:
```
A B C D
```
|
I try to fill all of my bitmap 1bpp with black, but there are still some pixels left out.
I wrote that code in C:
```
void fillBlack(void* img, int width, int height)
{
int i=0,j=0;
for(i=0;i<width;i++)
{
for(j=0;j<(height);j+=8)
{
*(char*)(img)=(*((char*)(img))^0xff);
img++;
}
}
}
```
where img is the pointer to the offset and all of the arguments are fine, especially width and height.
What am I doing wrong?
|
A bitmap image consists of scanlines with pixels. A scanline is rounded up to the nearest word. Assuming 32 bits per word:
```
fillBlack(void *img, int width, int height)
{
char *bmp = img;
int i,j, scanlinebytes;
scanlinebytes= ((width*1)+31) / 32 * 4; // 1 = bits per pixel
for (i = 0; i < height; i++) {
for(j = 0; j < scanlinebytes; j++) {
*bmp++ = 0;
}
}
}
```
|
i want to parse two different command line argument such that :
file -f something -o something
i found some code on internet and i changed it but i cannot parse both of them.
```
int
main (int argc, char **argv)
{
char *fvalue = NULL;
char *ovalue = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "fo:")) != -1)
switch (c)
{
case 'f':
fvalue = optarg;
break;
case 'o':
ovalue = optarg;
break;
default:
abort ();
}
printf ("fvalue = %s, ovalue = %s\n",
fvalue, ovalue);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
```
|
Your optstring is wrong, it must be
```
while ((c = getopt (argc, argv, "f:o:")) != -1)
```
the colon means that the option requires an argument.
|
I can't seem to change individual characters in a pointer without the program crashing. R1 must be a pointer.
```
char * R1[6];
int main (){
*R1 = "33333";
printf("%s\n", *R1);
R1[3] = '4';
printf("%s", *R1);
return 0;
}
```
|
This should work for you:
```
#include <stdio.h>
char R1[6] = "33333";
int main () {
printf("%s\n", R1);
R1[3] = '4';
printf("%s", R1);
return 0;
}
```
Output:
```
33333
33343
```
EDIT:
With a pointer this should work for you:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char * R1 = malloc(6*sizeof(char));
strcpy(R1, "33333");
printf("%s\n", R1);
R1[3] = '4';
printf("%s", R1);
free(R1);
return 0;
}
```
|
In C++ if you want to input a string and store it in a char array from index 1 you can do something like this:
```
ifstream f("data.in");
char a[100];
f.get(a+1,90);
```
Is there any way you can do this in C (like using fscanf)? Doing this:
```
fscanf(f,"%s",&a+1);
```
or this:
```
fscanf(f,"%s",&(a+1));
```
doesn't work.
|
Yes there is, this way
```
fscanf(f,"%90s",a+1);
```
|
I have an address in hexadecimal, say 007b183c. I want to change its bits.
I have read a bit (no pun intended) about bit shifting and masking but I don't know how to get the address in bit-format so to speak. How do I do this?
|
Assuming you're talking about manipulatingaddressbits, if you have an address such as this:
```
char * p = (char *)0x007b183c;
```
and you want to do some sort of bit manipulation such as, say, rounding up to the next 16 byte aligned address, then you cast to a suitable int type, do the manipulation, and cast back, e.g.
```
char *p_aligned - (char *)(((uint_ptr_t)p + 15) & ~15); // p_aligned = 0x007b1840
```
|
In the following code snippet, I am not able to understand why the error is coming on LineA , but no error in Line B ?
```
//Global
char strA[80] = "A string to be used for demonstration purposes";
int t=60;
int main(void)
{
strA[80] = "I am trying to modify the source"; //Line A, gives error
t=60; //Line B, no errors
}
```
The error is:
2 IntelliSense: a value of type "const char *" cannot be assigned to
an entity of type
"char" c:\users\hu\cplustutorial.cpp 69 12 CPLUStutorial
I am not having the char string asconst, so why this error?
Compiling with MS VS 2010.
|
Thischar strA[80] = "A string to be used for demonstration purposes";initializes your array.
ThisstrA[80]means a single character within that array. How can you store multiple characters in a single char. Usestrcpyto copy the new string.
|
I have a GSList which stores structures. When I save it to binary file using the "wb" option of fopen(), everything is ok except that any text editor easily recognizes the values of text fields from structure and displays them correctly. Is there any way to store structures so that text editors won't be able to recognize the text fields. Thanx
|
You probably just want to encode the data somehow. The easiest would probably be just XORing a the input with a fixed value, then XOR it again when reading. That said, you probably shouldn't be worrying about it… nobody else does (try runningstringson pretty much anything, you'll see).
|
This is my basic C test program.
After I built it, I just entered negative number like-1,-2, etc. in console.
But the result is "oh", not "another number".
I don't know why this happens, because negative numbers should make the 'if' statement true.
```
int main(int argc, char* argv[]){
long int num;
scanf("%d", &num);
if(num ==1 || num < 0){
printf("another number\n");
}else{
printf("oh\n");
}
}
```
|
When you use the%dformat string with scanf, the corresponding argument will be treated asint*. But you have passed along int*. The valuescanfstores will not be the same size as what yourifstatement reads.
Formally, you get undefined behavior. In practice, on most platformsscanfwill write only part of the variable, and the rest will be left with an arbitrary value, with the usual bad effects on future use.
|
Please can anyone help me with this simple program?
It has to be in C programming language c99 standard.
I have a file with many words (more than 500).
On the start the user will write 5 letters.
The program will find every word from the file which contains these letters and print it at the end. The letters don´t have to be in order. For example
Write letters: a,b,c,d,e
Words containing these letters: cbadfjdejhdis, axxxabxxcexd
|
If you only need "at least one of the letters a,b,c,d,e" then you can just callstrtok()
If you need "must contain all letters of a,b,c,d,e" then you would need to iterate, you could use simple loop ofstrchr(input, match[i])where match is "abcde" and i loops from 0 to strlen(match). If strchr returns NULL (no match) you should abort this word (input) and move on.
|
I am trying to swap two strings by using only pointer notation, (no arrays), with
a function that looks like this
```
void str_switch(char *a, char *b)
```
the swapping should work irrespective of the sizes of b and a, and it is not known.
my idea is this:
```
void str_switch(char *a, char *b) {
const char *temp = a;
strcpy(b, temp);
}
```
however, after this, I am not sure how to copy b to a, because b changes, I tried declaring other constant pointers, but once I change b, I can never get the old version.
|
This strays from your question, heading in particular asstrcpyis not used, and follow your comment to Martin James:
```
void str_switch(char **a, char **b) {
char *tmp = *a;
*a = *b;
*b = tmp;
}
```
If you really want to usestrcpyyou'll have to know size of C-strings.
|
I need to put 8 bytes, that I received on an arbitrary machine that my code runs on, in to big endian order. I believe that I can use thehtobe64function for that, but I'm not sure about the portability of that - i.e. the availability ofendian.h- across different machines architectures and operating systems when compiling my code. Is this a safe i.e portable method to use or is it better to use a different approach?
|
Please use the following, portable approach:
```
#include <stdint.h>
void write64be(unsigned char out[8], uint64_t in)
{
out[0] = in >> 56 & 0xff;
out[1] = in >> 48 & 0xff;
out[2] = in >> 40 & 0xff;
out[3] = in >> 32 & 0xff;
out[4] = in >> 24 & 0xff;
out[5] = in >> 16 & 0xff;
out[6] = in >> 8 & 0xff;
out[7] = in >> 0 & 0xff;
}
```
|
So for an assignment I need to use GnuTLS. I have downloaded gnutls by following this guidehttp://www.bauer-power.net/2014/06/how-to-install-gnutls-3123-from-source.html
However, using any of the gnutls functions, similar to how they are used in the official gnutls documentation (http://www.gnutls.org/manual/html_node/Client-examples.html), displays several errors after building. All errors follow this format:
...pathtofile:line#/..undefined reference to 'gnutls_...'
I understand that this might be a linking problem, however I am quite new to this type of environment. What should I do? I have tried to install gnutls again several times.
I am using Ubuntu 14.04, gnutls-3.1.23 and eclipse Luna.
Thanks in advance.
|
You probably have an error on your link line.
Add the flag-lgnutlsto theldcommand (or, if just one C file, the compile line).
|
I am getting aerror: 'else' without a previous ifwhen i'm compiling using gcc on this bit of code:
```
while(fgets(line, 50, fr) != NULL)
{
if(count == 0)
{
fileOpen1 = "pro1.pifz";
}
else
{
fileOpen2 = "pro2.pifz";
}
else
{
fileOpen2 = "pro3.pifz";
}
count++;
printf("%s", line);
printf("%s", fileOpen1);
printf("%s", fileOpen2);
printf("%s", fileOpen3);
}
fclose(fr);
```
The error come when i add the secondelsefunction. Is there a simple way of fixing this error?
Many thanks
|
You may not use two else statements one after another in if statement. The if statement may have only one else statement.
```
else
{
fileOpen2 = "pro2.pifz";
}
else
{
fileOpen2
}
```
You could write for example instead
```
else if ( /* some condition */ )
{
fileOpen2 = "pro2.pifz";
}
else
{
fileOpen2
}
```
|
I met this:
```
static void foo (ui32_t val)
{
if (condition)
{
return;
}
.......
.......
}
```
I don't understand how void function would have return in it, and how return don't return anything?
What is the purpose of return nothing and when do we use it? Thank you guys!
|
It doesn't return anything,return;simply terminates the function.
You use it when you don't want to execute a block depending on some condition and terminate the function.
If there was noreturn;, control returns to the calling function after executing thelaststatement of the function.
|
I'm trying to integrate a terminal on myGtk3app but when i compile the app,
i got that error.
```
(csimpleide:9858): Gtk-ERROR **: GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported
Trace/breakpoint trap (core dumped)
```
because thevtelib usegtk2.
i use this command to compile.
```
gcc -o test test.c `pkg-config --cflags --libs gtk+-3.0 vte`
```
how i can resolve this ??
|
You should define agtk3based VTE library version, on my Ubuntu 14.04 PC, the appropriatevteversion is2.90, so the compilation command would be:
```
gcc -o test test.c `pkg-config --cflags --libs gtk+-3.0 vte-2.90`
```
|
I am using eclipse luna. I have installed CDT into it. For accessing GNU tool chain I have installed latest version of MinGW and given the path of MinGW\bin in environment variables.
But when I have built a test project(written in C), I am getting the following errors:
Program "g++" not found in pathProgram "gcc" not found in path
Info: I am using Windows 8 32 bit OS
|
Hi I just had a similar problem and i tried many of the solutions offered by the members and nothing worked. after a long time i managed to find the main issue it is the ANTI VIRUS! it blocks the gcc.exe and g++.exe
Mke sure you disable every anti virus or make an exception.
(WINDOWS 7 64BIT Eclipse kepler)
|
I have a GSList which stores structures. When I save it to binary file using the "wb" option of fopen(), everything is ok except that any text editor easily recognizes the values of text fields from structure and displays them correctly. Is there any way to store structures so that text editors won't be able to recognize the text fields. Thanx
|
You probably just want to encode the data somehow. The easiest would probably be just XORing a the input with a fixed value, then XOR it again when reading. That said, you probably shouldn't be worrying about it… nobody else does (try runningstringson pretty much anything, you'll see).
|
This is my basic C test program.
After I built it, I just entered negative number like-1,-2, etc. in console.
But the result is "oh", not "another number".
I don't know why this happens, because negative numbers should make the 'if' statement true.
```
int main(int argc, char* argv[]){
long int num;
scanf("%d", &num);
if(num ==1 || num < 0){
printf("another number\n");
}else{
printf("oh\n");
}
}
```
|
When you use the%dformat string with scanf, the corresponding argument will be treated asint*. But you have passed along int*. The valuescanfstores will not be the same size as what yourifstatement reads.
Formally, you get undefined behavior. In practice, on most platformsscanfwill write only part of the variable, and the rest will be left with an arbitrary value, with the usual bad effects on future use.
|
Please can anyone help me with this simple program?
It has to be in C programming language c99 standard.
I have a file with many words (more than 500).
On the start the user will write 5 letters.
The program will find every word from the file which contains these letters and print it at the end. The letters don´t have to be in order. For example
Write letters: a,b,c,d,e
Words containing these letters: cbadfjdejhdis, axxxabxxcexd
|
If you only need "at least one of the letters a,b,c,d,e" then you can just callstrtok()
If you need "must contain all letters of a,b,c,d,e" then you would need to iterate, you could use simple loop ofstrchr(input, match[i])where match is "abcde" and i loops from 0 to strlen(match). If strchr returns NULL (no match) you should abort this word (input) and move on.
|
I am trying to swap two strings by using only pointer notation, (no arrays), with
a function that looks like this
```
void str_switch(char *a, char *b)
```
the swapping should work irrespective of the sizes of b and a, and it is not known.
my idea is this:
```
void str_switch(char *a, char *b) {
const char *temp = a;
strcpy(b, temp);
}
```
however, after this, I am not sure how to copy b to a, because b changes, I tried declaring other constant pointers, but once I change b, I can never get the old version.
|
This strays from your question, heading in particular asstrcpyis not used, and follow your comment to Martin James:
```
void str_switch(char **a, char **b) {
char *tmp = *a;
*a = *b;
*b = tmp;
}
```
If you really want to usestrcpyyou'll have to know size of C-strings.
|
I need to put 8 bytes, that I received on an arbitrary machine that my code runs on, in to big endian order. I believe that I can use thehtobe64function for that, but I'm not sure about the portability of that - i.e. the availability ofendian.h- across different machines architectures and operating systems when compiling my code. Is this a safe i.e portable method to use or is it better to use a different approach?
|
Please use the following, portable approach:
```
#include <stdint.h>
void write64be(unsigned char out[8], uint64_t in)
{
out[0] = in >> 56 & 0xff;
out[1] = in >> 48 & 0xff;
out[2] = in >> 40 & 0xff;
out[3] = in >> 32 & 0xff;
out[4] = in >> 24 & 0xff;
out[5] = in >> 16 & 0xff;
out[6] = in >> 8 & 0xff;
out[7] = in >> 0 & 0xff;
}
```
|
So for an assignment I need to use GnuTLS. I have downloaded gnutls by following this guidehttp://www.bauer-power.net/2014/06/how-to-install-gnutls-3123-from-source.html
However, using any of the gnutls functions, similar to how they are used in the official gnutls documentation (http://www.gnutls.org/manual/html_node/Client-examples.html), displays several errors after building. All errors follow this format:
...pathtofile:line#/..undefined reference to 'gnutls_...'
I understand that this might be a linking problem, however I am quite new to this type of environment. What should I do? I have tried to install gnutls again several times.
I am using Ubuntu 14.04, gnutls-3.1.23 and eclipse Luna.
Thanks in advance.
|
You probably have an error on your link line.
Add the flag-lgnutlsto theldcommand (or, if just one C file, the compile line).
|
I am getting aerror: 'else' without a previous ifwhen i'm compiling using gcc on this bit of code:
```
while(fgets(line, 50, fr) != NULL)
{
if(count == 0)
{
fileOpen1 = "pro1.pifz";
}
else
{
fileOpen2 = "pro2.pifz";
}
else
{
fileOpen2 = "pro3.pifz";
}
count++;
printf("%s", line);
printf("%s", fileOpen1);
printf("%s", fileOpen2);
printf("%s", fileOpen3);
}
fclose(fr);
```
The error come when i add the secondelsefunction. Is there a simple way of fixing this error?
Many thanks
|
You may not use two else statements one after another in if statement. The if statement may have only one else statement.
```
else
{
fileOpen2 = "pro2.pifz";
}
else
{
fileOpen2
}
```
You could write for example instead
```
else if ( /* some condition */ )
{
fileOpen2 = "pro2.pifz";
}
else
{
fileOpen2
}
```
|
I met this:
```
static void foo (ui32_t val)
{
if (condition)
{
return;
}
.......
.......
}
```
I don't understand how void function would have return in it, and how return don't return anything?
What is the purpose of return nothing and when do we use it? Thank you guys!
|
It doesn't return anything,return;simply terminates the function.
You use it when you don't want to execute a block depending on some condition and terminate the function.
If there was noreturn;, control returns to the calling function after executing thelaststatement of the function.
|
I'm trying to integrate a terminal on myGtk3app but when i compile the app,
i got that error.
```
(csimpleide:9858): Gtk-ERROR **: GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported
Trace/breakpoint trap (core dumped)
```
because thevtelib usegtk2.
i use this command to compile.
```
gcc -o test test.c `pkg-config --cflags --libs gtk+-3.0 vte`
```
how i can resolve this ??
|
You should define agtk3based VTE library version, on my Ubuntu 14.04 PC, the appropriatevteversion is2.90, so the compilation command would be:
```
gcc -o test test.c `pkg-config --cflags --libs gtk+-3.0 vte-2.90`
```
|
I am using eclipse luna. I have installed CDT into it. For accessing GNU tool chain I have installed latest version of MinGW and given the path of MinGW\bin in environment variables.
But when I have built a test project(written in C), I am getting the following errors:
Program "g++" not found in pathProgram "gcc" not found in path
Info: I am using Windows 8 32 bit OS
|
Hi I just had a similar problem and i tried many of the solutions offered by the members and nothing worked. after a long time i managed to find the main issue it is the ANTI VIRUS! it blocks the gcc.exe and g++.exe
Mke sure you disable every anti virus or make an exception.
(WINDOWS 7 64BIT Eclipse kepler)
|
I try to input a string inchar ch[20], I want when I press space key then it will stop to take input into the variable. But thegets()function takes input as long as I don't press enter key. How can I take input as long as I don't press space character?
|
gets()is no more a standard and it might lead to buffer overflow so you should usefgets()in-order to read till end of line . In order to read char by char until you encounter space you can usegetc()as shown below.
Check the below code:
```
#include <stdio.h>
int main(void) {
int i=0;
char ch;
char a[20];
while(((ch = getc(stdin)) != ' ') && i<19)
a[i++] = ch;
a[i] = '\0';
printf("%s\n",a);
return 0;
}
```
|
How can I reverse a number without using arrays or any arithmetic operations i.e from 85 to 58. Using bitwise operators might be the solution. But what series of operations are needed to reverse a number. I've tried shifting and complementing.
And is there a way to get binary or hexadecimal as input and perform operations on it. Rather than getting int and typecast at printf?
|
there are alot of api's to do that // but the easiest way use a stack :D or convert it to string then it will be such as array you can inverse it easilly
|
```
#include<stdio.h>
#include<stdlib.h>
void main()
{
int c = 1;
printf("%d" + 0 , c);
printf("%d" + 1 , c);
printf("%d" + 2 , c);
printf("%d" + 3 , c);
}
```
The output of the following program is:
1d
Can anyone please explain why?
|
when coding"literalstring" + 3you get the 4th(since 4 = 3+1 and arrays index start at 0) and following bytes of the"literalstring"(which is terminated by a zero-byte) so you get"eralstring", hence
"%d" + 0is"%d""%d" + 1is"d", notice thatprintf("d", 1)ignoresthe argument 1!"%d" + 2is""an empty string"%d" + 3points to an undefined location and dereferencing it (likeprintfprobably does) isundefined behavior...
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question
First-off, sorry for the vague title. Here's my problem:
Letn > 0be a natural number. Determine the positive numberksuch that2^i + k = nfor the largest possiblei.
How would I do this in C elegantly?
|
```
int i = 0; j = 1, k, n = (your value);
if ( n > 0 )
{
while ( 2 * j < n)
{
j = 2 * j;
i++;
}
k = n - j;
}
// replace '<' with '<=' if k = 0 is desired where n is a pure power of 2
```
(nb: there is no exponentiation operator in Standard C)
|
I want to put pointerchar* nameintochar* path. I'm getting value ofnamefrom scanf. Is it possible?
```
char* path = "/home/user/Desktop/name.jpg";
```
I know it's wrong but i want this to work in that way
|
I assume that you mean that you have:
```
char *name = "fred";
char *format = "/home/user/Desktop/name.jpg";
```
And you'd like to take that and thendo somethingsuch that you have as a result:
```
char *result = "/home/user/Desktop/fred.jpg";
```
To do this, you need to allocate some memory (or allocate enough somewhere else), and then usesprintf()orsnprintf():
```
char *name = "fred";
char *format = "/home/user/Desktop/%s.jpg";
char *result = malloc(strlen(format) - 2 + strlen(name) + 1);
sprintf(result, format, name);
printf("%s\n", result); // Output is "/home/user/Desktop/fred.jpg"
```
|
I have two functions to create arrays.
```
double *Array1D (int nx, int dsize) {
double *v;
v = calloc(nx, dsize);
return v;
}
double **Array2D (int ny, int nx, int dsize) {
double **v; int j;
for (j = 0; j < ny; j++)
v[j] = Array1D(nx, dsize);
return v;
}
int i, j;
pn = Array2D (ny, nx, sizeof(double));
for (j = 0; j < ny; j++)
for (i = 0; i < nx; i++)
pn[j][i] = 1.0 + (i + j * nx) * 1.0;
for (i = 0; i < ny; i++)
free(pn[i]);
free(pn);
```
The array elements get initialized properly, but freeing them creates a segmentation fault.
Error:
```
*** glibc detected *** ./array_test: free(): invalid pointer: 0x00007fff00d42a4f ***
Segmentation fault (core dumped)
```
|
```
double **Array2D (int ny, int nx, int dsize)
{
double **v; int j;
for (j=0; j<ny; j++) v[j] = Array1D(nx, dsize);
```
vobject is never initialized in your function.
|
```
#include<stdio.h>
#include<stdlib.h>
void main()
{
int c = 1;
printf("%d" + 0 , c);
printf("%d" + 1 , c);
printf("%d" + 2 , c);
printf("%d" + 3 , c);
}
```
The output of the following program is:
1d
Can anyone please explain why?
|
when coding"literalstring" + 3you get the 4th(since 4 = 3+1 and arrays index start at 0) and following bytes of the"literalstring"(which is terminated by a zero-byte) so you get"eralstring", hence
"%d" + 0is"%d""%d" + 1is"d", notice thatprintf("d", 1)ignoresthe argument 1!"%d" + 2is""an empty string"%d" + 3points to an undefined location and dereferencing it (likeprintfprobably does) isundefined behavior...
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question
First-off, sorry for the vague title. Here's my problem:
Letn > 0be a natural number. Determine the positive numberksuch that2^i + k = nfor the largest possiblei.
How would I do this in C elegantly?
|
```
int i = 0; j = 1, k, n = (your value);
if ( n > 0 )
{
while ( 2 * j < n)
{
j = 2 * j;
i++;
}
k = n - j;
}
// replace '<' with '<=' if k = 0 is desired where n is a pure power of 2
```
(nb: there is no exponentiation operator in Standard C)
|
I want to put pointerchar* nameintochar* path. I'm getting value ofnamefrom scanf. Is it possible?
```
char* path = "/home/user/Desktop/name.jpg";
```
I know it's wrong but i want this to work in that way
|
I assume that you mean that you have:
```
char *name = "fred";
char *format = "/home/user/Desktop/name.jpg";
```
And you'd like to take that and thendo somethingsuch that you have as a result:
```
char *result = "/home/user/Desktop/fred.jpg";
```
To do this, you need to allocate some memory (or allocate enough somewhere else), and then usesprintf()orsnprintf():
```
char *name = "fred";
char *format = "/home/user/Desktop/%s.jpg";
char *result = malloc(strlen(format) - 2 + strlen(name) + 1);
sprintf(result, format, name);
printf("%s\n", result); // Output is "/home/user/Desktop/fred.jpg"
```
|
I have two functions to create arrays.
```
double *Array1D (int nx, int dsize) {
double *v;
v = calloc(nx, dsize);
return v;
}
double **Array2D (int ny, int nx, int dsize) {
double **v; int j;
for (j = 0; j < ny; j++)
v[j] = Array1D(nx, dsize);
return v;
}
int i, j;
pn = Array2D (ny, nx, sizeof(double));
for (j = 0; j < ny; j++)
for (i = 0; i < nx; i++)
pn[j][i] = 1.0 + (i + j * nx) * 1.0;
for (i = 0; i < ny; i++)
free(pn[i]);
free(pn);
```
The array elements get initialized properly, but freeing them creates a segmentation fault.
Error:
```
*** glibc detected *** ./array_test: free(): invalid pointer: 0x00007fff00d42a4f ***
Segmentation fault (core dumped)
```
|
```
double **Array2D (int ny, int nx, int dsize)
{
double **v; int j;
for (j=0; j<ny; j++) v[j] = Array1D(nx, dsize);
```
vobject is never initialized in your function.
|
When I pass these arguments to the VC++ linker:
```
link D:\1.obj /OUT:D:\1.exe /SUBSYSTEM:CONSOLE /ENTRY:main
```
The linker actually treats the string "main" as if it were "_main" (if I were to enter /ENTRY:hello it will treat it as /ENTRY:_hello, etc.).
Why is that? and can I make the linker not add an underscore to the entry point?
|
This is due toname mangling(more detailed info on VC name mangling here). And I don't think you want to remove it.
|
I have a code like this:
```
int quotient = 100/*ptr;
```
where ptr is a pointer to interger.
But it's taking/*as the comment.How can I make the meaning of divide by pointer dereference value? What extra special character I have to put to have this meaning?
|
This happens because language tried to reuse the tokens. (*in this case)
Solution is to put a space between/and*to beat maximal munch.
```
int quotient = 100 / *ptr;
```
Another way is to add a parenthesis or use another local variable:
```
int quotient = 100/(*ptr);
```
|
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 a string format example :
1)
```
DATASET:students name:STRING sid:STRING graduated:BOOLEAN year:INTEGER gpa:INTEGER
```
2)
```
typedef struct param{
char *Name;
char *Value;
struct param *next;
}params;
```
we must get from string all fieldname:value and add to linked list or array of struct.
|
Read the whole line usingfgets()Break the line usingstrtok()using space as deleimter and store the respective strings in an array.Then break the contents of an array one by one usingstrtok()using:as delimter.
Please note thatstrtok()will modify your passed string.Now you can copy the data from the the array to your respective structure fields
|
This question already has answers here:Appending values to c array(4 answers)Closed8 years ago.
I am just wondering whether it is possible for me to add/append elements to a list in C, and I would go around doing it?
e.g.
```
int numbers[6] = {5,3,5,1,3,6}
```
Let's say I wanted to add another number to the array 'numbers', how would I do that?
|
Well, the original array needs to bemalloc'ed, rather than on the stack. Then you can userealloc:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * numbers = malloc(6*sizeof(int));
for(int ii = 0; ii < 6; ++ii) {
numbers[ii] = 5;
}
numbers = realloc(numbers, 7*sizeof(*numbers));
if(!numbers) {
printf("Memory allocation failed, sorry dude!\n");
exit(1);
}
numbers[6] = 7;
for(int ii = 0; ii< 7; ++ii) {
printf("%d\n", numbers[ii]);
}
free(numbers);
}
```
|
I have the following struct,
```
typedef struct arrays {
int *array;
int max;
int min;
} array;
```
Where*arraypoints to an dynamically allocated array,maxandminholds the maximum and minimum numbers in the array.
I need to share an instance (can I use the word 'instance' in C?) of this struct between two processes, am I supposed to useshm_open()first for allocating the array pointed by*arrayand second for allocating the struct itself, or is there a better way achieving the same result?
|
I don't know if it'sbetterbut you can do it with only a single allocation: Allocate one large buffer to include both the structureandthe array, then makearraypoint to the buffer + the size of the structure.
|
It's K&R-C and here is the code:http://v6shell.org/history/if.c
Look at the main-Method. There is this line "if(exp())".
But the function exp is declared as: exp(s). So it needs an argument.
Why does this work? And why would you do this?
|
Ultimately, it is a bug in the Unix V6 shell support command,if.
The code for the function is:
```
exp(s) {
int p1;
p1 = e1();
if (eq(nxtarg(), "-o")) return(p1 | exp());
ap--;
return(p1);
}
```
The function parameters, implicitly of typeint(as is the function iteself), is actually unused in the function, so the bug is the presence ofs, not the absence of an argument in the calls toexp(). All the calls with zero actual arguments are correct.
|
I am trying to avoid using sem_wait, and have something like:
"While waiting for semaphore, do something".
So then I found out about sem_getvalue which is supposed to return 0 in case of success.
So I initiate the semaphore with:
```
sem_init(&sem1, 0, 0);
```
And instead of
```
sem_wait(&sem1);
```
I need something like:
```
while(sem_getvalue(&sem1, 2) < 0){
printf("do this\n");
}
```
I have no problems with sem_wait, everything seems to function properly.
But with the second, I am getting Segmentation fault error during execution.
Any help is greatly appreciated, thanks!
|
You shouldn't usesem_getvaluefor this since you are losing atomicity. Usesem_trywaitfor the task
```
for (;;) {
if (sem_trywait(&sem1)) {
if (errno != EAGAIN) {
/* handle error */
abort();
}
errno = 0;
printf("do this\n");
} else {
break;
}
}
```
|
I just started to study about C Programing.
I want to write a program to solve this mathematical task (1/2*r2*3.14)
This is the code that I wrote:
```
#include <stdio.h>
#include <conio.h>
main()
{
int r=5;
float sum;
sum = 1/2*r^2*3.14;
printf("%f", sum);
getch();
}
```
but there is an error and I don`t know what the mistake is.
First I thought that there is something wrong about the number 3.14, but when I changed it to 3 the program ran but the answer was 6.0000 but it should be 37.5
|
In C there is no operator for power calculation.^is used as XOR operator. You need to use library functionpowfor power calculations.
```
sum = 1.0 / 2 * pow(r,2) * 3.14;
```
Note that I changed1/2to1.0/2because1/2will always give0and the result you will get is0.
|
This question already has answers here:two strings separated by blank being concatenated automatically(3 answers)Closed8 years ago.
I've doubt regarding the basics of C language while using printf statement.
well this is how my code looks like.
```
#include<stdio.h>
int main(){
printf("%s %s",("senthil""kumar"),("hello""world"),("stack""overflow");
return 0;}
```
I've got an output like,
senthilkumar helloworld
but i don't how does this code works.
could u pls help me to figure out how it works...
thanx in advance.
|
Two consecutive string literals are merged by the compiler.
I.e. the following examples are equivalent:
```
// 1:
"foo" "bar"
// 2:
"foobar"
// 3:
#define FOO "foo"
FOO "bar"
```
You do not need all those inner parentheses (also, there's a)missing at the end).
|
I need to kill a mac process but before that do I need to check, if it actually exists or not?
I have tried to use C++ methodsystem("killall process_name");to kill process by name.
But I think I should also check the process is actually running or not. Could anyone please let me know, how it can be done?
|
```
BOOL processIsRunning = system("ps -Ac | grep 'AProcessName' > /dev/null") == 0;
```
Or, if you want to check for a string in particular:
```
BOOL processIsRunning = system("ps -ef | grep 'AUniqueString' | grep -iv grep > /dev/null") == 0;
```
|
We have an array:int p[100].Whyp[i]is equivalent to*(p+i)and not*(p+i*sizeof(int))?
|
Why p[i] is equivalent to*(p+i)and not*(p+i*sizeof(int))?
Because*(p+i)is also the same as*((int *) ((char *) p + i * sizeof (int))). When you add an integerito a pointer, the pointer is moveditimes the size of the pointed object.
|
I have an application I would like to inspect and I don't have the sources to rebuild it and create the Symbol Table likehere(gcc -g my_app.c).
When I call theinfo localsI get the following error "No symbol table info available"
When I'm working with Eclipse even when I don't have the sources of the library it can resolve the arguments of the current function intoarg0, arg1... argNand if I remember correctly also the members of objects.
Is there any way to generate a custom/generic/default symbol table, one that would satisfy GDB and would allow me to see the values of local variables and arguments?
|
the answer is No.
The local symbols are only useful for debugging so there is no alternative. If they have been discarded they are gone.
|
It's K&R-C and here is the code:http://v6shell.org/history/if.c
Look at the main-Method. There is this line "if(exp())".
But the function exp is declared as: exp(s). So it needs an argument.
Why does this work? And why would you do this?
|
Ultimately, it is a bug in the Unix V6 shell support command,if.
The code for the function is:
```
exp(s) {
int p1;
p1 = e1();
if (eq(nxtarg(), "-o")) return(p1 | exp());
ap--;
return(p1);
}
```
The function parameters, implicitly of typeint(as is the function iteself), is actually unused in the function, so the bug is the presence ofs, not the absence of an argument in the calls toexp(). All the calls with zero actual arguments are correct.
|
I am trying to avoid using sem_wait, and have something like:
"While waiting for semaphore, do something".
So then I found out about sem_getvalue which is supposed to return 0 in case of success.
So I initiate the semaphore with:
```
sem_init(&sem1, 0, 0);
```
And instead of
```
sem_wait(&sem1);
```
I need something like:
```
while(sem_getvalue(&sem1, 2) < 0){
printf("do this\n");
}
```
I have no problems with sem_wait, everything seems to function properly.
But with the second, I am getting Segmentation fault error during execution.
Any help is greatly appreciated, thanks!
|
You shouldn't usesem_getvaluefor this since you are losing atomicity. Usesem_trywaitfor the task
```
for (;;) {
if (sem_trywait(&sem1)) {
if (errno != EAGAIN) {
/* handle error */
abort();
}
errno = 0;
printf("do this\n");
} else {
break;
}
}
```
|
I just started to study about C Programing.
I want to write a program to solve this mathematical task (1/2*r2*3.14)
This is the code that I wrote:
```
#include <stdio.h>
#include <conio.h>
main()
{
int r=5;
float sum;
sum = 1/2*r^2*3.14;
printf("%f", sum);
getch();
}
```
but there is an error and I don`t know what the mistake is.
First I thought that there is something wrong about the number 3.14, but when I changed it to 3 the program ran but the answer was 6.0000 but it should be 37.5
|
In C there is no operator for power calculation.^is used as XOR operator. You need to use library functionpowfor power calculations.
```
sum = 1.0 / 2 * pow(r,2) * 3.14;
```
Note that I changed1/2to1.0/2because1/2will always give0and the result you will get is0.
|
This question already has answers here:two strings separated by blank being concatenated automatically(3 answers)Closed8 years ago.
I've doubt regarding the basics of C language while using printf statement.
well this is how my code looks like.
```
#include<stdio.h>
int main(){
printf("%s %s",("senthil""kumar"),("hello""world"),("stack""overflow");
return 0;}
```
I've got an output like,
senthilkumar helloworld
but i don't how does this code works.
could u pls help me to figure out how it works...
thanx in advance.
|
Two consecutive string literals are merged by the compiler.
I.e. the following examples are equivalent:
```
// 1:
"foo" "bar"
// 2:
"foobar"
// 3:
#define FOO "foo"
FOO "bar"
```
You do not need all those inner parentheses (also, there's a)missing at the end).
|
I need to kill a mac process but before that do I need to check, if it actually exists or not?
I have tried to use C++ methodsystem("killall process_name");to kill process by name.
But I think I should also check the process is actually running or not. Could anyone please let me know, how it can be done?
|
```
BOOL processIsRunning = system("ps -Ac | grep 'AProcessName' > /dev/null") == 0;
```
Or, if you want to check for a string in particular:
```
BOOL processIsRunning = system("ps -ef | grep 'AUniqueString' | grep -iv grep > /dev/null") == 0;
```
|
We have an array:int p[100].Whyp[i]is equivalent to*(p+i)and not*(p+i*sizeof(int))?
|
Why p[i] is equivalent to*(p+i)and not*(p+i*sizeof(int))?
Because*(p+i)is also the same as*((int *) ((char *) p + i * sizeof (int))). When you add an integerito a pointer, the pointer is moveditimes the size of the pointed object.
|
I have an application I would like to inspect and I don't have the sources to rebuild it and create the Symbol Table likehere(gcc -g my_app.c).
When I call theinfo localsI get the following error "No symbol table info available"
When I'm working with Eclipse even when I don't have the sources of the library it can resolve the arguments of the current function intoarg0, arg1... argNand if I remember correctly also the members of objects.
Is there any way to generate a custom/generic/default symbol table, one that would satisfy GDB and would allow me to see the values of local variables and arguments?
|
the answer is No.
The local symbols are only useful for debugging so there is no alternative. If they have been discarded they are gone.
|
I understand that we can find the size of a pointer of certain type using the following:
```
printf("size of an int pointer: %d", sizeof(int*));
printf("size of a float pointer: %d", sizeof(float*));
printf("size of pointer to void: %d", sizeof(void*));
```
In C, is it possible to find the size of astructwithout needing to usesizeof?
|
Perform pointer arithmetic and measure the step size.
```
#include <stdio.h>
struct foo { char a[5],b[98];};
#define SYZEOV(t) ((size_t)((void*)(((t*)(NULL))+1)-NULL))
int main(int m, char**n){
printf("sizeexpr=%ld\n", (long)((void*)(((struct foo*)(NULL))+1)-NULL));
printf("syzeov =%ld\n", (long)SYZEOV(struct foo));
printf("sizeof =%ld\n", (long)sizeof(struct foo));
return 0;
};
```
|
Noob here. I'm learning C. and I faced this problem I couldn't find the error/bug in my code, everytime it prints the average of the program the value of 2686776 whatever the input is. I'm using Dev-C++
```
#include <stdio.h>
int main () {
int loop, money, total, avg;
total = 0;
loop = 0;
while(loop < 4) {
printf("Money Spent");
scanf("%d", &money);
total = total + money;
loop = loop + 1;
}
avg = total / 4;
printf(" average %d", &avg);
getch();
}
```
|
You have to remove the&from the printf statement otherwise you print the address of this variable.
Alsoavgisintso it can't have decimal digits! (e.g. 4, 5 -> 9 -> avg = 4). So you have to change it tofloatordouble
|
In the code below, please take a look at the part which has the 'continue' statement. What difference would it make if I remove 'continue' statement and I put nothing in the place of it.
```
int prime_or_not(int x){
int i;
if (x == 1 || x == 2){
return 1;
}else if (x % 2 == 0){
return 0;
}else if (x > 2){
for (i = 3; i < x; i += 2){
if (x % i == 0){
return 0;
break;
}else {
continue;
}
}
return 1;
}else {
return 0;
}
}
```
|
It would make no difference at all. Thecontinuestatement is ajump statement. Basically, it jumps back to your loop not executing the code after it.
Since thecontinuestatement is last executed in your loop it has no effect.
|
I have this code:
```
FLAC__StreamDecoderWriteStatus writeCallback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) {
//impl....
}
```
and then later on I have this declaration:
```
{
/// stuff
FLAC__StreamDecoderWriteStatus (*writeCallbackPtr) (const FLAC__StreamEncoder *, const FLAC__byte , size_t , unsigned , unsigned , void *) = writeCallback;
// more stuff
}
```
My understanding of the error is that the two are of different types, but I don't understand what I'm doing wrong in this case.
|
Your declaration is wrong, it should be
```
FLAC__StreamDecoderWriteStatus (*writeCallbackPtr) (
const FLAC__StreamEncoder *,
const FLAC__byte[],
/* here ^ you missed the [] */
size_t ,
unsigned ,
unsigned ,
void *) = writeCallback;
```
|
In Python, if I wanted to assign the vectorx=(1,2)to the first two elements ofy=(0,0,0,0), I would do something likey[:1] = x. Is there an equivalent in C to assign adouble x[2]={1.,2.}to the first two elements of an availabledouble y[4] = {0.,0.,0.,0.}? Or will I have to loop?
|
Just try this
```
#include <string.h>
#include <stdio.h>
int main()
{
double x[2] = {1., 2.};
double y[4] = {0., 0., 0., 0.};
memcpy(y, x, 2 * sizeof(*x));
/* ^ 2 elements of size -> sizeof(double) */
return 0;
}
```
instead of writingsizeof(double)which is ok, i didsizeof(*x)because if I change the type ofxI wouldn't need to fix thememcpy, but i would also have to change the type ofyin that case.
|
This question already has answers here:Appending strings in C(6 answers)Closed8 years ago.
How can I concatenate strings this way?
For example:
```
char *txt = "Hello";
txt=txt+"World!";
```
I tried it but it wasn't.
|
txtis a pointer and memory should be allocated to it.
It is good to have the below checks
The amount of memory which needs to allocated can be calculated bysize_t size = strlen("Hello") + strlen("World");char *txt = malloc(size + 1);Check the return value of malloc() before accessing it.if(txt != NULL)
Dynamically this can be done:
```
char *txt = malloc(size+1); /* Number of bytes needed to store your strings */
strcpy(txt,"Hello");
strcat(txt,"World");
```
The allocated memory should be freed after using it like
```
free(txt);
```
Alternatively you can have
```
char txt[30];
strcpy(txt,"Hello");
strcat(txt,"World");
```
|
Is it possible to define acharwith a variable length?
I have achar"name" (member of astructnamed "person") with a length of 25 but I want it to be a variable length between the values 1 and 25, because I want to generate random strings of thatcharwith different sizes and not always with the same length (25). One of the parameters of the method issizeof(n.name).
Note:nis astruct(struct person n).
Thestruct"person" is defined this way:
```
struct person{
int c;
char name[25];
};
```
Anyone?
|
```
struct person{
int c;
char name[]; /* Variable length array */
};
```
I think this should serve your purpose.
Else you can have dynamic memory allocation using
```
char *name;
```
nameis a pointer and memory should be allocated and it can be done usingmalloc()
|
I would like to know how I can generate a random string for a member of a struct and assign this value to the member of the struct.
My struct is defined this way:
```
struct student{
int key;
char name[25];
}
```
I already generated random numbers of the member "key" of struct.Part of the code of the method:
```
struct student s;
int r = rand() % 5000;
s.key=r;
```
Note: With srand(time(NULL)); defined in main().
How I do it for s.name?
|
rand() returnsintso you can't userand()to assign random strings to your struct member.
You can do something like below using rand() to generate random strings.
```
char a[]="abcde...z";
for(i=0;i<20;i++)
{
int r = rand() %26;
s.name[i] = a[r];
}
s.name[20] = '\0';
```
After the loop makes sure you NULL terminate the string.
|
In the for loop the second part i.e, after the 1st semicolon we do the condition checking( say i less than n). If we remove the condition part in general it goes into an infinite loop but here it shows a run time error and also if we simply write exp[] without the index i it gives a compiler error so what is exp[i] here and how is the condition checking taking place?
```
int infixToPostfix(char* exp)
{
int i,k;
for (i = 0, k = -1; exp[i]; ++i)
....
....
}
int main()
{
char exp[] = "a+b*(c^d-e)^(f+g*h)-i";
infixToPostfix(exp);
return 0;
}
```
|
Considering no access violation,expis acharpointer,exp[i]is the value of thei+ithcharelement.
Next, thevalueofexp[i]is used for condition checking. i.e,0forfalse,non-zerofortrue.
|
This question already has answers here:Scope of macros in C?(7 answers)Closed8 years ago.
As the title hints, my question is whether the preprocessor directives#ifand#endifact like a scope? Consider the example:
```
#define foo 1
#define bar 1
#if foo
#undef bar
#endif //foo
// Is 'bar' defined or undefined here?
```
|
Now with your example just test it and you will see it:
```
#include <stdio.h>
#define foo 1
#define bar 1
#if foo
#undef bar
#endif //foo
int main() {
printf("%d", bar);
return 0;
}
```
Output from my compiler:
```
[Error] 'bar' undeclared (first use in this function)
```
So as you can see it's undeclared
|
This question already has answers here:What is the difference between prefix and postfix operators?(13 answers)Closed8 years ago.
Why is the decrement operator--not bringing the value down by 1 when executed?
```
int a = 20;
int c ;
c = a--;
```
Inspecting the value ofcnow, it should be 19, yet it comes out as 20. What am I missing?
|
a--is Post-Decrement, what you need--aPre-Decrement. Please read Increment and decrement operators onWiki
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
```
int x;
int y;
// Increment operators
x = 1;
y = ++x;
// x is now 2, y is also 2
y = x++;
// x is now 3, y is 2
// Decrement operators
x = 3;
y = x--;
// x is now 2, y is 3
y = --x;
// x is now 1, y is also 1
```
|
Suppose i want to deal with certain patterns and have the other text(VHDL code) as it is in the output file.
For that purpose i would be required to write a master rule in the end as
```
(MY_PATTERN){
// do something with my pattern
}
(.*){
return TOK_VHDL_CODE;
}
```
Problem with this strategy is MY_PATTERN is useless in this case and would be matched with .* by maximum munch rule.
So how can i get this functionality ?
|
The easy way is to get rid of the*in your default rule at the end and just use
```
. { append_to_buffer(*yytext); }
```
so your default rule takes all the stuff that isn't matched by the previous rules and stuffs it off in a buffer somehwere to be dealt with by someone else.
|
Can someone please explain why am I getting the compilation error the below code.
Error says:
"expected unqualified-id before 'struct' " on line number 7 ".
My code:
```
struct node{
int data;
struct node *left;
struct node *right;
};
( struct node *) createNode(int num)
{
struct node *newNode;
newNode = (struct node *) malloc(sizeof(struct node));
newNode->data = num;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
```
|
change
```
( struct node *) createNode(int num)
```
to
```
struct node * createNode(int num)
```
Remember, you're specifying thereturn type. You're nottypecasting.
That said,
Pleasesee why not to castthe return value ofmalloc()and family inC.Always check for the return value ofmalloc()for success before using the returned pointer.
|
I have created a script that takes a file(FiletoModify.txt) and copy line by line everything it contains to a new txt file which I called it output.txt.My problem is that I want to call system to do the following in my code but it doesn't work.I'm a new in C programming and I'm making it clear that I can't see my mistake and I really need some help.Thank you
My code in my C program:
```
system("cd Desktop; chmod +x script.sh ; ./script.sh");
```
Here's the script code:
```
#!/bin/bash
while IFS= read -r line
do
echo "$line"
echo -e "$line\n" >>output.txt
done <"FiletoModify"
```
|
Okay, so from your error message your problem is with thecd Desktop;part of your C program. Two possible fixes:
Deletecd Desktop;from yoursystemcall.Run your C executable from a directory one level aboveDesktop(i.e. the directory which containsDesktop).
|
In a C-program I am trying to create a textfile where the file name should be based on the input to one or two char arrays in a structure.
At the moment I query the filename like this:
```
printf("Type a filename:");
scanf("%s", &filename);
strcat(&filename, ".txt");
pFile=fopen(filename,"a");
```
…but let's say my input to my char array isJohn, how could this input be used to create the filenameJohn.txt?
..or even better: combine a name from two char arrays:
```
fgets(pIndex->name, 20, stdin); //lets say input here is John
fgets(pIndex->country, 20, stdin); //...and input here is England
```
to generate a filename likeJohnEngland.txt
Thanks a lot !
-Espen
|
You can generate a filename likeJohnEngland.txtwith this
```
char filename[45];
sprintf (filename, "%s%s.txt", pIndex->name, pIndex->country);
```
|
Why doessched_setscheduler()require root priveledges?
I am writing some code that benefits from setting SCHED_FIFO. But if I use sched_setscheduler() I now must require this process to be run as root. Why not allowsched_setscheduler()to be run without root permissions?
|
Presumably because processes using a realtime scheduler can completely take over a machine and not give the CPU to other processes - which normal users should not have the power to do.
Linux allows you to do a bit more fine grained control than running as root though, you can set the CAP_SYS_NICEcapabilityon your executable (done once, as the root user) with the command:
```
setcap cap_sys_nice+ep ./your_program
```
Which will allow your executable to use sched_setscheduler even when it's not run as the root user.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.