question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I having a problem while passing a 2d array to a function. Have a look at the code-:
```
#include<stdio.h>
void display(int (*arr)[3],int i,int j,int length,int breadth) {
for(;i<length;i++){
for(;j<breadth;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
v... |
With what you are doing, when will j get reset to 0?
|
This question already has answers here:Undefined behavior and sequence points(5 answers)Closed9 years ago.
In C
```
i = 7;
j = i++ * ++i; // outputs 64?
```
according to precedence post increment comes first so
it should be 7*9. Point out my mistake. Can you please provide me a resource where i can learn in detail... |
Your problem is that there is no sequence point in the above. SeeUndefined behavior and sequence points
So you have no control over the order in which the two increments ofioccur (just whether you are are returned the incremented number or the number before the increment). This is thus undefined behaviour.
For insta... |
I've got a problem. I need to compile C code for linux, but I am using a windows IDE that I'd really want to use. Therefore I need an commandline compiler executable like gcc that is capable of compiling C code. Furthermore I also need to be able to compile CUDA C code into a linux program. Therefore my question:
Is ... |
I'd go for virtual Ubunto Linux on top of Windows
You can do it usingvirtual boxvirtual machine
|
I have .c files and .f files which are interdependent.
That means, the function used in .c files are defined in .f files.
Now, I want to call for some functions in .c file from my R. How can I do this using R CMD SHLIB?
|
Oh, I figured out this can be easily done by
```
R CMD SHLIB code1.f code2.c -o myLib
```
Then in R, I can call the myLib via
```
dyn.load("myLib")
```
|
This question already has answers here:Changing switch variable inside a case(4 answers)Closed9 years ago.
Will it work/is it allowed to have a switch-case statement and change the key in a statement?
For example:
```
temp = 1
switch(temp)
{
case 1:
temp = 2;
//Do something with temp..
br... |
This is perfectly fine. Virtually every state machine on the planet does something equivalent to what you do here.
|
lets say I have a linked list( any kind , let just say singly linked list)
```
for(current = head; current!=NULL; current=current->next)
free(current);
```
Let's say this is my code , is there going to be any point at which this code might fail? or is there a safer approach to free the nodes?
|
There is certainly a problem with this code: the for loop you are executing is equivalent to
```
current = head;
while (current!=NULL) {
free(current);
current=current->next;
}
```
That is you are accessingcurrentafterthe free.
You should change this to
```
current = head;
while (current!=NULL) {
tmp = cu... |
Difference:
If there is an overlap, usememmovein place ofmemcpy
Q: Could you provide a practical scenario of any C lib function where an overlap happens so memmove is used in place ofmemcpy?
|
Here's one:
```
// len => array length, idx => index where we want to remove
void removeAt(int* array, size_t* len, size_t idx)
{
// copy next values to replace current
// example: {1, 2, 3, 4} => {1, 3, 4}
// ^ remove
memmove(&array[idx], &array[idx+1], (--(*len) - idx) * sizeof(int));
}... |
I have the following code to declare and assign a string on the heap.
```
char *string = malloc(10);
string[9] = '\0';
strncpy(string, "welcometotherealworld", 9);
printf("string: %s\n", string);
```
Do I have to manually set the\0\to ensure the string ends?string[9] = '\0';
Or, doesstrncpydo this for me?
|
Two things: Firstmalloc(10)reserves 10 bytes,string[10]addresses the eleventh byte, so that is illegal. Second: Yes you have to set string[9] to null, because according to thestandardstrncpy does not ensure the string is null terminated if the source string is longer than count.
|
```
#include<stdio.h>
#include<conio.h>
#define CUBE(y)y*(y*y)
main()
{
int j;
j = CUBE(-2+4);
printf("value of j = %d",j);
getch();
}
```
Output of this code is-26. I just want to know how this code give-26as an output. How#definework in this code. I know that#defineperma... |
It does:
```
j = -2 + 4 * (-2 + 4 * -2 + 4)
```
A more correct definition of CUBE would be
```
#define CUBE(y) ((y)*(y)*(y))
```
|
I have a problem much like the oneherewhere the error is "Undefined reference to sqrt". I understand how using the -lm flag when compiling fixes the problem by linking it to the math library, however, are there any other possible ways to fix the problem without using any special compiler flags?
I've been happily usi... |
Other than making your own sqrt method no, though some compilers have the sqrt function already in them from what I've used so you may not need the extra flag potentially. I would email your instructor and talk to him about this.
|
```
int main(void) {
int i = 2, k = 3, a;
i++;
++k;
{
int i = 0;
i = k++;
printf("%d,%d,", i, k);
}
printf("%d,%d", i, k);
getchar();
return 0;
}
```
Why this code produces output "4,5,3,5" why not "4,5,4,5"? Why when I trace code by f7 key c++ then it goes firs... |
Secondprintfdoesn't "see" thatideclared asint i =0;, because thatiis in another scope created by your curly braces.
So, the secondprintftakes the firsti, which was declared (and defined) asint i =2and in the next line incremented to3withi++.
By the way, code indentation is your friend (and ours too:).
|
This question already has answers here:How Pointer of Multi-Dimension Arrays Work in C(3 answers)Closed9 years ago.
I know that for two-dimensional arraysA[i][j]is equivalent to*(*(A+i)+j), but what does(int *Arrptr)[5] mean?
|
(int *Arrptr)[5]is wrong syntax.
```
int (*Arrptr)[5]; // Arrptr is a pointer to an array of 5 int
int *Arrptr[5]; // Arrptr is an array of 5 pointeres to int
```
The array subscript operator[]binds tightly to the identifierArrptr, therefore parentheses are necessary in the first statement.
|
I tried something like :
```
typedef struct vec{
int sz;
int v[];
} ff;
int sum(struct vec z){
int o=0,i;
for(i=0;i<z.sz;i++)
o+=z.v[i];
return o;
}
int main(){
int test[]={10,1,2,3,4,5,6,7,8,9,10};
return sum((struct vec)test);
}
```
But this example code can't compile. How t... |
You can't send an array by value in C. Every time you try to pass an array to a function, you'll pass the pointer to the first value.To pass an array by value, you can cheat a little and encapsulate it in a struct, and send it by value (so it will be copied)... It's a dirty hack,as explained here, but well, if you rea... |
I am just back from an interview and this question is bugging me. I was asked to write an equivalent expression forx % 8and I couldn't get it. I know it's something to do with 8 being in powers of 2 but I just can't figure it out. This seems like a great programmer community so I'm hoping anyone here can answer this?
|
x&7is the answer. (I'm not some hot shot I just googled it)
|
I am looking to find the source code of the C functionmysql_stmt_free_result()
I searched everywhere but I didn't find out the the source code. I need to understand what exactly this function frees. Thedocumentationlacks information about what exactly is freed.
|
The version fromMySQL 5.6.11:
```
my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt)
{
DBUG_ENTER("mysql_stmt_free_result");
/* Free the client side and close the server side cursor if there is one */
DBUG_RETURN(reset_stmt_handle(stmt, RESET_LONG_DATA | RESET_STORE_RESULT |
... |
As we know, strtoXX functions return max(or min) value if overflow occur, for example,strtoul("999999999999999999999999999999999", NULL, 0)returnsULONG_MAX. Butstrtoul("0xffffffff", NULL, 0)returns alsoULONG_MAX(if sizeof(unsigned long) == 4).
Then, how can I check overflow?
|
http://www.cplusplus.com/reference/cstdlib/strtoul/
If the value read is out of the range of representable values by an
unsigned long int, the function returns ULONG_MAX (defined in
), and errno is set to ERANGE.
You're dealing with unsigned integers, so it doesn't matter what sign your integer has: they're all ... |
Look at Following code fragment
```
char ch[10] = "hello"; // is ok
```
but
```
char ch[10];
ch = "hello"; // showing lvalue error
```
It should have to be possible according to the concept that array decays into pointer.Why here ch is not decaying to char *?
please describe the distinction between the two.
|
```
char ch[10] = "hello";
```
is initialisation, and is allowed by the standard. It's effectively "give me a ten-char array and populate it with the C string"hello".
```
char ch[10];
ch = "hello";
```
is (attempted) assignment, and is not permitted. You can do:
```
char *ch;
ch = "hello";
```
but then you end up... |
This question already has an answer here:need of fseek() in c(1 answer)Closed9 years ago.
```
while(1)
{
ch=fgetc(ft);
if(ch==EOF)
{
break;
}
if(ch=='u')
{
fputc('b',ft);
fflush(ft);
}
}
```
I tried to replace character afteruwithbin a file pointed by*ft.
This cod... |
fflush only flushes output stream. Hence you need to putfseek(ft,0,SEEK_CUR)above yourfputs(ft)
|
This question already has answers here:How Pointer of Multi-Dimension Arrays Work in C(3 answers)Closed9 years ago.
I know that for two-dimensional arraysA[i][j]is equivalent to*(*(A+i)+j), but what does(int *Arrptr)[5] mean?
|
(int *Arrptr)[5]is wrong syntax.
```
int (*Arrptr)[5]; // Arrptr is a pointer to an array of 5 int
int *Arrptr[5]; // Arrptr is an array of 5 pointeres to int
```
The array subscript operator[]binds tightly to the identifierArrptr, therefore parentheses are necessary in the first statement.
|
I tried something like :
```
typedef struct vec{
int sz;
int v[];
} ff;
int sum(struct vec z){
int o=0,i;
for(i=0;i<z.sz;i++)
o+=z.v[i];
return o;
}
int main(){
int test[]={10,1,2,3,4,5,6,7,8,9,10};
return sum((struct vec)test);
}
```
But this example code can't compile. How t... |
You can't send an array by value in C. Every time you try to pass an array to a function, you'll pass the pointer to the first value.To pass an array by value, you can cheat a little and encapsulate it in a struct, and send it by value (so it will be copied)... It's a dirty hack,as explained here, but well, if you rea... |
I am just back from an interview and this question is bugging me. I was asked to write an equivalent expression forx % 8and I couldn't get it. I know it's something to do with 8 being in powers of 2 but I just can't figure it out. This seems like a great programmer community so I'm hoping anyone here can answer this?
|
x&7is the answer. (I'm not some hot shot I just googled it)
|
I am looking to find the source code of the C functionmysql_stmt_free_result()
I searched everywhere but I didn't find out the the source code. I need to understand what exactly this function frees. Thedocumentationlacks information about what exactly is freed.
|
The version fromMySQL 5.6.11:
```
my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt)
{
DBUG_ENTER("mysql_stmt_free_result");
/* Free the client side and close the server side cursor if there is one */
DBUG_RETURN(reset_stmt_handle(stmt, RESET_LONG_DATA | RESET_STORE_RESULT |
... |
As we know, strtoXX functions return max(or min) value if overflow occur, for example,strtoul("999999999999999999999999999999999", NULL, 0)returnsULONG_MAX. Butstrtoul("0xffffffff", NULL, 0)returns alsoULONG_MAX(if sizeof(unsigned long) == 4).
Then, how can I check overflow?
|
http://www.cplusplus.com/reference/cstdlib/strtoul/
If the value read is out of the range of representable values by an
unsigned long int, the function returns ULONG_MAX (defined in
), and errno is set to ERANGE.
You're dealing with unsigned integers, so it doesn't matter what sign your integer has: they're all ... |
Look at Following code fragment
```
char ch[10] = "hello"; // is ok
```
but
```
char ch[10];
ch = "hello"; // showing lvalue error
```
It should have to be possible according to the concept that array decays into pointer.Why here ch is not decaying to char *?
please describe the distinction between the two.
|
```
char ch[10] = "hello";
```
is initialisation, and is allowed by the standard. It's effectively "give me a ten-char array and populate it with the C string"hello".
```
char ch[10];
ch = "hello";
```
is (attempted) assignment, and is not permitted. You can do:
```
char *ch;
ch = "hello";
```
but then you end up... |
This question already has an answer here:need of fseek() in c(1 answer)Closed9 years ago.
```
while(1)
{
ch=fgetc(ft);
if(ch==EOF)
{
break;
}
if(ch=='u')
{
fputc('b',ft);
fflush(ft);
}
}
```
I tried to replace character afteruwithbin a file pointed by*ft.
This cod... |
fflush only flushes output stream. Hence you need to putfseek(ft,0,SEEK_CUR)above yourfputs(ft)
|
Takeunsigned charfor example.
Its range is0 to 255.
If I try to store256in it, following will happen :-
Binary of256
100000000
As it consists of9-bitshence MSB1will be discarded and it will become
00000000
Which is0.
So I want to know that why only left most bit is removed?
|
Because it's the most reasonable & useful thing that could happen when you only have 8 bits of space.
Discarding thelowermostbit would be a bad idea because now you can no longer increment the integer to get the next integer mod 28, etc... it would become useless as soon as it overflowed.Discarding any other bit in t... |
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
I want to program a micro controller with 4 I/O ports and 1 serial port and 512 kb of cod... |
Generally, using a high-level language, the code is much more readable and maintainable than assembly language, and in my experience most c-compilers produce machine code that is NEARLY as efficient as well-written assembly language...for MOST tasks. So unless you fear that the (seemingly) copious 512KB of memory MAY... |
```
main()
{
int a = 10, b = 5, c = 5;
int d;
d = a == (b + c);
printf("%d", d);
}
```
OUTPUT: 1
Can anyone please explain how this value is assigned to d??
|
==has a higher precedence than=, so
```
d = a == (b + c);
```
is equivalent to:
```
d = (a == (b + c));
```
it tests ifais equal tob + c,1if true, and0if false.
|
I have program
```
void alloc(char **p)
{
*p=(char*)malloc(sizeof(char)*3);
(*p)[0]='a';
(*p)[1]='f';
(*p)[2]='\0';
}
main()
{
char p[]="hrrgr";
alloc(&p);
printf("%s",p);
}
```
It prints nothing. Please explain this.
I know by passing char*p ; and alloc(&p) will do the trick. But ... |
pis an array of 6 characters. Thereforepis of typechar[6].&pis then of typepointer to char[6] type, i.e.,char (*)[6]. When you pass an array to a function, it evaluates to a pointer to its first element. Thus when you are passing achar (*)[6]type value to yourallocfunction, you are assigning achar (*)[6]type to achar ... |
What is the difference between
```
char ch [ ] = "hello";
```
and
```
char ch [ ] = { 'h','e','l','l','o','\0'};
```
and why we can only do
```
char *p = "hello";
```
But cant do
```
char *p = {'h','e','l','l','o','\0'};
```
|
```
char ch [ ] = "hello";
char ch [ ] = { 'h','e','l','l','o','\0'};
```
There is no difference.chobject will be exactly the same in both declarations.
On why we cannot do:
```
char *p = {'h','e','l','l','o','\0'};
```
An initializer list of more than one value can only be used for objects of aggregate type (stru... |
```
int main()
{
FILE *fp;
fp=fopen("pr1.c","r");
if(fp==NULL)
{
printf("can not open file");
}
getch();
return 0;
}
```
In the above code, the filepr1.cshould be in the same directory in which I am working, othwerwise it will printcan not open file.Is there any way by which I can ... |
Yes, you can. Just use the full path of the file, or relative path based on current folder.
For example:
```
fp = fopen("c:\\MyDirectory\\TestFile1.txt", "r");
fp = fopen("/full/path/to/TestFile1.txt", "r"); // use ../ go to parent folder
```
Updated:If you want user to enter the path, you can use
```
char pat... |
Can anyone explain to me why the following code outputs -50 even though it is being cast to an unsigned int?
```
int main()
{
signed char byte = -50;
unsigned int n;
n = (unsigned int) byte;
printf("n: %d", n);
}
```
output: -50
|
Assigning-50tounsigned intcauses the integer to wrap around, and this wrapped aroundunsigned inthas the same bits set as thesigned intcorresponding to-50in the twos complement representation that is used by almost every computer.
Now,printfis a function with a variable number of arguments that it interprets according... |
I'm using a mac OS X 10.8.4 64 bit.
I want to build some C/C++ programs on my mac, and then show them to some people who use windows.
I can successfully compile it into an exe, using
g++ test.cpp -o test.exeon the terminal
But when run in my PC, that exe file raises this error: "This verison of this file is not comp... |
Usingg++ test.cpp -o test.exedoes not produce a Windows EXE executable, it just produces a Mac OS X executable that happens to have the.exeextension on its filename. To produce Windows EXE executables you need to use a Windows compiler, such as Microsoft Visual Studio or gcc on cygwin.
|
I am using VC++ and trying to parse the ip (ipv4/ipv6) address from the url received. Is there any way I can achieve this. I know one way is to iterate through each character in the url and to look for [ and ] in the url for ipv6. This doesn't seem to be a good way so wondering if there is any function which help me ... |
Since you tagged the question withvisual-c++, I could suggest you to useInternetCrackUrl()from wininet library for parsing.
|
I am trying to do some Raw data handling of an IR Remote with Arduino.
```
unsigned int ArrayKey[68] = {30868,8900,4400,600,500,600,...,600};
irsend.sendRaw(ArrayKey,68,38);
```
Now I try to get a Raw IR Data via Serial, but there is a syntax problem:
readString is = 30868,8900,4400,600,500,600,1650,600,550,....
`... |
You cannot initialize it like that (non constant, non compatible etc.,), instead you can do it during run time
```
char *tmp;
int i = 0;
tmp = strtok(readString, ",");
while (tmp) {
ArrayKey[i++] = atoi(tmp);
tmp = strtok(NULL, ",");
}
```
|
What is the difference between
```
char ch [ ] = "hello";
```
and
```
char ch [ ] = { 'h','e','l','l','o','\0'};
```
and why we can only do
```
char *p = "hello";
```
But cant do
```
char *p = {'h','e','l','l','o','\0'};
```
|
```
char ch [ ] = "hello";
char ch [ ] = { 'h','e','l','l','o','\0'};
```
There is no difference.chobject will be exactly the same in both declarations.
On why we cannot do:
```
char *p = {'h','e','l','l','o','\0'};
```
An initializer list of more than one value can only be used for objects of aggregate type (stru... |
```
int main()
{
FILE *fp;
fp=fopen("pr1.c","r");
if(fp==NULL)
{
printf("can not open file");
}
getch();
return 0;
}
```
In the above code, the filepr1.cshould be in the same directory in which I am working, othwerwise it will printcan not open file.Is there any way by which I can ... |
Yes, you can. Just use the full path of the file, or relative path based on current folder.
For example:
```
fp = fopen("c:\\MyDirectory\\TestFile1.txt", "r");
fp = fopen("/full/path/to/TestFile1.txt", "r"); // use ../ go to parent folder
```
Updated:If you want user to enter the path, you can use
```
char pat... |
Can anyone explain to me why the following code outputs -50 even though it is being cast to an unsigned int?
```
int main()
{
signed char byte = -50;
unsigned int n;
n = (unsigned int) byte;
printf("n: %d", n);
}
```
output: -50
|
Assigning-50tounsigned intcauses the integer to wrap around, and this wrapped aroundunsigned inthas the same bits set as thesigned intcorresponding to-50in the twos complement representation that is used by almost every computer.
Now,printfis a function with a variable number of arguments that it interprets according... |
I'm using a mac OS X 10.8.4 64 bit.
I want to build some C/C++ programs on my mac, and then show them to some people who use windows.
I can successfully compile it into an exe, using
g++ test.cpp -o test.exeon the terminal
But when run in my PC, that exe file raises this error: "This verison of this file is not comp... |
Usingg++ test.cpp -o test.exedoes not produce a Windows EXE executable, it just produces a Mac OS X executable that happens to have the.exeextension on its filename. To produce Windows EXE executables you need to use a Windows compiler, such as Microsoft Visual Studio or gcc on cygwin.
|
I am using VC++ and trying to parse the ip (ipv4/ipv6) address from the url received. Is there any way I can achieve this. I know one way is to iterate through each character in the url and to look for [ and ] in the url for ipv6. This doesn't seem to be a good way so wondering if there is any function which help me ... |
Since you tagged the question withvisual-c++, I could suggest you to useInternetCrackUrl()from wininet library for parsing.
|
I am trying to do some Raw data handling of an IR Remote with Arduino.
```
unsigned int ArrayKey[68] = {30868,8900,4400,600,500,600,...,600};
irsend.sendRaw(ArrayKey,68,38);
```
Now I try to get a Raw IR Data via Serial, but there is a syntax problem:
readString is = 30868,8900,4400,600,500,600,1650,600,550,....
`... |
You cannot initialize it like that (non constant, non compatible etc.,), instead you can do it during run time
```
char *tmp;
int i = 0;
tmp = strtok(readString, ",");
while (tmp) {
ArrayKey[i++] = atoi(tmp);
tmp = strtok(NULL, ",");
}
```
|
Can anyone explain to me why the following code outputs -50 even though it is being cast to an unsigned int?
```
int main()
{
signed char byte = -50;
unsigned int n;
n = (unsigned int) byte;
printf("n: %d", n);
}
```
output: -50
|
Assigning-50tounsigned intcauses the integer to wrap around, and this wrapped aroundunsigned inthas the same bits set as thesigned intcorresponding to-50in the twos complement representation that is used by almost every computer.
Now,printfis a function with a variable number of arguments that it interprets according... |
I'm using a mac OS X 10.8.4 64 bit.
I want to build some C/C++ programs on my mac, and then show them to some people who use windows.
I can successfully compile it into an exe, using
g++ test.cpp -o test.exeon the terminal
But when run in my PC, that exe file raises this error: "This verison of this file is not comp... |
Usingg++ test.cpp -o test.exedoes not produce a Windows EXE executable, it just produces a Mac OS X executable that happens to have the.exeextension on its filename. To produce Windows EXE executables you need to use a Windows compiler, such as Microsoft Visual Studio or gcc on cygwin.
|
I am using VC++ and trying to parse the ip (ipv4/ipv6) address from the url received. Is there any way I can achieve this. I know one way is to iterate through each character in the url and to look for [ and ] in the url for ipv6. This doesn't seem to be a good way so wondering if there is any function which help me ... |
Since you tagged the question withvisual-c++, I could suggest you to useInternetCrackUrl()from wininet library for parsing.
|
I am trying to do some Raw data handling of an IR Remote with Arduino.
```
unsigned int ArrayKey[68] = {30868,8900,4400,600,500,600,...,600};
irsend.sendRaw(ArrayKey,68,38);
```
Now I try to get a Raw IR Data via Serial, but there is a syntax problem:
readString is = 30868,8900,4400,600,500,600,1650,600,550,....
`... |
You cannot initialize it like that (non constant, non compatible etc.,), instead you can do it during run time
```
char *tmp;
int i = 0;
tmp = strtok(readString, ",");
while (tmp) {
ArrayKey[i++] = atoi(tmp);
tmp = strtok(NULL, ",");
}
```
|
I was wondering what is a file descriptor of the network socket and how to get it? I believe it is a number?
|
It is indeed a number and you get it by issuing thesocket(2)system call. It is stored in the process'stask_structand you need it to send or receive data.
More exactly, the kernel uses the file descriptor to locateFile Objectsstored in thefiles_structstruct inside thetask_struct. It behaves like a bitmap where the num... |
I have the following code
```
#include <hcs12dp256.h>
void spinloop(int spins)
{
for (int i=0; i<spins; i++)
{
i ++;
}
}
void main(void)
{
DDRK = DDRK & 0x0F;
PORTK = PORTK & 0x00;
PORTK = PORTK | 0x01;
PORTK = PORTK | 0x02;
spinloop(100000);
PORTK = PORTK & 0x0C;
PORTK = PORTK | 0x03;
PORTK = PORTK... |
Change:
```
for (int i=0; i<spins; i++)
```
with
```
int i;
for (i=0; i<spins; i++)
```
Your compiler probably doesn't support C99.
|
I am using a DLL with load-time dynamic linking. I want to know how my executable know where the DLL file is without callingLoadLibrary()function which is run-time linking.
Does DLL has to be in same directory with the executable that load it with load-time linking?
|
1 The directory where the executable module for the current process is located.2 The current directory.3 The Windows system directory. The GetSystemDirectory function retrieves the path of this directory.4 The Windows directory. The GetWindowsDirectory function retrieves the path of this directory.5 The directories li... |
I have this code in C:
```
char c;
char *s;
....
while(1){
c = *(s++)
if(!c){
exit(1);
}
....
}
```
What does (!c) do? how can I reach the exit call?
|
!calways evaluates tofalseexcept whenc==0, that isc=='\0'. Therefore the code will exit when the end of the string thatsis pointing to is reached. (Assumingspoints to a null-terminated string).
Note thatc = *(s++)gets one character of the string and moves the pointer to the next character.
|
I am trying to gcc my library with another static library and I get this error while runtime
```
undefined symbol: security_getenforce
```
I am thinking this is related to selinux, not sure though... how do I resolve this?
Thanks,
Vik.
|
Figured it out, use -lselinux as the flag to resolve the issue and load the necessary libraries.
|
This question already has answers here:Executing code before main()(5 answers)Closed9 years ago.
I want to execute user define function before main().
Is it possible to execute a function beforemain()in c?
```
sum(int a, int b) { return (a+b); }
g_sum = sum(1, 5);
main(){
sum(5, 6);
printf("%d", g_sum);
}
``... |
Is it possible to execute a function before main()
Yes it is possible if you are using gcc and g++ compilers then it can be done by using__attribute__((constructor))
Example:
```
#include <stdio.h>
void beforeMain (void) __attribute__((constructor));
void beforeMain (void)
{
printf ("\nThis is before main\n");
... |
```
int a[10];
int *p = a; //way 1
int *p1 = &a[0]; //way 2
```
Could you tell me the differences between two ways above?
|
There is no difference. Both assign the address of the first element to the pointerpandp1respectively.
In the first case,ais automatically converted to the address of the first element. In the second case it uses the address of the first element explicitly.
|
I have a headerpath in a c program that reads
```
#include <lib/a.h>
#include <lib/b.h>
```
How do I specify where 'lib' should be in my makefile? It gives me a compile error saying lib/a.h is not found. But I know the system path where a.h is located. How do I tell my Makefile where to go find lib?
Thanks,
Vik.
|
Add an argument-I/path/to/includeto the compilation flags (e.g.,CFLAGSorCXXFLAGS) where the path leads to theparentdirectory of thelibdirectory.
|
Trying to open a file using open(). Returns the correct file descriptor when we call it like so:
```
fd = open("a.txt", O_RDONLY);
```
But when we use a token generated from strtok(), it returns -1:
```
token = strtok(NULL, " ");
fd = open(token, O_RDONLY);
```
|
Correctly guessed in comments:tokenis not actually the same string as"a.txt", but contains extra whitespace at the end, which makes it hard to see when printed as a string.
|
I'm trying
```
typedef struct
{
int x = 5;
char str[20];
} nodeStr;
```
It works in C++, but doesn't in C. For it to work in C I need to cut the definition ofx(i.e.,= 5) from the code. Is there in conceptual difference in C and C++ explaining this? Thanks!
|
In-class initialization is a new C++11 feature - if you use a (not much) older C++ compiler, it won't compile. So yes, it's a difference between C and C++.
|
The guys just helped me with a problem, got solved 100%, but now I have another one.
I compile my files and everything without problems, but when i want to run the program nothing happens.
enter.c :http://pastebin.com/GGzVeAhwsimple_interest.c:http://pastebin.com/XdESrxSk
This is how my header file looks like:
```... |
You have a bunch of prototypes inmain(), but no function call.
It should be:
```
int main(void)
{
enter();
return 0;
}
```
You seem really confused about how to declare and use functions, perhaps you need some tutorial?
|
My Program doesnt work.
I want to have the max and min values.
Whats the mistake?
Thx to all ;)
```
#include <stdio.h>
#include <stdlib.h>
#define N 5
int main()
{
int wert[N],i,min,max;
printf("Bitte geben Sie 5 Zahlen ein! \n");
for(i=0;i<N;i++)
scanf("%i",&wert[i]);//Eingabe der Werte
p... |
You did not initialisemin,max.
```
#include <limits.h>
int min = INT_MAX;
int max = 0;
```
|
I have something like the following, which I'm not satisfied with:
```
#define BEGIN {
#define END_1 };
#define END_2 END_1 };
#define END_3 END_2 };
// ... (possibly more of these) ...
#define END(x) END_ ## x
int main()
{
BEGIN
BEGIN
BEGIN
END(3) // <- I don't want to pass the 3 here
BEGIN
... |
GCCand MSVC offer a non-standard__COUNTER__macro that increments with each use. However, there is no way to reset it.
Whatever you are attempting should probably be done another way.
|
Since global and static variables are initialized to 0 by default, why are local variables not initialized to 0 by default as well?
|
Because such zero-initializations take execution time. It would make your program significantly slower. Each time you call a function, the program would have to execute pointless overhead code, which sets the variables to zero.
Static variables persist for the whole lifetime of the program, so there you can afford th... |
I am trying to debug some mutex errors, and I read this:http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_lock.html
There is some different kinds of types listed, like PTHREAD_MUTEX_ERRORCHECK etc. How do I initalize a mutex with that type?
I have used this line to initalize a mutex before:
```... |
To stay POSIX compliant usepthread_mutexattr_settype().
On GNUish systems just do
```
pthread_mutex_t mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
```
Also please not that the link you quote in your question refers to "Issue 6" which is outdated, the current version is"Issue 7".
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
fgetsis not working as I expected.
```
typedef struct {
int itemnumber;
char name [50];
double... |
You only malloc one instance.
you should do px[n] = malloc(sizeof(item)*n); after you scanf n
|
I am trying to check whether this equal to zero as
```
//Address already malloc
void MyCheck (void *Address){
if ( (long)Address & (~(sizeof(long)-1)) != 0 ){
printf("Invalid");
}
}
```
When try to compile it give me:
```
Error: suggest parentheses around comparison in operand
of '&... |
!=has higher precedence than&, so your code is really doing the same as :
```
if ((long)Address & ( (~(sizeof(long)-1)) != 0 ) )
^ ^
```
gcc suggests this might be an error, which it probably is. You'd want:
```
if ( ( (long)Address & (~(sizeof(long)-1)) ) != 0 )
... |
This is a syntax question. I came across the line:
```
void (*old_sigint_handler)(int);
```
And I have no idea what it is doing. It seems like the concatenation of three types with no variable name. I would appreciate clarification!
|
```
void (*old_sigint_handler)(int);
```
This definesold_sigint_handlerto be a pointer to a function which takes anintand returnsvoid, i.e, no value. The parentheses aroundold_sigint_handlerare necessary here else the following:
```
void *old_sigint_handler(int);
```
declares a functionold_sigint_handlerwhich take... |
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed9 years ago.
What makes this construction?
```
int a[10];
int x;
x = 2[a];
```
I do not understand what makes 2 [a]. It is another senility of C language?
|
It is
2[a] = *(2 + a) = *(a + 2) = a[2]
Note:+operator holds commutative property
|
look at the code below
```
char *p="bayant"; // char pointer
char str[ ] = "bayant"; // char array
printf("%s",p);//here we are passing pointer
printf("%s",str);//here we are passing strings base address
```
But how it works as we are using same format for a pointer and string?
|
%sconversion specification requires achar *argument.
In the second case you have an array ofcharargument, but C rules convert (except in a few cases) an expression of type array ofcharto typechar *.
|
I have this structure :
```
UID (4 byte unsigned integer)
Message size (4 byte unsigned integer)
Date (4 byte time_t value)
```
In a file I have this data :
```
UID : 3C 05 00 00
Message size : 2F EA 02 00
Date : FA 11 02 53
```
I dont find how get each value in human reading ? Can you help me please ?
Normally t... |
```
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv) {
unsigned u = 0x530211FA;// little endian
time_t t = (time_t)u;//sizeof(u) == sizeof(t) ?
printf("%s\n", ctime(&t));//Mon Feb 17 22:43:22 2014
return 0;
}
```
|
I have a DWORD dwCopyFlags which contains the copy flags of the function CopyFileEx. Is there some way to parse dwCopyFlags to check if it contains a certain type of flag, such as COPY_FILE_FAIL_IF_EXISTS?
|
A flag is a value with a single bit set. You test for that bit being set in a flags variable using bitwise and, the&operator. Bitwise and returns a value that each bit set if and only that bit was set in both operands. So, since your flag has a single bit set, the test is simplyflag & flags != 0.
With your variable n... |
I refer thelinkwhich says that if your device has compute capability greater than 2.0 then you can use printf() function in the CUDA kernel. When I tried the same I get the error"calling ahostfunction("printf") from aglobalfunction("mat_mul") is not allowed", but when I run same code on eclipse nsight I get the expect... |
The error you refer to:
"calling a host function("printf") from a global function("mat_mul") is not allowed"
arises fromcompilingthe code, not running the code.
So the difference lies in how your are compiling from "nvcc in terminal" vs. how it is set up to compile in nsight.
If you compile in the terminal with th... |
look at the code below
```
char *p="bayant"; // char pointer
char str[ ] = "bayant"; // char array
printf("%s",p);//here we are passing pointer
printf("%s",str);//here we are passing strings base address
```
But how it works as we are using same format for a pointer and string?
|
%sconversion specification requires achar *argument.
In the second case you have an array ofcharargument, but C rules convert (except in a few cases) an expression of type array ofcharto typechar *.
|
I have this structure :
```
UID (4 byte unsigned integer)
Message size (4 byte unsigned integer)
Date (4 byte time_t value)
```
In a file I have this data :
```
UID : 3C 05 00 00
Message size : 2F EA 02 00
Date : FA 11 02 53
```
I dont find how get each value in human reading ? Can you help me please ?
Normally t... |
```
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv) {
unsigned u = 0x530211FA;// little endian
time_t t = (time_t)u;//sizeof(u) == sizeof(t) ?
printf("%s\n", ctime(&t));//Mon Feb 17 22:43:22 2014
return 0;
}
```
|
I have a DWORD dwCopyFlags which contains the copy flags of the function CopyFileEx. Is there some way to parse dwCopyFlags to check if it contains a certain type of flag, such as COPY_FILE_FAIL_IF_EXISTS?
|
A flag is a value with a single bit set. You test for that bit being set in a flags variable using bitwise and, the&operator. Bitwise and returns a value that each bit set if and only that bit was set in both operands. So, since your flag has a single bit set, the test is simplyflag & flags != 0.
With your variable n... |
I refer thelinkwhich says that if your device has compute capability greater than 2.0 then you can use printf() function in the CUDA kernel. When I tried the same I get the error"calling ahostfunction("printf") from aglobalfunction("mat_mul") is not allowed", but when I run same code on eclipse nsight I get the expect... |
The error you refer to:
"calling a host function("printf") from a global function("mat_mul") is not allowed"
arises fromcompilingthe code, not running the code.
So the difference lies in how your are compiling from "nvcc in terminal" vs. how it is set up to compile in nsight.
If you compile in the terminal with th... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
For example:
Ifrprng(seed,index)is my function, then for any pair of(seed,index), I should always get the ... |
A simple idea is to use a PRNG that is so thorough that the values generated byseed,seed+1,seed+2... are acceptably random. E.g.:
```
#include <random>
unsigned prng(unsigned seed, unsigned index)
{
thread_local std::mt19937 engine; // or a different engine
engine.seed(seed + index);
return engine();
}
```
... |
I'm attempting to bitshift the value0xFFFFFFFFby 32 bits, and it correctly comes to
0 if I write
```
x = x << 32;
```
however it stays as0xFFFFFFFF
when I write:
```
x = x << y
```
wheny = 32
I really don't understand this at all.
I need to be able to use a variable though, for a function that shifts by32 - n
... |
It isundefined behaviorto shift by the bit length of a variable or greater. From the draft C99 standard section6.5.7Bitwise shift operators:
[...]If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
As Pascal says, you need to... |
I downloaded theSDL_gfxand did all the stuff (./configure,make install, ...), and even the make checks, but when I'm trying to use the actual function in a source code, it says :
```
undefined reference to pixelColor.
```
I included<SDL/SDL_gfxPrimitives.h>, and inside the.hfile, there is
```
int pixelColor(SDL_Sur... |
For now I use-lSDL -lSDL_ttf
Link against SDL_gfx too:-lSDL_gfx
You should probably usepkg-configthough:
```
`pkg-config sdl SDL_ttf SDL_gfx --libs`
```
That'll spit out everything you need, library-wise:
```
-lSDL_ttf -lSDL_gfx -lSDL
```
|
I am using a serial port in my c program. If there is nothing connected to this serial port, what can I expect from a call of read( )in my program? Would the program hang or return an error?
Thank you!
|
From theman pageit would probably returnEBADF.
Have you tried it? If not, it might be better to tell us what you want to achieve (block until something is connected, throw an error, etc.) so users can better guide you.
|
I have 2 enums.
```
typedef enum {
BLUE = 1,
RED = 2
} FavoriteColor;
typedef enum {
ORANGE = 1,
YELLOW = 2,
RED = 3
} Color;
```
In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?
|
You can't. And the compiler should warn you about that.
enumconstants live in the global namespace. The second definition is a redefinition that should produce an error.
|
Can somebody please explain me way thefree(test[0])is giving me asegmentation fault (core dumped)? I've tried to comment out the free and then the program terminates correctly (except from the lost memory). Also if I comment outtest[0] = "abcd"and insert thefree(...)again it terminates correctly too!?
```
char **test... |
Use strcpy instead of == , because here, you just gives test[0] the adresse of a static chain "abcd", that cannot be disallocated like that.
|
This question already has answers here:What does ## mean for the C(C++) preprocessor?(4 answers)How, exactly, does the double-stringize trick work?(2 answers)Closed9 years ago.
I was looking at the source code of the berkeley lab checkpoint/restart and found this pre-process macro definition:
```
#define io_wrap(_op... |
It's token concatenation. See the GCC manual:http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html
And for some of its nitty gritty details, see this question:How to concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?
|
Why I need the nested braces to compile this code?
```
#include <stdio.h>
#include <stdlib.h>
typedef union TEST TEST;
union TEST {
int type;
char *things;
};
int main () {
TEST test[] = {1, 2, .things = NULL}; // Compile time error
TEST test[] = {1, 2, {.things = NULL}}; // Works, but I didn't... |
The fact that you don't need inner braces on the first two elements is an odd detail in the syntax for initializer lists, which allows a union to be initialized as its first element. I would suggest using braces and designation forallthe initializers in the list, not just.things.
|
i'm working since a few weeks on the same project and never had this kind or error.
I got it now without touching to the concerned file, which is down there:
```
#ifndef DIJKSTRA_H_INCLUDED
#define DIJKSTRA_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INFINI 100000.0
typedef struc... |
I suspect the error lies in the file the header shown is included from, or in a file included just before this one.
|
I'm attempting to bitshift the value0xFFFFFFFFby 32 bits, and it correctly comes to
0 if I write
```
x = x << 32;
```
however it stays as0xFFFFFFFF
when I write:
```
x = x << y
```
wheny = 32
I really don't understand this at all.
I need to be able to use a variable though, for a function that shifts by32 - n
... |
It isundefined behaviorto shift by the bit length of a variable or greater. From the draft C99 standard section6.5.7Bitwise shift operators:
[...]If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
As Pascal says, you need to... |
I downloaded theSDL_gfxand did all the stuff (./configure,make install, ...), and even the make checks, but when I'm trying to use the actual function in a source code, it says :
```
undefined reference to pixelColor.
```
I included<SDL/SDL_gfxPrimitives.h>, and inside the.hfile, there is
```
int pixelColor(SDL_Sur... |
For now I use-lSDL -lSDL_ttf
Link against SDL_gfx too:-lSDL_gfx
You should probably usepkg-configthough:
```
`pkg-config sdl SDL_ttf SDL_gfx --libs`
```
That'll spit out everything you need, library-wise:
```
-lSDL_ttf -lSDL_gfx -lSDL
```
|
I am using a serial port in my c program. If there is nothing connected to this serial port, what can I expect from a call of read( )in my program? Would the program hang or return an error?
Thank you!
|
From theman pageit would probably returnEBADF.
Have you tried it? If not, it might be better to tell us what you want to achieve (block until something is connected, throw an error, etc.) so users can better guide you.
|
I have 2 enums.
```
typedef enum {
BLUE = 1,
RED = 2
} FavoriteColor;
typedef enum {
ORANGE = 1,
YELLOW = 2,
RED = 3
} Color;
```
In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?
|
You can't. And the compiler should warn you about that.
enumconstants live in the global namespace. The second definition is a redefinition that should produce an error.
|
Can somebody please explain me way thefree(test[0])is giving me asegmentation fault (core dumped)? I've tried to comment out the free and then the program terminates correctly (except from the lost memory). Also if I comment outtest[0] = "abcd"and insert thefree(...)again it terminates correctly too!?
```
char **test... |
Use strcpy instead of == , because here, you just gives test[0] the adresse of a static chain "abcd", that cannot be disallocated like that.
|
This question already has answers here:What does ## mean for the C(C++) preprocessor?(4 answers)How, exactly, does the double-stringize trick work?(2 answers)Closed9 years ago.
I was looking at the source code of the berkeley lab checkpoint/restart and found this pre-process macro definition:
```
#define io_wrap(_op... |
It's token concatenation. See the GCC manual:http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html
And for some of its nitty gritty details, see this question:How to concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?
|
Why I need the nested braces to compile this code?
```
#include <stdio.h>
#include <stdlib.h>
typedef union TEST TEST;
union TEST {
int type;
char *things;
};
int main () {
TEST test[] = {1, 2, .things = NULL}; // Compile time error
TEST test[] = {1, 2, {.things = NULL}}; // Works, but I didn't... |
The fact that you don't need inner braces on the first two elements is an odd detail in the syntax for initializer lists, which allows a union to be initialized as its first element. I would suggest using braces and designation forallthe initializers in the list, not just.things.
|
i'm working since a few weeks on the same project and never had this kind or error.
I got it now without touching to the concerned file, which is down there:
```
#ifndef DIJKSTRA_H_INCLUDED
#define DIJKSTRA_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INFINI 100000.0
typedef struc... |
I suspect the error lies in the file the header shown is included from, or in a file included just before this one.
|
I am using a serial port in my c program. If there is nothing connected to this serial port, what can I expect from a call of read( )in my program? Would the program hang or return an error?
Thank you!
|
From theman pageit would probably returnEBADF.
Have you tried it? If not, it might be better to tell us what you want to achieve (block until something is connected, throw an error, etc.) so users can better guide you.
|
I have 2 enums.
```
typedef enum {
BLUE = 1,
RED = 2
} FavoriteColor;
typedef enum {
ORANGE = 1,
YELLOW = 2,
RED = 3
} Color;
```
In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?
|
You can't. And the compiler should warn you about that.
enumconstants live in the global namespace. The second definition is a redefinition that should produce an error.
|
Can somebody please explain me way thefree(test[0])is giving me asegmentation fault (core dumped)? I've tried to comment out the free and then the program terminates correctly (except from the lost memory). Also if I comment outtest[0] = "abcd"and insert thefree(...)again it terminates correctly too!?
```
char **test... |
Use strcpy instead of == , because here, you just gives test[0] the adresse of a static chain "abcd", that cannot be disallocated like that.
|
This question already has answers here:What does ## mean for the C(C++) preprocessor?(4 answers)How, exactly, does the double-stringize trick work?(2 answers)Closed9 years ago.
I was looking at the source code of the berkeley lab checkpoint/restart and found this pre-process macro definition:
```
#define io_wrap(_op... |
It's token concatenation. See the GCC manual:http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html
And for some of its nitty gritty details, see this question:How to concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?
|
Why I need the nested braces to compile this code?
```
#include <stdio.h>
#include <stdlib.h>
typedef union TEST TEST;
union TEST {
int type;
char *things;
};
int main () {
TEST test[] = {1, 2, .things = NULL}; // Compile time error
TEST test[] = {1, 2, {.things = NULL}}; // Works, but I didn't... |
The fact that you don't need inner braces on the first two elements is an odd detail in the syntax for initializer lists, which allows a union to be initialized as its first element. I would suggest using braces and designation forallthe initializers in the list, not just.things.
|
i'm working since a few weeks on the same project and never had this kind or error.
I got it now without touching to the concerned file, which is down there:
```
#ifndef DIJKSTRA_H_INCLUDED
#define DIJKSTRA_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INFINI 100000.0
typedef struc... |
I suspect the error lies in the file the header shown is included from, or in a file included just before this one.
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed9 years ago.
I'm currently learning C, and my teacher gave us some homework. We had to identify the output of some code. I don't understand howy=4.
The code is as follows
```
int main() ... |
The behaviour is undefined since you modify the value of a variable twice between two sequence points.
You should read more about sequence pointshttp://en.wikipedia.org/wiki/Sequence_point.This is what the Standard says about it:
At certain specified points in the execution sequence called sequence points, all side ... |
Array initialization Code:
```
int m = 100;
int n = 50;
int i = 0, j = 0;
float **a = (float**)malloc(m*sizeof(float*));
for (i = 0; i < m; i++)
{
a[i] = (float*)malloc(n*sizeof(float));
for (j = 0; j < n; j++)
a[i][j] = i + j;
}
```
ais a 2D array and I want to traverse and update the elements of ... |
I guessais a 2 dimensional array likeint a[10][20], then the given statementa[i]++is "invalid".
The reason is that since a[i] being an array a[i] is a non-modifiable 'lvalue'.
In the above case*a[i]is valid but not thea[i]++
|
I am able to run a client and server on the same computer on two different terminals in Linux. Now I want to run the same model on two different computers. I am guessing there is more to this than just changing the IP address and the port number to that of the Server.
Any guidance on the matter is highly appreciated.... |
Make sure the port is forwarded in your router and exceptions for the port is added to the firewall. Then you should be ready to go!
If you have the computers in the same network you can do it without forwarding your port.
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question
Botha[i]and*(a + i)access theith element of arraya.
Are there reasons to prefer one... |
Neither one is better from a language point of view since they are the same, array indexing should just be syntactic sugar for pointer arithmetic. We can see this from thedraft C99 standardsection6.5.2.1Array subscriptingwhich says (emphasis mine):
[...]The definition of the subscript operator [] is that E1[E2] iside... |
I have an array that is already sorted in partitions of 4:
```
2, 23, 45, 55, 1, 4, 23, 74545, 75, 234, 323, 9090, 2, 43, 6342, 323452
```
What would be the most efficient way to sort this array? Note: the array size is always even and the program knows that every 4 elements are sorted.
|
I think you can usemerge sortfor problems like this.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.