question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
The documentation for glibc stays they are integer types (no narrower than unsigned int), but I'm not finding a standards reference that says they have to be an integer type (see also time_t).
So in the end, the question becomes: Is
```
#include <stdio.h>
#include <stdint.h>
struct stat st;
if (stat("somefile", &st) == 0) {
printf("%ju %ju\n", (uintmax_t)st.st_dev, (uintmax_t)st.st_ino);
}
```
portable.
|
POSIXstandard requiresdev_tto be an integer type andino_tto be an unsigned integer.
dev_t shall be an integer type.fsblkcnt_t, fsfilcnt_t, and ino_t shall be defined as unsigned integer
types.
Sinceintmax_tanduintmax_tare supposed to be the "greatest width" integers, your code is safe.
Just to be sure in casest_devhappens to be negative, you could write it as:
```
printf("%jd %ju\n", (intmax_t)st.st_dev, (uintmax_t)st.st_ino);
```
Otherwise, your code is safe.
|
This question already has answers here:What is the difference between const int*, const int * const, and int const *?(23 answers)Closed5 years ago.
I am currently working with production code in ANSI-C, which is partly getting generated by a very intransparent toolchain (so I could not find any clear information about it).
Somewhere in the generated code the following happens:
```
extern const volatile int16 * const volatile Varray[20];
```
And the access to it:
```
int16 myValue = *Varray[var];
```
It works, this is not part of the question. I just want to know why theconst volatileis written before AND after the datatypeint16 *.
|
```
extern const volatile int16 * const volatile Varray[20];
```
This just means that both the pointer and the value are "const volatile".
So, Varray is an array of const volatile pointers which will store const volatile int16's
|
Say I got an array
```
unsigned char digit[] = {0, 1, 2, 3, 4, 5, 6, 7};
```
Yet I want to modify part of the array, make the array become something like:
```
{0, 1, 2, 3, 0, 0, 0, 0}
```
Enumerate every element I want to modify and alter them might take some effort. Especially when there's a large amount of elements I want to change. I know in some languages like Python I may do something using a single line of code:
```
a = np.array([0, 1, 2, 3, 4, 5, 6, 7])
a[4:] = [0, 0, 0, 0]
//a: array([0, 1, 2, 3, 0, 0, 0, 0])
```
So I wonder, is there a similar way to do that in C?
|
There are fewer possibilities in C, but in case of anunsigned charand setting its values to zero you could usememset:
```
memset(&digit[4], 0, 4);
```
Demo.
|
```
int I;
I=0;
while ((CH1[I]=CH2[I]) != '\0')
I++;
puts(CH1);
```
This program is to copy CH2 in CH1 but I didn't understand the loop condition(CH1[I]=CH2[I]) != '\0')?
|
Thewhileloop condition contains of two parts:
```
CH1[I]=CH2[I] // this is an assignment that copies character at Ith position in array CH2 into array's CH1 Ith position
(...something...) != '\0' // checks if 'something' is not equal to '\0', the string termination character.
```
Thereforewhile((CH1[I]=CH2[I]) != '\0')copies characters one at the time fromCH2intoCH1and breaks as soon as it copies over '\0', which means end of string was reached and there are no more characters to copy.
|
I must make a server and a client on linux in C. The server must serve the concurent clients but i have a problem. It must also have a second port that an admin could connect to modify some files and i don't know how to open the same server on 2 ports. Moreover if the admin connect lets say on port 2080 he should have only his options while if the user connects on 2081 he should have different options. I already tried making 2 socket descriptors, binding them and listening on them but it crashes. Unfortunately i can't put any code on the platform as i am forbiden to do so. Please help me figure it out :D
|
Create two thread with server as routine.pass port as local variable to thread.
|
If I need to use the math library, I need to add-lmwhen I'm using GCC in Linux. But on Windows when I'm using GCC in MinGW-w64, I didn't use-lmand it works well.
I know the reason why it is necessary to linklibm. But I don't really know why I can omit that in Windows?
|
Because, under MinGW, the math functions aren't actually defined in libm. "libm" is an empty library used as a placeholder; the math functions are actually defined in MSVCRT.DLL,which MinGW uses as its standard library.
(The validity of using the system's MSVCRT as a standard C libraryis debatable. Nevertheless, that's what MinGW does.)
|
Say I got an array
```
unsigned char digit[] = {0, 1, 2, 3, 4, 5, 6, 7};
```
Yet I want to modify part of the array, make the array become something like:
```
{0, 1, 2, 3, 0, 0, 0, 0}
```
Enumerate every element I want to modify and alter them might take some effort. Especially when there's a large amount of elements I want to change. I know in some languages like Python I may do something using a single line of code:
```
a = np.array([0, 1, 2, 3, 4, 5, 6, 7])
a[4:] = [0, 0, 0, 0]
//a: array([0, 1, 2, 3, 0, 0, 0, 0])
```
So I wonder, is there a similar way to do that in C?
|
There are fewer possibilities in C, but in case of anunsigned charand setting its values to zero you could usememset:
```
memset(&digit[4], 0, 4);
```
Demo.
|
```
int I;
I=0;
while ((CH1[I]=CH2[I]) != '\0')
I++;
puts(CH1);
```
This program is to copy CH2 in CH1 but I didn't understand the loop condition(CH1[I]=CH2[I]) != '\0')?
|
Thewhileloop condition contains of two parts:
```
CH1[I]=CH2[I] // this is an assignment that copies character at Ith position in array CH2 into array's CH1 Ith position
(...something...) != '\0' // checks if 'something' is not equal to '\0', the string termination character.
```
Thereforewhile((CH1[I]=CH2[I]) != '\0')copies characters one at the time fromCH2intoCH1and breaks as soon as it copies over '\0', which means end of string was reached and there are no more characters to copy.
|
I must make a server and a client on linux in C. The server must serve the concurent clients but i have a problem. It must also have a second port that an admin could connect to modify some files and i don't know how to open the same server on 2 ports. Moreover if the admin connect lets say on port 2080 he should have only his options while if the user connects on 2081 he should have different options. I already tried making 2 socket descriptors, binding them and listening on them but it crashes. Unfortunately i can't put any code on the platform as i am forbiden to do so. Please help me figure it out :D
|
Create two thread with server as routine.pass port as local variable to thread.
|
If I need to use the math library, I need to add-lmwhen I'm using GCC in Linux. But on Windows when I'm using GCC in MinGW-w64, I didn't use-lmand it works well.
I know the reason why it is necessary to linklibm. But I don't really know why I can omit that in Windows?
|
Because, under MinGW, the math functions aren't actually defined in libm. "libm" is an empty library used as a placeholder; the math functions are actually defined in MSVCRT.DLL,which MinGW uses as its standard library.
(The validity of using the system's MSVCRT as a standard C libraryis debatable. Nevertheless, that's what MinGW does.)
|
I want to input a string by a keyboard, usually end by hitting key enter, but now i want to end by hitting key space
Ex :
Enter your name : Koichen (hitting enter('\n') for ending)
Enter your name : Koichen (hitting space bar(' ') for ending)
I use c/c++ for programming
Any hint would be grateful
|
Guess what, the standard input is yet not standardized across platforms.
On unix/linux/mac you need to configure the terminal tonot doing buffer. thengetcto poll for input.On Windows you callReadConsoleInput.
Either way you will need to consolidate the input characters until a space is read.
Note that there is no concept of keyboard here, what you read is theinput, which can for example come from a pipe.
|
Does C'svoid*lend some benefit in the form of compiler optimization etc, or is it just an idiomatic equivalent forchar*? I.e. if everyvoid*in the C standard library was replaced bychar*, would anything be damaged aside from code legibility?
|
In the original K&R C there was novoid *type,char *was used as the generic pointer.
void *serves two main purposes:
It makes it clear when a pointer is being used as a generic pointer. Previously, you couldn't tell whetherchar *was being used as a pointer to an actual character buffer or as a generic pointer.It allows the compiler to catch errors where you try to dereference or perform arithmetic on a generic pointer, rather than casting it to the appropriate type first. These operations aren't permitted onvoid *values. Unfortunately, some compilers (e.g.gcc) allow arithmetic onvoid *pointers by default, so it's not as safe as it could be.
|
I recently wrote this code to execute system command in C. I just want to measure time performed by this system command.
However, I don't want the output results to be displayed upon executing this program.
```
#include <stdio.h>
int main(int argc, char* argv[])
{
system("ls");
return 0;
}
```
How do I discard the output from the system command?
|
When you callsystem()from C, a shell is invoked to interpret your command. This means you can use shell redirects:
```
system("ls > /dev/null");
```
and if you want errors to also be suppressed
```
system("ls > /dev/null 2>&1");
```
However, due to the overhead of running a shell and the fragility of constructing shell commands, it's better to avoidsystem()when you can.
|
I am trying to output all of the combinations of various numbers in a set. I have the program running and I have an excel output file that is created, but I cannot seem to get the results to print to the output file. The linefputs(num[i],fp)seems to be the issue with the error
Source.cpp(45): error C2664: 'int fputs(const char *,FILE *)' : cannot
convert argument 1 from 'int' to 'const char *' 1> Conversion
from integral type to pointer type requires reinterpret_cast, C-style
cast or function-style cast
```
for (j = 1; j <= n; j++)
{
for (i = 0; i < n - 1; i++)
{
temp = num[i];
num[i] = num[i + 1];
num[i + 1] = temp;
print(num, n);
fputs(num[i],fp);
}
}
```
|
Yes you have to passchar*you are passing anint.
```
fputs(std::to_string(num[i]).c_str(),fp);
```
This would solve the issue. You can checkstd::string::c_str.
|
I'm wondering what the proper way is too convert a double of unknown valuesizeto a string without allocating too much memory. Is there any way to figure out the count of digits in a double? I don't want to allocate too much or too less memory.
|
You can useNULLas the first argument ofsnprintfto get the size:
C99 allows str to be NULL and gives the return value (as always) as
the number of characters that would have been written in case the
output string has been large enough.
And thenmalloc:
```
int main(void)
{
double num = 3.14;
size_t len;
char *str;
len = (size_t)snprintf(NULL, 0, "%f", num) + 1;
str = malloc(len);
snprintf(str, len, "%f", num);
puts(str);
free(str);
return 0;
}
```
|
I want to Shuffle an array of ints, the array is sorted and its size in n, values are 1 - n.
I Just want to avoid using a while loop in order to make sure the rand() doesn't give me the same index.
the code looks somthin like this:
```
void shuffleArr(int* arr, size_t n)
{
int newIndx = 0;
int i = 0;
for(; i < n - 1; ++i)
{
while((newIndx = i + rand() % (n - i)) == i);
swap(i, newIndx, arr);
}
}
```
The for loop goes until n-1, so for example in the last run it has 50/50 chance of being equal to i. I want to avoid this idea.
|
If you are searching for a random number in range 1...n but excluding some number m in that range, you can instead get a random number in range 1...(n-1) and for any result >= m add 1 to the value.
If you are looking for an explanation of an algorithm for shuffling a finite list, take a look at Fisher-Yates here:https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
|
I'm writing the header of a kernel module. The header is known to the module, but also used by callers in user space. This is a problem, because some types used should be included from different files depending on whether the header is currently in user or kernel space (or sothisquestion makes me think).
I don't want to maintain two separate header files, so I've been thinking of a solution like this:
```
#ifndef IN_KERNEL
#include <stdint.h>
#else
#include <linux/types.h>
```
With IN_KERNEL being defined somewhere in my kernel code. Is there a preprocessor constant that already does this?
|
From readingthis, it seems that an existing constant used for this purpose is__KERNEL__.
```
#ifndef __KERNEL__
#include <stdint.h>
#else
#include <linux/types.h>
#endif
```
|
Is there a way to send a signal to all the processes of a process ID group except for the one that is sending it?
Withkill(0, SIGUSR1)we can send it to all the processes of a group including the one calling it, but what if we wanted to send it to all except for the one calling it?
|
```
#include <signal.h>
#include <unistd.h>
...
signal(SIGUSR1, SIG_IGN); /* Ignore own signal */
killpg(getpgrp(), SIGUSR1); /* Send SIGUSR1 to pgrp */
```
|
I am trying to output all of the combinations of various numbers in a set. I have the program running and I have an excel output file that is created, but I cannot seem to get the results to print to the output file. The linefputs(num[i],fp)seems to be the issue with the error
Source.cpp(45): error C2664: 'int fputs(const char *,FILE *)' : cannot
convert argument 1 from 'int' to 'const char *' 1> Conversion
from integral type to pointer type requires reinterpret_cast, C-style
cast or function-style cast
```
for (j = 1; j <= n; j++)
{
for (i = 0; i < n - 1; i++)
{
temp = num[i];
num[i] = num[i + 1];
num[i + 1] = temp;
print(num, n);
fputs(num[i],fp);
}
}
```
|
Yes you have to passchar*you are passing anint.
```
fputs(std::to_string(num[i]).c_str(),fp);
```
This would solve the issue. You can checkstd::string::c_str.
|
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.Closed5 years ago.Improve this question
In turbo c 3.2 I am getting
Divide error
and in code blocks IDE I getting error that
initgraph() and closegraph() are refrence at compile time. (I added graphics header and library file in folder of codeblocks).Please give me solution?
the code i written is
```
#include<graphics.h>
int main()
{
int a=10,ab;
initgraph(&a,&ab,"C:\\TURBOC3\\BGI");
circle(100,200,20);
closegraph();
return 0;
}
```
|
In addition to the backslash issue in the path, it'sextremelyunlikely that you are using a 3270 compatible display. Why don't you pass in the address ofawitha=0.abmust be set to a requested mode unless you set the driver toautodetect, which will then select the highest available mode. Seehere.
|
I'm writing some simple example to understand how the things work with OpenMP programs.
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <omp.h>
int main (int argc ,char* argv[]){
omp_set_num_threads(4);
int j =0;
#pragma omp parallel private (j)
{
int i;
for(i=1;i<2;i++){
printf("from thread %d : i is equel to %d and j is equal to %d\n ",omp_get_thread_num(),i,j);
}
}
}
```
So in this example I should getj=0each time,unfortunately the result isj == 03 times, andj == 32707one time.
What is wrong with my example?
|
Usefirstprivate(j)rather thanprivate(j)if you want that each thread has a private copy ofjwith the initial value being the value before entering the parallel region.
|
When I run thebisonprogram below (bybison file.y) , I get the errormissing a declaration type for $2 in 'seq':
```
%union {
char cval;
}
%token <cval> AMINO
%token STARTCODON STOPCODON
%%
series: STARTCODON seq STOPCODON {printf("%s", $2);}
seq : AMINO
| seq AMINO
;
%%
```
I would like to know why I get this error, and how I can correctly declare the variable$2
|
You haven't told Bison what typeseqis, so it doesn't know what to do with$2.
Use the%typedirective:
```
%type <cval> seq
```
Note that the type used for$2is a singlechar, which is not a string as expected by the"%s"format. You need to come up with a way to create your own string from the sequence.
|
I'm writing some simple example to understand how the things work with OpenMP programs.
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <omp.h>
int main (int argc ,char* argv[]){
omp_set_num_threads(4);
int j =0;
#pragma omp parallel private (j)
{
int i;
for(i=1;i<2;i++){
printf("from thread %d : i is equel to %d and j is equal to %d\n ",omp_get_thread_num(),i,j);
}
}
}
```
So in this example I should getj=0each time,unfortunately the result isj == 03 times, andj == 32707one time.
What is wrong with my example?
|
Usefirstprivate(j)rather thanprivate(j)if you want that each thread has a private copy ofjwith the initial value being the value before entering the parallel region.
|
When I run thebisonprogram below (bybison file.y) , I get the errormissing a declaration type for $2 in 'seq':
```
%union {
char cval;
}
%token <cval> AMINO
%token STARTCODON STOPCODON
%%
series: STARTCODON seq STOPCODON {printf("%s", $2);}
seq : AMINO
| seq AMINO
;
%%
```
I would like to know why I get this error, and how I can correctly declare the variable$2
|
You haven't told Bison what typeseqis, so it doesn't know what to do with$2.
Use the%typedirective:
```
%type <cval> seq
```
Note that the type used for$2is a singlechar, which is not a string as expected by the"%s"format. You need to come up with a way to create your own string from the sequence.
|
When I run thebisonprogram below (bybison file.y) , I get the errormissing a declaration type for $2 in 'seq':
```
%union {
char cval;
}
%token <cval> AMINO
%token STARTCODON STOPCODON
%%
series: STARTCODON seq STOPCODON {printf("%s", $2);}
seq : AMINO
| seq AMINO
;
%%
```
I would like to know why I get this error, and how I can correctly declare the variable$2
|
You haven't told Bison what typeseqis, so it doesn't know what to do with$2.
Use the%typedirective:
```
%type <cval> seq
```
Note that the type used for$2is a singlechar, which is not a string as expected by the"%s"format. You need to come up with a way to create your own string from the sequence.
|
Iflink-time code generation (LTCG)is being used with MSVC, is it possible that code can be optimized across the C and C++ language boundary?
For example, can a C function be inlined into a C++ caller?
|
Yes, I just tried it with:
```
int foo() { return 5; }
```
in a .c file and:
```
extern "C" int foo();
printf("%d\r\n", foo());
```
in a .cpp the disassembly is:
```
00007FF60F6F3935 mov edx,5
00007FF60F6F393A lea rcx,[string "%d" (07FF60F727FB4h)]
00007FF60F6F3941 call printf (07FF60F701E00h)
```
|
Straight to the point. I want to change higher 8 bits of a variable.
```
ULONG parameters;
```
I can get them like that:
```
(parameters >> 24) & 0xFF
```
But I'm not really sure how can I clear the value there and set my own.
|
You can clear the high 8 bits with:
```
value &= 0x00FFFFFF;
```
Note that the 00 is not actually needed, it's just there for clarity. And if you want to set all of the high 8 bits:
```
value |= 0xFF000000;
```
|
Since LLVM uses Static Single Assignment Form, every operand is assigned a value exactly once. For some given instruction, I retrieve its operands, and I then want to find the instruction where the the operand was assigned its value.
|
These are basically the same. Say, you have
```
i32 %1 = inst1
inst2 i32 %1
```
When you doinst2->getOperand(0), you get aValue*pointing to%1. If you need to follow the chain of instructions, you'd need to callgetOperandover and over.
|
Straight to the point. I want to change higher 8 bits of a variable.
```
ULONG parameters;
```
I can get them like that:
```
(parameters >> 24) & 0xFF
```
But I'm not really sure how can I clear the value there and set my own.
|
You can clear the high 8 bits with:
```
value &= 0x00FFFFFF;
```
Note that the 00 is not actually needed, it's just there for clarity. And if you want to set all of the high 8 bits:
```
value |= 0xFF000000;
```
|
Since LLVM uses Static Single Assignment Form, every operand is assigned a value exactly once. For some given instruction, I retrieve its operands, and I then want to find the instruction where the the operand was assigned its value.
|
These are basically the same. Say, you have
```
i32 %1 = inst1
inst2 i32 %1
```
When you doinst2->getOperand(0), you get aValue*pointing to%1. If you need to follow the chain of instructions, you'd need to callgetOperandover and over.
|
I'm writing a multi-threaded program in C, where the main() changes the behavior of some signals and then spawns more threads. The question is: do the other threads continue executing when a signal arrives, or do they pause and resume execution when the signal is handled?
Thanks
|
do the other threads continue executing when a signal arrives
On Linux they do because a signal is only ever delivered to one thread. Unless the signal isSIGSTOP, which stops all threads of a process. Seeman signal(7)andman pthreads(7)for more details (ignore LinuxThreads info related to old threads implementation).
Although POSIX does not require that, so these details are OS specific.
|
This question already has answers here:How does "while(*s++ = *t++)" copy a string?(17 answers)Closed5 years ago.
I am readingThe C Programming Language, and when it gets toCharacter Pointers and Functions (5.5)I get a problem.
In5.5, the authors showed four versions ofstrcpy(). My problem lies in the version 3:
```
/*strcpy: copy t to s; pointer version 3*/
void strcpy(char *s, char *t)
{
while (*s++ = *t++)
;
}
```
There is no comparison against '\0'. And how does the termination of the loop work under such a condition?
|
```
*s++ = *t++
```
is equivalent to
```
(*s++ = *t++) != 0
```
which is equivalent to
```
(*s++ = *t++) != '\0'
```
|
Why "strrev()" and some other inbuilt string functions in c doesn't work in terminal?
```
#include<stdio.h>
main()
{
char c[50];
scanf("%s",c);
strrev(c);
printf("%s",c)
}
```
|
strrevis not standard, but can be easily implemented
```
void strrev(char *s) {
int i,n = strlen(s);
for(i=n/2 ; i>=0 ; i--) {
char c = s[i];
s[i] = s[n-i-1];
s[n-i-1] = c;
}
}
```
|
```
add_library(target1 funtion.c target1.c )
add_library(target2 funtion.c target2.c )
add_executable(main.out main.c)
target_link_libraries(main.out target1 target2 ${LDFLAGS})
```
Here is myCMakeLists.txtabove.
Both targets need to use the source filefunction.c. It is able to run though. My concern is that maybe it is not a good behavior for writingCMakeList.txt?
|
It's totally fine to use the same source file whatever number of times. Sometimes it's even necessary, if you want to compile the same source with different pre-processor/compiler flags.
But if you are concerned with compilation time, you could:
movefuntion.cto separate static library and linktarget1andtarget2libraries against it.Useobject libraryforfunction.cand archive output object file totarget1andtarget2.
|
```
add_library(target1 funtion.c target1.c )
add_library(target2 funtion.c target2.c )
add_executable(main.out main.c)
target_link_libraries(main.out target1 target2 ${LDFLAGS})
```
Here is myCMakeLists.txtabove.
Both targets need to use the source filefunction.c. It is able to run though. My concern is that maybe it is not a good behavior for writingCMakeList.txt?
|
It's totally fine to use the same source file whatever number of times. Sometimes it's even necessary, if you want to compile the same source with different pre-processor/compiler flags.
But if you are concerned with compilation time, you could:
movefuntion.cto separate static library and linktarget1andtarget2libraries against it.Useobject libraryforfunction.cand archive output object file totarget1andtarget2.
|
Inlinux/pfkeyv2.hI can see following values:
```
#define SADB_EALG_NONE 0
...
#define SADB_EALG_NULL 11
```
Anyone can explain what is the difference between those values and how specifying those values insadb_sa.sadb_sa_encryptwould affect ipsec encryption?
|
SADB_EALG_NONEis used to indicate that no encryption applies for an SA, whileSADB_EALG_NULLsignifies the NULL encryption algorithm as specified inRFC 2410. As stated inRFC 2367, section 3.5the former must only be used if no encryption can apply for an SA (e.g. for AH), the latter may be used for ESP SAs and can be negotiated via IKE.
|
```
int n;
scanf("%d",&n);
int *score;
score=(int *)malloc(sizeof(int)*n);
int i;
for (i=0;i<n;i++)
{
scanf("%d",sizeof(int)*i+score);
}
printf("ok");
```
In the above code I get an error but when I comment the last lineprintfthe program runs correctly.
what is the problem??
(I want to give n number from user without using arrays)
|
Pointer arithmetic of the formscore + iis already done in multiples ofsizeof(*score). So when you writescore + i * sizeof(int)you doubly multiply by the size of the items. You reach way beyond the bounds of the buffer.
Either write it simply asscore + i, or if you insist on doing the multiplication yourself, be sure to cast to a character pointer type first:
```
(int*)((char*)score + i * sizeof(int))
```
Oh, anddon't cast the result of malloc. C doesn't require it, and it's somewhat unidiomatic.
|
I have 3 files:main.c,def.c,def.h. Both.cfiles includedef.h.
All the files are in the same directory.
My compiler isgcc version 4.9.2.
Indef.h:
```
struct _info {
int a;
};
```
Indef.c:
```
#include "def.h"
struct _info info[] = {};
```
And inmain.c:
```
#include "def.h"
extern struct _info info[];
```
When I builddef.cas an object file and then build withmain.clike:
```
gcc -c def.c
gcc main.c def.o
```
And I got an error message:array type has incomplete element type
If I usetypedefto definestruct _infoasINFOlike:
```
typedef struct _info INFO;
```
And replacestruct _infowithINFOin.cfiles.
Compile ok then.
Butwhyandwhatdoestypedefdo?
|
Thanks for everybody's help. This question end up with a misspelling inmain.c.
Something like:
extern struct _infoo info[];
Whentypedefreplace them, all work fine definitely.
|
Just curious. I've tended to name variables of the typestruct tmsomething liketime_bitsor similar, since it contains the broken-down calendar time bits. Most of the documentation I've seen refers to this type as 'calendar time', as opposed to 'clock time' or 'epoch seconds' fortime_t.
|
If it were namedstruct time, a lot of people would confuse it with this function:
```
time_t time(time_t *);
```
Although in C structure tags don't interfere with variable/function names, having different names for them reduces confusion.
|
I have a small problem assigning a string variable in C. Let's say we havechar string[100]and I want to assign a string with an integer to this variable like in here.
What I tried was..
```
strcpy(string, "The tile in %d,%d is occupied: ", row, col);
```
But I get an error
Unresolved externals symbol message.
Is there any other way that I could do it?
|
```
char string[100];
sprintf(string, "The tile in %d,%d is occupied: ", row, col);
```
|
There is a tiny part of my code in C.
```
read(fd,&bufferSize,sizeof(bufferSize);
buffer = malloc(bufferSize);
read(fd,&buffer,bufferSize);
printf("%d",buffer);
fflush(stdout);
printf("%s",buffer);
fflush(stdout);
```
When I print buffer with%dformat, it's working, but when I try to consider the buffer as a string, I get segmentation fault. SIGSEGV occurs even when I usestrcmpor other functions like that.
|
```
read(fd,&buffer,bufferSize);
```
Here,bufferis the address of the start of your buffer. So, when you call the above function, you as passing inthe address of your address.
Thus, you can see why it segfaults, because the address passed in is not the actual address of the buffer. Replace that line with
```
read(fd,buffer,bufferSize);
```
|
I would like to re-program in C the program Burp (https://portswigger.net/burp), at least the part with the proxy.
Burp starts on the computer a proxy over which then the clients in the network "log in" or "access" can.
A CA certificate from Burp will be installed on the clients.
From now on Burp can also read HTTPS traffic.
I would like to re-program this principle in C.
I do not know which libraries to use for
- the proxy
- decrypting the data with de certificate key
|
Many people already wrote a proxy in C (for example, nginx).
You can often look through their C code and discover what they did and which libraries they used.
As for the network layer, I am biased since I'm the author offacil.io, which I love... But a quick search will offerlibev,libuvandlibeventas very common choices that support more platforms (such as Windows).
|
I'm trying to develop an app using GTK3 + Glade and following examples and suggestions on internet I can obtain a first prototype of the application.
Now I want to add some plots in the app. I found that, in this contest, the Cairo library is the right solution. For the Cairo library I found this tutorialhttp://zetcode.com/gfx/cairo/
I tried to merge GTK3, Glade and Cairo using the C language but I'm not sure to use this tools in the right way.
Could you suggest me an example where using these tools is built an app that, e.g. pushing a button appear the plot of a curve?
Thank you
|
In Glade, you just need to add a GtkDrawingArea and you draw in it using cairo. Give a look at mygtk3-graphsample application that uses GTK+ 3 and cairo to plot a curve.
|
getchar()insidewhileloop takes input after printing whole string. Can anyone explain howgetchar()andputchar()works?
I am including following code snippet and output. Also unable to understand behavior of this code
```
#include <stdio.h>
int main(int argc, char **argv)
{
int c ;
c = getchar();
while(c!=EOF){
putchar(c);
printf("%d\n",EOF);
printf("before getchar in while loop");
c=getchar();
printf("after getchar in while loop");
printf("jas\n");
}
return 0;
}
```
Output
|
getcharis eventually being handled through to the console input management routines. These routines, in a default config (noioctlor equivalent calls), will read and echo the entire line before returning the string to the program for processing. Once returned, getchar will be prepared to process the entire line before it goes back to the console input routines.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed5 years ago.Improve this question
lets say i have this variable:
```
unsigned int a = 13428;
```
It binary values is:11010001110100
I want to get the first 5 bits (11010001110100)
I tried to do this:
```
a &= 11111; // because in left is always 0
```
What I am doing wrong?
If I do on paper
```
11010001110100
&
00000000011111
```
It should be00000000010100
|
11111is just eleven-thousand-hundred-and-eleven. Which is10101101100111in binary.
So in binary you're doing11010001110100 & 10101101100111, which is in binary10000001100100.
|
I'm trying to develop an app using GTK3 + Glade and following examples and suggestions on internet I can obtain a first prototype of the application.
Now I want to add some plots in the app. I found that, in this contest, the Cairo library is the right solution. For the Cairo library I found this tutorialhttp://zetcode.com/gfx/cairo/
I tried to merge GTK3, Glade and Cairo using the C language but I'm not sure to use this tools in the right way.
Could you suggest me an example where using these tools is built an app that, e.g. pushing a button appear the plot of a curve?
Thank you
|
In Glade, you just need to add a GtkDrawingArea and you draw in it using cairo. Give a look at mygtk3-graphsample application that uses GTK+ 3 and cairo to plot a curve.
|
I have the following:
```
static unsigned int *tick = NULL;
...
if (tick == NULL)
tick = calloc(MAX_PORT,sizeof(unsigned int));
...
```
which functionally works as expected but coverity complains with:Parse warning (PW.INCOMPATIBLE_ASSIGNMENT_OPERANDS)
1. incompatible_assignment_operands: a value of type "int" cannot be assigned to an entity of type "unsigned int *"and I don't entirely understand why
|
The error message suggests that Coverity thinks thatcallocreturns anint,
which can happen if you haven't includedstdlib.h(forcalloc)in the older C.
But this is not allowed in modern C (i.e., no implicit declarations allowed in C99 and above).
|
This question already has answers here:Is there a shorter way to write compound 'if' conditions? [duplicate](12 answers)Closed5 years ago.
How can I compare a variable to a list of values of the same type in anifstatement and make it readable and clean?
For example, I have the following, but there are a lot of values, and I want to make it more readable.
```
if ((lst->type == 'p' || lst->type == 'x' || lst->type == 'X' ||
lst->type == 'o' || lst->type == 'O' || (lst->type == 'd' ||
lst->type == 'i' || lst->type == 'D'))
```
|
Easiest way to handle this using thestrchrfunction:
```
const char *lookups = "pxXoOdiD";
if (strchr(lookups, lst->type)){
// Do your thing here to handle the condition
}
```
More information aboutstrchrcan be found.
Returns a pointer to the first occurrence of character in the C string str.
|
I need to add quotes in begging and ending of a char.
```
char *Mychar = "hello";
printf("%c\n",Mychar[0]);
```
My result ishand my desired result is'h'.
|
Just add them in the format string. For single quotes, you can just put them in there:
```
printf("'%c'\n",Mychar[0]);
```
For double quotes, you'll have to escape them:
```
printf("\"%c\"\n",Mychar[0]);
```
|
I found this question in many interviews and my teacher asked me the same the main doubt was that if I include<stdbool.h>in C99 standard will that evaluate this as(true)<cor(false)>c. Need a more clear answer than the linked post -->Usage of greater than, less than operators.
Howa<b<cora>b>care evaluated in Cfor example in the following code.
```
# include<stdbool.h>
int main(void){
int a = 1,b=2,c=3;
if(a<b<c)
printf("a great b great c");
}
```
thank you in advance.
|
From standarditself(Relational operators footnotes)
The expressiona<b<cis not interpreted as in ordinary mathematics.
As the syntax indicates, it means(a<b)<c; in other words, ifais less thanb, compare1toc; otherwise, compare0toc.
|
I have compiled a c program for arm v7 usingarm-linux-gnueabi-gcc -static -fno-stack-protector -fno-pie -march=armv7-a hello.c -o helloand pushed the binary to /data/local/hello inside the root of android device. I'm able to run the program using adb shell. But my question is how can I debug the program i.e., how can I see the Program Counter and such info?
|
Try to use gdb in remote mode:https://source.android.com/devices/tech/debug/gdbprobably it works already (had problems with it in past).
Also you can try to use Google Breakpad:https://github.com/google/breakpad/blob/master/README.ANDROIDit works sometimes :)
|
This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago.
The result of the values of A and B is as follows.
|
In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.
|
I am writing a code that accepts a string of length as much a user want and displays it.so this is what I have written
```
#include<stdio.h>
#include<stdlib.h>
void main()
{
char *a;
int i,n;
a=(char*)calloc(1,sizeof(char));
printf("enter the string\t");
for(i=0;a[i]!=0;i++)
{
scanf("%[^0]c",&a[i]);
n=2+i;
a=(char*)realloc(a,(n)*sizeof(char));
}
for(i=0;a[i]!=0;i++)
{
printf("%c",a[i]);
}
free(a);
a=NULL;
}
```
but it's not entering into the loop and accepts any input. can you tell me what's going wrong? THANKS
|
You are not entering the loop because you allocatedawithcalloc, soa[0]is 0. It will fail the initiala[i]!=0test of both of yourforloops.
|
This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago.
The result of the values of A and B is as follows.
|
In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.
|
I am writing a code that accepts a string of length as much a user want and displays it.so this is what I have written
```
#include<stdio.h>
#include<stdlib.h>
void main()
{
char *a;
int i,n;
a=(char*)calloc(1,sizeof(char));
printf("enter the string\t");
for(i=0;a[i]!=0;i++)
{
scanf("%[^0]c",&a[i]);
n=2+i;
a=(char*)realloc(a,(n)*sizeof(char));
}
for(i=0;a[i]!=0;i++)
{
printf("%c",a[i]);
}
free(a);
a=NULL;
}
```
but it's not entering into the loop and accepts any input. can you tell me what's going wrong? THANKS
|
You are not entering the loop because you allocatedawithcalloc, soa[0]is 0. It will fail the initiala[i]!=0test of both of yourforloops.
|
I know that this question has been asked several times, anyway I didn't find and answer to my specific case:
IAR Embedded Workbench returs this warning on compiling:
"Warning [pe069] integer conversion resulted in truncation" on the line:
```
SPI2_Tx(DVC_CTR2, 0x1000);
```
where DVC_CTR2 is
```
#define DVC_CTR2 0x0F
```
and SPI2_Tx definition is
```
static void SPI2_Tx(uint8_t pAddress, uint8_t pData)
```
How can I resolve this warning?
Thanks in advance!
|
This is because you cannot transmit a two-byte value through SPI routine that transmits a single byte.
You should be able to do it with two separate calls:
```
SPI2_Tx(DVC_CTR2, 0x10);
SPI2_Tx(DVC_CTR2, 0x00);
```
If you must transmit 16 bits at once, look up a different routine that takesuint16_t.
|
I know that this question has been asked several times, anyway I didn't find and answer to my specific case:
IAR Embedded Workbench returs this warning on compiling:
"Warning [pe069] integer conversion resulted in truncation" on the line:
```
SPI2_Tx(DVC_CTR2, 0x1000);
```
where DVC_CTR2 is
```
#define DVC_CTR2 0x0F
```
and SPI2_Tx definition is
```
static void SPI2_Tx(uint8_t pAddress, uint8_t pData)
```
How can I resolve this warning?
Thanks in advance!
|
This is because you cannot transmit a two-byte value through SPI routine that transmits a single byte.
You should be able to do it with two separate calls:
```
SPI2_Tx(DVC_CTR2, 0x10);
SPI2_Tx(DVC_CTR2, 0x00);
```
If you must transmit 16 bits at once, look up a different routine that takesuint16_t.
|
I want to create a list with some additional functions (inserting an additional element at the end, finding a given a element, removing element). Finding a removing works fine, however I have a problem with the list itself (and with the input).
This is my actual code. I have removed a few functions to make it more readable to you.
http://codepad.org/dTGjtYRx
When more elements are created at the beginning of the program or during inserting additional elements the program crashes and gives an error
Thread 1: EXCBADACCESS (code=EXCI386GPFLT)
What is more sometimes when the list is printed 'name' is printed as a weird combination of letters/digits for example -> \360-`.
|
this
```
ListElement *e = malloc(sizeof(Book));
```
should change to that:
```
ListElement *e = malloc(sizeof(ListElement));
```
also all your arrays should be of size[51]to keep the string terminator character.
|
I'm trying to print the value pointed by a pointer who is himself pointed by a pointer.
I have 2 structs
```
typedef struct s_thread_police
{
l_hash *lhash;
// other stuff for thread purpose
} thread_police_arg;
typedef struct s_l_hash
{
struct s_l_hash* next;
char* hash;
} *l_hash;
```
How do I print the hash of the struct I point to?
```
police_arg.lhash = &lhash;
printf("%s\n", *(police_arg.lhash)->hash);
```
The compiler is telling me "error: request for member ‘hash’ in something not a structure or union"
I have try some other way but none of them are working
Thx for your help
|
You want this:
```
printf("%s\n", (*police_arg.lhash)->hash);
```
*police_arg.lhashgives you anl_hash, which is a pointer to as_l_hashwhich you then dereference to gethash.
|
```
int x = ~!printf;
printf("%d\t%x",x,x);
```
It gives : -1 ffff
Can anyone explain ?
|
printfwithout arguments is thefunction pointer, worth a non-zero value (it'sbuilt-inso the pointer cannot be zero)
Now you apply logical negation (!) on this non-zero value: you get zero.
Now negate this zero bit-wise (using bit to bit negation~), you get all 1s in theintbit range (which can vary depending on the compiler)
Printing it in decimal yields-1, and in hexadecimal yields a given number offs, depending on the size of the integer (on my 32bit integer compiler, I getffffffff)
(note that -specially the negation of the function pointer- cannot be part of some valid program, this is only for academic purposes)
|
When I callpthread_yieldorpthread_blockand the CPU does a context switch
Is the program counter stored in thethread stack(alongside its temporary registers) or in thethread control block(alongside the stack pointer)
|
Usually it shall be in the TCB. But I beleive it is implementation specific.
An example of information contained within a TCB is:
Thread Identifier:Unique id (tid) is assigned to every new threadStack pointer: Points to thread's stack in the processProgram counterState of the thread (running, ready, waiting, start, done)Thread's register valuesPointer to the Process control block (PCB) of the process that the thread lives on
|
I'm running MSYS under Windows and although it works I want to know if there is such a thing as a MSYS script file.
For example to compile a GTK program in C I need to type:gcc source.c -o executable.exe 'pkg-config --cflags --libs gtk+-3.0'to compile. Is there a way to store this in a file and run the file from MSYS without having to type in the command each time (IE like.bat,.shfiles)?
|
If you want to automate building an application, just use a build system. TheMeson build systemis what the GTK+ developers recommend now (and GStreamer, and many other projects). It's multiplatform, and available as a package in MSYS2 (I used it there, works like a charm). They have asimple Meson tutorialwhere they build a GTK application. That's 3 lines of code.
|
```
#include <stdio.h>
int main()
{
int i;
for ( i=0; i<5; i++ )
{
int i = 10;
printf ( "%d", i );
i++;
}
return 0;
}
```
In this variableiis declared outside theforloop and it is again declared and initialized insideforloop. How does C allows multiple declarations?
|
Theioutside the loop and theiinside the loopare two different variables.
The outeriwill live for the entire duration ofmain.The inneriwill only live for the duration of one loop iteration.
The inner oneshadowsthe outer one in this scope:
```
{
int i = 10;
printf ( "%d", i );
i++;
}
```
Due to shadowing rules, it is impossible to refer to the outer one while inside the aforementioned scope.
Note that it is impossible to declare two variables with the same namein the same scope:
```
{
int i = 0;
int i = 1; // compile-time error
}
```
|
Why does C use the word_Boolto define boolean values? Whereas they use the wordfloatfor floats and not_Float?
Furthermore, why doesboolhave to be included, why isn't part of the basic functionality, likefloat?
|
_Boolwas not originally in C, but was added in the 1999 C Standard. If it had been calledboolthen a large amount of existing code would break because many projects made their own type aliasboolalready.
The C89 standard set aside identifiers starting with_followed by upper-case character as reserved for implementation use. This is why new features added to C always start with such names._Complex,_Alignofand_Static_assertare other examples.
There is also a header<stdbool.h>which aliasesboolto_Booland definestrueandfalse; this header can be included by new projects or by projects that didn't already definebool.
|
I'm trying to calculate, for0 < n ≤ 10⁹, the value of
```
re=(2^n)%1000000007
```
I wrote this code:
```
int main()
{
int n,i,re=1;
scanf("%d",&n);
for(i=0; n>i; i++) re=(2*re)%1000000007;
printf("%d",re);
}
```
Whennis 10⁹, my code takes too long.
What can I do to make it faster?
|
You can follow binary exponentiation which will be something like
```
#define MOD 1000000007
long long fastExp(int b, int e) {
long long r=1;
while(e>0) {
if(e&1) r=(r*b)%MOD;
b=(b*b)%MOD;
e/=2;
}
return r%MOD;
}
```
Call it like thisfastExp(2,n).
Well the complexity is pretty simple in that it doeslog2(n)operations so this will work better than yourO(n)solution.
As an explanation to why your solution got TLE. The online judges available like that ofSPOJetc usually take 1 sec to do10^8loop operations. Here you do much more than that when you haven=10^9as input.
|
I want to use sparse matrix or matrix, depending on efficiency and space saving
I’m trying to find what’s is more efficient and save space in run time
The size of the matrix is changing but every value is char (can be nothing -‘\0’)
I’m reading the data of the matrix values from file...
(In the beginning of each file there is the size of the matrix)
Thank you in advance
|
You can think on this as a graph representation.
As you know, if you use matrix, the space complexity would be|V|^2(|V|is number of nodes).
Moreover, if you use adjacency matrix (or sparse matrix) the space complexity would be|V||E|, which|E|is the number of non-zero strings which are related to a node.
Hence, you can traverse the file and compare|V|^2and|V||E|and decide base on these two values.
|
I'm using thestdlibrary. I don't know what the difference betweenI2C_FLAG_TXEandI2C_IT_TXEis.
Why when in interrupt function we don't useI2C_ClearFlaginsteadI2C_ClearITPendingBit? When do we usedI2C_ClearFlag?
I'm starting learnstm32f4. I have very little experience.
|
I'm using the std library. I don't know what the difference between
I2C_FLAG_TXE and I2C_IT_TXE is.
From the processor point of view - the interrupt flag which has to be cleared by interrupt routine is set when the processor enters the interrupt.
Interrupt pending flag - indicates that the event which triggers the interrupt occurred but for some reason the interrupt routine has not been invoked yet.
It is good to know your hardware before using any libraries.
|
When I callpthread_yieldorpthread_blockand the CPU does a context switch
Is the program counter stored in thethread stack(alongside its temporary registers) or in thethread control block(alongside the stack pointer)
|
Usually it shall be in the TCB. But I beleive it is implementation specific.
An example of information contained within a TCB is:
Thread Identifier:Unique id (tid) is assigned to every new threadStack pointer: Points to thread's stack in the processProgram counterState of the thread (running, ready, waiting, start, done)Thread's register valuesPointer to the Process control block (PCB) of the process that the thread lives on
|
I'm running MSYS under Windows and although it works I want to know if there is such a thing as a MSYS script file.
For example to compile a GTK program in C I need to type:gcc source.c -o executable.exe 'pkg-config --cflags --libs gtk+-3.0'to compile. Is there a way to store this in a file and run the file from MSYS without having to type in the command each time (IE like.bat,.shfiles)?
|
If you want to automate building an application, just use a build system. TheMeson build systemis what the GTK+ developers recommend now (and GStreamer, and many other projects). It's multiplatform, and available as a package in MSYS2 (I used it there, works like a charm). They have asimple Meson tutorialwhere they build a GTK application. That's 3 lines of code.
|
```
#include <stdio.h>
int main()
{
int i;
for ( i=0; i<5; i++ )
{
int i = 10;
printf ( "%d", i );
i++;
}
return 0;
}
```
In this variableiis declared outside theforloop and it is again declared and initialized insideforloop. How does C allows multiple declarations?
|
Theioutside the loop and theiinside the loopare two different variables.
The outeriwill live for the entire duration ofmain.The inneriwill only live for the duration of one loop iteration.
The inner oneshadowsthe outer one in this scope:
```
{
int i = 10;
printf ( "%d", i );
i++;
}
```
Due to shadowing rules, it is impossible to refer to the outer one while inside the aforementioned scope.
Note that it is impossible to declare two variables with the same namein the same scope:
```
{
int i = 0;
int i = 1; // compile-time error
}
```
|
Why does C use the word_Boolto define boolean values? Whereas they use the wordfloatfor floats and not_Float?
Furthermore, why doesboolhave to be included, why isn't part of the basic functionality, likefloat?
|
_Boolwas not originally in C, but was added in the 1999 C Standard. If it had been calledboolthen a large amount of existing code would break because many projects made their own type aliasboolalready.
The C89 standard set aside identifiers starting with_followed by upper-case character as reserved for implementation use. This is why new features added to C always start with such names._Complex,_Alignofand_Static_assertare other examples.
There is also a header<stdbool.h>which aliasesboolto_Booland definestrueandfalse; this header can be included by new projects or by projects that didn't already definebool.
|
I'm trying to calculate, for0 < n ≤ 10⁹, the value of
```
re=(2^n)%1000000007
```
I wrote this code:
```
int main()
{
int n,i,re=1;
scanf("%d",&n);
for(i=0; n>i; i++) re=(2*re)%1000000007;
printf("%d",re);
}
```
Whennis 10⁹, my code takes too long.
What can I do to make it faster?
|
You can follow binary exponentiation which will be something like
```
#define MOD 1000000007
long long fastExp(int b, int e) {
long long r=1;
while(e>0) {
if(e&1) r=(r*b)%MOD;
b=(b*b)%MOD;
e/=2;
}
return r%MOD;
}
```
Call it like thisfastExp(2,n).
Well the complexity is pretty simple in that it doeslog2(n)operations so this will work better than yourO(n)solution.
As an explanation to why your solution got TLE. The online judges available like that ofSPOJetc usually take 1 sec to do10^8loop operations. Here you do much more than that when you haven=10^9as input.
|
I want to use sparse matrix or matrix, depending on efficiency and space saving
I’m trying to find what’s is more efficient and save space in run time
The size of the matrix is changing but every value is char (can be nothing -‘\0’)
I’m reading the data of the matrix values from file...
(In the beginning of each file there is the size of the matrix)
Thank you in advance
|
You can think on this as a graph representation.
As you know, if you use matrix, the space complexity would be|V|^2(|V|is number of nodes).
Moreover, if you use adjacency matrix (or sparse matrix) the space complexity would be|V||E|, which|E|is the number of non-zero strings which are related to a node.
Hence, you can traverse the file and compare|V|^2and|V||E|and decide base on these two values.
|
I'm performingOtsu's method(linkhttps://en.wikipedia.org/wiki/Otsu%27s_method) in order to determine how many black pixels are in the raw frame. I'm trying to optimize process and I want to do it withOpenCL. Is there any way to pass thesingle variableto OpenCL kernel and increment it, instead of passing thewhole bufferwhen it's not necessary?
|
The problem you want to solve is very much like a global reduction. While you could use a single output variable and atomic read/modify/write access, it would be very slow (due to contention on the atomic) unless the thing you are counting is very sparse (not the case here). So you should use the same techniques used for reduction, which is to do partial sums in parallel, and then merge those together. Google for "OpenCL reduction" and you'll find some great examples, such as this one:https://developer.amd.com/resources/articles-whitepapers/opencl-optimization-case-study-simple-reductions/
|
I saw something in someones code that I don't understand. What does it say in the return statement?
```
static cell_ptr UD_self(cell_ptr c) { return c->U = c->D = c; }
```
here is defined:
```
struct cell_s;
typedef struct cell_s *cell_ptr;
struct cell_s {
cell_ptr U, D, L, R;
int n;
union {
cell_ptr c;
int s;
};
};
```
|
It's just a shorthand way of writing this:
```
{
c->D = c;
c->U = c->D;
return c->U;
}
```
The statementreturn c->U = c->D = c;works because the assignment operator=returns the value it has just assigned. This value is then used in the next assignment. It associates from right to left, so it meansreturn (c->U = (c->D = c));
|
I study computer engineering, and the teachers here have always told us to define an µC address like this:
#define FIO0DIR (* (unsigned int *) 0x2009C000) //GPIO direction register from the lpc1769
But they never really explained why or what's happening.
So my question is: why is the cast there, at all?
|
why the cast at all?
Because0x2009C000is an integer constant. Not an address. The C type system differentiates integers from addresses, even if the target architecture may not. It allows for conversions with various constraints on them, but the two types arenotone and the same.
You need the cast to turn the integral constant into the proper pointer type, so you may dereference it and access what's at that address.
|
it prints only FG and other characters are garbage
```
#include<stdio.h>
void putstr(char *s1[])
{
while(*s1!='\0')
{
printf("%c",*s1);s1++;
}
}
int main()
{
char s1[10]="fedfgh";
putstr(s1);
}
```
|
void putstr(char *s1[])This is wrong. The actual argument toputstris an array (which decays to a pointer) but the formal parameter saysputstraccepts an array of pointers tochar.
Usevoid putstr(char *s1)orvoid putstr(char s1[]).
|
```
unsigned long long int first( int b , int c){
int h=b;
//int k;
for(int k=b-1;k>c;k--){
b=b*k;
}
int comb=b/factorial(h-c);
return comb;
}
```
this function return right answers for some cases and wrong answer to others. can anyone help me please is there anything wrong with this function?!
|
Sinceint combisintyou are returning int!
It does not matter that you are suppose to returnunsigned long long int first. The result of the devision is rounded tointvalue, precision is lost.
|
I came across this code implementing a queue
```
typedef struct Node {
void * data;
struct Node * next;
} node_t;
```
the node is free'd in this way
```
static void freeNode(node_t *node) { free((void*)node); }
```
Why is the node casted tovoid *?
Should't have been justfree(node)?
And since I'm working on another structure :
```
typedef struct TaskNode {
void (* fun)(void *);
void * arg;
struct Task * next;
} task_t;
```
Should I cast the pointer to the malloc'd structure tovoid *too before freeing it?
|
The cast is useless in this context, c auto-promote any pointer tovoid *in a lot of context(not for stdarg for exemple):
```
free((void*)node);
```
is equivalent to:
```
free(node);
```
|
Is it possible (using the CPLEX C APIs) to retrieve the variables type (CPX_CONTINUOUS, CPX_BINARY, CPX_INTEGER, ...) of a model not handled by me but directly built from an .mps file?
|
Yes, you can use theCPXgetctypefunction. Here's the example given in the documentation link:
```
status = CPXgetctype (env, lp, ctype, 0, cur_numcols-1);
```
To get the number of columns useCPXgetnumcols.
|
I have a code where am gettingPC Lint info 825, even though I'm using/* fallthrough */comment. Tell me if any of my usage is wrong.
Example code:
```
case 1:
case 2:
case 3:
{
statement;
}
/* fallthrough */
case 4:
{
statement 1;
statement 2;
break;
}
default:
break;
```
|
That's the wrong comment content. Try:
```
//lint -fallthrough
```
Seethe huge text filefor details.
|
I am working with XILINX VIVADO HLS in which I need to run C/C++ codes with "Arbitrary Precision Types". So, I have gone through the "Arbitrary Precision Types" topics in UG902 Xilinx guidebook.But I am not clear on the topic. I don't know how to initialize"total width of the variable". Can anyone explain me with examples?
```
int#W,
uint#W
```
The number #W specifies the total width of the variable being declared.
Suppose my array size is 102 (1D-array) or 102x204 (2d array). How u will declare "total width of the variable".
|
The width of an arbitrary precision type refer to the number of bits in the variable, and it is orthogonal to storing precision types in an array.
For instance, if you want 102 elements of 4 bits, you would use:
```
int4 array[102];
```
|
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.Closed5 years ago.Improve this question
I am trying to understand why this program prints out 8.
```
#define mul(x,y) (x * y)
int main() {
int x = 3;
int y = 4;
int z = 0;
z = mul(x+1, y+1);
printf(“4*5 = %d \n”, z);
}
```
|
Macrosaren't functions
After the first phase of compilation, preprocessing, the macrois expanded:
```
z = mul(x+1, y+1);
// becomes
z = (x+1 * y+1);
```
No doubt thatx + 1*y + 1 == 8.
A better way to define this macro is toparenthesizexandy:
```
#define mul(x, y) ((x)*(y))
```
You can try it yourself: Compile this code withgcc -E foo.c -o foo.i
```
#define mul(x, y) (x * y)
int x = 3;
int y = 4;
int z = mul(x+1, y+1)
```
And see the content offoo.i.
|
I am working on a project to send the values of a temperature and humidity sensor to a server via a GET.
The line in the library of W5500 is:
client.println ("GET / search? q = arduino HTTP / 1.1");
So I change the / search? Q = arduino by the frame I have to send on my database.
The problem is that I can not create my frame. In this frame I have two values uint16_t (Temperature and humidity) and I need to separate them by a "_" to differentiate and parse the frame in my php.
But that's how to change the "GET / search? Q = arduino HTTP / 1.1" by a variable, and how to build a frame with integers and a "_"?!
I have already try strcpy, but strcpy work only with a char or string.
|
The command you are looking for issprintf
sprintf (str, "%d_%d", temp, humid);
|
I was trying to understand some code, wherein I found the statement:
```
n=n&(n-1);
```
What does this do?
|
That equation zeroes out the least significant non-zero bit inn.
If we assume 8 bits, then here is the back of the envelop explanation. Letnbe 70.
```
n = 01000110
n-1 = 01000101
--------
n&(n-1) = 01000100
```
As a consequence, if the result is 0, it means there was only one bit set innoriginally, which means it was a power of 2 (or it was 0 to being with).
If applied iteratively in a loop untilnbecomes 0, the number of iterations counts the number of bits set innoriginally. However, most processors will have a built-in operation to do this for you.
If bit-hacks interest you generally, searching this site for "bithacks" generates many hits.
|
This question already has answers here:"strlen(s1) - strlen(s2)" is never less than zero(3 answers)Closed5 years ago.
The output for the code is 3? Please explain.According to me it should be
5.After removing "unsigned" still i got the output as 3.
```
#include<stdio.h>
#include<string.h>
void main(){
unsigned int c=0;
int len;
char x[20]="abc";
char y[20]="defgh";
if((strlen(x)-strlen(y))>c)
len=strlen(x);
else
len=strlen(y);
printf("%d",len);
}
```
|
Becausesize_tis unsigned inC. So the comparison being negative yields a positive number. (sign extended bits of signed number yields a large value in unsigned case). Then that value is compared with0- being true it enters the first condition. Outputs 3.
Even if you remove unsigned fromCthat result of thestrlensubstraction yields a positive number much larger than 0. That's why you always get 3.
|
And the two functions are:
```
void readFromFile(char file[], int antal_varor, struct storagemanipulation
*inventory)
{
```
|
```
fp==fopen("minFil.txt","r")
```
This is the bug.
```
fp=fopen("minFil.txt","r")
```
will be the correct way.
You can do it simply like this
```
fp=fopen("minFil.txt","r");
if( fp == NULL ){
// error
}
else{
// do cool stuff
}
```
This is much more readable. Less error prone.
Also op is writing to the same file from which content was read. maybe the file where it is to be written is different.
|
I'm trying to compare a field of a struct that is holding a pointer of char with a pointer of char, but the comparison is not working.
```
typedef struct node{
char * word;
struct node * next;
int occurrence;
}No;
```
```
aux = list;
while(aux != NULL){
if(aux->word == token)
{
new_node->occurrence = new_node->occurrence+1;
exist = 0;
}
aux = aux->next;
}
```
|
if(aux->word == token)
Well you are comparing addresses and in the case they are equal (which is highly unlikely) it will enter the block.
Correct way to do is to check the contents.strcmp()is there to help you with that.
```
strcmp(aux->word, token) == 0
```
Compares the content pointed by them. That is appropriate here.
|
Here is a slide from System Programming course I'm currently taking:
catch_childisSIGCHLDhandler. How does the output correspond to the code? Why are some "Child #x started" messages not printed?
|
By definition,deadlockis a situation when no progress is made.
So it is not that someprintfmessages are not printed/ignored, but that after some particularprintfcall the program is waiting for something that will never happen and it keeps waiting there forever.
For more info about what causes such behavior see:Why are malloc() and printf() said as non-reentrant?
|
I am pretty new at C and I tried to start writing functions because I will need this the most, however the return command in my functions seems not to be working, not sure if this is the cause.
```
#include <stdio.h>
int pega(int ppp);
int main() {
int ui, marlin;
printf("plotaaa\n");
scanf("%d", &ui);
marlin=pega(ui);
printf(marlin);
return 0;
}
int pega(int ppp) {
int ju;
ju = ppp+3;
return (ju);
}
```
this is a simple function that should just get a number and sum 3 and then return that to the main function where I am trying to print.
|
You are usingprintfincorrectly, you need to pass it a format string as the first argument, and a value as the second argument.
Something like this:
```
printf("%d", marlin);
```
|
This question already has answers here:Return value of "==" operator in C(4 answers)Closed5 years ago.
To test "What does this expression, 1>0, evalutes to (on 64 bit) in C?" question, I wrote this program.
```
int main()
{
printf("char=%d", 1>0 );
return 0;
}
```
It prints "1". Is it right way to find the expression, 1>0?And does operating system bit (64bit) matter? Why did the problem state (on 64 bit)???
|
In C,a > bis an expression ofinttype that is either equal to0or1. That is not a function of the operating system: of course though the exact nature of anintis dependent on your platform.
So1 > 0is anintwith value1.
So your code is equivalent toprintf("char=%d", 1);
|
I want to get a samesemIdusing same key.
Although, I calledsemgetmethod using same key, and returned differentsemId.
Please answer me the reason why this problem happened.
Sample source :
```
int id1, id2;
int semflg = IPC_CREAT | 0666;
id1 = semget(0, 1, semflg);
id2 = semget(0, 1, semflg);
```
Result : id1 != id2
|
Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.
|
I'm assuming no but not positive. Not sure If other variables can take up the same spot in the stack.
|
No. A function's local variables are not always at the same address.
Consider a recursive function. If the local variables were supposed to be in the same place, all their values would have to be copied in and out each time you went in and out of recursion.
The normal way of doing it is that each function call has a "block" on the stack. If you call the same function twice in a row the local variable addresses will probably be the same. If you call it recursively the second call will be in a different area of stack and so the local variable addresses will be different.
|
I'm trying to create a macro for my program in C to use in aprintf
```
#define TIME(t) \
(t->tm_hour >= 6 && t->tm_hour < 12) ? "Good morning":"" && \
(t->tm_hour >= 12 && t->tm_hour < 18) ? "Good afternoon":"" && \
(t->tm_hour >= 18 && t->tm_hour < 23) ? "Good night":""
```
theprintffunction is the same as below
```
printf("%s\n", TIME(t));
```
in compilation is returning me alert C4474
```
C4474: too many arguments passed for format string
```
Does anyone know why the error?
|
You need to have the else-conditions cascade:
```
#define TIME(t) \
(((t)->tm_hour >= 6 && (t)->tm_hour < 12) ? "Good morning" : \
((t)->tm_hour >= 12 && (t)->tm_hour < 18) ? "Good afternoon" : \
((t)->tm_hour >= 18 && (t)->tm_hour < 23) ? "Good night" : "")
```
|
I am pretty new at C and I tried to start writing functions because I will need this the most, however the return command in my functions seems not to be working, not sure if this is the cause.
```
#include <stdio.h>
int pega(int ppp);
int main() {
int ui, marlin;
printf("plotaaa\n");
scanf("%d", &ui);
marlin=pega(ui);
printf(marlin);
return 0;
}
int pega(int ppp) {
int ju;
ju = ppp+3;
return (ju);
}
```
this is a simple function that should just get a number and sum 3 and then return that to the main function where I am trying to print.
|
You are usingprintfincorrectly, you need to pass it a format string as the first argument, and a value as the second argument.
Something like this:
```
printf("%d", marlin);
```
|
This question already has answers here:Return value of "==" operator in C(4 answers)Closed5 years ago.
To test "What does this expression, 1>0, evalutes to (on 64 bit) in C?" question, I wrote this program.
```
int main()
{
printf("char=%d", 1>0 );
return 0;
}
```
It prints "1". Is it right way to find the expression, 1>0?And does operating system bit (64bit) matter? Why did the problem state (on 64 bit)???
|
In C,a > bis an expression ofinttype that is either equal to0or1. That is not a function of the operating system: of course though the exact nature of anintis dependent on your platform.
So1 > 0is anintwith value1.
So your code is equivalent toprintf("char=%d", 1);
|
I want to get a samesemIdusing same key.
Although, I calledsemgetmethod using same key, and returned differentsemId.
Please answer me the reason why this problem happened.
Sample source :
```
int id1, id2;
int semflg = IPC_CREAT | 0666;
id1 = semget(0, 1, semflg);
id2 = semget(0, 1, semflg);
```
Result : id1 != id2
|
Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.
|
I'm assuming no but not positive. Not sure If other variables can take up the same spot in the stack.
|
No. A function's local variables are not always at the same address.
Consider a recursive function. If the local variables were supposed to be in the same place, all their values would have to be copied in and out each time you went in and out of recursion.
The normal way of doing it is that each function call has a "block" on the stack. If you call the same function twice in a row the local variable addresses will probably be the same. If you call it recursively the second call will be in a different area of stack and so the local variable addresses will be different.
|
I'm trying to create a macro for my program in C to use in aprintf
```
#define TIME(t) \
(t->tm_hour >= 6 && t->tm_hour < 12) ? "Good morning":"" && \
(t->tm_hour >= 12 && t->tm_hour < 18) ? "Good afternoon":"" && \
(t->tm_hour >= 18 && t->tm_hour < 23) ? "Good night":""
```
theprintffunction is the same as below
```
printf("%s\n", TIME(t));
```
in compilation is returning me alert C4474
```
C4474: too many arguments passed for format string
```
Does anyone know why the error?
|
You need to have the else-conditions cascade:
```
#define TIME(t) \
(((t)->tm_hour >= 6 && (t)->tm_hour < 12) ? "Good morning" : \
((t)->tm_hour >= 12 && (t)->tm_hour < 18) ? "Good afternoon" : \
((t)->tm_hour >= 18 && (t)->tm_hour < 23) ? "Good night" : "")
```
|
This question already has answers here:Assigning optarg to an int in C(2 answers)Closed5 years ago.
I want to process some command line options.
```
int main(int argc, char **argv) {
char c;
int n = 10000;
int nThreads = 3;
while ((c = getopt (argc, argv, "n:t:")) != -1){
switch (c)
{
case 'n':
n = *optarg;
break;
case 't':
nThreads = *optarg;
break;
default:
abort();
}
}
printf("n=%d, nThreads=%d\n", n, nThreads);
}
```
But this does not work as I expect. Running./program -n 10000 -t 2will cause the program to outputn=49, nThreads=50.
What am I missing?
|
```
n = atoi(optarg);
```
Otherwise you are assigningcharto anint.
Also you can see from where the49and50is coming from.
Ascii value of char1is49and2is50.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.