question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I'm getting the error:
```
error: 'void*' is not a pointer-to-object type
```
For the following code:
```
Button config_b1 = Button("b1");
Button config_b2 = Button("b2");
Button config_b3 = Button("b3");
const void *const buttons[3] PROGMEM = {
&config_b1, &config_b2, &config_b3
};
```
in some function:
```
(Button)*buttons[1]->setText("Foo");
```
The casting to Button fails.
This is just a simplified example. The array "buttons" will have different types of objects, so I need to initialize it as void and then cast to the proper type inside the function.
|
I think this is a simple precedence error, and you need
```
((Button *) buttons[1])->setText("foo");
```
Are you sure this is C, by the way? That kind of call really looks like C++ (it could be C, but then you'd need an explicitthisequivalent in most cases).
|
I'm trying to search a 3x3 2d array diagonally, like this:
I want to check if all boxes in the diagonal have the same value. Here is how I try to do it:
```
thisOne = board[0][2]; //set to 'X'
for(i = 0; i<3; i++) {
for(j = 3; j>0; j--){
if(board[i][j-1] != thisOne) {
thisOne= '\0';
}
}
}
//since all boxes were 'X', thisOne is still set to 'X'
if(thisOne != '\0') {
winner = thisOne;
printf("vinnare på nördöst\n");
}
```
So after running this code,winnershould be 'X', if all boxes are X's. But the code does not do that, why is that?
|
You need to check only diagonal cells instead of checking all the cells.
|
I have a basic C function, which creates a pdf and then writes it to the disc withHPDF_SaveToFile(pdf, filename)wherepdfis an instance ofHPDF_Doc.
But now I want to change the function behaviour so instead of writing to disc, it would return pdf as binary, which I will work with elsewhere.
How do I get binary fromHPDF_Docvariable?
|
Solved, here's how I did it:
```
HPDF_SaveToStream(pdf);
unsigned int streamSize = HPDF_GetStreamSize(pdf);
unsigned char* buffer = malloc(streamSize * sizeof(buffer));
HPDF_Stream_Read(pdf->stream, buffer, &streamSize);
```
this waybuffervariable will contain the binary
|
I want to detect the last element of an array of integer in C code.
Otherwise i need to stop handling array data when the array element is empty.
really my array have a maximum size fixed and it was filled from an external file so i dont know when it stop filling the array.
|
Last element is in position
```
sizeof(array)/sizeof(array[0]) - 1
```
|
I have declaredchar data[101];and after that read message from socket into it(server - client communication). After the message is displayed on screen I want to clear/empty that char array. I triedmemset(data, 0, sizeof(data))andbzero(data, sizeof(data));And I think it still didn't clear it. At the output after receiving the first message I also get some weird characters: ��|V� and after them also the message is shown. Now I don't know if that is from clients or servers side. I tried to clear it on both but the result isn't any different.
This is how I send message:
```
char data[101];
read(0, data, 101);
dprintf(socket_fd, data);
bzero(data, sizeof(data));
```
|
Here is another alternative solution
```
//Declare and initialize to NUL characters.
char data[101] ="";
//fgets() will take care of out of boundary issue.
if (fgets(stdin, data, sizeof(data))
dprintf(socket_fd, "%s", data); // Send the data
```
|
This question already has answers here:How much memory would be freed if pointer is changed in C?(3 answers)Closed6 years ago.
I have written the following code, however I get a crash (without warnings or errors) and do not know the cause:
```
const int N = 1000;
int main(){
int *pI = calloc(N,sizeof(int));
for (int i=0;i<N;i++) {
*(pI++) = (i+1);
}
free(pI);
return EXIT_SUCCESS;
}
```
I am thankful for any advice!
|
You are not releasing the original pointer received fromcalloc():
```
free(pI);
```
You have been modifying the value contained in this pointer:
```
*(pI++) = (i+1);
```
Do instead:
```
int *p = calloc(N,sizeof(int));
int *pI = p;
// ...
free(p);
```
That is, save the value returned fromcalloc()and then pass it tofree()when you don't need the allocated memory anymore.
|
I have a parent process which is handling the signalSIGCHLD.
If I callabort()in the child process , theSIGABRTsignal is raised in the child process.
My question is , at the time of child process core dumping ,SIGCHLDsignal will be sent to parent process or not ?
|
The SIGCHLD signal isalwayssent by the (unixoid at least) OS to your process as soon as the child dies - no matter of which reason it dies (because of SIGABRT or SIGSEGV, terminating regularly by calling exit or simply leaving main, ...).
You get some information about what happened in the child in the status variable you provide to the functions of the wait family, a small example you find e. g.here.
|
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed6 years ago.
Im trying to create a generic stack. I have a problem when i try to push a value
into the stack, the programm crashes in the memmove line:
```
typedef struct s_node{
void *info;
struct s_node *next;
}t_node;
typedef struct{
char name[50];
int salary;
}t_employee;
typedef t_node* t_stack;
void createStack(t_stack *p){
*p=NULL;
}
int push(t_stack *p,void *inf,int siz){
t_node *new=(t_node*)malloc(sizeof(t_node));
if(!new)return 0;
memmove(new->info,inf,siz); !!!!!CRASH
new->next=*p;
*p=new;
return 1;
}
int main()
{
t_stack p;
t_employee e={"Jhon Freeman",30000};
createStack(&p);
push(&p,&e,sizeof(t_employee));
return 0;
}
```
|
new->info is pointing to nowhere. Initialize it :)
|
I've made a little test program in python to test some C functions in many cases. This python program usectypesto import and use my C functions.
But I'd also like to test minimum and maximum values cases (limits.h'sULLONG_MAXfor instance).
But since some of these limits can be system dependant, I'd prefer to avoid hard coding it in my program; I'd rather dynamically get it.
Is it possible to get these limits values in python?
|
I believe the closest you can get is
```
ctypes.sizeof(whatever_type)
```
which gives you the size of the type in bytes. For example, you can usectypes.sizeof(ctypes.c_int)to figure out whether a byte is 4 bytes, 8, or some other weird number.
|
I'm writing a WAV Player in C with SIGIL API and windows.h library, I'm using GetOpenFileName from the windows.h library to open the file, and I need a way to the program "read" the duration of the WAV file, there is some function to do so?
|
As far as I know:
Time = [Size of file]/[Byte rate]
You may also have some more factors:
Frequency in cycles per second;Number of channels (1, 2, 4, 8...);A bit value (8, 16, etc.) determining the resolution per cycle;
This information should be in the header.
|
```
#include<stdio.h>
void main() {
int x = 0,y = 0,k = 0;
for(k = 0; k < 5; k++){
if(++x > 2 && ++y > 2) x++;
}
printf("x = %d and y = %d",x,y);
}
```
I'm not able to understand how the above piece of code generates x = 6 and y = 3.
RESOLVED : I didn't know that when there is &&, if the first statement evaluates to false the second will not be executed.
|
&&is ashort-circuitoperator.
The first time through the loop, only++xis evaluated.The second time through the loop, only++xis evaluated.The third time through the loop, both are evaluated....
|
I want to write in Makefile like this
```
foo: foo.c
$(CC) -o foo -Wall foo.c
```
but I'm not sure if allccimplementations support-Wall.
|
No, there is no standard regarding the command-line interface of C compilers.
The Microsoft compiler (in Windows) for instance does not accept options starting with-at all, since that's not the syntax typically used with Windows programs.
|
I have a pretty large application which holds most of the program data in a large container object calledsystem.
So I access things all the time, e.g.printf("%s\n",system.constants.jobname);, and changing the name ofsystemis undesirable.
I learned later that the functionsystemexists as a nativeCfunction for running terminal commands, e.g.system("rm *.txt");
My problem is that I get compilation errors trying to usesystemas a function because it's already defined as an object.
Is there any way one can call a nativeCfunction explicitly ignoring programmatically defined variables? Or give the nativesystemfunction an alias? (I'm using C++ so using it would be fine)
|
If you're using C++,systemis in the global namespace. Assuming you've put your stuff in a proper namespace (you have, right?) you can refer to it as::system.
|
I know how to use the two functions, but I do not know what the suffix "at" means. Does it represent the abbreviation of "another"?
|
At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.
|
I wrote a program that prints the homedirectory of a user but it's not working.
Here is my code:
```
#include <stdio.h>
char cmd[256], name[256], homedir[256];
int main()
{
printf("Username: ");
fgets(name,256,stdin);
sprintf(cmd, "grep %s /etc/passwd|awk -F : '{print $6}'", name);
FILE *fp = popen (cmd, "r");
if (fp)
{
fgets(homedir, sizeof homedir, fp);
printf("%s %s", name, homedir);
pclose(fp);
}
return 0;
}
```
it prints:
```
Username:
```
and after I type 'Paul' it prints nothing and I don't know why.
|
Thefgets(name,256,stdin);line gets the\ncharacter as an input after you're pressing enter. Then yourcmdstring looks like this:
```
grep <your username input>
/etc/passwd|awk -F
```
Change the linefgets(name,256,stdin);toscanf("%s",name);.
|
I have a pretty large application which holds most of the program data in a large container object calledsystem.
So I access things all the time, e.g.printf("%s\n",system.constants.jobname);, and changing the name ofsystemis undesirable.
I learned later that the functionsystemexists as a nativeCfunction for running terminal commands, e.g.system("rm *.txt");
My problem is that I get compilation errors trying to usesystemas a function because it's already defined as an object.
Is there any way one can call a nativeCfunction explicitly ignoring programmatically defined variables? Or give the nativesystemfunction an alias? (I'm using C++ so using it would be fine)
|
If you're using C++,systemis in the global namespace. Assuming you've put your stuff in a proper namespace (you have, right?) you can refer to it as::system.
|
I know how to use the two functions, but I do not know what the suffix "at" means. Does it represent the abbreviation of "another"?
|
At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.
|
I wrote a program that prints the homedirectory of a user but it's not working.
Here is my code:
```
#include <stdio.h>
char cmd[256], name[256], homedir[256];
int main()
{
printf("Username: ");
fgets(name,256,stdin);
sprintf(cmd, "grep %s /etc/passwd|awk -F : '{print $6}'", name);
FILE *fp = popen (cmd, "r");
if (fp)
{
fgets(homedir, sizeof homedir, fp);
printf("%s %s", name, homedir);
pclose(fp);
}
return 0;
}
```
it prints:
```
Username:
```
and after I type 'Paul' it prints nothing and I don't know why.
|
Thefgets(name,256,stdin);line gets the\ncharacter as an input after you're pressing enter. Then yourcmdstring looks like this:
```
grep <your username input>
/etc/passwd|awk -F
```
Change the linefgets(name,256,stdin);toscanf("%s",name);.
|
During compilation, when c code is converted into assembly language, does ternary operator converted into if-else block ?
|
Short answer: no.
Machine instructions (or assembly which, roughly speaking, is a higher level representation of machine instructions that a human can understand more easily) does not have anif/elseconstruct. At most, there will be some form of conditional jump.
Practically,if/elseconstructs might initially be mapped to code which uses conditional jumps. And the working of the ternary?:might, initially at least, be mapped the same way.
However, compilers do some fairly advanced optimisation of code. Depending on needs of the CPU, the optimiser might completely reorder or remove some blocks of code that have conditional jumps, and replace it with other code that produces the same results, using some other mechanism.
|
(int ( * ) (void*, void*))(numeric ? numcmp : strcmp));
numcmp and strcmp are functions with two arguments.
I understand what the conditional operator is doing. That is straightforward.
I can reason that this will evaluate to numcmp(void*, void*) or strcmp(void*, void*), but I don't understand why? Particularly, the:
int (*), confuses me.
|
The expression(int ( * ) (void*, void*))is just a cast to a function pointer with twovoid*arguments returningint. As for other casts, the syntax resembles a variable declaration without variable name. Then depending on the boolean switch, it is decided which of the functions to cast.
|
```
#include<stdio.h>
int main(){
char a[20],*p;
p=a;
printf("Enter the String");
scanf("%s",p);
printf("\n\n%s\n",p);
printf("Copying the String\n");
char b[20],*pp;
pp=b;
while((*pp++=*p++));
printf("\n%s\n",pp);
}
```
This code is not copying Strings. However, If I changeb[20]tob[10], it's copying last 9 characters of a String. By the way, when I setb[10]and if the input consists of a space then it is not copying the strings.
Compiler Setup:
Configured with:--prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1Apple LLVM version 8.1.0 (clang-802.0.42)Target:x86_64-apple-darwin16.5.0Thread model:posixInstalledDir:/Library/Developer/CommandLineTools/usr/bin
|
After:
```
while((*pp++=*p++));
```
ppis pointing to the end of the string. You want:
```
printf("\n%s\n",b);
```
|
InLazy Foo's tutorialabout timers he usedstd::stringstream timeText;. However, since I'm coding in C, I was wondering if there was anything similar I can use? Ultimately, if the result gets stored as a string, that would be perfect because I can render it through TTF. Right now,getticks()returns auint32; how can I convert that to a string?
|
The example is just using a string stream in order to then use the << operators to build s string.
In C, you could use, sprintf:
```
char timeText[100];
sprintf(timeText,"Milliseconds since start time %lu", (SDL_GetTicks() - startTime);
.
.
if( !gTimeTextTexture.loadFromRenderedText( timeText, textColor ) )
.
.
```
|
If I have:
```
str1 = "str1s2"
str2 = "djfs1d2.3"
```
How can I get the last number in string by sscanf()?
I tried:
```
sscanf(str1, "%*[^0-9]%d", &n1);
sscanf(str2, "%*[^0-9]%d", &n2);
```
But I get only the first number:
```
n1 = 1
n2 = 1
```
|
Using the%nspecifier to store the number of characters processed by the scan, you can iterate through the string until scanf fails.
```
#include <stdio.h>
int main ( ) {
char str2[] = "2to3";
int span = 0;
int index = 0;
int lastvalue = 0;
int value = 0;
if ( 1 == sscanf ( &str2[index], "%d%n", &value, &span)) {
index += span;
lastvalue = value;
}
while ( 1 == sscanf ( &str2[index], "%*[^0-9]%d%n", &value, &span)) {
index += span;
lastvalue = value;
}
printf ( "last value = %d\n", lastvalue);
return 0;
}
```
|
Why are pointer to array ofchardifferent between rvalues is&"hello"and array ofchar?
Whypointerto array by&"hello"needconst, but by array ofcharnot?
Whyx[0] typeidname ischar[6]?
Why*x = temp2compile error?
The following observation arose as I was following some question :
```
char temp[] = { 'h','e','l','l','o','\0'};
char temp2[] = { 'w','o','r','l','d','\0' };
char (*x)[6] = &temp;
//*x = temp2;//error
x = &temp2;//OK
cout << typeid(x[0]).name() << endl;
//char (*y)[6] = &"hello"; //error
char const (*y)[6] = &"hello";//OK
```
output :
```
char [6]
```
|
*x = temp2does not work because arrays are not assignable. If you want assignable arrays you should use::std::arrayinstead.
char (*y)[6] = &"hello";does not work because in C++ string literals are arrays ofconst char.
You declarexas a pointer to array of 6chars, sox[0]and*x(the same thing) denote a reference to an array of 6 chars.
|
```
#include <stdio.h>
int main(void) {
int i;
i = 10;
i*= 10+2;
printf("%d",i);
return 0;
}
```
why is the output of the following code 120 and not 102?
|
Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=.
C reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence
|
I am trying to empty all data in the struct array.
but it turns out to be segmentation fault.
Can someone please help me.
Struct
```
struct entry
{
char user;
char name[9];
char extension[4];
short blockcount;
short block[8];
};
struct entry directory[128];
```
main()
```
for (int i = 0; i < 128; ++i)
{
memset(&directory[i], 0, sizeof(directory));
}
```
|
You need to change
```
memset(&directory[i], 0, sizeof(directory));
```
to
```
memset(&directory[i], 0, sizeof(struct entry));
```
as you want to memset single element of array of structure
To memset entire arry you can also use
```
memset(directory, 0, sizeof(directory));// single statement, no need to loop all elements
```
|
I am putting together a Windows console app in Eclipse c/c++ Neon (Win 10) and Mingw.
When I run the program the output appears in the console window within Eclipse, but I need/want to be able to debug with the program running a a normal Windows console app (like it would in a vs studio console app).
I have tried adding-mwindowsto theminGWin Command line pattern and in linker options. I tried a number of other things I found on the web.
I have spent hours searching and nothing seems to do the trick.
|
1) Create a file named.gdbinit(or it can be named whatever you want, but this one is the conventional)2) Add a lineset new-console onto the file. Save it.3) Open "Debug Configurations" in the Eclipse, and select your project debug configuration.4) Go to the "Debugger" tab.5) Point the "GDB command file" to the file you have created.Done! now run this debug configuration.
|
I am aware when using char arrays you must initialise the size to at the length of the string + 1 to account for\0But if I don't account for\0how does strchr claim that\0Is in the char array since this prints"is null terminated"
```
char mark[4] = "mark";
if(strchr(mark, '\0')) {
puts("Is null terminated.");
} else {
puts("Is not");
}
```
|
strchrisn't limited to, or even aware of, the length of the array you're passing to it, so will continue on throughout the rest of memory until it finds what it is looking for.
If you print the value returned bystrchryou'll see that it is beyond the end of the array.
|
One can have a function that contains an anonymous enum in its signature. However, when i tried moving function signature to the header file, i have encountered a compiler errors.
```
void myfunct (enum {a=1} param);
void myfunct (enum {a=1} param)
{}
```
That yields the following:
error: conflicting types for ‘myfunct’
If enum is named (and moved outside of the function declaration), there is no error.
What would be a correct syntax to use?
|
As said in the comments:
Use a named enum. You can never have two anonymous enums be considered the same type.
Edit this post if something can be added to make it more useful or clear.
|
I have a client server connection where the client is sending data to the server.
```
while (1) {
bzero(buffer, 256);
sleep(1);
n = read(sock, buffer);
if(n < 0) error("ERROR reading from socket");
c = message[0];
//do something
}//close while loop
```
The issue i only want to wait for a read to happen only for some seconds - in my code, if the client does not send anything, it gets stuck waiting for the server to read something.
How can I wait for a read to happen only some seconds please?
|
If your socket is non-blocking you can use theselectfunction.
If your socket is blocking you can set a read timeout using thesetsockoptfunction. See this stackoverflow question for more details.Linux: is there a read or recv from socket with timeout?
|
```
#include <stdio.h>
int main(void) {
int i;
i = 10;
i*= 10+2;
printf("%d",i);
return 0;
}
```
why is the output of the following code 120 and not 102?
|
Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=.
C reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence
|
I am trying to empty all data in the struct array.
but it turns out to be segmentation fault.
Can someone please help me.
Struct
```
struct entry
{
char user;
char name[9];
char extension[4];
short blockcount;
short block[8];
};
struct entry directory[128];
```
main()
```
for (int i = 0; i < 128; ++i)
{
memset(&directory[i], 0, sizeof(directory));
}
```
|
You need to change
```
memset(&directory[i], 0, sizeof(directory));
```
to
```
memset(&directory[i], 0, sizeof(struct entry));
```
as you want to memset single element of array of structure
To memset entire arry you can also use
```
memset(directory, 0, sizeof(directory));// single statement, no need to loop all elements
```
|
Is there any difference between the following two code snippets? Which one is better to use? Is one of them faster?
case 1:
```
int f(int x)
{
int a;
if(x)
a = 42;
else
a = 0;
return a;
}
```
case 2:
```
int f(int x)
{
int a;
if(x)
a = 42;
return a;
}
```
|
Actually that both snippets can return totally different results, so there is no better...
Incase 2you can return a non initialized variablea, which may result on a garbage value other than zero...
if you mean this:
```
int f(int x)
{
int a = 0;
if(x)
a = 42;
return a;
}
```
then I would say is that better, since is more compact(but you are saving only an else, not much computational wasted anyways)
|
If you're going to define these at all, why not define them as
```
#define SIZEOF_INT sizeof(int)
```
etc. so they are correct even if someone tries to use them to compile against a different architecture?
|
I found the answer a minute after asking the question. These macros are sometimes used in the predicates of #if etc. where sizeof calls cannot be evaluated.
For example
```
#if SIZEOF_LONG_LONG_INT == 8
stuff
#endif
```
|
Consider the following question from a previous paper on C:
Show step-by-step how the following C expression is evaluated, giving the
value of the expression and thetype of that value.9 / 3 / 2 * 6 + 2 * 1.5
Is the type a float or a double? Could someone please clarify? (Note the lack of an explicit type in the question.)
|
According to theusual arithmetic conversions(6.3.1.8 Usual arithmetic conversions)
Otherwise, if the corresponding real type of either operand isdouble,
the other operand is converted, without change of type domain, to a
type whose corresponding real type is double.
the answer:
9 / 3 = 3 (int)3 / 2 = 1 (int)1 * 6 = 6 (int)2 * 1.5 = 3.0 (double)6 + 3.0 = 9.0 (double)
|
I'm reading some c source code and the there is a new type called 'lwm2m_object_t' defined using this syntax.
```
#define OBJ_COUNT (9)
lwm2m_object_t * objArray[OBJ_COUNT];
```
Could somebody explain how you can define a type like this? Do you not have to usetypedef?
Is this an array of pointers of typelwm2m_object_t?
Thanks
|
The following:
```
lwm2m_object_t * objArray[OBJ_COUNT];
```
declares anarray of pointers tolwm2m_object_t.
The typelwm2m_object_tis for sure somewhere else defined in the source code.
Most probably in library headerliblwm2m.h.
|
I have some data files, saydata1.txt,data 2.txt,... and so on. I want to read all these data files using a single loop structure and append the data values into a single file, say data-all.txt.
I am fine with any of the following programming languages:c,python,matlab
|
pathlibmodule is great for globbing matching files, and for easy read/write:
```
from pathlib import Path
def all_files(dir, mask):
for path in Path(dir).glob(mask):
yield from path.open()
Path('data_all.txt').write_text(''.join(all_files('.', 'data*.txt')))
```
|
I have a below program and compilation is success but while running,program crashes in eclipse
```
struct Student
{
unsigned int *ptr; //Stores address of integer Variable
}*s1;
int main()
{
unsigned int roll = 20;
s1->ptr = &roll;
printf("\nRoll Number of Student : %d",*(s1->ptr));
return(0);
}
```
how to print the value of roll using pointer to a structure
|
Create aStudentstructure, allocate it and use it
```
typedef struct Student
{
unsigned int *ptr; //Stores address of integer Variable
} Student;
int main()
{
Student *s1;
unsigned int roll = 20;
s1 = malloc(sizeof(Student));
if (s1 == NULL) {
return -1;
}
s1->ptr = &roll;
printf("\nRoll Number of Student : %d",*(s1->ptr));
free(s1);
return(0);
}
```
|
This question already has answers here:Clarification needed regarding getchar() and newline(4 answers)Closed6 years ago.
After the initial iteration, theprintf()output is shown twice each iteration. Why?
```
int main()
{
int ch;
for( ch = ' '; ch != 'q'; ) {
printf("Enter a character: ");
ch = getchar();
}
printf("You entered a q!\n");
return 0;
}
```
The terminal output is:
```
Enter a character: w
Enter a character: Enter a character: a
Enter a character: Enter a character: q
You entered a q!
```
|
You didn't enterwon the command line. You enteredw\n. That's two characters.
|
Is there a reason why we need to use:
```
"test of split".split(" ")
```
and we can't use:
```
"test of split".split(sep=" ")
```
Of course split is implemented this way (in C). But does it really mean we cannot handle**kwargsfor functions written in C?
|
Python functions implemented in Ccanbe written to take keyword arguments - for example,sorted(whatever, key=whatever)- but many of them don't, mostly for historical reasons.
Note that on Python 3, you can now passseptostr.splitby keyword.
|
This question already has answers here:Why output of int 070 is 56 in C program? [duplicate](1 answer)When displaying the value of variable "int a = 011", I get 9. Why? [duplicate](3 answers)Closed6 years ago.
In c, why is that ~177 yields -178, while ~0177 yields -128?
I tried printing out the values before and after, but couldn't discern anything. I also couldn't anything explaining this topic. I am reading "The C Programming Language".
|
The leading zero indicates that0177is an octal number (127).
|
I'm reading some c source code and the there is a new type called 'lwm2m_object_t' defined using this syntax.
```
#define OBJ_COUNT (9)
lwm2m_object_t * objArray[OBJ_COUNT];
```
Could somebody explain how you can define a type like this? Do you not have to usetypedef?
Is this an array of pointers of typelwm2m_object_t?
Thanks
|
The following:
```
lwm2m_object_t * objArray[OBJ_COUNT];
```
declares anarray of pointers tolwm2m_object_t.
The typelwm2m_object_tis for sure somewhere else defined in the source code.
Most probably in library headerliblwm2m.h.
|
I have some data files, saydata1.txt,data 2.txt,... and so on. I want to read all these data files using a single loop structure and append the data values into a single file, say data-all.txt.
I am fine with any of the following programming languages:c,python,matlab
|
pathlibmodule is great for globbing matching files, and for easy read/write:
```
from pathlib import Path
def all_files(dir, mask):
for path in Path(dir).glob(mask):
yield from path.open()
Path('data_all.txt').write_text(''.join(all_files('.', 'data*.txt')))
```
|
I have a below program and compilation is success but while running,program crashes in eclipse
```
struct Student
{
unsigned int *ptr; //Stores address of integer Variable
}*s1;
int main()
{
unsigned int roll = 20;
s1->ptr = &roll;
printf("\nRoll Number of Student : %d",*(s1->ptr));
return(0);
}
```
how to print the value of roll using pointer to a structure
|
Create aStudentstructure, allocate it and use it
```
typedef struct Student
{
unsigned int *ptr; //Stores address of integer Variable
} Student;
int main()
{
Student *s1;
unsigned int roll = 20;
s1 = malloc(sizeof(Student));
if (s1 == NULL) {
return -1;
}
s1->ptr = &roll;
printf("\nRoll Number of Student : %d",*(s1->ptr));
free(s1);
return(0);
}
```
|
This question already has answers here:Clarification needed regarding getchar() and newline(4 answers)Closed6 years ago.
After the initial iteration, theprintf()output is shown twice each iteration. Why?
```
int main()
{
int ch;
for( ch = ' '; ch != 'q'; ) {
printf("Enter a character: ");
ch = getchar();
}
printf("You entered a q!\n");
return 0;
}
```
The terminal output is:
```
Enter a character: w
Enter a character: Enter a character: a
Enter a character: Enter a character: q
You entered a q!
```
|
You didn't enterwon the command line. You enteredw\n. That's two characters.
|
Is there a reason why we need to use:
```
"test of split".split(" ")
```
and we can't use:
```
"test of split".split(sep=" ")
```
Of course split is implemented this way (in C). But does it really mean we cannot handle**kwargsfor functions written in C?
|
Python functions implemented in Ccanbe written to take keyword arguments - for example,sorted(whatever, key=whatever)- but many of them don't, mostly for historical reasons.
Note that on Python 3, you can now passseptostr.splitby keyword.
|
I am running a for loop with openmp static load balancing. I´d like to print the first and the last iteration processed by each thread (a.k.a the first and last value ofi, for every thread).
The loop looks like this:
```
#pragma omp parallel for schedule(static) private(i)
for(i=0;i<n;i++){
//loop code
}
```
I am well aware that OpenMP doc specifies the range of iterations to be divided equally in static schedule although I would like to print the iteration values.
|
Just remember the index in a private variable that is initialized to a marker value (-1):
```
#pragma omp parallel
{
int index = -1;
#pragma omp for schedule(static)
for(int i=0; i<n; i++){
//loop code
if (index == -1) {
printf("%d: start %d\n", omp_get_thread_num(), i);
}
index = i;
}
printf("%d: last %d\n", omp_get_thread_num(), index);
}
```
|
I came across this below program and I don't understand the output.
Can someone please shed some light on it?
```
#include <stdio.h>
int main()
{
int i=1,j=1;
for(;j;printf("%d %d\n",i,j))
j=i++ <=5;
return 0;
}
```
And its output is:
```
2 1
3 1
4 1
5 1
6 1
7 0
```
|
```
#include <stdio.h>
int main()
{
int i=1,j=1;
//for(initialisation; condition; operations)
// here no initialisation,
// 1. condition is j, if j is true
// 2. then it will execute block statements
// 3. then finally it execute operations, here printf
// 4. again check step 1.
for(;j;printf("%d %d\n",i,j))
j=i++ <=5; // j = (i <= 5); i++;
return 0;
}
```
Your question can be simplified as follows
```
#include <stdio.h>
int main()
{
int i=1,j=1;
while(j) {
j = (i++ <=5);
printf("%d %d\n",i,j);
}
return 0;
}
```
|
How to write a program that calculates the multiples of 7 between 21 and 210 inclusive?
This is an incorrect example:
finding multiples of 7
```
#include<stdio.h>
int main(){
int multiple;
int sum;
int i=0;
int j=0;
int sum1,sum2;
for (i=1;i>=21;i++){
printf(i);
sum1=i+sum1;
for(j=1;j<=210;j++){
printf(j);
sum2=j+sum2;
}
}
sum=sum1+sum2;
printf("sum",sum);
}
```
|
Define lower and upper limit asn1andn2with 21 and 210 respectively.
```
#include <iostream>
#include <stdio.h>
int main()
{
int n1,n2;
n1=21;
n2=210;
while(n1<=n2)
{
if(n1%7==0)
printf("%d ",n1);
n1=n1+1;
}
}
```
Tested code on Code Chef -https://www.codechef.com/ide
Output:
21 28 35 42 49 56 63 70 77 84 91 98 105 112 119 126 133 140 147 154 161 168 175 182 189 196 203 210
|
I think this is C code, but I'm not entirely sure. I found it in a few persons' online signatures, and in SO chat once. I tried compiling it, but received a really hard to read error taking issue with the unusual characters presented.
Does it do anything? I have no idea what to do with this in my head.
```
enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵╰(ಠ_ಠ ⚠) {exit((int)⚠);}
```
|
Let's deobfuscate this.
```
enum eyes {a=1, b, c};
void f(eyes e) {exit((int)e);}
```
So basically it defines a function that aborts the program execution with an exit code from an enum type.
It won't work in C though.
|
Is there any way in MPI to get the total number of bytes transferred by my entire MPI program in C?
|
The best way is to use a MPI profiling tool such as the simplempiP. There are more sophisticated / heavyweight tools that can also do that, such as Score-P. You should check if there is something available if you are running your code on an HPC site.
|
Below is the script that runsgcc:
build_hello_tf.sh:
```
#!/bin/bash
TARGET_DIRECTORY="$(pwd)/src/addons/tensorflow/"
echo ${TARGET_DIRECTORY}
gcc -L${TARGET_DIRECTORY} hello_tf.c
ls ${TARGET_DIRECTORY}
```
Here is it's output:
```
/home/karl/dev/node/tensorflow/src/addons/tensorflow/
gcc: error: hello_tf.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
hello_tf.c src
```
It looks likegccis not able to locate the source file in the directory.
|
As said in the comments :
-L is the library search path. Source files are not searched there. You have to name them with the full path.
|
So I have aCHLfunction x
```
void x(char * args) {
char * arg;
arg = chl_next_arg(args);
printf("%s<br />", arg);
}
chl_func_append("printx", x);
```
Normally I would call this function from within a view, but I want to be able to call it from the code like it would be a normal function. Like:
```
x("hello"); // should output hello
```
But since it is not a normal function, but using chl formatting I'm not sure how to do it. Do you know of any way how I could accomplish this?
|
Okey, so apparently there is a function calledchl_funcwhich enables you to envoke a chl function using its predefined name passed tochl_func_append, as well as passing it arguments.
```
chl_func("printx", "Output");
```
src:https://github.com/it4e/CHL/wiki/chl_func
|
This question already has answers here:What's the difference between passing by reference vs. passing by value?(18 answers)Closed6 years ago.
The final values forxandyshould bex = 4andy = 21. I understand whyy = 21, but why isx = 4? Should "a = 5" not change the value to 5? Thanks
```
int f(int a, int *b){
a = 5;
*b = *b + 3*a;
}
int main(){
int x, y;
x = 4;
y = 6;
f(x, &y);
// What are x and y now?
}
```
|
In your function a is passed by value not by reference, so the x value will no tb e changed. While b is passed by reference, so value of y is changed.
|
If I write a simple http server in C. I can read http request through a file descriptor generated byaccept()function in a while loop. And I can send http response to client through that file descriptor.
In Django I know theHttpRequestobject will be passed to view function as a argument, but I want to know which function reads theHttpRequestthrough the socket and generate aHttpRequestobject?
I know view function will return aHttpResponseobject. But which function will send the actual http response to the client?
And where is the while loop?
|
Django doesn't do this. It implementsWSGIstandard and sits behind a WSGI server (such as Gunicorn or uWSGI) and lets it interact with sockets. If you want to learn more about it, you need to look up what's going on inside a wsgi server.
|
I am a beginner in C language. I want to copy a char array to another, but I cannot. I got these errors:
```
Line 10 - [Warning] passing argument 1 of 'insert' makes pointer from integer without a cast
Line 4 - [Note] expected 'char *' but argument is of type 'char'
```
Can you help me with finding the errors in this code?
```
#include <stdio.h>
#include <string.h>
void insert(char d[100]);
int main( ) {
char m[100];
scanf("%s", &m);
insert(m[100]);
return 0;
}
void insert (char d[100]) {
char s[200];
strcpy(s, d);
}
```
|
You should passmtoinsert()notm[100]. In that context,m[100]represents a single element of themarray and not the array itself. That's why the "integer to pointer without a cast" warning, becausecharis an integer after all.
|
For example, I have a CSV file:
```
1 ,2 ,3 ,4
5 ,6 ,7 ,8
a ,b ,c ,d
e ,f ,g ,h
```
and I want to know which row contains the char 'c'.
How can I know it?
i
below its my code
```
FILE* srcFile = fopen(argv[ONE], "r");
char str[MAX_LETTERS] = { 0 };
char letter = ' ';
char copy = ZERO;
int count = 1;
fgets(str, MAX_LETTERS, stdin);
str[strcspn(str, "\n")] == ZERO;
copy = fgetc(srcFile);
while (copy != EOF)
{
if (copy == str)
{
printf("find %d", count);
break;
}
else if (copy == "\n")
{
printf("nextLine");
count++;
}
copy = fgetc(srcFile);
}
```
|
Assuming that you are reading the file line by line, you could just create a counter and for every line read in increment the counter by one. If you are reading in character by character you can count the number of newlines.
|
Let's say I have(-5) mod 8.
I tried it in both languages Java and C, and they gave me a-5result when I was expecting3.
Why is this happening? Can a modulus be negative? And what should I change to get the correct result?
Java code
```
public class Example {
public static void main(String[] args) {
int x;
x = -5%8;
System.out.println(x);
}
}
```
C code
```
int main(){
int x;
x = -5%8;
printf("%d", x);
}
```
OUTPUTS
|
The%operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.
If you want a modulo function, you can do something like this:
```
int mod(int a, int b)
{
int ret = a % b;
if (ret < 0)
ret += b;
return ret;
}
```
|
I have assignment to write program that sort an array and search for a specific number, that part I've already done, My problem is how to Initialize the array in the size that the user sets with random values smaller than 500? I know how to do that with known size but not with unknown size?
example for input/output:
"Please enter the size of the array:
5"
|
This will help you.
```
int main(void)
{
int n,i;
n=rand()%500; // Get random value
int arr[n]; // Initialize the dynamic array
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
// Do your stuff
}
```
|
I have assignment to write program that sort an array and search for a specific number, that part I've already done, My problem is how to Initialize the array in the size that the user sets with random values smaller than 500? I know how to do that with known size but not with unknown size?
example for input/output:
"Please enter the size of the array:
5"
|
This will help you.
```
int main(void)
{
int n,i;
n=rand()%500; // Get random value
int arr[n]; // Initialize the dynamic array
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
// Do your stuff
}
```
|
I have a buffer and function pointer which is going to be overflowed with an address, what
```
static char buffer[12];
static int (*target_function)(char * str);
```
The overflow itself is not the problem, but I cant seem to put in the right address which is0x8048338
As stated in the question, the problem I face now, is how do I encode this address to little endian, or any endianness for that matter ?
|
0x8048338as a 32-bit integer in BE byte order is08 04 83 38.
0x8048338as a 32-bit integer in LE byte order is38 83 04 08.
Hardcoded:
```
buf[0] = 0x38;
buf[1] = 0x83;
buf[2] = 0x04;
buf[3] = 0x08;
```
From a var:
```
uint32_t n = 0x8048338;
buf[0] = n && 0xFF; n >>= 8;
buf[1] = n && 0xFF; n >>= 8;
buf[2] = n && 0xFF; n >>= 8;
buf[3] = n;
```
With a loop:
```
uint32_t n = 0x8048338;
char* p = buf;
for (int i=4; i--; ) {
*(p++) = n && 0xFF;
n >>= 8;
}
```
|
I have two source files,foo.candbar.c. I've got a Makefile to build them like so:
```
OBJ1 := foo.o
OBJ2 := bar.o
EXE1 := foo
EXE2 := bar
all: $(EXE1) $(EXE2)
$(EXE1): $(OBJ1)
gcc $(OBJ1) -o $(EXE1)
$(EXE2): $(OBJ2)
gcc $(OBJ2) -o $(EXE2)
```
Then I realized thatfoo.candbar.care identical except for one function. So I deletedbar.cand infoo.cI put#if defined()s around the function like so:
```
#if defined(FOO)
void function(int blah) { /* do what foo does */ }
#elif defined(BAR)
void function(int blah) { /* do what bar does */ }
#endif
```
How can I rewrite my Makefile to:
#define FOOinfoo.cBuildfoofromfoo.c#define BARinfoo.cBuildbarfromfoo.c
???
|
Use GCC's-Doption to define macros, and eliminate the object files:
```
SRC := foo.c
EXE1 := foo
EXE2 := bar
all: $(EXE1) $(EXE2)
$(EXE1):
gcc -DFOO $(SRC) -o $(EXE1)
$(EXE2):
gcc -DBAR $(SRC) -o $(EXE2)
```
|
What is the optimal code for the following block:
```
if (a != b)
a = b
```
|
You can just do
```
a = b;
```
because this way only one assignment will be run every time instead of the possibility of a condition check and an assignment.
|
I believe I roughly understood what pointers do, but I don't get what a pointer *(x+i) does.
So for example *(x+1).
Does it point to x and increase it's value by 1 or what?
Also I found this example:
*(x+1) = 5
What does that do?
Thanks for your replies!
|
*(x+1)is exactly the same as the clearerx[1]. Regard this as the value of the second element of thearraywhose first element is at the addressx.
So*(x+1) = 5;is the same asx[1] = 5;, which is assigning the value5to the element of the arrayxat position1.
Note that it (and the way you have it -*(x+1)) isonlydefined ifxis the address of an element of an array with at least 1 element after it. Pointer arithmetic is only valid within arrays. Otherwise the behaviour isundefinedand the compiler might leap up and eat your cat.
|
I am using the following method to iterate through a string:
```
char is_words(char *word)
{
if (word != NULL) {
for (int i = 0; i<strlen(word)-1; i++) {
char c = word[i];
printf("c is: %c\n", c);
if (!isalpha(c) || !isspace(c)) {
return c;
}
}
}
return 'a';
}
```
Yet when use it, it only prints out "c is X", where X is the first letter of the string. Why does it not iterate through the entire string?
|
it returns C in this line
```
if (!isalpha(c) || !isspace(c)) {
return c;
}
```
function finishes execution after returning a value
learn how to use && and ||
some explanation
ifcis abc symbol -isalpha(c) = true , isspace(c) = false
```
true || false = true
```
ifcis space symbol
```
isalpha(c) = false , isspace(c) = true
false || true = true
```
ifcis digit you l get false and print 1 more symb
|
I am using Neon.3 Release (4.6.3) Eclipse IDE for C/C++ Developers under Ubuntu 15.5. When I build an run my C-program the program
the program executes without any errors/warningsdelivers the expected output in the eclipse-consoleand generates an.exe filein the the debug folder
For me it is very much surprising that an .exe file is generated using an Linux OS (I thought these files can only be created under Windows?). How can I configure Eclipse to generate a typical Linux-executable instead?
Many thanks!
|
Extensions don't matter much in Linux. You can name an executablesomething.exeand it won't change how it runs...
|
I am using Neon.3 Release (4.6.3) Eclipse IDE for C/C++ Developers under Ubuntu 15.5. When I build an run my C-program the program
the program executes without any errors/warningsdelivers the expected output in the eclipse-consoleand generates an.exe filein the the debug folder
For me it is very much surprising that an .exe file is generated using an Linux OS (I thought these files can only be created under Windows?). How can I configure Eclipse to generate a typical Linux-executable instead?
Many thanks!
|
Extensions don't matter much in Linux. You can name an executablesomething.exeand it won't change how it runs...
|
I must use main() and call a function fromwindows.h.
The following code wants aWinMain()function to be used instead ofmain().
```
#include <windows.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int vk_Shift = 16;
while (1)
{
if (GetAsyncKeyState(vk_Shift) < 0)
{
printf("Shift is pressed\n");
}
}
}
```
Error
```
Error 1 error LNK2019: unresolved external symbol _WinMain@16
referenced in function ___tmainCRTStartup
Error 2 error LNK1120: 1 unresolved externals
```
How can I get this work in VS2013?
|
Okay, guys, I got it.
Felix Palmen's advice works.
... ... I guess configuring it as "console" application should do the trick.
So, what I did is, I changed my project's preference fromWIDOWStoCONSOLE.
|
I am writing an application on Ubuntu 16.04 with PJSUA/PJSIP.I need to detect when a call is hanged-up. Is there a sort offcall_state()function ?
Thank you !
|
Found the solutionhereandhere:You have to modify thestatic void on_call_state(pjsua_call_id call_id, pjsip_event *e)function like so :
```
/* Callback called by the library when call's state has changed */
static void on_call_state(pjsua_call_id call_id, pjsip_event *e)
{
pjsua_call_info ci;
PJ_UNUSED_ARG(e);
pjsua_call_get_info(call_id, &ci);
PJ_LOG(3,(THIS_FILE, "Call %d state=%.*s", call_id,
(int)ci.state_text.slen,
ci.state_text.ptr));
if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
/*YOUR CODE HERE*/
}
}
```
|
This question already has an answer here:What is the maximum number of characters in an USSD message?(1 answer)Closed6 years ago.
What is the maximum length of a USSDresponse(not the length of a request) from a modem ?
so I can define my response variable to that length.
```
#define Max_Response_Length ???
BYTE response[Max_Response_Length];
```
Thank you for your understanding.
EDIT:What are you people!
do you think I am that lazy or even retarded to not even do agoogleorwikipediasearch, before I come here!
I spent hours trying to search for answers to my question, of theUSSD RESPONSE (NOT, NOT and NOT REQUEST) LENGTHand wikipedia does not specify if (182 characters) does include the response or not.
|
USSD messages are up to 182 alphanumeric characters long.
Source:https://en.wikipedia.org/wiki/Unstructured_Supplementary_Service_Data
|
I am trying to initialize this Kind of structure but it just won't work. Any ideas what the problem is over here?
```
#include <stdint.h>
#define txBufLen 3
struct {
uint8_t Buf[txBufLen];
uint16_t out;
uint16_t len;
}txBuf;
struct txBuf a = {{1, 2, 3}, 5, 3 };
```
|
```
struct {
uint8_t Buf[txBufLen];
uint16_t out;
uint16_t len;
}txBuf;
```
This defined an untagged struct type, and immediately created a global variable of that type.
You need to change the definition to this:
```
struct txBuf {
uint8_t Buf[txBufLen];
uint16_t out;
uint16_t len;
};
```
|
I am currently creating an array in C of a dynamic number of Ncurses windows.
However, windows are an "incomplete type" so their size can be variable. How can I create a variable size array of windows ifcalloccrashes when invoked withsizeof(WINDOW)?
|
Windows are referred to by variables declared asWINDOW *(from the ncurses manpage)
That is also true of arrays of Windows. You need to use an array ofWINDOW*; even thoughWINDOWis an incomplete type, aWINDOW*is a complete type, and so
```
WINDOW* windows[NWINDOWS];
```
is just fine.
For a dynamic array, you will wantWINDOW** windows;.
|
I am trying to define a macro -
```
#define macro1(arg1) \
do{ \
int _state = 0; \
if (arg1 && arg1->member_) \
_state = arg1->member_->state_; \
printf("%d", _state); \
} while(0)
A *a = new A():
macro1(a); // Works
macro1(NULL); // Error
```
The specific error I see is -
"error: base operand of ‘->’ is not a pointer"
Aren't we allowed to passNULLas an argument to macros?
|
Macro expansion is just text replacement, so when you passedNULL, it will expand toNULL->member, clearly it is an error. One way is to use a temporary variable for that:
```
#define macro1(arg1) \
do{ \
A* p = (arg1);
int _state = 0; \
if (p && p->member_) \
_state = p->member_->state_; \
printf("%d", _state); \
} while(0)
A *a = new A():
macro1(a);
macro1(NULL);
```
This way both cases will work.
|
```
#include <stdio.h>
int main() {
int arr [6] = {22,3,30,1};
int * p = arr ;
p++;
int ** p2 = &p;
int x = 50 &(** p2 );
printf("\n\n%d\n\n", x);
}
```
Can someone explain what happens in the second last row?printfprints2.
|
xis assigned the value of50bitwise-and'd with the integer pointed to by the pointer pointed to byp2.
Or in other terms, it is bitwise-and-ing 50 and 3. 50 is in binary 00110010 where 3 is 00000011. The only bit that they both have a 1 in is the second-least-significant. Therefore, the result is 00000010, or 2.
|
I had to made something for a little programm some days ago, I needed to turn a string like"foo\n"into its stringified form (something like"\"foo\\n\"").
But I found nothing, so I ended up writing my own function (and it worked fine). But I'm still wondering : Is there a function to stringify strings like this?
I know the python equivalent"%r" % strtostringify, and I know that I can strinfifying pieces of code at compiling with preprocessor directives :
```
#define TOSTRING(X) #X
#define STRINGIFY(X) TOSTRING(X)
```
but is there a way to make it dynamically inC?
|
Escaping special characters is not provided in any standardcfunction.
For GPL, you can take a look instandard c library for escaping a string.
|
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.Closed6 years ago.Improve this question
I have encountered a problem which I do not know where to begin with. I developed code on my laptop and it works fine. I moved to another computer and now during compilation I get,
error: unknown type name 'mpfr_exp_t'
The mpfr library is located in the same place on both computers. Can anyone give me a clue how to learn what is wrong on the new computer?
|
The MPFR libraries changed some syntax between versions. In particular, as stated in the comments,
"The official type for exponent values changed from mp_exp_t to mpfr_exp_t in MPFR 3.0".
Changing the code fixes the problem.
|
I'm exercise code. The thing is, to replace space from input, with a new line.
I wrote something like this:
```
int input;
while((input = getchar()) != EOF)
{
if (input == ' ')
{
input = '\n';
}
putchar(input);
}
```
But I don't know how to make it change more than one space into exactly one new line. I had an idea to make something like buffer variable (ex. int buffer) and store space in there, and then check if after input, previous character was space, but I don't have any idea how to make it work :P
|
```
int input, last_was_space = 0;
while((input = getchar()) != EOF)
{
if(input == ' ')
{
last_was_space = 1;
}
else
{
if(last_was_space)
{
last_was_space = 0;
putchar('\n');
}
putchar(input);
}
}
```
|
For some special reason I need to get the length (in character) of a pointer.
If the pointer is :
```
0x2ADF4
```
It should return5,
because there are 5 characters in the pointer.
In fact I want the length of the hexadecimal representation of the pointer casted as an integer.
This number should vary from pointer to pointer.
Please note I do not want the total memory occupation my pointer (which I can get via sizeoff).
|
You can cast the ptr to typeintptr_tand from there use a standard digit counting algorithm :
```
int main() {
int counter = 0;
int* ptr = &counter;
intptr_t val = (intptr_t)ptr;
while ( val > 0 )
{
val/=16;
++counter;
}
printf("%d", counter);
return 0;
}
```
|
If i create a pointer like:
```
int *pointer;
```
is also a variable (called pointer) created in the C Language? Why/why not?
|
Let's get the terminology straight:
int *pointerdeclares a variableVariables have a name and a typeThe name of the variable ispointerThe type of the variable is "pointer toint"
|
I have a hard time uderestanding how #define works when combined with pointers.
Here is my pseudocode:
```
#define ID "28" // I need to keep it as string
int main()
{
char * my_id = ID;
...
...
}
```
Now what is actuallymy_idpointing to ? I did not call alloc nor statically allocated memory for my variable so can data under addressmy_idbe overwritten?
|
A#definejust does text substitution. So what you have is equivalent to:
```
char *my_id = "28";
```
What this means is thatmy_idpoints to the string constant"28". String constants are typically stored in a read-only data section, so there's nothing to allocate/deallocate.
|
This question already has answers here:variable not declared in for loop condition in C-still works(3 answers)Is a^a or a-a undefined behaviour if a is not initialized?(3 answers)(Why) is using an uninitialized variable undefined behavior?(7 answers)Closed6 years ago.
Is there UB in the following code?
```
#include <stdio.h>
int main(void)
{
int x;
printf("%d", 0*x);
return 0;
}
```
Here, the variablexwas not initialized, but was multiplied by0and the result was passed toprintf. Mathematically, the result passed toprintfshould be0, but I guess that in c language this invokes UB. If the variable was not multiplied by0it is clearly UB but I am not sure is it UB in this particular case.
Ideone link
|
Yes, it's UB.
A conforming compiler may not do any optimization and run into a trap representation inx.Some implementations may reserve some bits for special values, including trap representations.
|
I'm on a linux system (arch linux specifically) and I'm trying to compile the introduction project from the official glfw page but I cannot seem to get gcc to compile it. If anyone doesn't know what I'm talking about it'sthis.
Also this is how I'm trying to compile it:
```
gcc -Iinclude test.c -o test -lglfw3 -lm -lGL -lGLU
```
and it gives me the following errors:
```
/usr/bin/ld: cannot find -lglfw3
collect2: error: ld returned 1 exit status
```
|
I completely forgot about this question until I got a notification for it. For me the solution was to not use-lglfw3but rather use-lglfw
|
I have been doing some com interop stuff in c# lately to try and control buttons, comboboxes, textboxes, etc. on another application. My question is related to the Win32 constants some people would post, example:
```
const int WM_SETTEXT = 0x000C;
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hwnd, int msg, int wParam, int lParam);
```
Where do I find the WM_SETTEXT constant ? I have looked up certian functions on MSDN but they don't always explicitly say what the constant value is. For example, looking for the CBN_SELCHANGE constant on MSDN gives this pageCBN_SELCHANGED MSDN. So, where is the best place to get this information?
|
C++ MSDN.#define WM_SETTEXT 0x000Chttps://msdn.microsoft.com/en-us/en-us/library/windows/desktop/ms632644%28v=vs.85%29.aspxIn a header.
Look at theHeadersection onto MSDN page (Winuser.h (include Windows.h))
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
Suppose I'm designing a file manager and want to implement searching of a file by its type hypothetically then which one of these methods will be more efficient -
use the name of the file and trim the extension of each file.use of specific bytes for the type of file we are searching for example in the case of jpeg images.
bytes 0xFF, 0xD8 indicate start of image
bytes 0xFF, 0xD9 indicate end of image
|
Since you have to know it's filename before open it, the name trim option will be probably faster. However, you could have false results with that method if an extension does not match with actual file type.
Doing that way will save you some system calls (open, read, maybe fseek, close).
|
How to add an integer to the ASCII value of the characters in a string?
Example:- if the ASCII values of the characters in string"eat"are 101 97 116, how would I add an integer value, suppose it is 10, to each ASCII value so it changes to 111 107 126.
Can anyone write code in C for that??
|
You'd have to loop over each element of the char array and add 10 one by one.
```
int i;
char string[4] = "abc\0";
for(i = 0; i < string[i]; i++) {
string[i] += 10;
}
```
Since a char is an (n bit) integer you can simply add integers to it.
|
I have recently seen an answer that went over my head,
the guy wrote this piece of code and it had the value of 1.cris an integer.
```
cr = scanf("%d %.2f",&x,&y)
```
so how can you do so? and why does it give out 1?
|
First off, you are obviously gonna get 1 due to the fact there is a problem in thatscanfstatement. You need to remove.2from there as @weathervane has stated.
```
cr = scanf("%d %.2f",&x,&y)
```
to this:
```
cr = scanf("%d %f",&x,&y)
```
When you printcr, you will get a value of 2 instead of 1. You add another var to scan in thatscanfstatement and print it, you will see a value of 3.
```
#include <stdio.h>
main(){
int x, cr, z;
float y;
cr = scanf("%d %f %d",&x,&y, &z);
printf("%d\n", cr);
}
```
Output:
```
56
5
2
3
```
As you could see,cris storing the number of var being used.
|
How to add an integer to the ASCII value of the characters in a string?
Example:- if the ASCII values of the characters in string"eat"are 101 97 116, how would I add an integer value, suppose it is 10, to each ASCII value so it changes to 111 107 126.
Can anyone write code in C for that??
|
You'd have to loop over each element of the char array and add 10 one by one.
```
int i;
char string[4] = "abc\0";
for(i = 0; i < string[i]; i++) {
string[i] += 10;
}
```
Since a char is an (n bit) integer you can simply add integers to it.
|
I have recently seen an answer that went over my head,
the guy wrote this piece of code and it had the value of 1.cris an integer.
```
cr = scanf("%d %.2f",&x,&y)
```
so how can you do so? and why does it give out 1?
|
First off, you are obviously gonna get 1 due to the fact there is a problem in thatscanfstatement. You need to remove.2from there as @weathervane has stated.
```
cr = scanf("%d %.2f",&x,&y)
```
to this:
```
cr = scanf("%d %f",&x,&y)
```
When you printcr, you will get a value of 2 instead of 1. You add another var to scan in thatscanfstatement and print it, you will see a value of 3.
```
#include <stdio.h>
main(){
int x, cr, z;
float y;
cr = scanf("%d %f %d",&x,&y, &z);
printf("%d\n", cr);
}
```
Output:
```
56
5
2
3
```
As you could see,cris storing the number of var being used.
|
I am making a program in C language which prints theASCIIvalue of the string/textincluding spaces. The program works fine and give exact ASCII values of string including spaces but the problem is that it also prints '10' at the end of all ASCII values.
This is my code :
```
#include<stdio.h>
#include<conio.h>
int main()
{
char str[100];
int i;
printf("Enter a string: ");
fgets(str,100,stdin);
//scanf("%s",str);
printf("String is: %s\n",str);
printf("ASCII value in Decimal is: ");
for(i=0; str[i]!='\0'; i++)
{
printf("%d ",str[i]);
}
printf("\n");
getch();
}
```
Please help me out, tell me what's the problem and how to fix it. Thanks in advance.
|
When you read a string withfgetsthe enter you press is included in the string(man page). ASCII code for\nis10.
|
I need to write an array whose parts are scattered in code.
In short, my code is this:
```
(...)
FILE *f = fopen(filepath, "wb"); // wb -write binary
for (uint i = 0; i < num_points; i++) {
fwrite(points[i].loc, sizeof(float[3]), 1, f);
}
fclose(f);
```
As you can see, my solution was writing each new part of the array in front of the file.
But does this have a problem with efficiency, or memory reading? Should I allocate the entire array in RAM and then write the file?
|
fwritewill buffer your data until its buffer is full, orfflush/fclose/etc. is called. So it won't perform a syscall each iteration.
|
Can someone explain what this macro does and how it works?
```
#define STRCMP(a, R, b) (strcmp(a, b) R 0)
```
In code it is used as:if(STRCMP(some_string, "==", " blabla"))
What does theR 0in the macro mean? What is the macro doing in theifstatement?
|
You can do the expansion yourself:
```
if(STRCMP(some_string, "==", " blabla"))
if((strcmp(some_string, " blabla") "==" 0 ))
```
Unfortunately, I think having the quotes around the"=="makes it incorrect, and likely won't compile.
The correct syntax would be:
```
if(STRCMP(some_string, ==, " blabla"))
```
And it is a test to see if variablesome_stringrepresents the text" blabla", by using either an==or!=comparison. (as is done with other values in C)
|
I wrote a program that lets the user type words and it saves them to a char array until the user types "*end".How can i make the program stop when the user presses Ctr+Z instead of typing "*end"?
Here is the code
```
char text[1000][100];
char end[100] = "*end";
int count =-1;
do
{
count++;
scanf("%s",&text[count]);
}while(strcmp(text[count],end)==1);
```
|
It could beoperating systemspecific. The C11 (or C++14) standard does not know aboutterminals(orterminal emulators) or keyboards, only aboutstandard output, standard input, etc....
On Linux, read abouttty demystified,termios(3)and consider using some library likencursesorreadline.
BTW, you'll better use Cdynamic memory allocationinstead of using an array of arrays and you should check the result count ofscanf(3). Look intostrdup&asprintf.
|
Inside one of my classes i've got a
```
Reservation * availability[30] = {nullptr};
```
(which I of course initialize later with some values).
Nevertheless, I've got a getReservations() function which is supposed to return a reference to that array of 30 elements, so that it can be used like:
```
getReservations()[i] ...
```
How should I declare that function?
|
The syntax for declaring a function that returns the array by reference is this:
```
Reservation * (& getReservations())[30];
```
Of course, as you can see, you shouldn't use this in real life. Instead do it with a type alias:
```
using Reservations = Reservation * [30];
Reservations & getReservations();
```
Or, because arrays aren't bounds-checked anyway, just return a pointer which you can then index like an array:
```
Reservation * getReservations();
```
|
I'm trying to print a unicode star character (0x2605) in a linux terminal using C. I've followed the syntax suggested by other answers on the site, but I'm not getting an output:
```
#include <stdio.h>
#include <wchar.h>
int main(){
wchar_t star = 0x2605;
wprintf(L"%c\n", star);
return 0;
}
```
I'd appreciate any suggestions, especially how I can make this work with thencurseslibrary.
|
Two problems: first of all, awchar_tmust be printed with%lcformat, not%c. The second one is that unless you callsetlocalethe character set is not set properly, and you probably get?instead of your star. The following code seems to work though:
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main() {
setlocale(LC_CTYPE, "");
wchar_t star = 0x2605;
wprintf(L"%lc\n", star);
}
```
And forncurses,just initialize the localebeforethe call toinitscr.
|
I have a source tree for a program I am working on which is written in mixed C/C++ code. For debugging purposes, I would like to be able to run a command line tool likeunifdefon the entire tree (recursively) to remove a certain set of#ifdef/#endifmacros from all source files.
I was wondering if there was any specific way I could go about doing this in an efficient way. Any help would be appriciated, thank you.
|
I've solved this issue by using the following command:
find . -name '*.c' -o -name '*.h' -o -name '*.cpp' -o -name '*.hpp' -exec unifdef <macro definitions> -o '{} {} ;'
|
```
int duration = mediaPlayer.getDuration();
textView = (TextView) findViewById(R.id.tvduration); textView.setText(duration);
```
|
FromMediaPlayer:
the duration in milliseconds, if no duration is available (for
example, if streaming live content), -1 is returned.
That's why you will get fromgetDuration()the duration in milliseconds.You can use this to get the time ofMediaPlayeras String:
```
int duration = mediaPlayer.getDuration();
String time = String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
);
```
And then as you write in your question:
```
TextView textView = (TextView) findViewById(R.id.tvduration);
textView.setText(time);
```
|
I am using kdbg for debugging.
```
> kdbg -v
Qt: 4.8.6
KDE Development Platform: 4.13.3
KDbg: 2.5.4
>
```
Theofficial documentationis somewhat rudimentary. I am searching for a keyboard shortcut to continue running the program till it hits the next breakpoint. According tothisF7 should do. However running on Ubuntu F7 seems to always jumop at the end of the current function. How can I get kdbg to run the executable till the next breakpoint?
|
How can I get kdbg to run the executable till the next breakpoint?
Hit F5.
Yes, I know, the menu does not change text toContinueor so, but the icon shows something like thePlayicon that you know from your media software (or CD player, if you grew up in the past century) which also just continues, and does not start from the beginning.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
I have a lot of unindented C/C++ source files.I want to beautify all of them programmatically. How can I achieve that?
|
Write a python script that calls a C++ beautifier like Artistic Style.
http://astyle.sourceforge.net/
Here's how your python script would look:
```
# Collect all the files you need to beautify in "files"
#Loop through each C/C++ file
for file in files:
command = "astyle " + file
import subprocess
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
```
Example usage of Artistic Style is:
```
astyle example.cpp
```
or
```
astyle --style=ansi --indent=tab example.cpp
```
|
My question is how to passintarguments throughargv[].
The form I want to use is the following: while the NTHREADS, and LETTER can be optional, the FILE1 must be provided.
./test [-t NTHREADS] [-l LETTER] FILE1
How can I handle this?
|
You can't. All arguments tomain()arechar*by definition. If you want you can convert them, but that's done at your own discretion. There are tools likegetoptthat make writing interfaces like this a lot easier, and they can be used to do conversion as necessary.
|
I used the code in below link:
Readline Library
And I defined a struct like this
```
typedef struct {
char *name; /* User printable name of the function. */
Function *func; /* Function to call to do the job. */
char *doc; /* Documentation for this function. */
} COMMAND;
```
When I compile the code the compiler displays these warnings:
"Function is deprecated [-Wdeprecated-declarations]"
So what type should I change if I cannot use the function type?
|
Functionis atypedef(an alias of a pointer to function returningint) marked as deprecated by thelibrary:
```
typedef int Function () __attribute__ ((deprecated));
```
Just use:
```
typedef struct {
char *name; /* User printable name of the function. */
int (*func)(); /* Function to call to do the job. */
char *doc; /* Documentation for this function. */
} COMMAND;
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.