question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
In how many ways we can declare an array in C programming? if there are many ways to declare an array in C, what are the best practices or best way among?
So far I have been initializing an array like this:
```
int myArray[SIZE] = {1,2,3,4....};
```
What are the other ways do the same?
|
From C99, you can also use explicit indexes, calleddesignators, in the initializer expression, which is sometimes very nice:
```
const int threetoone[] = { [2] = 1, [1] = 2, [0] = 3 };
```
The above is the same as
```
const int threetwoone[] = { 3, 2, 1 };
```
|
I am trying to find all places where#includeis placed insideexternCblock. Is is possible to check this using preprocessor? I would like to do add something like this to my header files:
```
#ifdef EXTERN_C_IS_IN_EFFECT
#error File included from extern "C" block!
#endif
```
I am also looking for other ways to fail compilation in such case, e.g. use some special attribute. I am using gcc 4.4.7.
I defined following macro and then use it in every header which needs protection against inclusion inexternCblock:
```
#define ASSERT_NO_EXTERN_C void assert_no_extern_c(int); void assert_no_extern_c(double);
```
|
Maybe you can define 2 function prototypes with same name and different parameters. You will get warnings in case of extern "C" block. And it is allowed in C++.
|
I want to usestrcmpto compare the subset of a string with another string.
Say I have:
a[] = {'h','e','l','l','o',' ','w','o','r','l',d'};
and
b[] = {'w','o','r','l','d};
I want to compare the second word ofawith the entire stringb. I know the starting index of the second word ina. Is there a way to do this directly usingstrcmpor does more word onaneed to be done first?
|
aandbarechararrays, but they are not strings, because they are not null-terminated.
If they were modified to null-terminated like this:
```
char a[] = {'h','e','l','l','o',' ','w','o','r','l','d', '\0'};
char b[] = {'w','o','r','l','d', '\0'};
```
And the index of the second word ofais known like you said, then yes, you can usestrcmp(a + 6, b)to compare.
|
First, I usedbind()andlisten()to bind a port to address 0.0.0.0. However, now I cannot connect.
```
sprintf (addrbuf, "%s-%d", SVR_ADDR, SVR_PORT);
StringToSockaddr (addrbuf, &destAddr);
if (connect(psock,(struct sockaddr *) &destAddr,sizeof(destAddr)) < 0)
die("failed to connect to server");
printf("connected to server at %s\n",getTime());
```
|
Thebind()function assigns a local address and/or port to the socket. This is well and good. Thelisten()function, however, configures the socket as one that willacceptconnections. If you intend to use the socket to initiate a connection to a remote machine, then you should not uselisten()on it.
|
My question involves methods like memset and strcat that return pointers that were passed as arguments. For instance:
Case 1:
```
const char *src = /*assign space*/;
char *dst = /*assign space*/;
dst = strcat(dst, src);
```
Case 2:
```
const char *src = /*assign space*/;
char *dst = /*assign space*/;
strcat(dst, src);
```
Can case 2 be considered unsafe peradventure the called function changes the memory pointed to. Should the explicit reassignment of case 1 be used always?
If to use case 2, can a variant:
```
char * const dst = /*assign space*/;
```
be used to ensure that the pointer remains the same after the call?
|
Both of your cases would be just as safe, but the extra assignment in the first one is not needed.
strcatdoesn't reallocate anything, and doesn't "changes the memory pointed to", so there's no need to take the return value here. The pointer isguaranteedto remain the same after the call.
|
Hi i am trying to build a java program but i need run a C program with arguments and after i need get the return value..
Here is what i have done.
```
public static void main(String[] args) throws IOException {
ProcessBuilder pr = new ProcessBuilder("C:\\Users\\MyFolder\\Desktop\\MyExe.exe", "param1", "param2");
Process process = pr.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
```
|
You can use:
```
int retVal = process.waitFor()
```
to block execution until the process is finished, and returns the return value.
See the docs forProcesshere:http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#waitFor()
|
I'm trying to determine array length ofmsgon the below code. I usedstrlenandsizeofbut they don't return 6. What function can I use to determine the length ofuint8_tarray or how can I modify the below code (osal_DataLenght()func)?
```
int osal_DataLength( char *pString ){
return (int)( strlen( pString ) );
}
void setNewLevel( uint8_t newLevel ){ //GW specific
uint8_t msg[8] = {'\0'};
msg[0] = '0';
msg[1] = '7';
msg[6]= newLevel;
//msg[7] = '0';
printf("the array length:%d\n", osal_DataLength(msg) );
}
int main(void){
setNewLevel(0xD5);
return 0;
}
```
|
To know the size of your array, write (insetNewLevel()as said @Dabo) :
```
sizeof(msg)/sizeof(uint8_t);
```
strlen()returns the size of a string (char array terminated byNULL, ie'\0'). You CAN'T use it in this context, since :
msg[2]tomsg[5]values are not initializedmsgis not acharsequence terminated byNULL.
|
This is a school assignment but I cannot get my loop to work. We have to use scanf and terminate the loop when an EOF is inputted. This is the part of the code that is the problem:
```
{int
main(void){
char str[MAX];
while(scanf("%s", str) != EOF)
{
printf("\nEnter a String: ");
scanf("%s", str);
two_ele_subs(str);
}
return 0;
}
```
|
The sscanf returns the number of read variables, that in your case is only one, or EOF (ie: -1) in case of end of file. So I suggest you to use a different approach, like in the following:
```
#include <stdio.h>
#define MAX 100
int main(void){
char str[MAX];
int retVal;
printf("\nEnter a String: ");
while((retVal = scanf("%s", str)) == 1 || retVal != EOF)
{
printf("\nEnter a String: ");
two_ele_subs(str);
}
return 0;
}
```
|
I want to be able to do this in visual studio:
```
struct A
{
int x;
};
struct B
{
int y;
struct A;
};
struct B b;
b.x //...
```
How can I do this? In gcc you use -fms-extensions to compile it
|
Youjust do it.MSVS supports this as an extension.
|
First, I usedbind()andlisten()to bind a port to address 0.0.0.0. However, now I cannot connect.
```
sprintf (addrbuf, "%s-%d", SVR_ADDR, SVR_PORT);
StringToSockaddr (addrbuf, &destAddr);
if (connect(psock,(struct sockaddr *) &destAddr,sizeof(destAddr)) < 0)
die("failed to connect to server");
printf("connected to server at %s\n",getTime());
```
|
Thebind()function assigns a local address and/or port to the socket. This is well and good. Thelisten()function, however, configures the socket as one that willacceptconnections. If you intend to use the socket to initiate a connection to a remote machine, then you should not uselisten()on it.
|
My question involves methods like memset and strcat that return pointers that were passed as arguments. For instance:
Case 1:
```
const char *src = /*assign space*/;
char *dst = /*assign space*/;
dst = strcat(dst, src);
```
Case 2:
```
const char *src = /*assign space*/;
char *dst = /*assign space*/;
strcat(dst, src);
```
Can case 2 be considered unsafe peradventure the called function changes the memory pointed to. Should the explicit reassignment of case 1 be used always?
If to use case 2, can a variant:
```
char * const dst = /*assign space*/;
```
be used to ensure that the pointer remains the same after the call?
|
Both of your cases would be just as safe, but the extra assignment in the first one is not needed.
strcatdoesn't reallocate anything, and doesn't "changes the memory pointed to", so there's no need to take the return value here. The pointer isguaranteedto remain the same after the call.
|
I'm encountering issues when trying to compile my C code on Win64. More specifically, the compiler cannot find thesys/mman.hheader, which I understand is found in Unix environments only.
I already know this is deals with memory allocation.
Is there an equivalent for Windows I can use in order to port the code (first time trying)?
Code in that causes issues:
```
/* Allocate memory required by processes */
buf = (int*) malloc (sizeof(int));
if (!buf)
{
perror("Error");
free (buf);
return -3;
}
/* Lock down pages mapped to processes */
puts("Locking down processes.");
if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0)
{
perror("mlockall");
free (buf);
return -4;
}
```
|
You should look at themman-win32 library. But as @Mgetz pointed out, a more simple way is to look at theVirtualAllocExfunctions and try to adapt your code.
|
Basically, I can't figure this out, I want my C program to store the entire plaintext of a batch program then insert in a file and then run.
I finished my program, but holding the contents is my problem. How do I insert the code in a string and make it ignore ALL special characters like %s \ etc?
|
You have to escape special characters with a \, you can escape backslash itself with another backslash (i.e.\\).
|
I am new to Visual Studio 2013, having used 2010 in the past. How do I add a C file? There only seems to be an option for C++. I do not use C++, only C, and I compile to ANSI C99. This is what the dialog box looks like when I pick "Add New Item":
As you can see it has choices to add a C++ file or a header file, but not a C file.
|
Short answer: you can't.
Visual C++ is a C++ IDE backed by a C++ compiler. It supports the common subset of C and C++ (because it is also valid C++), but does not directly support C. It only partially supports C99. So there is no way to add a file that will be compiled as C99 to a project.
|
Consider the following program
```
void main(){
char t = 179;
printf("%d ",t);
}
```
Output is -77.
But binary representation of 179 is
```
10110011
```
So, shouldn't output be -51, considering 1st bit is singed bit.
Binary representation of -77 is
```
11001101
```
It seems bit order is reversed. What's going on? Please somebody advice.
|
You claimed that the binary representation of-77is11001101, but the reversal is yours. The binary representation of-77is10110011.
Binary10110011unsigned is decimal179.
Binary10110011signed is decimal-77.
You assigned the out-of-range value179to asigned char. It might theoretically be Undefined Behaviour, but apart from throwing an error, it would be a very poor compiler that placed anything but that 8-bit value in thesigned char.
But when printed, it's interpreted as a negative number because b7 is set.
|
I'm trying to write the code below in C but I have a real problem with doing that so if someone can help me out and explain to me in the same time I'd be grateful.
```
array .word ?
mystery:
add r2,r0,r0
addi r7,r0,32
loop:
movia r4, array
slli r3,r2,2
add r5,r3,r4
ldw r14, (r5)
add r15, r3, r14
stw r0, (r15)
addi r2, r2, 1
bge r7,r2,loop
ret
```
|
I don't believe thatarray .word ?is correct syntax. I think it is just representing that there is an array of some size at the location array. Here's the translation:
```
int *array[];
void mystery () {
int r2;
int *r14;
for (r2 = 0; r2 <= 32; r2++) {
r14 = array[r2];
r14[r2] = 0;
}
}
```
|
I'm encountering issues when trying to compile my C code on Win64. More specifically, the compiler cannot find thesys/mman.hheader, which I understand is found in Unix environments only.
I already know this is deals with memory allocation.
Is there an equivalent for Windows I can use in order to port the code (first time trying)?
Code in that causes issues:
```
/* Allocate memory required by processes */
buf = (int*) malloc (sizeof(int));
if (!buf)
{
perror("Error");
free (buf);
return -3;
}
/* Lock down pages mapped to processes */
puts("Locking down processes.");
if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0)
{
perror("mlockall");
free (buf);
return -4;
}
```
|
You should look at themman-win32 library. But as @Mgetz pointed out, a more simple way is to look at theVirtualAllocExfunctions and try to adapt your code.
|
Basically, I can't figure this out, I want my C program to store the entire plaintext of a batch program then insert in a file and then run.
I finished my program, but holding the contents is my problem. How do I insert the code in a string and make it ignore ALL special characters like %s \ etc?
|
You have to escape special characters with a \, you can escape backslash itself with another backslash (i.e.\\).
|
I am new to Visual Studio 2013, having used 2010 in the past. How do I add a C file? There only seems to be an option for C++. I do not use C++, only C, and I compile to ANSI C99. This is what the dialog box looks like when I pick "Add New Item":
As you can see it has choices to add a C++ file or a header file, but not a C file.
|
Short answer: you can't.
Visual C++ is a C++ IDE backed by a C++ compiler. It supports the common subset of C and C++ (because it is also valid C++), but does not directly support C. It only partially supports C99. So there is no way to add a file that will be compiled as C99 to a project.
|
Consider the following program
```
void main(){
char t = 179;
printf("%d ",t);
}
```
Output is -77.
But binary representation of 179 is
```
10110011
```
So, shouldn't output be -51, considering 1st bit is singed bit.
Binary representation of -77 is
```
11001101
```
It seems bit order is reversed. What's going on? Please somebody advice.
|
You claimed that the binary representation of-77is11001101, but the reversal is yours. The binary representation of-77is10110011.
Binary10110011unsigned is decimal179.
Binary10110011signed is decimal-77.
You assigned the out-of-range value179to asigned char. It might theoretically be Undefined Behaviour, but apart from throwing an error, it would be a very poor compiler that placed anything but that 8-bit value in thesigned char.
But when printed, it's interpreted as a negative number because b7 is set.
|
I'm trying to write the code below in C but I have a real problem with doing that so if someone can help me out and explain to me in the same time I'd be grateful.
```
array .word ?
mystery:
add r2,r0,r0
addi r7,r0,32
loop:
movia r4, array
slli r3,r2,2
add r5,r3,r4
ldw r14, (r5)
add r15, r3, r14
stw r0, (r15)
addi r2, r2, 1
bge r7,r2,loop
ret
```
|
I don't believe thatarray .word ?is correct syntax. I think it is just representing that there is an array of some size at the location array. Here's the translation:
```
int *array[];
void mystery () {
int r2;
int *r14;
for (r2 = 0; r2 <= 32; r2++) {
r14 = array[r2];
r14[r2] = 0;
}
}
```
|
Am I handling the pointer the wrong way? I want to update the value of a variable by passing it's address to the function.
```
void func(int *p){
int x = 3;
p = &x;
}
int main(){
int y = 0;
func(&y);
printf("\n Value = %d",y);
}
```
I get the following output:
Value = 0
Exited: ExitFailure 11
|
You must dereference the pointer to replace the value on which the pointer points.
See:
```
#include <stdio.h>
void func(int *p){
int x = 3;
*p = x;
}
int main(){
int y = 0;
func(&y);
printf("\n Value = %d",y);
return 0;
}
```
To remove the exit failure add the return 0; statement into the main function.
See running example:http://ideone.com/rO8Gua
|
I'm trying to make a program that prints out the ^2, ^4, and ^(1/3) of all even numbers between 0 and 100. This is what I have.
```
#include <stdio.h>
#include <math.h>
main(){
int a, b, c, i;
for (i=0; i<100; i=i+2;)
a = (1*1);
b = (i*i*i*i);
c = pow(i, (1/3));
printf("%d, %d, %d", a, b, c);
return 0;
}
```
It's giving me an error on line 6 that says
```
error: expected ')' before ';' token.
```
This is my first day with c so I'm really stymied right now.
|
A for loop is expected to look like:
```
for (initialization; condition; increment/decrement)
```
Yours doesn't look like that. Note that there are exactly two semicolons inside the parentheses.
|
So I have a struct as follows:
```
typedef struct {
......
char* filenames[];
}
int myFunction(char* filenames[]) {
myStruct->filenames = filenames;
}
```
This is giving me an "invalid use of flexible array member" error. Why is this? I know that I can't malloc my structs array so I am not sure how I would even use it if I can't assign values to it.
|
You need to usechar** filenames.c++doesn't accept variable length arrays.
Seeexample.
As a suggestion, not an answer, use astd::string. Or if you need the container,std::vector<std::string>.
|
I don't really understand how fork() works.I understand examples with one fork,but when there are more than one call I don't.I have an example like this and it prints 4 lines of hello, how many processes are created?
```
int main(void)
{
fork();
fork();
printf("hello\n");
return 0;
}
```
|
Afterfork()call, both processes (original and spawned) continue to execute from next line of code. So both processes execute secondfork()instruction, so in the end you have4processes. Hence you see 4 instances of"hello"lines printed.
One picture is worth a thousand words:
|
I'm trying to make a program that prints out the ^2, ^4, and ^(1/3) of all even numbers between 0 and 100. This is what I have.
```
#include <stdio.h>
#include <math.h>
main(){
int a, b, c, i;
for (i=0; i<100; i=i+2;)
a = (1*1);
b = (i*i*i*i);
c = pow(i, (1/3));
printf("%d, %d, %d", a, b, c);
return 0;
}
```
It's giving me an error on line 6 that says
```
error: expected ')' before ';' token.
```
This is my first day with c so I'm really stymied right now.
|
A for loop is expected to look like:
```
for (initialization; condition; increment/decrement)
```
Yours doesn't look like that. Note that there are exactly two semicolons inside the parentheses.
|
So I have a struct as follows:
```
typedef struct {
......
char* filenames[];
}
int myFunction(char* filenames[]) {
myStruct->filenames = filenames;
}
```
This is giving me an "invalid use of flexible array member" error. Why is this? I know that I can't malloc my structs array so I am not sure how I would even use it if I can't assign values to it.
|
You need to usechar** filenames.c++doesn't accept variable length arrays.
Seeexample.
As a suggestion, not an answer, use astd::string. Or if you need the container,std::vector<std::string>.
|
I don't really understand how fork() works.I understand examples with one fork,but when there are more than one call I don't.I have an example like this and it prints 4 lines of hello, how many processes are created?
```
int main(void)
{
fork();
fork();
printf("hello\n");
return 0;
}
```
|
Afterfork()call, both processes (original and spawned) continue to execute from next line of code. So both processes execute secondfork()instruction, so in the end you have4processes. Hence you see 4 instances of"hello"lines printed.
One picture is worth a thousand words:
|
I am making a program in C in which I am trying to use the values of local variable in other function. Lets say I have two functionfoo1foo2.
```
int foo1()
{
int a=2,b=3,c;
c=a+b;
return c;
}
int foo2(int c)
{
printf("Value of C is %d",c);
}
```
is this method correct, if not what else is the way to use values of local variable in other function?
|
first of all, this two functions foo1() and foo2() are not related...
and local variables have block scope only.
If you want to use them in other functions make them global or use pass by value and pass by reference methods to pass the variables from one function to others...
|
I write a pam module that is called when user execute the sudo command. I have already got theusername,password,tty, but now, I have to get the user command to encrypt.
If user exec
```
sudo ls -l
```
I have to getls -l
I have no pam app for my module. (So I use onlypam_modules.h) and my module is called first in/etc/pam.d/sudo
I thought about using thenetlinksocket likepam_tty_audit, but I don't thinks this is the best method (or the most simple)
Have you any idea for getting the user command ?
Thank you and sorry for my bad english
|
According tothe API documentation of sudo's authentication mechanisms, the command is not passed to the authentication backend, so PAM is the wrong place to do whatever you are trying to do. Consider writing asudo plugininstead.
|
I'm working on a project using msp430. How can i read the value received by a specific port and assign it to a variable? Like P1.5 ? I already set P1DIR to input.
I did:
```
data = (P1IN & SDA_TMP); // Where SDA_TMP is a defined prep
```
|
Something like this:
```
const bool data = (P1IN & (1 << 5)) != 0;
```
This uses bitwise and (&) to mask out the fifth bit (whose value is1 << 5), then does a comparison against zero. The result indatawill betrueif bit 5 is set,falseif it isn't.
See alsothis tutorialfor more.
|
I am making a program in C in which I am trying to use the values of local variable in other function. Lets say I have two functionfoo1foo2.
```
int foo1()
{
int a=2,b=3,c;
c=a+b;
return c;
}
int foo2(int c)
{
printf("Value of C is %d",c);
}
```
is this method correct, if not what else is the way to use values of local variable in other function?
|
first of all, this two functions foo1() and foo2() are not related...
and local variables have block scope only.
If you want to use them in other functions make them global or use pass by value and pass by reference methods to pass the variables from one function to others...
|
I write a pam module that is called when user execute the sudo command. I have already got theusername,password,tty, but now, I have to get the user command to encrypt.
If user exec
```
sudo ls -l
```
I have to getls -l
I have no pam app for my module. (So I use onlypam_modules.h) and my module is called first in/etc/pam.d/sudo
I thought about using thenetlinksocket likepam_tty_audit, but I don't thinks this is the best method (or the most simple)
Have you any idea for getting the user command ?
Thank you and sorry for my bad english
|
According tothe API documentation of sudo's authentication mechanisms, the command is not passed to the authentication backend, so PAM is the wrong place to do whatever you are trying to do. Consider writing asudo plugininstead.
|
I'm working on a project using msp430. How can i read the value received by a specific port and assign it to a variable? Like P1.5 ? I already set P1DIR to input.
I did:
```
data = (P1IN & SDA_TMP); // Where SDA_TMP is a defined prep
```
|
Something like this:
```
const bool data = (P1IN & (1 << 5)) != 0;
```
This uses bitwise and (&) to mask out the fifth bit (whose value is1 << 5), then does a comparison against zero. The result indatawill betrueif bit 5 is set,falseif it isn't.
See alsothis tutorialfor more.
|
I write a pam module that is called when user execute the sudo command. I have already got theusername,password,tty, but now, I have to get the user command to encrypt.
If user exec
```
sudo ls -l
```
I have to getls -l
I have no pam app for my module. (So I use onlypam_modules.h) and my module is called first in/etc/pam.d/sudo
I thought about using thenetlinksocket likepam_tty_audit, but I don't thinks this is the best method (or the most simple)
Have you any idea for getting the user command ?
Thank you and sorry for my bad english
|
According tothe API documentation of sudo's authentication mechanisms, the command is not passed to the authentication backend, so PAM is the wrong place to do whatever you are trying to do. Consider writing asudo plugininstead.
|
I'm working on a project using msp430. How can i read the value received by a specific port and assign it to a variable? Like P1.5 ? I already set P1DIR to input.
I did:
```
data = (P1IN & SDA_TMP); // Where SDA_TMP is a defined prep
```
|
Something like this:
```
const bool data = (P1IN & (1 << 5)) != 0;
```
This uses bitwise and (&) to mask out the fifth bit (whose value is1 << 5), then does a comparison against zero. The result indatawill betrueif bit 5 is set,falseif it isn't.
See alsothis tutorialfor more.
|
I am trying to use a function with a string as a parameter. I am running into a couple of error messages. First, it says that string[i] is not an array, pointer, or vector, despite the fact that string is a character array. Secondly, it says that I am doing a pointer to integer conversion. Here is my code:
```
#include <stdio.h>
#include <string.h>
void example (char string) {
int i;
for (i = 0; i < strlen(string); i++) {
printf (string[i]);
}
}
int main (void) {
example("I like pie");
return 0;
}
```
|
void example(char string)should bevoid example(char *string). You declared it to take a character, you want it to take a character pointer or array.
Also, you need to tellprintfyou are giving it a character:printf("%c", string[i]);.
|
Consider there is a path from source to destination but is jumbled up.
For example
```
A B E F
B C A B
C D -> D E
D E C D
E F B C
```
Assuming there are no cycles, Given the Jumbled path can we get back the original path in O(n) time.
|
The start of the path is the element that appears as the first thing in a pair, but not the second. Build a map from start to next node in the path, and iterate through it.
Each of the three steps is O(n), giving an O(n) overall solution.
Here's some example code in Python 2.7:
```
import sys
follow = dict(line.strip().split() for line in sys.stdin)
x = set(follow).difference(follow.itervalues()).pop()
while x:
print x
x = follow.get(x)
```
Example run:
```
$ echo -e "E F\nA B\nD E\nC D\nB C" | python follow.py
A
B
C
D
E
F
```
|
Can someone explain to me how it displays the value of x[2]?
When the array index is x[4].
```
Array x
{
x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]
16.0 12.0 6.0 8.0 2.5 12.0 14.0 β54.5
printf("%.1f", x[(int)x[4]]); Displays 6.0 (value of x[2])
}
```
|
x[4] has a value 2.5, when prefixed with "(int)" what happens is that you "cast" the resulting value into an integer thereby dropping the decimal part without doing any rounding-off to it. This is called "Type casting" or converting from one data type to another. In this case, the value of x[4] which is in "float" is converted into an integer.
The equation will become:
x[ (int)x[4] ] = x[ 2 ] = 6.0
|
I am getting
Msg(3:4130) Bitwise operations on signed data will give implementation defined results
this warning in QAC. The code like
```
functionName( a | b | c);
```
QAC on PIC micro controller code. Anyone can explain. what is this warning and how to avoid this warning.
|
Don't use signed integers for bitwise operations, useunsigned.
That is what the warning is telling you.
You don't show the types ofa,bandc, so it's hard to be more specific.
|
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.Closed8 years ago.Improve this question
How I can get the filename when I click on it using Win API ?
I need to get the text from any mouse clicked object on the screen using Win API,
I was able to get the text inside GUI Application (ex:button) usingWindowFromPoint, but I need to know the filename when I click on a file on the Desktop, or Explorer.
|
Possible workaround is clicking twice (not double click), emulating Ctrl+A and Ctrl+C events and getting text from clipboard. Another way is using UI Automation API based framework (likeTeststack.White in C#) or calling UIA API immediately (seeAutomationElement.FromPoint).
|
I have a small project in C programing, Eclipse Linux. But when I build it I always get an error"undefined reference to `pthread_create'"at line
```
re = pthread_create(&interrupt, NULL, clientHandler, NULL);
```
I have no idea about I get this issue. I also searched and tried applying a solution discussed atEclipse Juno - GCC compiler pthreadbut it still appears. So, is there another way that I can apply to solve it?
Here is the code of minehttps://ide.c9.io/nkphuc700/cworkspace, the issue fires at line 51.
Error message on Console
|
You don't need Eclipse to build code. AFAIK, it will just run some builder commands (perhaps usingmake) which in turn runs theGCCcompiler.
You should compile withgcc -c -Wall -Wextra -pthread -gand link withgcc -pthread...your object files....-o yourprogram...your libraries...-lpthread
|
In C, we can build a debug version or a release version of the binary files (the object files and the executable). How can we do this in Go?
|
In Go, it isn't typical to have a debug version or a release version.
By default,go buildcombines symbol and debug info with binary files. However, you can remove the symbol and debug info withgo build -ldflags "-s -w".
|
I'm trying to work with inotify. For some reason inotifytools_next_event is blocking forever, despite putting a 0 in the timeout field. Did I miss something?
```
inotifytools_initialize();
inotifytools_watch_recursively(".", IN_CLOSE_WRITE|IN_DELETE|IN_MODIFY);
inotifytools_next_event(0);
```
|
Looks like there was an official bugreport.
Wich basically has been fixed by
```
Closed by Sergej Pupykin (sergej)
Wednesday, 04 March 2015, 12:31 GMT
Reason for closing: Fixed
```
Try to update theinotify-toolswith recent source changes.
|
```
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
```
What exactly is "book" at the end?
|
It is a declaration of an instance of a structure of typestruct Bookswith namebook.
It is equivalent to
```
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
struct Books book;
```
Take into account that in general declarations look like (simplified form)
```
type-sepcifier identifier;
```
where identifier is some declarator. For example
```
int x;
```
And a structure definition also belongs to type specifiers.
So you may write for example
```
struct A { int x; } s;
```
|
There is a C code and the I want to know where's a bad part.
```
int main() {
// PART A
int a = 12;
printf("%p\n", &a);
int *ptr = &a;
*ptr = 15;
printf("%i\n", a);
// PART B: something bad starts
ptr = (int*)12;
*ptr = 42;
printf("%i\n", *ptr);
}
```
In PART (B), Why is ptr = (int*)12 and *ptr = 42 bad programming in C?
|
The problem is:
```
ptr = (int*)12; // This will assign memory address 0x0000000C (12) to ptr
```
You are trying to assign memory address to a pointer without knowing whether it exist or not. The program may crash here.
Also :printf("%f\n", &a);β it should be"%p"
|
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.Closed8 years ago.Improve this question
How I can get the filename when I click on it using Win API ?
I need to get the text from any mouse clicked object on the screen using Win API,
I was able to get the text inside GUI Application (ex:button) usingWindowFromPoint, but I need to know the filename when I click on a file on the Desktop, or Explorer.
|
Possible workaround is clicking twice (not double click), emulating Ctrl+A and Ctrl+C events and getting text from clipboard. Another way is using UI Automation API based framework (likeTeststack.White in C#) or calling UIA API immediately (seeAutomationElement.FromPoint).
|
I have a small project in C programing, Eclipse Linux. But when I build it I always get an error"undefined reference to `pthread_create'"at line
```
re = pthread_create(&interrupt, NULL, clientHandler, NULL);
```
I have no idea about I get this issue. I also searched and tried applying a solution discussed atEclipse Juno - GCC compiler pthreadbut it still appears. So, is there another way that I can apply to solve it?
Here is the code of minehttps://ide.c9.io/nkphuc700/cworkspace, the issue fires at line 51.
Error message on Console
|
You don't need Eclipse to build code. AFAIK, it will just run some builder commands (perhaps usingmake) which in turn runs theGCCcompiler.
You should compile withgcc -c -Wall -Wextra -pthread -gand link withgcc -pthread...your object files....-o yourprogram...your libraries...-lpthread
|
In C, we can build a debug version or a release version of the binary files (the object files and the executable). How can we do this in Go?
|
In Go, it isn't typical to have a debug version or a release version.
By default,go buildcombines symbol and debug info with binary files. However, you can remove the symbol and debug info withgo build -ldflags "-s -w".
|
I'm trying to work with inotify. For some reason inotifytools_next_event is blocking forever, despite putting a 0 in the timeout field. Did I miss something?
```
inotifytools_initialize();
inotifytools_watch_recursively(".", IN_CLOSE_WRITE|IN_DELETE|IN_MODIFY);
inotifytools_next_event(0);
```
|
Looks like there was an official bugreport.
Wich basically has been fixed by
```
Closed by Sergej Pupykin (sergej)
Wednesday, 04 March 2015, 12:31 GMT
Reason for closing: Fixed
```
Try to update theinotify-toolswith recent source changes.
|
```
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
```
What exactly is "book" at the end?
|
It is a declaration of an instance of a structure of typestruct Bookswith namebook.
It is equivalent to
```
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
struct Books book;
```
Take into account that in general declarations look like (simplified form)
```
type-sepcifier identifier;
```
where identifier is some declarator. For example
```
int x;
```
And a structure definition also belongs to type specifiers.
So you may write for example
```
struct A { int x; } s;
```
|
There is a C code and the I want to know where's a bad part.
```
int main() {
// PART A
int a = 12;
printf("%p\n", &a);
int *ptr = &a;
*ptr = 15;
printf("%i\n", a);
// PART B: something bad starts
ptr = (int*)12;
*ptr = 42;
printf("%i\n", *ptr);
}
```
In PART (B), Why is ptr = (int*)12 and *ptr = 42 bad programming in C?
|
The problem is:
```
ptr = (int*)12; // This will assign memory address 0x0000000C (12) to ptr
```
You are trying to assign memory address to a pointer without knowing whether it exist or not. The program may crash here.
Also :printf("%f\n", &a);β it should be"%p"
|
Is it possible to load akernel extension(kext) through aC APIinstead of using thesystem()call?
|
Yes, you want theKextManagerAPI. In particular,KextManagerLoadKextWithIdentifier()is probably the function you'll want to use to load an installed kext, versusKextManagerLoadKextWithURL()if you want to load a kext that is not in /System/Library/Extensions or /Library/Extensions but e.g. in an .app bundle.
|
I need to read/write device registers (which in my case are in big endian address space) from both little endian cores (e.g. arm). I do not want to use intermediate endian conversion routines (e.g. htonl). My understanding is that modern cores have instructions using which they can do reads/writes to big endian memory directly.
Does gcc offer any builtin for the above which automatically generates right assembly instruction(s)?
|
There are built-in functions available from GCC 4.3.0:
Built-in Function: int32_t __builtin_bswap32 (int32_t x), it returns the order of byes reversed. for eg. 11223344 will be 0x44332211Built-in Function: int64_t __builtin_bswap64 (int64_t x)
is also similar to __builtin_bswap32, except that it returns 64 bits.
Please refer to theBeware the builtins.
|
My problem is: Input name and print out in the order
Ex: input the name : Martin Luther King
result : King,Martin-Luther
But when i run this code it prints out : King,LutherMartin-Luther. Can you help show me the mistake?
```
#include<stdio.h>
#include<conio.h>
#include <string.h>
int main()
{
char name[100];
int i;
printf("input full name: "); gets(name);
char * c =&name[strlen(name)-1];
while (*(c)!=' ')
c--;
printf("%s,",c);
*c= '\0';
char *d=&name;
while (*(d)!=' ')
d++;
printf("%s",d);
*d='-';
printf("%s",name);
getch();
return 0;
}
```
|
```
printf("%s",d);
```
is the root of the problem as it results in the extra print of the middle name. Simply remove that line.
|
I am just wondering out of curiosity, why is in C time structure
```
struct tm
```
used as this and not withtypedef. This way I always need to writestruct tm, to have a correct code. A lot of structures are "typedefed", why not this one?
|
Because it would be rather rude to pollute the general namespace with an unnecessarytypedefwhen the language has a separate namespace for struct tags. If you really want atypedefto hide the fact that it's astruct, you can easily provide one yourself without forcing it on the rest of us.
A lot of structures are "typedefed", why not this one?
I don't know why you say that; there are no typedefed structs in the C library.FILEis a typedef, but not necessarily a struct.
Maybe you mean that there are a lot in other bodies of code. That's because some people, like yourself, think that namespace pollution is a good idea for some reason. The C library authors don't.
|
How do you get input using prompt? I tried compiling the code bellow into "a.exe" and executing it from CMD like "gcc a.exe 5", but it doesn't output the number like it was supposed to.
```
#include <stdio.h>
int main(int a)
{
printf("%d\n", a);
return 1;
}
```
Have I done anything wrong when installing the compiler or am I trying to run it wrong?
|
Yourmain()parameters are wrong, you should do it this way:
```
int main(int argc, char **argv) {
if(argc > 2) {
printf("%s\n", argv[2]);
}
else {
printf("No arguments\n");
}
}
```
Note thatint argcrepresents the number of parameters andchar **argvis an array containing all the parameters, as strings, including "gcc", "a.exe", etc.
In your case, if you run your program this way:gcc a.exe 5, your parameters would be:argc = 3, argv = ["gcc", "a.exe", "5"]
|
Is there a way to print doubles in c using fprint so that the precision of the print is the least possible (So for example that an integer is always printed without decimals?)
I know that you can do something like printf("%.0f",number); But I am wondering if there is a way to use the minimum precision that makes the print exact (whenever the number can be expressed finitely in base 10 of course).
|
Allfinitedouble, encoded in base 10 or base 2 (the usual), or base 16 can beexactlyfinitely printed in base 10.DBL_MINmay take 100+ of digits to do so, but it is not infinite.printf()need not perform to that level. So it ends up being custom code and of course that can "printing doubles without zeros"
Recommendsprintf(buffer, "%.*e", DBL_DECIMAL_DIG - 1, some_double)and post-process the buffer to remove least significant0as needed for a "close enough" answer to code's goal.
Ref
|
This question already has answers here:Error "initializer element is not constant" when trying to initialize variable with const(8 answers)Closed8 years ago.
What is the reason for this?
```
const int a = 0;
static int b = a * 5; // compile error
int main()
{
const int x = 1;
static int y = x * 10; // compile error
}
```
|
According to C standard:
All the expressions in an initializer for an object that has static or thread storage duration
shall be constant expressions or string literals.
This is valid C++ code though.
|
I have the following code:
```
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
#define MAXSIZE 1024
typedef struct stack{
struct TreeNode volum[MAXSIZE];
int top;
}STACK;
STACK st;
st.top = -1;
/* other function definitions such as pop() and push() */
```
But when I compile it, it gives me errorLine 18: expected β=β, β,β, β;β, βasmβ or β__attribute__β before β.β token. Where Line 18 isst.top=-1;
So here I need to initialize the stack, i.e setting the top to -1. I also tried to do it inside the struct:int top=-1;But got the same error. I wonder what the correct way of doing it is. Thanks in advance.
|
You could try
```
typedef struct stack {
int top;
struct TreeNode volum[MAXSIZE];
} STACK;
STACK st = { -1 }; // top has to be the first member of the struct
```
|
```
int **arr; //For example: 4 by 3 array
```
How can I print 2d-array with comma and new line like below?
```
01, 02, 03, 04 // At last, new line without comma
05, 06, 07, 08
09, 10, 11, 12
```
I need the fastest method to print like it.
|
A simple solution for anym x nmatrix defined as a double pointer to type is:
```
/* print a (m x n) matrix */
void mtrx_prn (size_t m, size_t n, float **matrix)
{
register size_t i, j;
for (i = 0; i < m; i++)
{
char *pad = "[ ";
for (j = 0; j < n; j++)
{
printf ("%s%6.3f", pad, matrix [i][j]);
pad = ", ";
}
printf ("%s", " ]\n");
}
}
```
Output
```
$ ./bin/mtrx_dyn_example
[ 1.900, 2.800, 3.700, 4.600 ]
[ 2.800, 3.700, 4.600, 5.500 ]
[ 3.700, 4.600, 5.500, 6.400 ]
```
Just adjust the data type (e.g.int,double, etc...) as needed.
|
I've been trying to compare two char variables in C, one being the keyword, and the other being the password the user inputs, but despite both being the same, it doesn't let me in. This is the code:
```
#include<stdio.h>
#include<conio.h>
#include<bios.h>
#include <string.h>
int main(){
char pass[4], key[4]="tres";
start:
clrscr();
printf("Write your password: ");
scanf("%s", &pass);
if (strcmp(pass,key)!= 0){
printf("\nWrong password, try again.");
getch();
goto start;
}else if(strcmp(pass,key) == 0){
printf("Welcome!");
getch();
clrscr();
//here goes the rest of the program
}
return 0;
}
```
|
strcmpworks with null terminated strings. You need a\0character at the end of each string, and each string in this case should be 5 characters long.
|
So I have a text file, assume called text.txt. Its format is:4C 4D 4E 4F(i.e the hex values for the character string "LMNO"). I have correctly opened the text file, etc. How should I usefscanfto read the sequence of four bytes (i.e 1 byte at a time), storing each byte in a variable (with its appropriate data type). My end goal is to understand how to store in a character arraychar test[4];the lettersLMNO(i.e test[0] = 'L', test[1] = 'M',...)
|
```
#include<stdio.h>
int main(void){
FILE *fp = fopen("text.txt", "r");
char test[5] = {0};
unsigned hex;
int i;
for(i=0; i < 4; ++i){
if(1==fscanf(fp, "%2x", &hex))
test[i] = (char)hex;
else
break;
}
fclose(fp);
puts(test);
return 0;
}
```
|
I want to write a simple C program with hardcoded options, which does nothing else than remount root filesystem toread-only
I see, the mount() syscall takes following parameters:
```
mount(const char *spec, const char *node, const char *type, int flags, void *data)
```
I have following C code:
```
#include <stdio.h>
#include <errno.h>
#include <sys/mount.h>
int main(int argc, char *argv[]) {
return mount ("/dev/sda1", "/", "ext4", "MS_RDONLY", NULL);
}
```
I know, in place ofMS_RDONLYI should use a typeint. But where do I find the value corresponding toMS_RDONLY(or which ever option I need to use) ?
|
MS_RDONLY should be defined in mount.h, that you already included in your code. Changing"MS_RDONLY"toMS_RDONLYshould do the trick.
|
This question already has answers here:Can you define the size of an array at runtime in C(10 answers)Closed8 years ago.
I ask the user to input two numbers and I read them in using scanf. I assign these numbers to the variables x and y as such:
```
int x;
int y;
scanf("%d %d", &x, &y);
```
Can I then declare a 2D-array using the variables x and y, like such?
```
int array[x][y];
```
|
Yes you can. C99 and latter added this feature calledvariable length arrays.
|
Please explain me why the last printf gives value 11?
I really don't understand why it happened.
When a = 10 the condition is not fulfilled so why this value has changed to 11?
Incrementation goes as soon as the condition is checked?
Code:
```
int main(void) {
int a = 0;
while(a++ < 10){
printf("%d ", a);
}
printf("\n%d ", a);
return 0;
}
```
Output:
```
1 2 3 4 5 6 7 8 9 10
11
```
|
Let's look ata++ < 10whenais equal to10.
The first thing that will happen is10 < 10will be evaluated (to false), and thenawill be incremented to11. Then yourprintfstatement outside thewhileloop executes.
When the++comes on the right hand side of the variable, it's the last thing evaluated on the line.
Try changinga++ < 10to++a < 10, rerunning your code, and comparing the results.
|
In the language described by ISO 9899:2011 (that is, C11), withTbeing a complete data type and the declaration
```
struct { T a, b; } s;
```
can I assume that&s.a + 1 == &s.b? Did the situation change in between revisions of the C language?
|
No. The standard places no requirement on structure padding or lack of it, other than that there cannot be initial padding before the first member.
Each structure member must be correctly aligned for its type, of course.
|
I used theabs()function and I added#include <math.h>at the top of code. But I keep getting this error:
```
hello.c:20:11: warning: implicit declaration of function 'abs' is invalid in C99
[-Wimplicit-function-declaration]
int a = abs(arrOfHour[i] - hour) * 60 + minute;
^
```
I'm using LLVM compiler.
Why does this error occurs even though I have includedmath.h?
|
I'm going to quote straight from the docs :"Prototypes for abs, labs and llabs are in stdlib.h"
As a rule of thumb the mathematical functions that operate on floating point numbers are in math.h, and the ones that operate on integers are in stdlib.h.
There's apretty good Wikipedia articleon C mathematical functions if you need more information.
|
How do I read 3 bytes fromunsigned charbuffer at once (as a whole number)?
```
uint_24 p = *(unsigned char[3])buffer;
```
The above code doesn't work.
|
If the buffer can be redefined as part of a union and integer endian is as expected:
```
union {
unsigned char buffer[3];
uint_24 p;
} x;
foo(x.buffer); // somehow data is loaded into x.buffer
uint_24 destination = x.p; // read: let compiler do the work
```
By putting into a union, alignment issues are satisfied.
|
Is such function prototype valid in C?
```
int (*func())[*];
```
And if it is, how can I define such functions?
|
You should return a pointer to an incomplete array type instead as*notation for variable-length arrays is only valid in parameter lists.
Example prototype and function definition:
```
extern float (*first_row(unsigned, unsigned, float (*)[*][*]))[];
float (*first_row(unsigned n, unsigned m, float (*matrix)[n][m]))[]
{
return *matrix;
}
```
You'd invoke it like this:
```
unsigned n = 3, m = 4;
float matrix[n][m];
float (*row)[m] = first_row(n, m, &matrix);
```
Note that it is undefined behaviour to return a pointer to an array (variable-length or otherwise) that has been declaredwithinthe function if it has automatic storage duration. This implies that you can only return a pointer to a variable-length array that you passed in as an argument or allocated dynamically.
|
I am currently writing a program in c that requires me to read a text file more than once. That is, I am reading the data from the first line of the text file (which is fine), but then want to go back and re-read the same data from the same first line of the text file again (my problem). The data on the text file are simple numbers spaced out such that they may be read with scanf. I am a beginner and would appreciate some help. If it is in fact not possible to do this using scanf what can I do in order to solve my problem?
|
you can userewind(FILE *stream)it is equivalent to:
```
fseek(stream, 0, SEEK_SET)
```
which sets the file position indicator for the stream pointed to by stream to the beginning of the file
|
I read a unit test, that checks for invalid free or double-free:
```
int main() {
char *a = (char*) my_malloc(200);
char *b = (char*) my_malloc(50);
char *c = (char*) my_malloc(200);
char *p = (char*) my_malloc(3000);
(void) a, (void) c;
memcpy(p, b - 200, 450);
my_free(p + 200);
printstatistics();
}
```
Why do we need to castchar*tovoidand what happens in memory when we do this cast?
|
```
(void) a, (void) c;
```
is a common way to get rid of compiler warnings about unused variables. Since those two variables are initialised only and not used later, most compilers would issue warnings about it. Since this is apparently some kind of a test of memory allocation they are not used on purpose, so someone decided to silence warnings.
|
Is there a possible way to sum two differentlong long intvariables when the result is going to be bigger than along long intin C?
|
As OP wants to "print the result in the screen", divide the number in 2 parts: Most-Significant-Digits and Least-Significant-Digit.
```
#include <stdlib.h>
void print_long_long_sum(long long a, long long b) {
if ((a < 0) == (b < 0)) { // a and b of the same sign?
// Sum the Most-Significatn_Digits and Least-Significant Digit separately
int sumLSD = (int) (a % 10 + b % 10);
long long sumMSDs = a / 10 + b / 10 + sumLSD / 10;
sumLSD %= 10;
printf("sum = ");
if (sumMSDs) {
printf("%lld", sumMSDs);
// Since sign already printed, insure next print is positive
sumLSD = abs(sumLSD);
}
printf("%d\n", sumLSD);
} else { // No need to separate as there is no chance for overflow
printf("sum = %lld\n", a + b);
}
}
```
|
For example, thestdio.hlibrary has some functions that require aFILE *argument but acceptstdinfor user input from a terminal.
|
Cstdiofunctions operate onstreams, not files. As far as your code is concerned, a stream is simply a consumer (output stream) or producer (input stream) of bytes.
A stream may be associated with a file on disk. It may also be associated with a terminal. Or a printer. Or a network socket. Or anything else that you might want to communicate with. A stream is anabstractionof anything that can read or write a string of bytes.
stdinandstdout(along withstderr) are predefinedFILE *objects which normally refer to your console, although you can override that either at the command line or within your code.
|
I recently read that MD5 is not secure because it can be traced within a small amount of time.
If I give only a fixed 512 bit data as input.
MD5 will give 128 bit hash (32 hex values)
If MD5 is flawed, then can anyone suggest the best way to reconstruct the 512 bit input, given the 128 bit hash?
(Side note: I badly want to implement this. Would C++ be a better choice for speed or Java for its inbuilt security packages?)
|
There are 2 ** 384 (about 4x10**115) different 512-bit blocks that hash to the same MD5. Reversing isn't possible even in principle.
Itispossible, however, to findoneof those 4x10**115 blocks that produces the same MD5 as the block you want, andthat'swhy it's considered insecure. For example, if you posted a file to the net along with an MD5 hash to verify its integrity, a hacker might be able to replace it with a different file with the same hash.
With a more secure hash like SHA256, even this wouldn't be possible.
|
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.Closed8 years ago.Improve this question
I want to know how the string manipulation functions are implemented internally so I can figure out their performance. Is there a way to find this out?
I'm talking about null-terminated c strings (arrays of chars) and the related functions (strcat and such) in C++, if that has anything to do with it.
|
Is there a way to find this out?
Use the source, Luke
The sources for GNU libc string functions are easily viewable in theGit repository
You can also look at other free software or open source C libraries, such asnewlib,FreeBSD,NetBSD,OpenBSD, OpenSolaris etc.
|
I am beginner at modelling and etc., but I have a school task which I explained in the title and I searched for tutorials and I found many at Unity's page, but I didn't find anything about lighting in fragment shader. Any lead how to start?
|
I would recommend checking outhttps://github.com/bkaradzic/bgfxThe samples are a great resource to get started.
If you feel you need to know more about computer graphics, how the pipeline works and some of the math. I would recommend taking this free coursehttps://www.udacity.com/course/cs291
|
In case of a shared library between two applications, does each application use it's own copy of the library during run time ? If they use the same instance of the library, what happens to the global variables inside the library ?
|
It depends on the operating system. On most Unix-like systems, shared libraries use position-independent code, so the memory used by the code segment(which holds instructions and read-only variables) can be shared between processes, but each process still has its own data segment(which holds other variables).
|
This question already has answers here:How to generate NaN, -Infinity and +Infinity in ANSI C?(4 answers)Closed8 years ago.
I want to initialize a variable in C language to be the plus infinity or minus infinity, how can I do that ? The below fails:
float plus_inf = 0.0/0.0;
|
You can try
```
#include <math.h>
....
float x = INFINITY;
```
According to the standard:
The macroINFINITYexpands to a constant expression of typefloatrepresenting positive or unsigned
infinity, if available; else to a positive constant of typefloatthat overflows at translation time.
|
This question already has answers here:Fill with variable number of ones(2 answers)Closed8 years ago.
I have a number in range 1-8.
I want to convert it to
```
0b00000001 // 1
0b00000011 // 2
0b00000111 // 3
0b00001111 // 4
0b00011111 // 5
0b00111111 // 6
0b01111111 // 7
0b11111111 // 8
```
Can it be done without a switch or a for loop?
Ideally with a simple formula.
|
What you are looking for is
```
(1 << v) - 1
```
|
How would I use pointers in my program to keep track of the current position of array, instead of using "counter"?
```
#include <stdio.h>
#include <string.h>
#define MAX 100
int main(void){
int counter = 0, c;
char *charPtr, characterArray[MAX] = { 0 };
printf("Enter a message: ");
for (c = getchar(); c != EOF && c != '\n'; c = getchar()){
charPtr = &characterArray[0];
characterArray[*charPtr++] = c;
}
counter = strlen(characterArray) - 1;
printf("The reverse order is: ");
while (counter >= 0){
printf("%c", characterArray[counter]);
--counter;
}
printf("\n\n");
return 0;
}
```
|
Roughly like this:
```
char *endptr = characterArray + strlen(characterArray) - 1;
printf("The reverse order is: ");
while (endptr >= characterArray){
printf("%c", *endptr--);
}
```
Code is untested.
|
My book states: "The expression used to specify the length of" a variable array "could refer to variables outside the function".
I guess this is what the book means:
```
int main(void)
{
int xternal = 3;
int variable_array[xternal];
function(variable_array);
}
void function(int variable_array[xternal])
{
...
}
```
I understood that variables outside the function are invisible to it. Am I wrong?
|
You can reference variables outside of a function,butnot ones within other functions
```
int xternal = 3;
int main(void)
{
int variable_array[xternal];
function(variable_array);
}
void function(int variable_array[xternal])
{
...
}
```
|
This question already has answers here:Fill with variable number of ones(2 answers)Closed8 years ago.
I have a number in range 1-8.
I want to convert it to
```
0b00000001 // 1
0b00000011 // 2
0b00000111 // 3
0b00001111 // 4
0b00011111 // 5
0b00111111 // 6
0b01111111 // 7
0b11111111 // 8
```
Can it be done without a switch or a for loop?
Ideally with a simple formula.
|
What you are looking for is
```
(1 << v) - 1
```
|
How would I use pointers in my program to keep track of the current position of array, instead of using "counter"?
```
#include <stdio.h>
#include <string.h>
#define MAX 100
int main(void){
int counter = 0, c;
char *charPtr, characterArray[MAX] = { 0 };
printf("Enter a message: ");
for (c = getchar(); c != EOF && c != '\n'; c = getchar()){
charPtr = &characterArray[0];
characterArray[*charPtr++] = c;
}
counter = strlen(characterArray) - 1;
printf("The reverse order is: ");
while (counter >= 0){
printf("%c", characterArray[counter]);
--counter;
}
printf("\n\n");
return 0;
}
```
|
Roughly like this:
```
char *endptr = characterArray + strlen(characterArray) - 1;
printf("The reverse order is: ");
while (endptr >= characterArray){
printf("%c", *endptr--);
}
```
Code is untested.
|
My book states: "The expression used to specify the length of" a variable array "could refer to variables outside the function".
I guess this is what the book means:
```
int main(void)
{
int xternal = 3;
int variable_array[xternal];
function(variable_array);
}
void function(int variable_array[xternal])
{
...
}
```
I understood that variables outside the function are invisible to it. Am I wrong?
|
You can reference variables outside of a function,butnot ones within other functions
```
int xternal = 3;
int main(void)
{
int variable_array[xternal];
function(variable_array);
}
void function(int variable_array[xternal])
{
...
}
```
|
Let's say I have a thread that handles a HTTP connection using a socket, I need to somehow get the how long it took to process this connection. (timeAfterConnection - timeBeforeConnection).
I know I can use API like timer_gettime but after Googled around I did not find any working example about how to do this.
Can anybody give me an example of getting time elapse in C code?
|
```
#include <time.h>
struct timespec before, after;
long elapsed_nsecs;
clock_gettime(CLOCK_REALTIME, &before);
/* handle connection */
clock_gettime(CLOCK_REALTIME, &after);
elapsed_nsecs = (after.tv_sec - before.tv_sec) * 1000000000 +
(after.tv_nsec - before.tv_nsec);
```
|
Im curious because I checked on a linux host in Sydney, Australia and the date command saysESTas the timezone, as doesstrftime(tz, sizeof(tz), "%Z", &time)when running a simple C binary to print that out. However, I know the timezone isAEST. Are timezone abbreviations truncated? Where can I find out more about this?
|
Australian time zone abbreviationschanged in tzdb 2014f, released in August 2014.
You simply need to update your time zone data file to the current version (2015b as of this writing). On linux, this is usually in thetzdatapackage, which you can update usingapt-get, orrpm, or whatever is appropriate for your distro.
|
How can I get the size of my char pointer
```
char *data = "\x30\x2e\x30\x2e\x30\x2e\x30\x3a\x30";
```
Usingstrlen(data)orsizeof(data)always returns1
|
strlencounts characters in C string till it encounters 0. It maybe
tricky to get length of shell code usingstrlensince shell code
may contain 0 bytes in between; it appears there even exists notion of null free shell code (link) - in that case I believe you can usestrlen. Otherwise you can try:
```
char data[] = "\x30\x2e\x30\x2e\x30\x2e\x30\x3a\x30"; // you were missing \ in the beginning
printf("%zu", sizeof(data));
```
gives you 10 bytes.
|
The code is c and compiling on gcc compiler.
How to append string and char like as following example
```
unsigned char MyString [] = {"LOREM IPSUM" + 0x28 + "DOLOR"};
```
|
```
unsigned char MyString [] = {"LOREM IPSUM\050DOLOR"};
```
The\050is an octal escape sequence, with 050 == 0x28. The language standard also provideshexescape sequences, but"LOREM IPSUM\x28DOLOR"would be interpreted as athree-digit hex (\x28D), the meaning of which (since it would be overflowing the usual 8-bitchar) would be implementation-defined. Octal escapesalwaysend after three digits, which makes them safer to use.
And while we're at it, there is no guarantee whatsoever that your escapes would be considered ASCII. There are machines using EBCDIC natively, you know, and compilers defaulting to UTF-8 -- which would get you into trouble as soon as you go beyond0x7f. ;-)
|
I have a pointer variable of type char declared in this way:
```
char *name;
```
So to turn it into a string of 80 characters i did the next thing:
```
name=malloc(sizeof(char)*80);
```
this worked fine at school but when i came home i got this error:
```
error: invalid conversion from 'void*' to 'char*' [-fpermissive]
```
the compilers are exactly the same as are the compile and build code.
what is the problem?
|
mallocreturns a pointer of typevoid*.void*is automatically and safely promoted to any other pointer type in C , but not in C++. The error can only appear if you are compiling in C++ instead of C. Youshouldcast the result ofmallocif you are compiling in C++ andshould not, if you are compiling in C.
|
How do i get the random number generator in c to give me different numbers when ever my function is called.
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("%i",num());
printf("%i",num());
}
int num() {
int MAX = 100;
srand ( time(NULL));
int num = rand() % MAX;
return num;
}
```
No matter how many times i call the num function, it always prints the same number. How do i fix this so the number is different for every call.
|
Thetimefunction typically returns the time in second resolution, which means that if you calltime(NULL)twice within one second then you will get the same result.
That will of course mean that you set the same starting seed to the random-number generator, which means the sequence will be the same.
You typically only callsrandonce, early in themainfunction.
|
Why I need to make two inputs confirmed by "Enter" for a first iteration? How to make it to work as I expect (one input -> one enter -> next iteration)?
```
int vector[4];
for(j=0; j<4; j++)
{
printf("Another number\n");
printf("%d: ", j+1);
scanf("%d\n", (vector+j));
}
```
|
The reason is that you placed a\ncharacter inscanf. This will letscanfto ignore any number of\n(orEnterbutton hit) after the input. Remove\ncharacter fromscanf.
```
scanf("%d\n", (vector+j));
// ^^Remove this.
```
|
I got a gcc compilation error:
```
gcc-4.9: error: unrecognized command line option '-rdynamic'
```
and I tested compilation with -rdynamic in some environments. While I used the same version of gcc (4.9.2), in some environments gcc worked well, but others (e.g. Homebrew gcc 4.9.2_1, cygwin 64bit) not. What makes the difference?
|
-rdynamicpasses the flag-export-dynamicto ELF linker,on targets that support it.
Executable formats in OS X and Windows are not ELF, thus the option-rdynamicis not supported building for these operating systems.
|
This question already has answers here:close vs shutdown socket?(9 answers)Closed8 years ago.
I tried server client tcp code in c, I want to add some functionality to disconnect client from server. I search on google for it. I found functionshutdown(), I am not getting idea how to do it ?
|
To disconnect a client from the server, justclosethe fd linked to this client.
To disconnect a client to a server from the client, justclosethe client socket.
This is a quick way to disconnect, but don't forget to send a last exit message when you are leaving from a server / disconnecting a client.
No need of shutdown here. (Except if you share fd between processes, but without more information we cannot be more precise)
|
```
if (abs(u) > Vdc)
u = Vdc*((u > 0) - (u < 0));
```
This code is in C
considering we enter the if condition what will happen ?
Vdc = 24;
consider any arbitrary value of u for an explanation
|
Ifu > 0the statement will become1 - 0(true - false) =1. Ifu < 0it will become-1. If it is zero, it will become0as well. So basically it is returning the "sign" ofu(or more precisely1with corresponding sign). The overall code snippet is for clampingubetween+Vdcand-Vdc. (As suggested, it will work only for positiveVdc).
|
```
if (abs(u) > Vdc)
u = Vdc*((u > 0) - (u < 0));
```
This code is in C
considering we enter the if condition what will happen ?
Vdc = 24;
consider any arbitrary value of u for an explanation
|
Ifu > 0the statement will become1 - 0(true - false) =1. Ifu < 0it will become-1. If it is zero, it will become0as well. So basically it is returning the "sign" ofu(or more precisely1with corresponding sign). The overall code snippet is for clampingubetween+Vdcand-Vdc. (As suggested, it will work only for positiveVdc).
|
The -T command to the GCC linkerreplaces the default linker script.
But I don't want to replace the default linker script.
I want to append my new section definitions to the existing default linker script.
How to add new memory sections to the default linker script?
|
I don't think there is a direct way to do what you want to.
What you could do though, is to haveldprint the default script file (with-Wl,-verbose, the section between===============s is the linker script), put it in a file, modify the file with your additions and finally feed this to your link command as the linker script.
It should be fairly easy to write a script that does this and integrate it in your build scripts.
|
I have a 24 bit register that comprises a number of fields. For example, the 3 upper bits are "mode", the bottom 10 bits are "data rate divisor", etc. Now, I can just work out what has to go into this 24 bits and code it as a single hex number 0xNNNNNN. However, that is fairly unreadable to anyone trying to maintain it.
The question is, if I define each subfield separately what's the best way of coding it all together?
|
The classic way is to use the<<left shift operator on constant values and combine all values with either+or|. For example:
```
*register_address = (SYNC_MODE << 21) | ... | DEFAULT_RATE;
```
|
I have a variable that holds these sets of characters:
```
char recvBuff[1024] = "OK lastname,firstname 127.0.0.1";
```
I'm trying to parse the127.0.0.1IP address from that entire string and assign it to another variable. How can I parse this IP address from the string?
(I don't need 127, 0, 0, and 1 separate. I need "127.0.0.1" as a whole string.
|
You can usestrtok()orstrtok_r()function to separate the string.
```
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);
```
Before separating the string You can take the backup of the string because it will affect the original string.
|
An array of n numbers is given. Number of times minimum to be found out is given,let it be p, Indices are also given for each case repeatedly . I traversed the array to find min in array between given indices and repeated this procedure p times using for loop but I want it to be more efficient, How can I do so?
|
What you need, is to use some efficient algorithm forRange Minimum Queryproblem. Please follow the provided link. There you will find a comprehensive explanation how to do this.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.