question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I know that C compilers do structure padding by default. I also know that one can disable structure padding, though this
is not recommended and even prohibited for some CPU architectures. I was wondering why structure padding is taking place and what are the advantages of it?
|
What are the advantages of structure padding?
Variables put on machine-aligned addresses can be read or written in fewer assembly instructions — usually one. Thus, the compiler uses padding to optimize its access.
|
For example, if I allocate more memory space then needed on a C string is there a way to return back the unused memory? Or is this automatically done?
```
char *x = malloc(256);
strcpy(x, "Hello World");
// return back unused x memory allocation
```
|
You can callreallocto change the size of an allocation; this can be used to make it bigger or smaller.
The computer would have no basis for automatically making your allocation smaller.
|
I have read the following answer from@noson how to implement the execlp command but I am unable to run the same specifically forls -l $pwdusing execlp. I have tried bothexeclp("ls","ls", "-l", "$pwd", (char *)NULL);andexeclp("ls","ls", "-l", "pwd", (char *)NULL);but nothing seems to work. Any directions in this thought process would be really helpful
Thanks.
|
Those$...variable belongs toshell,notthe OS internal. When in shell you type such variables, shell will transform them to their actual value and then call system call.
In C program, you need to do it by yourself:
```
#include <unistd.h>
int main() {
char *cwd = getcwd(NULL, 0);
execlp("ls","ls", "-l", cwd, (char *)NULL);
}
```
getcwd()will give you the current directory.
|
I have anuint8_tarray of raw data that I want to write to a file (I have it's length)
The problem is that because I'm dealing with raw data there might be a0x00(aka null terminator) somewhere, meaningfputsis not reliable, the obvious alternative is to have a loop to usefputc()but is there a way i can do it without that?
Is there say a function that takes a pointer and a size and writes that amount of data from the pointer's location to the file?
|
In addition to the problem with null-character, there is problem reading binary data when file is opened in text mode (for examplefgetsstops when it encounters new line or0x0Aand0x1Acharacter in Windows)
Open the file in binary mode instead, and usefread/fwrite
```
FILE *fout = fopen("test.bin", "wb");
```
And usefwriteandfread
Reference
|
I made a simple program in Visual Studio and would like to distribute it. However, before I can do that, I would like to add metadata to the executable file (such as author, version, etc.) Is there any way to do this in a C or C++ project in Visual Studio 2017?
|
In the VS2008 Resource view, right-click on your project.
From the pop-up menu, select Add resource.
In the dialog, select Version
A Versioning resource is added to your project (program). Double-click on it and it will be shown in the editing pane. You can adapt the standard versioning elements.
If you right-click in the editor, you can add your own blocks.
If you compile your application, the version information will be added to the executable. Right-click the excutable, select Properties and then select the Detail tab to see your information.
Note: when testing, the executable was now flagged harmfull by F-Secure. I reported this false positive to F-Secure.
|
srand( (unsigned)time(null))is not working though I have includestdlib.hlibrary too. It saystimeis an undefined word as an error.
```
int i, max = 16, a[16];
for (i = 0; i < 16; i++)
a[i] = i;
srand((unsigned) time_t( NULL));
for (int i = 0; i < 16; i++) { // shuffle array
int temp = a[i];
int randomIndex = rand() % max;
a[i] = a[randomIndex];
a[randomIndex] = temp;
}
```
|
time_tis the type, not the function. You still calltime. "Calling"time_t( NULL )is constructing atime_twith a value of0, so of course you get the same random stream every time.
As the other answer notes, you need to#include <time.h>, but you also need to calltimeproperly; your use oftime_there is equivalent to always seeding with zero. You need to change your seeding to:
```
srand((unsigned)time(NULL));
```
which willreturnthe current time as atime_twhich you then cast tounsignedfor use as the seed.
|
I am writing a scanner for my compiler project usingflexand writing it indecaf(a language similar to C/C++ & Java), my scanner is up and running, except it fails in identifying boolean constants (true, false) I wrote below pattern and C code:
```
"true" { yylval.boolConstant = 1;
return T_BoolConstant; }
"false" { yylval.boolConstant = 0;
return T_BoolConstant; }
```
but instead of returningT_BoolConstantit keeps returning asT_Identifier. Basically scanner is recognizing both "true" & "false" as text valid to be considered as identifier not as boolean binary variable.
There isthisanswer for similar type of question but still it doesn't work for me!
Any guess why it isn't returning true/false ?
|
This will be because you have your rule for identifiers above these rules. Flex matches rules top to bottom.
|
Hey I'm trying to figure out if it's possible that
the function fscanf operates on the integer that it has read from a file before storing it into an array.
For ex:
```
for(int i = 0 ;i < size;i++){
//Here it just stores the number read
fscanf(file, "%d", &arr[i]);
//However I'm trying to do such a thing(substract the number by 1 everytime)
fscanf(file, "%d -1 ", &arr[i]);
printf("\n%d",arr[i]);
}
```
Thanks in advance
|
This won't do what you need?
```
for(int i = 0; i < size; i++){
int temp;
fscanf(file, "%d", &temp);
arr[i] = temp - 1;
printf("\n%d",arr[i]);
}
```
|
srand( (unsigned)time(null))is not working though I have includestdlib.hlibrary too. It saystimeis an undefined word as an error.
```
int i, max = 16, a[16];
for (i = 0; i < 16; i++)
a[i] = i;
srand((unsigned) time_t( NULL));
for (int i = 0; i < 16; i++) { // shuffle array
int temp = a[i];
int randomIndex = rand() % max;
a[i] = a[randomIndex];
a[randomIndex] = temp;
}
```
|
time_tis the type, not the function. You still calltime. "Calling"time_t( NULL )is constructing atime_twith a value of0, so of course you get the same random stream every time.
As the other answer notes, you need to#include <time.h>, but you also need to calltimeproperly; your use oftime_there is equivalent to always seeding with zero. You need to change your seeding to:
```
srand((unsigned)time(NULL));
```
which willreturnthe current time as atime_twhich you then cast tounsignedfor use as the seed.
|
I am writing a scanner for my compiler project usingflexand writing it indecaf(a language similar to C/C++ & Java), my scanner is up and running, except it fails in identifying boolean constants (true, false) I wrote below pattern and C code:
```
"true" { yylval.boolConstant = 1;
return T_BoolConstant; }
"false" { yylval.boolConstant = 0;
return T_BoolConstant; }
```
but instead of returningT_BoolConstantit keeps returning asT_Identifier. Basically scanner is recognizing both "true" & "false" as text valid to be considered as identifier not as boolean binary variable.
There isthisanswer for similar type of question but still it doesn't work for me!
Any guess why it isn't returning true/false ?
|
This will be because you have your rule for identifiers above these rules. Flex matches rules top to bottom.
|
Hey I'm trying to figure out if it's possible that
the function fscanf operates on the integer that it has read from a file before storing it into an array.
For ex:
```
for(int i = 0 ;i < size;i++){
//Here it just stores the number read
fscanf(file, "%d", &arr[i]);
//However I'm trying to do such a thing(substract the number by 1 everytime)
fscanf(file, "%d -1 ", &arr[i]);
printf("\n%d",arr[i]);
}
```
Thanks in advance
|
This won't do what you need?
```
for(int i = 0; i < size; i++){
int temp;
fscanf(file, "%d", &temp);
arr[i] = temp - 1;
printf("\n%d",arr[i]);
}
```
|
New to Doxygen and wondering can it be used to draw a graph showing what functions use a given global variable. I have been able to get call/caller graphs working for functions and want to do something similar for a hand full of variables.
|
REFERENCED_BY_RELATION = YES: In a Variable description it documents all functions which have used the variable and generates a hyperlink to these functions in the code. In the function documentation, this documents all functions being used in that particular function and also generates a hyperlink to the actual code.
REFERENCES_RELATION = YES: In a function documentation, this documents all functions that have called the function being described and also generates a hyperlink tot he code.
Although this is not a graphical solution (which would be way better), this is something one can definitely work with.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question
I'm using a char array:
```
char *strs[3] = {"foo", "bar", "bletch"};
LCDPutStr(*strs, 17);
```
The output isfoo. How can I select another item? e.gbarorbletchfrom array.
|
strsis an array ofchar *. Arrays in C have a starting index of 0 are indexed with[].
So if you want the second element you would usestrs[1].
|
I came across a wield code and I can't understand it:
```
int x=259;
char *p = (char*)&x;
printf("%d ", *p);
printf("%d ", *(p + 1));
printf("%d ", *(p + 2));
printf("%d ", *(p + 3));
```
The output is:
```
3 1 0 0
```
I've try changing x to many different numbers, the results made me more confused
```
X Output
127 127 0 0 0
128 -128 0 0 0
256*127 0 127 0 0
256*128 0 -128 0 0
```
so on...
Can someone explain what is p pointing to in
```
char *p = (char*)&x;
```
and what does it print out.
Thank you.
|
```
int x=259;
char *p = (char*)&x;
```
x is 4 bytes0x03 0x01 0x00 0x00since the machine you are on is little endian (seehttps://en.wikipedia.org/wiki/Endianness)
so
p points at the first byte = 3p+1 points at 1p+ 2 and + 3 points at 0
you can do the same analysis for other values.
|
Just a quick question for which I fail in finding proper answer.
If I want to declare a const text variable, is it absolutely equal to do:
```
const char my_variable [] = {'t', 'e', 's', 't', 0};
```
or
```
const char my_variable [] = "test";
```
Many thanks in advance
|
Yes, the two declarations are identical.
"test"is achar[5]type in C, with elements't','e','s','t', and0.
(Note that in C++, the type is aconst char[5]: yet another difference between the two languages. SeeWhat is the type of string literals in C and C++?).
|
I want to see how many errors I have in my source code but compiler stops when it encounters some errors (but not all).
Is there a way to make Visual Studio to continue compiling until it finds all errors in code?
(Visual Studio 2008 is mandatory)
EDIT:I need to do this for the following reason. We have a c99 code base but customer demands an older version which Visual Studio 2008 should be able to compile. Thus we want to see how many errors occur because of the difference between c99 and c89 (not c 89 but a version in between for Visual Studio 2008).
|
"Thus we want to see how many errors occur because of the difference between c99 and c89"
I don't think you can do that. For example:
```
int example(void)
{
getsomething();
int i; // <== invalid in C89
```
The above example is just 1 error but will generate lots of errors becauseiis not declared in the remainder.
|
I'm new inCprogramming. Could you read and explain the purpose of below code:
```
typedef void (*func_ptr)();
void func_call (int addr)
{
func_ptr func;
func = (func_ptr)(addr);
func();
}
```
I don't understand whatfunc = (func_ptr)(addr);do and the purpose offunc();Thanks.
|
The very first line
```
typedef void (*func_ptr)();
```
declarefunc ptras an alias of typevoid (*)(). Nowfunc_ptrcan be used to declare a function pointer in the program. Therefore
```
func_ptr func;
```
declaresfuncas a function pointer of typevoid (*)(). It is equivalent to
```
void (*func)();
```
Now this function pointer can point to a function and then can be used to call that function. I guessaddris used as an address of a function and then this address is casted to the type offunc_ptrin the statement
```
func = (func_ptr)(addr);
```
func()is used to call that function.
|
I have aconst char*string, I want to copy that string character by character to dynamic `char*.
```
const char *constStr = "Hello world";
char *str = (char*) malloc(strlen(constStr)+1);
while(*constStr){
*str = *constStr;
constStr++;
str++;
}
printf("%s", str);
free(str);
```
The problem is that previous code just copies each character ofconstStrto only the first index of thestr. I don't know why?
|
As others have pointed out, you are incrementingstrpointer in each iteration, so you always end up printing the end of the string.
You can instead iterate over each character without incrementing the pointer. The following code worked for me:
```
const char *constStr = "Hello world";
int len = strlen(constStr);
char *str = (char *) malloc(len + 1);
int i;
for (i = 0; i <= len; ++i) {
str[i] = constStr[i];
}
printf("%s", str);
free(str);
```
|
When I add an endless loop to my, code it doesn't work. It just runs and does nothing.
For example, this code doesn't print"hello".
```
#include <stdio.h>
int main(){
printf("hello");
while(1){
}
return 0;
}
```
but this code prints "hello".
```
#include <stdio.h>
int main(){
printf("hello");
//while(1){
//}
return 0;
}
```
How can I add awhile(1)loop to my code?
|
for example in this code, doesn't print "hello".
It is because of thebuffering.
You can callfflush(stdout)just after theprintf()in order to flush the buffer:
```
#include <stdio.h>
int main(){
printf("hello");
fflush(stdout);
while(1){
}
return 0;
}
```
In your second case the buffer is flushed at program's termination.
|
Say I have a struct defined as follows:
```
typedef struct {
int width;
int height;
char **data;
} puzzle;
```
Then, according to my textbook, the free function should look like this:
```
void puzzle_free(puzzle** puzzle)
```
But I don't see why puzzle should be a double pointer in the free function.
|
It probably has nothing to do with the double pointer contained in the struct, but is just a way to write free functions that helps prevent access after free.Eugene Sh. refers to it in his comment.
The implementation ofpuzzle_freewould be:
```
void puzzle_free(puzzle** puzzle_p) {
puzzle *puzzle = *puzzle_p
// Somehow free puzzle->data
free(puzzle);
*puzzle_p = NULL;
}
```
And usage would be:
```
puzzle *puzzle = malloc(...)
// Fill it, use it.
puzzle_free(&puzzle);
// puzzle pointer is now NULL
```
|
Not C# or C++, but C. Is there any C support in Visual Studio?
|
Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community).
UnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler.
Answer:by default it appears not, but you can install the Clang component and it appears you will be able to.
|
When I add an endless loop to my, code it doesn't work. It just runs and does nothing.
For example, this code doesn't print"hello".
```
#include <stdio.h>
int main(){
printf("hello");
while(1){
}
return 0;
}
```
but this code prints "hello".
```
#include <stdio.h>
int main(){
printf("hello");
//while(1){
//}
return 0;
}
```
How can I add awhile(1)loop to my code?
|
for example in this code, doesn't print "hello".
It is because of thebuffering.
You can callfflush(stdout)just after theprintf()in order to flush the buffer:
```
#include <stdio.h>
int main(){
printf("hello");
fflush(stdout);
while(1){
}
return 0;
}
```
In your second case the buffer is flushed at program's termination.
|
Say I have a struct defined as follows:
```
typedef struct {
int width;
int height;
char **data;
} puzzle;
```
Then, according to my textbook, the free function should look like this:
```
void puzzle_free(puzzle** puzzle)
```
But I don't see why puzzle should be a double pointer in the free function.
|
It probably has nothing to do with the double pointer contained in the struct, but is just a way to write free functions that helps prevent access after free.Eugene Sh. refers to it in his comment.
The implementation ofpuzzle_freewould be:
```
void puzzle_free(puzzle** puzzle_p) {
puzzle *puzzle = *puzzle_p
// Somehow free puzzle->data
free(puzzle);
*puzzle_p = NULL;
}
```
And usage would be:
```
puzzle *puzzle = malloc(...)
// Fill it, use it.
puzzle_free(&puzzle);
// puzzle pointer is now NULL
```
|
Not C# or C++, but C. Is there any C support in Visual Studio?
|
Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community).
UnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler.
Answer:by default it appears not, but you can install the Clang component and it appears you will be able to.
|
I'm trying to link a program built with MSVC against a DLL compiled with MinGW. The problem is the DLL assumes the functionfprintfexists, but MSVC doesn't have a definition for it in any of the libraries it links against. I cannot change versions of neither MSVC nor of MinGW, so the only way I can think around the problem is to write my ownfprintf, but I would hope there's a simple implementation that doesn't require from me to maintain a whole library of code...
|
Is there a way to define fprintf in terms of printf / simpler functions (easily)?"
Yes, if the library hasvfprintf()
```
#include <stdarg.h>
#include <stdio.h>
int my_own_fprintf(FILE * stream, const char * format, ...) {
int y;
va_list args;
va_start(args, format);
y = vfprintf(stream, format, args);
va_end(args);
return y;
}
```
|
I am creating a 5x5 board game in C. The problem I am having is that when I use the rand() it duplicates some of the numbers. How do I stop the duplicates and 0's?
Sorry if too basic a question. I'm new to C.
```
int createboard() {
int rows;
int columns;
int board[5][5];
int board2[5][5];
srand(time(NULL));
for (rows = 0; rows < 5; rows++) {
for (columns = 0; columns < 5; columns++) {
randomNumber = rand() % 25;
board[rows][columns] = randomNumber;
}
}
}
```
|
rand()would not be a particularly good generator if the probability of drawing the same number twice was zero.
A standard approach here would be to generate theboardwith consecutive numbers, thenshuffleit by swapping elements at random a certain number of times.
A good shuffling algorithm ishttps://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
|
I would like to send data from an STM32 (Cortex M4) device via its I2S peripheral using DMA in 24bit mode, MSB first.
The I2S data register is however only 16bit, according to the datasheet you have to send the upper halfword first, then the lower one.
This is problematic when using the DMA, it will always send the lower halfword first.
What is an efficient way in c or ARM-assembler to switch the two halfwords?
|
Write the common idiom
```
unsigned w;
w = w << 16 | w >> 16;
```
an optimizing compiler generally translates this to a singlerororrev16instruction. It is reasonable to expect the compiler to do this optimization. Make sure thatwis unsigned so the right shift is an unsigned one.
If the compiler does not optimize this, it's still just two instructions (a shift and an or with a shifted operand), so not much performance is lost.
|
```
FILE * fp = fopen ("excel.csv" , " w+ ");
fprintf (fp, "%s", "hello,world");
```
I want to printhello,worldwith comma in a single cell.
How can I print the same without printing in two different cells?
|
Put quotes around the cell:
```
fprintf(fp, "%s", "\"hello,world\"");
```
IIRC Wikipedia hasa pretty good article on CSV.
|
This question has to do with a college assignment, so I'll keep it abstract to not give away any part of the challenge.
Given a compiled C program (x86_64 ELF on Linux), is there a way to know, just from the disassembly, which address a function pointer inside of that program would contain to point to a specific function (also inside of the program, not an external library) in any execution of the program? Is it possible to infer the complete address just from the address of that function in the disassembly?
For example, if the program contains a pointer:void (*ptr) () = &someFunc;, is the content of ptr inferable from the adress of someFunc in the disassembly?
|
So I managed to solved the problem. As it turned out, the addresses the function pointers were using were the exact addresses in the disassembly. At the end I figured it out stepping through with gdb and looking at the contents of the registers.
|
this is my code :
```
int x, y, z,n;
printf("Introduceti minimul de cifere,vocale,consoane pe care trebuie sa le contina un cuvant\nSub forma x\\y\\z\n");
scanf("%d\%d\%d", &x, &y, &z);
printf("Introduceti numarul pe care il doriti de cuv asemanatoare\n");
scanf(" %d", &n);
```
This program doesn't readn.
|
You can't separate your numbers entered by a backslash in this manner...
```
scanf("%d\%d\%d", &x, &y, &z);
```
...because what the compiler sees is you escaping the %. To put a backslash into a string you need to double it up like this
```
scanf("%d\\%d\\%d", &x, &y, &z);
```
|
This question already has answers here:Call by reference, value, and name(6 answers)Closed5 years ago.
We called the functionfoo(&x, &y)in themainfunction but then why did we callswap (x, y)insidevoid foofunction asswap (&x, &y)?
```
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void foo(int*p1, int*p2) {
*p1 += *p2;
swap(p1, p2);
*p2 *= *p1;
}
int main(){
int x = 5, y = 9;
foo(&x, &y);
printf("x=%d\n", x);
printf("y=%d\n", y);
system("PAUSE");
return 0;
}
```
|
The difference is the type of the parameters you call the function with.
First case:
The type ofxisintand thefoofunction is expectingint *.
So you havefoo(&x, &y);
Second case:
The type ofp1isint *and theswapfunction is also expectingint *.
So you haveswap(p1, p2);
|
Assume the following code in c:
```
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
char *args[] = {"/bin/echo", "1", NULL};
execvp(args[0], args);
}
```
Why doesexecvpaccept 2 arguments? Why can't it beexecvp(args)and internally it would automatically grab the executable to run fromargs[0]?
|
What if you want the "name" of the process (args[0]in your case) to be different from the actual executable program? That is a valid use-case, and the simplest solution to handle both the cases is the two-argumentexecvpwe now have.
|
When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?
|
You can view the symbols of a compiled program or object file withnm(1):
```
nm a.out
```
Displays all symbols ina.out.
|
Why does the firstprintf()just return the value -536870912 and the second return the difference between the maximum value of anunsigned intwith the result of multiplying 65535 * 65535. (Running a 64 bit machine).
```
int x = 7 * 536870912;
printf("%d\n", x);// 536,870,912
//answer: 3,758,096,384 - 3 Billion
//returns : - 536870912
printf("%d\n", 65535 * 65535 );// 65,535
// answer : 4,294,836,225 4 Billion
// returns: -131071
```
|
Typically, even on 64-bit systems, theinttype is still a signed 32-bit type. You could have easily verified it by printingsizeof(int). If you want more then uselong longwhich is guaranteed to be at least 64 bits.
Be careful withlong, it might be 64 bits or it might be only 32 bits. Uselong long.
|
Assume the following code in c:
```
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
char *args[] = {"/bin/echo", "1", NULL};
execvp(args[0], args);
}
```
Why doesexecvpaccept 2 arguments? Why can't it beexecvp(args)and internally it would automatically grab the executable to run fromargs[0]?
|
What if you want the "name" of the process (args[0]in your case) to be different from the actual executable program? That is a valid use-case, and the simplest solution to handle both the cases is the two-argumentexecvpwe now have.
|
When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?
|
You can view the symbols of a compiled program or object file withnm(1):
```
nm a.out
```
Displays all symbols ina.out.
|
Why does the firstprintf()just return the value -536870912 and the second return the difference between the maximum value of anunsigned intwith the result of multiplying 65535 * 65535. (Running a 64 bit machine).
```
int x = 7 * 536870912;
printf("%d\n", x);// 536,870,912
//answer: 3,758,096,384 - 3 Billion
//returns : - 536870912
printf("%d\n", 65535 * 65535 );// 65,535
// answer : 4,294,836,225 4 Billion
// returns: -131071
```
|
Typically, even on 64-bit systems, theinttype is still a signed 32-bit type. You could have easily verified it by printingsizeof(int). If you want more then uselong longwhich is guaranteed to be at least 64 bits.
Be careful withlong, it might be 64 bits or it might be only 32 bits. Uselong long.
|
I ran across a problem where I need to extract each element of string to an integer array, the string only contains integer values without any space or delimiter.
Here is an example.
```
char input[8]="02320000";
```
to
int output[8]={0,2,3,2,0,0,0,0};
I tried to use theatoi()and it is taking the entire string as digit.
The string characters will be 0-3.
thank you
|
```
char input[8]="02320000";
int output[8];
for(int i = 0; i < 8; i++)
{
output[i] = input[i] - '0';
}
```
explanation of the -'0'Convert a character digit to the corresponding integer in C
|
I am learning pointers now, and i have some troubles with reallocating of char* in function.
When i am running this code, i have this error.
p.s. the one only goal of this code, it to understand how are pointers working.
```
void redefine(char** string) {
*string = realloc(*string, 10 * sizeof(char));
*string = "otherText";
}
int main(){
char *first = malloc(5 * sizeof(char));
first = "text";
redefine(&first);
return 0;
}
```
thanks in forward
|
C doesn't use assignment to copy strings.
When you do
```
first = "text";
```
firstnow points to the literal stringtext, it no longer points to the memory that was allocated withmalloc(). So you can't callrealloc()on that pointer.
You should use:
```
strcpy(first, "text");
```
to copy the sdtring into the allocated memory.
Similarly, in the function you should use
```
strcpy(*string, "otherText");
```
|
This question already has answers here:Why a structure is allowed to have "pointer to its own type" as member but not "(an array of the) structure type" itself?(3 answers)Closed5 years ago.
Why do we use pointers in self-referential structs? It is obligatory or not? If not, what advantages does us having a pointer to struct in struct versus normal struct definition give?
```
typedef struct _Struct {
struct _Struct* next; // do we really need this pointer?
} Struct;
```
|
Pointer has fixed size, so compiler can determine the size of the struct_Structwhen parsing it.
If_Structcontains itself physically, there is no way to determine its size, it's a cyclic definition.
|
I have a C file called fileTest.c, which simply contains this:
```
#include <stdio.h>
int main()
{
FILE* file = fopen("test.txt","r");
if (file == NULL) {
printf("file failed to open\n");
}
fclose(file);
return 0;
}
```
In the same directory, I have the test.txt file, which is empty.I compile like so:gcc -Wall -std=gnu99 fileTest.c -o fileTestEverything works perfectly (nothing is printed) if I run the resultant executable in the command line with ./fileTest, but when I try to run the executable by double clicking the exec file, I get "file failed to open". I'm using macOS High Sierra 10.13.3. Why is this happening?
|
You need to provide the full path of the file"test.txt".
I tested it on the macOS High Sierra 10.13.2 with g++ 5.5.0. This is the output
|
I would like to realize in GTK3 a text window where to redirect the stdout using the c language.
Could you help me with suggestions about how to start.
Thank you.
|
I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.
|
In my code I need to pass a pointer to an array of pointers as a function argument. Code snippets:
```
struct foo * foos[] = {NULL, NULL, NULL};
some_function(&foos);
```
and:
```
static void some_function(struct foo ** foos) {
foos[0] = get_a_foo();
/* some more code here */
}
```
This works as expected (aftersome_function()returns,foos[]contains the pointers I set there), but I get a compiler warning for the call tosome_function():
note: expected ‘struct foo **’ but argument is of type ‘struct foo * (*)[3]’
What’s the correct way to accomplish what I want (i.e. pass a pointer to the array of pointers to the function, so that the function can change pointers in the array)?
|
Pass it assome_function(foos)
|
A question ask me if this code, contains any error.
The compiler doesn't give me any errors but this code contains some arguments that I don't know
The code is this:
```
int* mycalloc(int n) {
int *p = malloc(n*sizeof(int)), *q; //what does the ", *q"?
for (q=p; q<=p+n; ++q) *q = 0;
return p;
}
```
The possible solutions are:
The program is correctThere is an error at line 1There is an error at line 2There is an error at line 3There is an error at line 4
|
There is nocompile timeerror in the above code but atrun timeit will crash because ofq<=p+n.qis simply an integer pointer.
It should be
```
for (q=p; q<p+n; ++q) /** it works even though n is zero or you can add seperate if condition for the same, this may be the interviewer concern **/
*q = 0;
```
|
I have a file with ";" as a separator, i want to get some characters and save them as float, I've come up with something like this:
```
int c;
char help[10];
float x;
while(getc(c)!=';'){
strcpy(help, c);
}
float = atof(help);
```
|
Correct usage ofgetc. It isint getc(FILE *stream). So you need to provide thestreamfrom which it reads.
```
while(getc(c)!=';'){ <-- wrong
strcpy(help, c); <-- wrong
...
```
is wrong. The second parameter tostrcpyshould be a nul termnatedchararray.
```
char cs[]={c,0}
strcpy(help,cs);
```
or even betteralk suggested
```
{strcpy(help, (char[2]){c});}
```
About the input part you can do this though:
```
while((c=getc(stdin))!=';'){
...
```
Instead of usingatofit is much better to usestrtoforstrtodfunctions. They provide error checking unlike theseato*functions.
|
I have the following struct:
```
struct foo
{
...
char* cp;
};
```
And I want to pass astruct footype pointer to a function, but I want the function to cast the pointer toconst char* const cp, and I don't want theconstqualifier as part of the definition ofstruct foo. Declaring the function as:
```
void func (const struct foo* foo_i);
```
will ensure the pointercpis unchanged, but not the data it points to. Is there a way to declare the function so that the data is ensured to be read-only too?
|
What you describe isnotpossible.
Consider makingcpof typeconst char*.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed5 years ago.Improve this question
I'm trying to say "if a variable is equals either one of the values then execute a function",but I'm stuck onif (a / b == value1 || value).
How can I write this in a right way?
|
You need to change that into two logically ored comparison expressions.
```
if ((a / b == value1) || (a / b == value))
```
Consider havinga/bin a variable, which might be more efficient, especially if it has to go into a variable later anyway or already happens to be in one.If you do:
```
c = a/b;
if ((c == value1) || (c == value))
```
|
Why do I have to initialize one of the stacks to -1? Where would top1 point to?
```
int ar[SIZE];
int top1 = -1;
int top2 = SIZE;
void push_stack1 (int data)
{
if (top1 < top2 - 1)
{
ar[++top1] = data;
}
else
{
printf ("Stack Full! Cannot Push\n");
}
}
```
|
The difference is whether you lettop1point to the last used element or the first free element.
With-1you let it point to the last used element.
With0you let it point to the first free element.
There is also symmetry in the use of pre-increment/decrement and post-increment/decrement.
Initializing to-1implies++top1for push andtop1--for pop.
Initializing to0impliestop1++for push and--top1for pop.
|
In the code below, do I need to "free" the pointer pointing to an area of memory that was allocated using malloc? Isn't it sufficient to free the main pointer?
```
char * parentArray = malloc( 10 * sizeof(char));
char * miniArray = &parentArray [1];
free(myArr);
// free(miniArray) ?
```
|
In your code,parentArrayis the value returned bymallocand this is the value that needs to be passed tofree. The family of functions in C that perform dynamic memory allocation are:malloc,calloc, andrealloc. Callingfreeon a value not returned by one of these functions or callingfreeon the same value twice is undefined behavior.
There do exist other functions such asstrdupthat callmallocand return the result, so these pointers must be freed too. The documentation forstrdupwill tell you this. In general when writing C you must understand who is responsible for allocating and freeing memory and make sure this "contract" is well documented.
|
I would like to realize in GTK3 a text window where to redirect the stdout using the c language.
Could you help me with suggestions about how to start.
Thank you.
|
I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.
|
In my code I need to pass a pointer to an array of pointers as a function argument. Code snippets:
```
struct foo * foos[] = {NULL, NULL, NULL};
some_function(&foos);
```
and:
```
static void some_function(struct foo ** foos) {
foos[0] = get_a_foo();
/* some more code here */
}
```
This works as expected (aftersome_function()returns,foos[]contains the pointers I set there), but I get a compiler warning for the call tosome_function():
note: expected ‘struct foo **’ but argument is of type ‘struct foo * (*)[3]’
What’s the correct way to accomplish what I want (i.e. pass a pointer to the array of pointers to the function, so that the function can change pointers in the array)?
|
Pass it assome_function(foos)
|
A question ask me if this code, contains any error.
The compiler doesn't give me any errors but this code contains some arguments that I don't know
The code is this:
```
int* mycalloc(int n) {
int *p = malloc(n*sizeof(int)), *q; //what does the ", *q"?
for (q=p; q<=p+n; ++q) *q = 0;
return p;
}
```
The possible solutions are:
The program is correctThere is an error at line 1There is an error at line 2There is an error at line 3There is an error at line 4
|
There is nocompile timeerror in the above code but atrun timeit will crash because ofq<=p+n.qis simply an integer pointer.
It should be
```
for (q=p; q<p+n; ++q) /** it works even though n is zero or you can add seperate if condition for the same, this may be the interviewer concern **/
*q = 0;
```
|
I have declared this array of unions:
```
union Function {
char* name;
double (*fnct)();
int args;
};
union Function functions[] = {
{.name = "acos", .fnct = acos, .args = 1},
{.name = "asin", .fnct = asin, .args = 1},
{.name = "atan", .fnct = atan, .args = 1},
};
```
But, when I try to use it I get an Segmentation fault error.
```
for(int i = 0; i < sizeof(functions) / sizeof(union Function); i++) {
printf("%d\n", functions[i].args);
printf("%s\n", functions[i].name); //HERE!
}
```
|
A union containseitherof its members, notallof its members.
So the last initializer is the final one, meaning its value is just1. So printing the name ( a string) results in a seg fault becauseprintftries to dereference the address1.
If you want to have all of its members, usestructinstead ofunion.
|
I want to use CMake to check whetherstdlib.hhas thegetopt()function (I know this has been true for many years, but I still need to perform this check, and this question is about the general issue).
I know how to check for the presence of an include file:
```
check_include_files(malloc.h HAVE_MALLOC_H)
```
but not the presence of a function made available by that file. How can I do that?
Edit:Actuallygetopt()is never instdlib.h, it's typically inunistd.h, but never mind, the question can stand as asked.
|
You can do it usingCheckSymbolExists():
```
CHECK_SYMBOL_EXISTS(getopt stdlib.h HAVE_GETOPT)
```
|
This question already has answers here:Wait for and/or kill process grandchildren produced by fork(3 answers)Closed5 years ago.
I was wondering if we can use the system call
waitpid()
to wait a pid of a grandchildren
|
waitpid()is POSIX.
The POSIX standard says:
Thewait()andwaitpid()functions shall obtain status information (see Status Information) pertaining to one of the caller's child processes.
So the answer to your question is "No", at least from the standard's perspective.
This does not necessarily have to keep implementations from providing extensions to the standard.
From POSIX as well:
Nothing in this volume of POSIX.1-2008 prevents an implementation from providing extensions that permit a process to get status from a grandchild or any other process, but a process that does not use such extensions must be guaranteed to see status from only its direct children.
|
I've attempted to gcc a test.c file on my windows linux bash subsystem, gives me the "gcc not installed" so i go and try to install gcc usingsudo apt install gccso i'm using the root "sudo" so permissions should be granted, and i've tried with a few different variations of the install command
When I run the above the command I get the a series of errors saying that the ubuntu site's IP address couldn't be located(full can be seen here)
I think the Ubuntu server's IP has changed? or moved, I mean it literally gives 404 errors. This what i suspect, I don't know for sure, is there a way to download the gcc compiler? I don't know of any other routes to get the gcc compiler on my bash subsystem.
|
It's a 404 error (file not found). apt is connecting to the IP in question, it just doesn't have that file. Update your cache (sudo apt update), then try installing again.
|
I have declared this array of unions:
```
union Function {
char* name;
double (*fnct)();
int args;
};
union Function functions[] = {
{.name = "acos", .fnct = acos, .args = 1},
{.name = "asin", .fnct = asin, .args = 1},
{.name = "atan", .fnct = atan, .args = 1},
};
```
But, when I try to use it I get an Segmentation fault error.
```
for(int i = 0; i < sizeof(functions) / sizeof(union Function); i++) {
printf("%d\n", functions[i].args);
printf("%s\n", functions[i].name); //HERE!
}
```
|
A union containseitherof its members, notallof its members.
So the last initializer is the final one, meaning its value is just1. So printing the name ( a string) results in a seg fault becauseprintftries to dereference the address1.
If you want to have all of its members, usestructinstead ofunion.
|
I want to use CMake to check whetherstdlib.hhas thegetopt()function (I know this has been true for many years, but I still need to perform this check, and this question is about the general issue).
I know how to check for the presence of an include file:
```
check_include_files(malloc.h HAVE_MALLOC_H)
```
but not the presence of a function made available by that file. How can I do that?
Edit:Actuallygetopt()is never instdlib.h, it's typically inunistd.h, but never mind, the question can stand as asked.
|
You can do it usingCheckSymbolExists():
```
CHECK_SYMBOL_EXISTS(getopt stdlib.h HAVE_GETOPT)
```
|
This question already has answers here:Wait for and/or kill process grandchildren produced by fork(3 answers)Closed5 years ago.
I was wondering if we can use the system call
waitpid()
to wait a pid of a grandchildren
|
waitpid()is POSIX.
The POSIX standard says:
Thewait()andwaitpid()functions shall obtain status information (see Status Information) pertaining to one of the caller's child processes.
So the answer to your question is "No", at least from the standard's perspective.
This does not necessarily have to keep implementations from providing extensions to the standard.
From POSIX as well:
Nothing in this volume of POSIX.1-2008 prevents an implementation from providing extensions that permit a process to get status from a grandchild or any other process, but a process that does not use such extensions must be guaranteed to see status from only its direct children.
|
I've attempted to gcc a test.c file on my windows linux bash subsystem, gives me the "gcc not installed" so i go and try to install gcc usingsudo apt install gccso i'm using the root "sudo" so permissions should be granted, and i've tried with a few different variations of the install command
When I run the above the command I get the a series of errors saying that the ubuntu site's IP address couldn't be located(full can be seen here)
I think the Ubuntu server's IP has changed? or moved, I mean it literally gives 404 errors. This what i suspect, I don't know for sure, is there a way to download the gcc compiler? I don't know of any other routes to get the gcc compiler on my bash subsystem.
|
It's a 404 error (file not found). apt is connecting to the IP in question, it just doesn't have that file. Update your cache (sudo apt update), then try installing again.
|
I have at my disposal a pretty elaborate printing function to help me debug. Unfortunately, it prints directly to a specified file stream, rather than returning a string (it returns some irrelevant value instead).calldoesn't seem to have any parameters when I callhelp callin GDB. Is it really not possible to hide the return result of thecallcommand? Or is there another command I should be entertaining?
|
We can cast the result of the function tovoidto discard its value.
MWE
callnoresult.c
```
#include <stdio.h>
void pretty_printer() {
fprintf(stderr, "Hello world!\n");
}
int main() {
return 0;
}
```
Then, in terminal:
```
gcc callnoresult.c -o callnoresult
gdb ./callnoresult
<gdb message>
b main
run
call (void) pretty_printer()
<"Hello world!">
```
SeeWhat does casting tovoidreally do?for more info on the cast.
|
can anyone help me this c program.i am trying to execute this palindrome check code but its not getting executed after i enter number.is there any error?
```
#include<stdio.h>
int main()
{
int num,rev=0,r,temp;
printf("enter the number: ");
scanf("%d",&num);
temp=num;
while(num>0)
{
r=num%10;
rev=(rev*10)+r;
temp=temp/10;
}
if(num==rev)
{
printf("the number is palindrome %d: ",temp);
}
else
{
printf("%d is not a palindrome",temp);
}
return 0;
}
```
the block shows nothing, neither it stops executing.i tried it in code block and some online websites.
|
I believe you have an infinite loop here asnumdoes not change within the loop, so the outcome ofnum>0never changes:
```
while(num>0)
{
r=num%10;
rev=(rev*10)+r;
temp=temp/10;
}
```
|
I have macros:
```
#if defined DEBUG && DEBUG
# define D(...) printf(__VA_ARGS__)
#else
# define D(...)
#endif
```
Which effectively do nothing whenDEBUGhasTRUEvalue.
But now I want to provide theTYPEthing. Which will show the type of debugging:
```
D( 1, "some string" );
D( 2, "another thing" );
```
Is there a way to define such macros which will do nothing forD(1,..)and print debug messages forD(2,...)whenDEBUGis2and viceversa when1?
I wanna something like this::
```
#if defined DEBUG && DEBUG
# define D(type,...) if DEBUG&type THEN printf(__VA_ARGS__) else do nothing
#else
# define D(...)
#endif
```
|
Well, it won't be truely evaluated at preprocessing time, but if the type is a compile-time-constant, still at compile-type.
```
#define D(type, ...) (void)((type & DEBUG) && fprintf(stderr, __VA_ARGS__))
```
The above needs at least C99 though.
|
I have macros:
```
#if defined DEBUG && DEBUG
# define D(...) printf(__VA_ARGS__)
#else
# define D(...)
#endif
```
Which effectively do nothing whenDEBUGhasTRUEvalue.
But now I want to provide theTYPEthing. Which will show the type of debugging:
```
D( 1, "some string" );
D( 2, "another thing" );
```
Is there a way to define such macros which will do nothing forD(1,..)and print debug messages forD(2,...)whenDEBUGis2and viceversa when1?
I wanna something like this::
```
#if defined DEBUG && DEBUG
# define D(type,...) if DEBUG&type THEN printf(__VA_ARGS__) else do nothing
#else
# define D(...)
#endif
```
|
Well, it won't be truely evaluated at preprocessing time, but if the type is a compile-time-constant, still at compile-type.
```
#define D(type, ...) (void)((type & DEBUG) && fprintf(stderr, __VA_ARGS__))
```
The above needs at least C99 though.
|
My code does not return any value. Can anyone help me explain why it does not work?
```
#include<stdio.h>
int main()
{
int nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%1d\n", nc);
}
```
|
You have to inputEOFto get out of the loop.
Windows:Ctrl+Z
Linux :Ctrl+D
SeeC : How to simulate an EOF?
Only aftergetchar()returnsEOFwill the value ofncbe printed.
And%1dis effectively same as%das a number has at least one digit.
If you do%10dor something the number would be printed occupying the space that would've been occupied by a 10 digit number. Default alignment is right.
You can make it left aligned with%-10d
|
Can someone explain what exactly is happening in these two statements listed below:
```
1) int enabled = val == 0; //val is an int
2) int sync = param || (foo->delay == NULL); //param and delay is both int
```
|
```
int enabled = val == 0;
```
read as
```
int enabled = (val == 0);
```
and
```
(val == 0)
```
will be either 0 or non zero if val is 0 or not.enabledwill then be initialized with that value
Equivalent to:
```
int enabled;
if(val == 0)
{
enabled = 1;
}
else
{
enabled = 0;
}
```
now you do that same analysis on the second one
|
I have to show the output of the program and explain what it does.
Where are the arguments of the functions?
```
int main(void)
{
printf("Answer: %d\n", f1(f2));
return 0;
}
int f1(int (*f)(int))
{
int n = 0;
while ((*f)(n))
n++;
return n;
}
int f2(int i)
{
return i * i + i - 12;
}
```
|
First of all you have missed the declaration of the function. If we consider they are there where it should be then you are passing a function pointer to the functionf1and then you are executing it inwhileloop's condition and if it turns out to be nonzero (the resukt off2) then the condition becomes true and then++is executed ornis increased by1.
It starts with (the value thatf2returns)-12then-10then-6then0. As a result your function will return3. So output is
```
Answer: 3
```
Note:int (*f)(int)meansfis a pointer to a function which returns anintand takes anintas it's argument.
|
```
#include<stdio.h>
int main()
{
int x=1,y=1;
for(;y&x<6;printf("%d %d\n",x,y++))
x++;
}
```
Here I expected an output like:
```
2 1
3 2
4 3
5 4
6 5
```
but I got an output
```
2 1
```
|
Because<has higher precedence than&fromhere.
So in the second iterationy=2andx=1.x<6becomes true - results in1whichwhenANDed withythe result becomes0. So it stops.y<x&6is equivalent toy&(x<6).
To explain you howANDworks :- (shown in 6 bits - but the logic holds same way forsizeof(int)*8bits).
```
000010
AND 000001
----------
000000
```
|
Hey i am working on a code and i stuck inside this if condition which is
(Not a actual Code simplified for better understanding)
```
if(18&2==2)
do something;
```
this if condition not executing but if i write like this
```
if(18|2==18)
do something;
```
it executed normal
also when I,
```
printf("%d",18&2);
```
it gives 2 now i am so confused why the above if statement not executing,
is it because of precedence ,please explain thanks.
|
Yours is aprecedence"error". The bit-wise operators have lower precedence than equality. Making18 & 2 == 2into18 & (2 == 2), which is18 & 1. That last one obviously evaluates to 0, since 18 is divisible by 2.
In such cases, when you get "weird results". Start by adding parenthesis to make sure every operator operates on the operand you expect it too.
|
Is there a way to compile Linux programs on Windows using MinGW and cmd? I really need to do that. And how will I have to link libraries?
Edit: The Libraries I want to link are SFML. They should be compatible on Linux and MacOSX. Is there at least a simlar Compiler that can compile to those three platforms?
|
MinGW compiles to executables referencing the Windows NT ABI. A program compiled in MinGW will, generally speaking, not be usable on Linux. You want a cross-compiler that goes the other direction, i.e., runs on Windows but compiles to executables referencing the Linux ABI. Alternatively, just get a crappy old computer, boot it into Arch and compile your code there.
|
```
#include<stdio.h>
int main()
{
int x=1,y=1;
for(;y&x<6;printf("%d %d\n",x,y++))
x++;
}
```
Here I expected an output like:
```
2 1
3 2
4 3
5 4
6 5
```
but I got an output
```
2 1
```
|
Because<has higher precedence than&fromhere.
So in the second iterationy=2andx=1.x<6becomes true - results in1whichwhenANDed withythe result becomes0. So it stops.y<x&6is equivalent toy&(x<6).
To explain you howANDworks :- (shown in 6 bits - but the logic holds same way forsizeof(int)*8bits).
```
000010
AND 000001
----------
000000
```
|
Hey i am working on a code and i stuck inside this if condition which is
(Not a actual Code simplified for better understanding)
```
if(18&2==2)
do something;
```
this if condition not executing but if i write like this
```
if(18|2==18)
do something;
```
it executed normal
also when I,
```
printf("%d",18&2);
```
it gives 2 now i am so confused why the above if statement not executing,
is it because of precedence ,please explain thanks.
|
Yours is aprecedence"error". The bit-wise operators have lower precedence than equality. Making18 & 2 == 2into18 & (2 == 2), which is18 & 1. That last one obviously evaluates to 0, since 18 is divisible by 2.
In such cases, when you get "weird results". Start by adding parenthesis to make sure every operator operates on the operand you expect it too.
|
I am looking into utilizing semaphores as classic counter. It would have a starting value of 5, which could go down to 0, but could not go above 5.
```
sem_t sem;
sem_init(&sem, 0, 5);
// ...
sem_wait(&sem); // goes down to 4
//...
sem_post(&sem); // goes up to 5
sem_post(&sem); // goes up to 6 ?!
```
I went thought the docs, but I don't see anysem_post-like function which does just that. Now, I know this behavior could implemented with mutex and int, but I was kind of interested if similar thing could be done this way (a bit less of code).
|
Semaphores block the waiter/decrementer (consumer) not the poster/incrementer. This means that there is no mechanism to prevent the increments to above 5 from happening. Therefore if you want to block both waiter/consumer and poster/incrementer (to prevent going above 5) you will need to use a combination of mutex and conditional variable. There is no other way.
|
Is anyone able to better inform me on successfully compiling a Lex source file on OS X in terminal. I have written inHelloWorld.lthe following:
```
%%
"hello world" printf("GOODBYE\n");
. ;
%%
```
Within the console I executedlex HelloWorld.lfollowed bygcc lex.yy.c -lland./a.outreceiving a blank state within my window and no result.
I am basing my knowledge on this topic from the source[1]and similar Stack question[2].
|
flex, will by default, read from standard input. You need to actually provide it some input. You can doecho "hello world" | ./a.outand you should see your result.
|
Is anyone able to better inform me on successfully compiling a Lex source file on OS X in terminal. I have written inHelloWorld.lthe following:
```
%%
"hello world" printf("GOODBYE\n");
. ;
%%
```
Within the console I executedlex HelloWorld.lfollowed bygcc lex.yy.c -lland./a.outreceiving a blank state within my window and no result.
I am basing my knowledge on this topic from the source[1]and similar Stack question[2].
|
flex, will by default, read from standard input. You need to actually provide it some input. You can doecho "hello world" | ./a.outand you should see your result.
|
The output is coming as just 0 and 1.
```
int main()
{
int i, n=0, rem, sum=0, temp;
for(i=0; i<1000; i++) {
temp = n;
while(temp>0){
rem = temp%10;
sum += rem*rem*rem;
temp /= 10;
}
if (sum == i){
printf("%d ", i);
}
n++;
}
```
|
for each value sum has to be zero that is first correction.and i has to be assigned to variable temp because i value has to be checked if it is armstrong number or not.do the changes it will work.
```
#include<stdio.h>
int main()
{
int i, rem, sum=0, temp;
for(i=0; i<1000; i++)
{
temp = i;
sum=0;
while(temp>0)
{
rem = temp%10;
sum += rem*rem*rem;
temp /= 10;
}
if (sum == i)
{
printf("\n%d ", i);
}
```
}
Output
01153370371407
|
In my understandings, the while should end the loop, cause
int number "in" the loop should initialize it with 0.
Or am i wrong? But it gives me an endless loop, printing zeroes.
I compiled it with gcc and tried to debug it with gdb.
It makes no sense for me, that the while doesn't stop the loop.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number = 20;
do
{
int number = number / 2;
printf("%d ", number);
} while (number > 10);
}
```
|
You create newnumberevery time in the loop, visible only within the loop and unrelated to the one outside the loop. Removeintinint number = number / 2;
|
I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives:
Use of undeclared identifier 'byte'
in the next line:
```
buf[2] = (byte)(addr & 0xff);
```
|
In the .c file i have declaredbytewith the next code:
```
typedef uint8_t byte
```
uint8_t is similar to byte, so it compiled
|
Is there any way to know if a process has started to run from a call ofexec()or has started from the terminal by the user?
|
Helpful to you:child and parent process id;
getppid() returns the process ID of the parent of the calling
process. This will be either the ID of the process that created this
process using fork(), or, (!!!CARE!!!) if that process has already terminated, the
ID of the process to which this process has been reparented;
I would also consider adding additional program arg.
|
I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives:
Use of undeclared identifier 'byte'
in the next line:
```
buf[2] = (byte)(addr & 0xff);
```
|
In the .c file i have declaredbytewith the next code:
```
typedef uint8_t byte
```
uint8_t is similar to byte, so it compiled
|
Is there any way to know if a process has started to run from a call ofexec()or has started from the terminal by the user?
|
Helpful to you:child and parent process id;
getppid() returns the process ID of the parent of the calling
process. This will be either the ID of the process that created this
process using fork(), or, (!!!CARE!!!) if that process has already terminated, the
ID of the process to which this process has been reparented;
I would also consider adding additional program arg.
|
Why does this function work?I don't think that this is the proper way to copy achar*in C.
```
#include <stdio.h>
int main() {
const char* original = "TEST";
char* copy;
copy = original;
printf("%s\n", original);
printf("%x\n", &original);
printf("%s\n", copy);
printf("%x\n", ©);
return 0;
}
```
|
It does not copy the string. You just assign the pointercopywith the address of the string literal which address is also stored in theoriginalpointer. Both point to the same place in the memory but have different types.
|
Is there a way to use named arguments in C function?
Something like function with prototypevoid foo(int a, int b, int c);
and I want to call it withfoo(a=2, c=3, b=1);[replaced the order ofb & cand used their names to distinguish]
Motivation: I want a more Pythonic C, where I can easily manipulate my function arguments without mixing them by mistake
|
Kinda, sorta, with a compound literal and designated initializers:
```
typedef struct foo_args {
int a;
int b;
int c;
} foo_args;
// Later
foo(&(foo_args) {
.a = 2,
.c = 3,
.b = 1
});
```
But I honestly wouldn't bother. It requires you to bend the function definition to accept a pointer, and makes calling it cumbersome.
|
Is there a way to use named arguments in C function?
Something like function with prototypevoid foo(int a, int b, int c);
and I want to call it withfoo(a=2, c=3, b=1);[replaced the order ofb & cand used their names to distinguish]
Motivation: I want a more Pythonic C, where I can easily manipulate my function arguments without mixing them by mistake
|
Kinda, sorta, with a compound literal and designated initializers:
```
typedef struct foo_args {
int a;
int b;
int c;
} foo_args;
// Later
foo(&(foo_args) {
.a = 2,
.c = 3,
.b = 1
});
```
But I honestly wouldn't bother. It requires you to bend the function definition to accept a pointer, and makes calling it cumbersome.
|
Is it possible to transmit whole numbers (int) and characters (char) for the same pipe or do I need to create two different pipes? How?
|
pipes are handled likefilesand so you can use the standard file i/o commands to write any format you want, i.e.write,read,fwrite,fread,fprintf,fscanf, ...
https://www.gnu.org/software/libc/manual/html_node/Creating-a-Pipe.html
(Why fprintf and fscanf does not work with pipe,fread() reading from a descriptor based on a pipe sets error, not EOF where there is no data)
|
Here is code of mpi scatter:
```
#include <stdio.h>
#include <mpi.h>
int a[10]={1,2,3,4,5,6,7,8,9,10};
int b[1];
int main(int argc, char *argv[]) {
int rank;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Barrier(MPI_COMM_WORLD);
if(rank ==0){
MPI_Scatter(a,1,MPI_INT,b,1,MPI_INT,0,MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);
printf("\n%d from rank=%d\n",b[0],rank);
MPI_Finalize();
return 0;
}
```
I want output as follows:
1 from rank 02 from rank 13 from rank 2...
But I am getting
1 from rank 00 from rank 10 from rank 20 from rank 30 from rank 4...
|
MPI_Scatter()is a collective operation, and hence it must be called byallthe ranks of the communicator.
get rid of theif (rank == 0)and you will be fine.
Note that in your example, theasend buffer is small enough and does not cause any hang.
|
```
#include <stdio.h>
void f1(char* str, int index)
{
*(str + index) &= ~32;
}
int main()
{
char arr[] = "gatecsit";
f1(arr, 0);
printf("%s", arr);
return 0;
}
```
How is functionf1()working?Being specific*(str + index) &= ~32;this one....
thanks
|
The expression
```
*(str + index)
```
is equivalent to
```
str[index]
```
So the character at positionindexis changed the following way
```
*(str + index) &= ~32;
```
In the ASCII table lower case letters differ from upper case letters by having one more set bit. For example the lower case letter'a'has the code in hex61while the upper case letter'A"has the code in hex41. So the difference is equal to the value in hex20that in decimal is equal to32.
So the original expression resets the corresponding bit in the character to 0 converting a lower case letter to the upper case letter.
|
In the following code:
```
struct a {
char name[18];
}customer;
scanf("%s",customer.name);
printf("%s",customer.name);
struct a *pt=&customer; `
```
Because of pointing array name to the first element of that, iscustomer.namepointing to the first element of this member?
In a book it was wrote that*(customer.name+2)is equivalent withcustomer.name[2]andpt->name[2]. But I cant understand these note and also whycustomer.nameinscanf()function is an address and inprintf()function isn't address?
|
In both the examples forprint()andscanf()here,customer.nameresolves to a pointer to the first element of the arraynamewhich is a member ofcustomervariable of typestruct a.
To clear the confusion, in case of%sformat specifier withprintf()the argument type expected is pointer to the first element of the array. So, in case of thisprintf()call, the argumentcustomer.nameis correct, it's a pointer.
|
What does this line mean?
```
if (strcmp(argv[0],"./lower")==0)
```
Before converting to lower or upper case why this condition is checked?
What does it results to?
|
Comparingargv[0]is checking the name of the executable.
I assume you look at code similar tobusyboxin which you check the executable that the user used so you know which action to perform.
|
I've been playing around and trying to experiment with C for my university class and I've found something that my program does even though I did not tell it to!
My full code:
```
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
printf("%d\n", (c - '1'));
}
return 0;
}
```
The output of it looks like this:
```
7
6
-39
```
Now, can anyone tell me why that -39 is being printed?
|
Pretty clear if you look atthis. First you entered8then7and then you entered\n(or pressedENTER) which has ASCII value of10.10-49(49being the ascii value of'1') is-39you have printed it.
|
This question already has answers here:What is the behavior of printing NULL with printf's %s specifier?(4 answers)Closed5 years ago.
I tried the following code on Linux
```
#include<stdio.h>
int main()
{
char *p=NULL;
printf("%s",p);
return 0;
}
#include<stdio.h>
int main()
{
char *p=NULL;
printf("%s\n",p);
return 0;
}
```
The first one outputs:(null)
While the second one causes a segmentation fault.
Why does\nmake such a difference?
|
Both of your examples are undefined behavior per standard. Callingprintfwith%sand passing a NULL pointer is UB.
Therefore it makes no sense to discuss the outcome. On one system you might get one result and on another system you get another result.
Also seehttps://stackoverflow.com/a/11589479/4386427
|
I've been playing around and trying to experiment with C for my university class and I've found something that my program does even though I did not tell it to!
My full code:
```
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
printf("%d\n", (c - '1'));
}
return 0;
}
```
The output of it looks like this:
```
7
6
-39
```
Now, can anyone tell me why that -39 is being printed?
|
Pretty clear if you look atthis. First you entered8then7and then you entered\n(or pressedENTER) which has ASCII value of10.10-49(49being the ascii value of'1') is-39you have printed it.
|
This question already has answers here:What is the behavior of printing NULL with printf's %s specifier?(4 answers)Closed5 years ago.
I tried the following code on Linux
```
#include<stdio.h>
int main()
{
char *p=NULL;
printf("%s",p);
return 0;
}
#include<stdio.h>
int main()
{
char *p=NULL;
printf("%s\n",p);
return 0;
}
```
The first one outputs:(null)
While the second one causes a segmentation fault.
Why does\nmake such a difference?
|
Both of your examples are undefined behavior per standard. Callingprintfwith%sand passing a NULL pointer is UB.
Therefore it makes no sense to discuss the outcome. On one system you might get one result and on another system you get another result.
Also seehttps://stackoverflow.com/a/11589479/4386427
|
I'm using a STM32F4 for receiving data from a FPGA (now it only relays data from a PC) using DMA UART. The DMA UART is working as it should, but it can only give an interrupt when the buffer for the UART it is half full or full. The problem is that I want to know if I got new data in the buffer without it being half or full.
In short I am looking for a register which point to where the next byte from the UART should go in the DMA buffer. Does anyone know of a register like that.
Thank you!
|
The DMA has a CNDTR register (be aware that it counts down)
|
This question already has answers here:How come an array's address is equal to its value in C?(6 answers)Closed5 years ago.
I am just trying to learn how 2D arrays implemented and how memory allocation takes place. so I get some doubt in the given c program that why a and *a giving same address.
```
#include<stdio.h>
main()
{
int i,j;
int a[3][3]={1,2,3,4,5,6,7,8,9};
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
printf("%d\n",a);
printf("%d\n",a[0]+1);
printf("%d\n",a[0][0]);
printf("%d\n",a+1);
printf("%d\n",*a);
}
```
and here's the output
|
The 2D array resides on the same address as the first 1D array, which in turn resides on the same address as the first element. That's it, there's nothing more to it.
|
What is the difference between the two Instruction pointers (eip)? What is the goal of each one?
Frame info image:
There are two different eip?
|
saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL).
eipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).
|
I am doing a problem set from the CS50 course, and in this problemargcneeds to be 2. I made this:
```
#include <cs50.h>
#include <stdio.h>
int main (int argc, string argv [])
{
if ( argc != 2){
printf ("Retry\n");
return 1;
} else {
int x = atoi(argv [1]);
string a = get_string ("Enter plaintext: ");
printf ("%s", a);
printf ("%d", x);
}
}
```
But even whenargcis different than 2 it ignores the if statement and goes to the else statement.
Why is that? And how do I fix it?
|
Pretty sure that you're forgetting that the command itself counts as one of the args from the shell. In other words:
```
> myprog myparam myotherparam
```
has argc == 3 because myprog is arg[0]
|
What is the difference between the two Instruction pointers (eip)? What is the goal of each one?
Frame info image:
There are two different eip?
|
saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL).
eipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).
|
I am doing a problem set from the CS50 course, and in this problemargcneeds to be 2. I made this:
```
#include <cs50.h>
#include <stdio.h>
int main (int argc, string argv [])
{
if ( argc != 2){
printf ("Retry\n");
return 1;
} else {
int x = atoi(argv [1]);
string a = get_string ("Enter plaintext: ");
printf ("%s", a);
printf ("%d", x);
}
}
```
But even whenargcis different than 2 it ignores the if statement and goes to the else statement.
Why is that? And how do I fix it?
|
Pretty sure that you're forgetting that the command itself counts as one of the args from the shell. In other words:
```
> myprog myparam myotherparam
```
has argc == 3 because myprog is arg[0]
|
this is the question what asked in my exam is: "write cource code of a character taken from user is alphanumeric or not."
alphanumeric means-->A-Z|a-z|0-9(alphabetic or numeric)
if it is return true or someting. help me to solve this question please..
in summary we will buildisalnum()function ourselves.(with #define macros)
|
Here is the macro:
```
#define IS_ALNUM(x) (((x)>='a' && (x) <= 'z')) ||((x)>='A' && (x) <= 'Z')) || (((x)>='0' && (x) <= '9')))
```
It tests if it is
Between a and zBetween A and ZBetween 0 and 9
Quite simple
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.