question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Is it possible to create arrays based of their index as in
```
int x = 4;
int y = 5;
int someNr = 123;
int foo[x][y] = someNr;
```
dynamically/on the run, without creating foo[0...3][0...4]?
If not, is there a data structure that allow me to do something similar to this in C?
|
No.
As written your code make no sense at all. You needfooto be declared somewhere and then you can index into it withfoo[x][y] = someNr;. But you cant just makefoospring into existence which is what it looks like you are trying to do.
Either create foo with correct sizes (only you can say what they are)int foo[16][16];for example or use a different data structure.
In C++ you could do amap<pair<int, int>, int>
|
I'm trying to get a 4 digit input from the user but a non numeric entry is not acceptable. Instead of checking for non numeric values, can I allow the user to only enter numeric values into the GtkEntry box?
```
GtkWidget *entry_pin;
entry_pin=gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY(entry_pin),4);
```
By the way I'm running on Ubuntu.
|
Antoher way is stopping the emission in a callback
```
#include <ctype.h>
void insert_text_event(GtkEditable *editable, const gchar *text, gint length, gint *position, gpointer data)
{
int i;
for (i = 0; i < length; i++) {
if (!isdigit(text[i])) {
g_signal_stop_emission_by_name(G_OBJECT(editable), "insert-text");
return;
}
}
}
```
The callback can be set as:
```
g_signal_connect(G_OBJECT(widget), "insert-text", G_CALLBACK(insert_text_event), NULL);
```
|
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.Closed4 years ago.The community reviewed whether to reopen this questionlast yearand left it closed:Original close reason(s) were not resolvedImprove this question
I want to solve this problem without "#pragma warning (disable:4996)" please help me.
I tried many things.
I think it may have problem with visual studio.
|
Usescanf_s()and make the necessary other changes, or#define _CRT_SECURE_NO_WARNINGS. Basically, read the error message and do what it suggests.
Note thatscanf_s()requires extra arguments for the lengths of “string” arguments.
|
When I try to read data out my i2c-bus, i need to press RETURN to execute the read. I dont want it to do that automatically.
Also it does not read data but that might a problem of the i2c slave at the other end.
I dont know why it wants to have this keypress..
```
char recievedbyte[1];
printf("rB 0\n");
int er = read(I2C_BUS, recievedbyte, 1);
printf("rB 1\n");
```
I would expect that it does read the bus automatically at the read()-call. Actually, I need to press RETURN betweenprintf("rB 0\n");andprintf("rB 1\n");. when i do a read() with for example a textfile everything works fine...
|
I forgot to open() the I2C_BUS.
Due to that I2C_BUS was 0 (zero) and it read lines from stdin (thats why the ENTER key was needed.)
|
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.Closed4 years ago.Improve this question
I getting code 0 error while compiling very simple code. How do I solve it?
I using VS 2017 for the first time.
```
#include <stdio.h>
void main()
{
printf("My name is Haim");
}
```
The two rows in the middle are not supposed to be there!
Haim
|
Yourmain()should return some exit code. So int should be as the return type.
In the other hand exit code0means, that everything was succesfull,see.
|
Say I got two CMake targets,myexeandmylib, wheremylibisSHARED.
I'm loadingmylibfrommyexeat runtime (usingdlopen). So my requirement is that when I buildmyexe,mylibwill also get built. To my understanding,target_link_libraries()is not accurate here because linkage is at runtime only.
How can I model that in CMake?
|
Use simpleadd_dependenciesfor make one target to automatically build another one:
```
# The library used via dlopen should be built with MODULE type.
add_library(mylib MODULE <mylib-source-files>)
add_executable(myexe <myexe-source-files>)
# For build myexe, mylib should also be built.
add_dependencies(myexe mylib)
```
|
I'm trying to use NumPy in a C extension for python.
I'm getting a segfault I can't explain, I've narrowed it down to this simple example.
```
#include "numpy/arrayobject.h"
int main()
{
int dims[] = {1};
double d[] = {1};
PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, &d);
}
```
| ERROR: type should be string, got "\nhttps://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html\n\nThis function must be declared so that it is visible to code outside\n of the routine.Besides adding the methods and constants you desire,\n this subroutine must also contain calls like import_array()and/or\n import_ufunc() depending on which C-API is needed. Forgetting to place\n these commands will show itself as anugly segmentation fault(crash)\n as soon as any C-API subroutine is actually called.\n\nI also had to includePy_Initialize()beforehand since this was a standalone example not being run through a Python vm as it would normally be.\n" |
I am getting an error for conflicting types in the function getline. I am consistent in the variable and function types in both function declaration statements, so I do not know what the problem is.
```
#include <stdio.h>
int getline(char line[]);
int main()
{
char line[100];
int len;
while ((len = getline(line)) > 0)
printf("%d\n", len);
}
int getline(char line[])
{
int i, c;
for (i = 0; (c = getchar())!=EOF && c!='\n'; ++i)
line[i] = c;
if (c == '\n'){
line[i] = c;
++i;
}
line[i] = '\0';
return(i);
}
```
|
It seems your compiler is configured to use the POSIX standard, and in POSIX environment,getline()is already prototyped instdio.has
```
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
```
which conflicts with your declaration / definition.
Use a different function name (ex:my_getline()or similar).
|
I need to write a iterative function for this recursive function.
```
int funcRec(int n){
if(n>1) {
return 2*funcRec(n - 1) + 3*funcRec(n - 2);
}else{
return n;
}
}
```
|
Try this one
```
int funcIter(int n) {
int value0 = 0;
int value1 = 1;
int res = n;
for (int i = 2; i <= n; i++) {
res = 2 * value1 + 3 * value0;
value0 = value1;
value1 = res;
}
return res;
}
```
|
I am facing a function which takes a pointer to achararray but it performs only read operations on the mem thechar *points to.
I could addconstto the prototype directly before thechar *parameter, but this would break the rest of the non const-correct code. I decided to add a comment/*const*/instead to indicate that the function performs only read operations.
However, this confuses my colleagues and I wonder if adding the comments is a common approach and the criticism is unjustified.
Example:
```
int func(const char *readat);
```
versus
```
int func(/*const*/ char *readat);
```
|
Addingconstto the function parameter won't break any calling code. It is allowed to assign a non-const object to a const object.
So this is allowed:
```
char c;
char *p = &c;
const char *cp = p;
```
But this is not:
```
char c;
const char *cp = &c;
char *p = cp;
```
|
I'd like to build a custom Windows button without subclassing it.
I simply want to draw it, like I would draw a rectangle by callingFillRect().
How do I call the window procedure registered by the BUTTON window class that performs the painting?
update
As noted in the comments, I want to draw an image that looks like a button without having a child window that is a button.
|
By Andreas Rejbrand:
Old style:DrawFrameControl. New style:DrawThemeBackground,DrawThemeText, etc.
|
I need to write a iterative function for this recursive function.
```
int funcRec(int n){
if(n>1) {
return 2*funcRec(n - 1) + 3*funcRec(n - 2);
}else{
return n;
}
}
```
|
Try this one
```
int funcIter(int n) {
int value0 = 0;
int value1 = 1;
int res = n;
for (int i = 2; i <= n; i++) {
res = 2 * value1 + 3 * value0;
value0 = value1;
value1 = res;
}
return res;
}
```
|
So I am trying to write a begginers program in which it is necessary to create a series of files, depending on the users choosing option, and where the first file created should be name by for example "book1.txt" and second one "book2.txt" etc...
```
FILE *fnew;
int num; //i do have a lot of code before to get the 'num' value from where I want, don't bother it;
char filename[]= "bookX.txt";
filename[4]=num+1;
fnew = fopen(filename,"w");
fclose(fnew);
```
|
You can usesprintfto build the filename:
```
sprintf(filename, "book%03d.txt", num);
```
This will create files named booknnn.txt, wherennnis the number in question padded with 0's, ex. book001.txt, book002.txt.
|
When I hover over to GL_POINTS, it shows
#define GL_POINTS 0x0000
and it falls under the category of primitives
Similarly, GL_POINT falls under 'polygons' category and
shows the descritption:
#define GL_POINT 0x1B00
there is no clear documentation available for GL_POINT, though there is for GL_POINTS (reference: docs.gl)
Similarly, replacing either doesn't work
|
GL_POINTSis a primitive type: it defines how vertices are grouped together. It is themodeparameter in commands such asglDrawArrays,glDrawElements, and otherglDraw...GL_POINTis a rendering mode for polygons using inglPolygonMode. Normally, triangles are rasterized onto the framebuffer, filling the space between vertices. If one wishes to render only triangles' vertices or edges, this can be achieved byglPolygonMode(GL_POINT)orglPolygonMode(GL_LINE), respectively.
|
I found this in linux-2.6.26 (linux-2.6.26/include/asm-alpha/atomic.h), and donot know why +0 here.
```
#define atomic_read(v) ((v)->counter + 0)
#define atomic64_read(v) ((v)->counter + 0)
```
|
If+ 0is not used, it would be an lvalue that you could assign to by accident, i.e.
```
if (atomic_read(v) = 42) {
...
}
```
would "work"... Instead of+ 0you could just use unary+, i.e.
```
(+(v)->counter)
```
However+ 0hasonegood advantage over+in generic case:+requires that the argument be anarithmetic type- but pointers are not of arithmetic type. Yet+ 0would work for pointers alike (and for pointers alone, you can use&*to convert lvalue to a value of expression; this is guaranteed to work for even null pointers)
|
So I am trying to write a begginers program in which it is necessary to create a series of files, depending on the users choosing option, and where the first file created should be name by for example "book1.txt" and second one "book2.txt" etc...
```
FILE *fnew;
int num; //i do have a lot of code before to get the 'num' value from where I want, don't bother it;
char filename[]= "bookX.txt";
filename[4]=num+1;
fnew = fopen(filename,"w");
fclose(fnew);
```
|
You can usesprintfto build the filename:
```
sprintf(filename, "book%03d.txt", num);
```
This will create files named booknnn.txt, wherennnis the number in question padded with 0's, ex. book001.txt, book002.txt.
|
When I hover over to GL_POINTS, it shows
#define GL_POINTS 0x0000
and it falls under the category of primitives
Similarly, GL_POINT falls under 'polygons' category and
shows the descritption:
#define GL_POINT 0x1B00
there is no clear documentation available for GL_POINT, though there is for GL_POINTS (reference: docs.gl)
Similarly, replacing either doesn't work
|
GL_POINTSis a primitive type: it defines how vertices are grouped together. It is themodeparameter in commands such asglDrawArrays,glDrawElements, and otherglDraw...GL_POINTis a rendering mode for polygons using inglPolygonMode. Normally, triangles are rasterized onto the framebuffer, filling the space between vertices. If one wishes to render only triangles' vertices or edges, this can be achieved byglPolygonMode(GL_POINT)orglPolygonMode(GL_LINE), respectively.
|
I found this in linux-2.6.26 (linux-2.6.26/include/asm-alpha/atomic.h), and donot know why +0 here.
```
#define atomic_read(v) ((v)->counter + 0)
#define atomic64_read(v) ((v)->counter + 0)
```
|
If+ 0is not used, it would be an lvalue that you could assign to by accident, i.e.
```
if (atomic_read(v) = 42) {
...
}
```
would "work"... Instead of+ 0you could just use unary+, i.e.
```
(+(v)->counter)
```
However+ 0hasonegood advantage over+in generic case:+requires that the argument be anarithmetic type- but pointers are not of arithmetic type. Yet+ 0would work for pointers alike (and for pointers alone, you can use&*to convert lvalue to a value of expression; this is guaranteed to work for even null pointers)
|
What would happen if the follow lines were a part of a compiled program?
```
void main() {
int x = 5;
while (x == 5);
}//end main
```
I believe it is, I have compiled it, and the screen just stays the same, I also tried to add after the while statement
```
int y = 10;
printf("%i", y);
```
and then end main. However it never prints. So I am fairly certain that its an infinite loop but I would just like to be sure.
|
Yes it is, but it could actually leave the loop in some scenarios:
There is a thread that changes the x variable.An external program modifies the program memory.As tadman said, a bitflip occurs on the memory itself, which is very unlikely but also a possibility.
There must be other cases where the loop can end, but those are the ones I could think of.
If you're interested, you can try to do so with Cheat Engine to change the value of x.
|
I'm running this code and getting some garbage value while printing *ptr. What could be the possible reason and how can I avoid getting that?
```
# include <stdio.h>
int main()
{
int test = 1;
int *ptr = &test;
*ptr++ = 10;
test++;
printf("\nThe value is %d", *ptr);
}
```
|
You movedptrwithptr++. Why?
Don't do that.
|
I've been working with some basic coding challenges and I've come across this syntax "ch = input[c] - 'a'" a couple of times and I would like to understand it before moving on.
```
n = strlen(input);
for (c = 0; c < n; c++) {
ch = input[c] - 'a';
no[ch]++;
}
```
|
'a'=97format is based on ASCII table
and when you want to use alphabets whit their numbers, it will be useful.
This program wants to count number of each alphabet in your input
so it well increase the index of array which is the same of your alphabet index.
As we see'a'is48and for example for'b',ch=49-48=1so inindex=1you will seecb[index]+=1
|
I use free() to free the structure I allocated before, and I want to test if they have successfully free, but I get only one of them free why?
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student{
char *name;
struct student *next;
}student;
int main(int argc, const char * argv[]) {
student *a=malloc(sizeof(student));
a->name="echo";
student *b=malloc(sizeof(student));
b->name="harry";
a->next=b;
b->next=NULL;
free(a);
free(b);
printf("%s\n", a->name);
printf("%s\n", b->name);
return 0;
}
```
and I got this output.Why?
```
(null)
harry
Program ended with exit code: 0
```
|
You can't "test" if they have successfully been freed, trying to access any memory that has been freed is undefined behavior, instead of testing just accept and move on.
|
```
(int) + 4*5;
```
Why is this(adding a type with a value)possible? (tried with g++ and gcc.)
I know that it doesn't make sense (and has no effect), but I want to know why this is possible.
|
The+here isunary+operator, not thebinary addition operator. There's no addition happening here.
Also, the syntax(int)is used for typecasting.
You can re-read that statement as
```
(int) (+ 4) * 5;
```
which is parsed as
```
((int) (+ 4)) * (5);
```
which says,
Apply the unary+operator on the integer constant value4.typecast to anintmultiply with operand5
This is similar to(int) (- 4) * (5);, where the usage of the unary operator is more familiar.
In your case, the unary+and the cast toint- both are redundant.
|
I use free() to free the structure I allocated before, and I want to test if they have successfully free, but I get only one of them free why?
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student{
char *name;
struct student *next;
}student;
int main(int argc, const char * argv[]) {
student *a=malloc(sizeof(student));
a->name="echo";
student *b=malloc(sizeof(student));
b->name="harry";
a->next=b;
b->next=NULL;
free(a);
free(b);
printf("%s\n", a->name);
printf("%s\n", b->name);
return 0;
}
```
and I got this output.Why?
```
(null)
harry
Program ended with exit code: 0
```
|
You can't "test" if they have successfully been freed, trying to access any memory that has been freed is undefined behavior, instead of testing just accept and move on.
|
```
(int) + 4*5;
```
Why is this(adding a type with a value)possible? (tried with g++ and gcc.)
I know that it doesn't make sense (and has no effect), but I want to know why this is possible.
|
The+here isunary+operator, not thebinary addition operator. There's no addition happening here.
Also, the syntax(int)is used for typecasting.
You can re-read that statement as
```
(int) (+ 4) * 5;
```
which is parsed as
```
((int) (+ 4)) * (5);
```
which says,
Apply the unary+operator on the integer constant value4.typecast to anintmultiply with operand5
This is similar to(int) (- 4) * (5);, where the usage of the unary operator is more familiar.
In your case, the unary+and the cast toint- both are redundant.
|
```
while(str[i]!='\0')
{
if(str[i]!=str1[i])
{
printf("not equal");
return 1;
}
i++;
}
printf ("equal");
return 0;
```
What happens here if we use return 1.
Will return 1 terminate the if condition or the whole loop?
|
it exists the current scope
e.g.
```
int foo()
{
return 42;
}
int main()
{
int n = 0;
do
{
n = foo();
printf("received %d\n",n); /* will print "received 42" */
}
while (n != 42) // will quit since n == 42
return 0; // returns 0 to the operating system
}
```
|
I found some existing answer on SO, but I actually don't understand how does everythingthereworks.
Basically, I want to define a macro in if/switch condition
```
if (condition)
{
#define SOME_MACRO
}
```
So, if some condition is true, there will be defined some new macro.
But, as for now, it just defines macro anyway. I understand that it's not really how it should be done, but there's no normal explanation to that.
|
You can't mix macros and code like that. Macros are all processed before your code is compiled, it is just a convenience feature to save typing (and make code easier to read).
There is a macro syntax for conditions for example, you can do:
```
#if Condition
#define X
#endif
```
to conditionally define a macro.
|
I am trying to get gcov to run from the terminal on a program that has arguments.
Running the command "gcov ./program" works but shows me coverage on the program with no inputs.
I am trying to run the command "gcov ./program -e file1 file2"
I believe its getting caught up on -e by taking it as a gcov flag or just getting tripped up on everything after ./programm
|
You compile your program with -fprofile-arcs -ftest-coverage flags.
Example:
gcc -fprofile-arcs -ftest-coverage -o sample tprogram.c
Then you run your program with any number of arguments you want. Example:
./sample 1 2 3
After this two new files with extension .gcno and .gcda will be created.Then run gcov on your program. Example:
gcov tprogram.c
This will generate your required coverage report.
|
I'm very new to CLion and to proggraming and don't know a lot of the expressions so please be gentle.
I have downloaded CLion for Windows. I opened a new project and I can't run it.
The versioni is 2019.1.
The (default) CMakeLIsts is
```
cmake_minimum_required(VERSION 3.13)
project(untitled4 C)
set(CMAKE_C_STANDARD 99)
add_executable(untitled4 main.c)
```
Maybe I have a configuration problem (which as I said before don't understand what it means). Thanks.
|
try shift+f10 (or whatever combination you see when you hover your mouse on the button although i guess it is the same in 2019.1 just as 2018.3), just created a project from scratch, bumped into the same problem(run button not available for pressing) however shift+f10 happened to solve it.
edit: after running the code for first time the button is now available.
|
Basically I want to pass main'sargcand*argv[]to global variables, but am getting:
error:argshas an incomplete typechar *[];
code:
```
int argi;
char *args[];
int main(int argc, char *argv[]){
argi = argc;
args = argv;
// blah bah blah
}
int foo(){
printf("argv[0]: %s\n", args[0]);
// ayy what it is.
}
```
Note: for some reason, I don't want to dofoo(int argc, char *argv[])and then in main calling it asfoo(argc, argv);
So precisely said, I need to assign main'sargcandargvto my global variables.
|
Arrays and pointers aren't perfectly equivalent, even though they often appear to be convertible. Usechar **argvinstead ofchar *argv[](and the same for the global), and this will then work.
|
When running the simple code below I want to check the size of my array with a printf statement to output the value of size. I believe that I have coded this correctly but the output is completely blank.
I so far have only been able to get this to work when reading from a file. I've also tried initializing size=0 which I already knew would not work. Ran code on Codeblocks only.
```
int main()
{
int x[50]= {1,3,43,5,7,49,3,6},i,size;
for(i=0;i<50;i++)
{
scanf("%d",&x[i]);
++size;
}
printf("The size is %d", size);
return 0;
}
```
This code should simply output "The size is 8".
|
How can you expect your output to appear as 8.
since you have already initialized value of the array to 50 you will get size of the array 50 .
|
I'm trying to convert a uint32_t from network byte order to host format. I'm reading from a tcp connection 4 bytes that I store in the buffer like this:
```
ssize_t read = 0;
char *file_buf;
size_t fb_size = 4 * sizeof(char);
file_buf = malloc(fb_size);
read = recv(socket_file_descriptor,file_buf,fb_size,0);
```
so I store the number in file_buf but I want a number, how can I do this?
|
This looks straightforward:
```
ssize_t read = 0;
uint32_t myInteger; // Declare a 32-bit uint.
// Pass a pointer to the integer, and the size of the integer.
read = recv(socket_file_descriptor,&myInteger,sizeof(myInteger),0);
myInteger = ntohl(myInteger); // Change from Network order to Host order.
```
|
I am trying to drive an LED matrix and have an issue with shifting the whole display down. My end goal is to shift all of the rows and hopefully eventually implement a wrap around. The problem is that the first row is copied every time each row gets shifted.
The code that i used is as follows:
```
for (int i = (LAYERS - 1); i >= 0; i-- ) {
for(int z = 0; z < BYTES; z++) {
LED_Buffer[i+1][z] = LED_Buffer[i][z];
}
}
```
|
You'll need some manner of temporary variable for the wrap-around.
The general algorithm for shifting elements one position down the array, given some arrayfoobar[size], is:
```
tmp = foobar[size-1];
for(int i=size-1; i>0; i--) // note i>0, don't include first item
{
foobar[i] = foobar[i-1];
}
foobar[0] = tmp;
```
where thesize-1comes from 0-indexed arrays. Now simply apply the same to your specific case.
|
I know that x++ refers to post increment. It first uses the original value and then resorts to the incremented value.
But when does that actually happen?
Does it happen when the next immediate line in code is executed?
Does it happen when original value is returned once?
|
It happens between sequence points.
Other than that, it's unspecified when it happens.
Imagine this
```
x = y = z = 42
; // sequence point A
n = x++ + y++ + z++
; // sequence point B
```
At seq. point A x, y, and z are all 42; at sequence point B they are all 43. For all you care, the compiler could emit code to update all 3 variables at the same time.
```
// pseudo code
n = 126;
[vector increment][x,y,z];
//n = 126;
```
|
I know that x++ refers to post increment. It first uses the original value and then resorts to the incremented value.
But when does that actually happen?
Does it happen when the next immediate line in code is executed?
Does it happen when original value is returned once?
|
It happens between sequence points.
Other than that, it's unspecified when it happens.
Imagine this
```
x = y = z = 42
; // sequence point A
n = x++ + y++ + z++
; // sequence point B
```
At seq. point A x, y, and z are all 42; at sequence point B they are all 43. For all you care, the compiler could emit code to update all 3 variables at the same time.
```
// pseudo code
n = 126;
[vector increment][x,y,z];
//n = 126;
```
|
Please consider the following code:
```
// Thing is a typedef struct
void f(Thing* things, int size) {
for (int i = 0; i < size; i++) {
Thing my_thing = things[i];
my_thing.a = 10;
}
}
```
The array pointed to bythingsis allocated somewhere on the heap.
And yet -my_thingis a "stack variable" - allocated on the stack.
So what is happening behind the scenes? Isthings[i]copiedto the stack and stored inmy_thing? And what doesmy_thing.a = 10;do - does it modify the originalthings[i]or does it modify the "stack copy"?
|
Is things[i] copied to the stack and stored in my_thing?
Yes, as a memory copy, not deep copy.
And what does my_thing.a = 10; do - does it modify the original things[i] or does it modify the "stack copy"?
It only modifies stack copy. However be careful when dealing with pointers, see examplehere
|
I have a source pointer (pSource) and a goal pointer (pGoal). I also have a number of characters (n) that need to be copied to thepGoalfrompSource.
I thought that I can just copy what's in thepSourcetopGoaland move both pointers to the next location. (Both are pointing at the start at the beginning).
```
for (int i = 0; i < n; i++) {
pGoal+i = pSource+i;
}
```
|
Assuming that your pointers are of typechar *, the correct way of doing this is:
```
for (int i = 0; i < n; i++) {
*(pGoal+i) = *(pSource+i);
// or pGoal[i] = pSource[i]
}
```
You can also checkmemcpy
|
If I compile a C program with any arm compiler (e.g.arm-none-eabi-gcc) and afterwards callgdb-multiarchwith the binary as second paramter, it will correctly determine the machine type and I can debug my remote application.
If however I callgdb-multiarchon its own, it will assume my machine type (x86_64) and tries to debug the remote target with the wrong architecture..
How do I specify the machine type/architecture (e.g.armv5te) ingdb-multiarch?
|
The fine manual says:
set architecture archThis command sets the current target architecture to arch. The value of arch can be
"auto", in addition to one of the supported architectures.
This sure sounds like what you're after, to me.
|
I have a source pointer (pSource) and a goal pointer (pGoal). I also have a number of characters (n) that need to be copied to thepGoalfrompSource.
I thought that I can just copy what's in thepSourcetopGoaland move both pointers to the next location. (Both are pointing at the start at the beginning).
```
for (int i = 0; i < n; i++) {
pGoal+i = pSource+i;
}
```
|
Assuming that your pointers are of typechar *, the correct way of doing this is:
```
for (int i = 0; i < n; i++) {
*(pGoal+i) = *(pSource+i);
// or pGoal[i] = pSource[i]
}
```
You can also checkmemcpy
|
If I compile a C program with any arm compiler (e.g.arm-none-eabi-gcc) and afterwards callgdb-multiarchwith the binary as second paramter, it will correctly determine the machine type and I can debug my remote application.
If however I callgdb-multiarchon its own, it will assume my machine type (x86_64) and tries to debug the remote target with the wrong architecture..
How do I specify the machine type/architecture (e.g.armv5te) ingdb-multiarch?
|
The fine manual says:
set architecture archThis command sets the current target architecture to arch. The value of arch can be
"auto", in addition to one of the supported architectures.
This sure sounds like what you're after, to me.
|
I expected that below code will output10because(~port)equal to10100101So, when we right shift it by4we get00001010which is10.
But the output is250! Why?
```
int main()
{
uint8_t port = 0x5a;
uint8_t result_8 = (~port) >> 4;
//result_8 = result_8 >> 4;
printf("%i", result_8);
return 0;
}
```
|
C promotesuint8_ttointbefore doing operations on it. So:
portis promoted to signed integer0x0000005a.~inverts it giving0xffffffa5.An arithmetic shift returns0xfffffffa.It's truncated back into auint8_tgiving0xfa == 250.
To fix that, either truncate the temporary result:
```
uint8_t result_8 = (uint8_t)(~port) >> 4;
```
mask it:
```
uint8_t result_8 = (~port & 0xff) >> 4;
```
or xor it (thanks @Nayuki!):
```
uint8_t result_8 = (port ^ 0xff) >> 4;
```
|
I'm trying to start gvim using this line:
```
execl("/usr/bin/gvim", "-f", path, (char *)NULL);
```
however I'm getting
```
Vim: Warning: Output is not to a terminal
Vim: Warning: Input is not from a terminal
```
and I'm not sure how to solve this. I mean, I know that output is not a terminal, that's why I'm usinggviminstead of justvim. It's probably something really obvious, but I just don't know.
|
If you forget to put the program's name as the first parameter of exec, gvim will try to open in terminal mode.
It should be:
```
execl("/usr/bin/gvim", "/usr/bin/gvim",
"-f", path, (char *)NULL);
```
From theexeclman page:
The first argument, by convention, should point to the filename
associated with the file being executed. The list of arguments must be
terminated by a NULL pointer, and, since these are variadic functions,
this pointer must be cast (char *) NULL.
|
I've seen both(size_t)-1and~0used to represent large numbers, or numbers with all their bits flipped.
Is there any difference between the two? If so, what is it?
I found this question:What is the difference between -1 and ~0, however it did not answer my question because I'm dealing with unsigned integers (such assize_t), as opposed to signed integers (such asint).
|
What's the difference between (size_t)-1 and ~0?
Type and value differ.
(size_t)-1is the same value asSIZE_MAXand has a type ofsize_t.
~0is often -1 and has the type ofint.
Assigning both of those to asize_twill result inSIZE_MAX.
```
size_t a = (size_t)-1;
size_t b = ~0;
```
In the 2nd case,-1is assigned to aband undergoes a conversion first, wrapping around the -1 to the maximumsize_tvalue.
|
This question already has answers here:printf and ++ operator [duplicate](5 answers)Closed4 years ago.
I tried running this program :
```
#include<stdio.h>
int main(){
int a=5;
printf("%d %d", ++a,a++);
return 0;
}
```
with gcc in arch-chroot on a armv7 device. I expect to get output7 5but i'm getting7 6. Can anyone explain what's going on?
|
Your code is invokingUndefined Behavior(UB)!
Use the warning flgas-Wall -Wextraduring compilation, and the compiler will tell you the story:
```
prog.c: In function 'main':
prog.c:4:30: warning: operation on 'a' may be undefined [-Wsequence-point]
4 | printf("%d %d", ++a,a++);
| ~^~
7 5
```
In thatonline demo, I got a different output, a characteristic of UB.
Read more inprintf and ++ operator.
|
Note this question does not refer to ellipsis.
Consider the following code
```
#include <stdio.h>
void foo() {
printf("I AM AWESOME\n");
}
main(void) {
foo(1,2,3);
foo();
return 0;
}
```
This program runs perfectly and provides the output.
However, in case of 'main', this works irrespective of
main(void)
or
main()
When, defining foo as
foo(void)
gives an error - "too many arguments".
If both are functions, shouldn't they also follow the same rules?
|
When you declare a function without parameters it means to disable type checking and to use K&R calling convention. It does not mean that the function does not have parameters.
In ANSI when you want to explicitly say that the function does not have parameters, you need to declare it as fun(void).
|
This question already has answers here:switch case: error: case label does not reduce to an integer constant(6 answers)Closed4 years ago.
I used a predefined char variable in a case in my switch and got this errorcase label does not reduce to an integer
```
char player = 'X';
switch(.....){
case player:
.
.
.
.
```
I need a solution for this.
|
From theC11 standard:
The expression of each case label shall be an integer constant expression
playerisnota "constant expression".
Please note that in C qualifying a variable asconst, doesnotmake it a "constant expression" in the sense of the C standard.
A label either need to be an integer literal, or aenum, which in factisan integer.
|
I had written a code:
```
EXEC SQL
SELECT COLUMN.NAME into :h_HOST_VARIABLE :i_HOST_VARIABLE
FROM TABLE_NAME
WHERE
someCondition......
```
The column from which data is being fetched isNULL-able. There was already some value inh_HOST_VARIABLE, so when this query was executed the value in that column wasNULL.
So I was expecting that the host variable would be set toNULL(due to which I didn't memset the host variable) but it didn't happen, it retained it's previous value. Why did this happen?
|
This works as designed.Identifying null SQL values with null indicator variables:
The null-indicator variable is examined for a negative value. If the
value is not negative, the application can use the returned value of
the host variable.If the value is negative, the fetched value is
null and the host variable should not be used. The database manager
does not change the value of the host variable in this case.
|
In C, how do I scan an print an array of 20 numbers given by the user.
Example desired output:
Enter data: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
The data entered is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
This is what I have so far for my loop:
```
for (i = 0; i <= 20; i++){
scanf("%d", &arry[i]);
}
```
This however keeps asking for 21 inputs before the loop terminates.
|
Everything is fine except that=. It means:
RunFOR-LOOPfrom0up to20.
Which means a total of21values. Just remove that=and you are good to go:
```
for (i = 0; i < 20; i++)
{
scanf("%d", &arry[i]);
}
```
|
Lets say i have simple function to print text. (school homework its like chat with professor server)
```
// a) This should be right
while (recvbuf[i] != '\n') {
printf("%c", recvbuf[i]);
i++;
};
// b) This should be left
printf("I am text");
```
But "a)" can be only on right side cant be on left and "b)" can be only on left side cant be on right.
How can i do it? Thanks for any help.
// console window is of exactly size 24*80
|
For printing on left side of the terminal, you can simply use a print function likeprintforputs.
For printing on right side of the terminal, you can use printf padding like that :
```
printf("%+80s\n", text);
```
You can seeprintf man pagefor more information on format option
|
I read that macOS Mojave does not support OpenGL anymore. I have to make a small C project for University with OpenGL using gcc.
Does macOS Mojave not supporting OpenGL anymore mean that I wont be able to compile such files anymore under macOS? Or will it still be possible?
Or do I have to install Linux / Windows for that?
|
OpenGL does still work, and can be compiled against, under Mojave (i.e. the OpenGL.framework is still in System/Library/Frameworks, and you can select the framework in in Xcode for development).
However, Apple announced that it is deprecated from now on. This means that it might be removed in any later version and limited development will go into it (i.e. don't expect bug fixes any more).
|
```
// Assuming these definitions
int x;
float y;
```
What is the difference between this:
```
x = y = 7.5;
```
and this:
```
y = x = 7.5;
```
How come the first one printsyvalue as7.5,
and second one printsyas7.00?
|
The explanation is very simple:=is right to left associative, which meansx = y = 7.5;is evaluated asx = (y = 7.5);hence essentially the same as:
```
y = 7.5; // value is converted from double to float, y receives 7.5F
x = y; // value of y is converted from float to int, x receives 7 (truncated toward 0)
```
Whereasy = x = 7.5;is evaluated asy = (x = 7.5);:
```
x = 7.5; // 7.5 is converted to int, x receives value 7 (truncated toward 0)
y = x; // value of x is converted to float, y receives 7.0F
```
These implicit conversions can be counter intuitive. You might want to increase the warning level to let the compiler warn you about potential mistakes and unwanted side effects.
|
I read that macOS Mojave does not support OpenGL anymore. I have to make a small C project for University with OpenGL using gcc.
Does macOS Mojave not supporting OpenGL anymore mean that I wont be able to compile such files anymore under macOS? Or will it still be possible?
Or do I have to install Linux / Windows for that?
|
OpenGL does still work, and can be compiled against, under Mojave (i.e. the OpenGL.framework is still in System/Library/Frameworks, and you can select the framework in in Xcode for development).
However, Apple announced that it is deprecated from now on. This means that it might be removed in any later version and limited development will go into it (i.e. don't expect bug fixes any more).
|
```
// Assuming these definitions
int x;
float y;
```
What is the difference between this:
```
x = y = 7.5;
```
and this:
```
y = x = 7.5;
```
How come the first one printsyvalue as7.5,
and second one printsyas7.00?
|
The explanation is very simple:=is right to left associative, which meansx = y = 7.5;is evaluated asx = (y = 7.5);hence essentially the same as:
```
y = 7.5; // value is converted from double to float, y receives 7.5F
x = y; // value of y is converted from float to int, x receives 7 (truncated toward 0)
```
Whereasy = x = 7.5;is evaluated asy = (x = 7.5);:
```
x = 7.5; // 7.5 is converted to int, x receives value 7 (truncated toward 0)
y = x; // value of x is converted to float, y receives 7.0F
```
These implicit conversions can be counter intuitive. You might want to increase the warning level to let the compiler warn you about potential mistakes and unwanted side effects.
|
So I'm trying to make achar**, I fully understand how it works in the background and all that stuff but I don't seem to understand how to write the code for it. I want to make a pointer to an array of chars which has a name in it. I need help with storing a string in it (using strcpy() ) and print it after that.
```
char** name = (char**)malloc((strlen("MyName") + 1) * sizeof(char*));
strcpy(name, "MyName"); // I get an error right here
```
|
If you really want a pointer to an char array, you could do the following:
```
char** name = (char**)malloc(sizeof(char*)); //initialize the pointer
*name = (char*)malloc((strlen("MyName") + 1) * sizeof(char)); //initialize the array
strcpy(*name, "MyName");
```
|
This question already has answers here:How can I read an input string of unknown length?(11 answers)Closed4 years ago.
I have been trying to learn C, and was wondering: how would one get a string with an unknown length in C? I have found some results, but am not sure how to apply them.
|
If you're ok with extensions to the Standard, tryPOSIXgetline().
Example from documentation:
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(1);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
if (ferror(fp)) {
/* handle error */
}
free(line);
fclose(fp);
return 0;
}
```
|
I know the C11 standard definesrsize_tassize_tin the optional Annex K, but in what header file(s)? Where does the C standard say this type should be defined?
|
K.3.3 Common definitions<stddef.h>
The header<stddef.h>defines a type.The type isrsize_twhich is
the typesize_t.
Quoting thedraft.
Reading further, this is also defined in<string.h>,<stdlib.h>,<stdio.h>,<wchar.h>and<time.h>. There may be others.
|
while Copying the data from const string to an array-(-> which is a member of structure) using memcopy, compiler throwing error for buffer overflow in dest object
Thanks for the learnings.
```
#define LEN 9
typedef struct buff_ {
....
..
char bowl[LEN];
}buff;
buff *dest= NULL;
dest= malloc......();// This is allocated properly
'
'
'
memcpy(dest->bowl,"y",LEN); //compiler throwing error here:buffer overflow
```
There shouldn't be any error as I am copying the string in to buffer(dest) which LEN greater than the src.
|
Try using, this will limit to LEN or actual length of the string whichever is smaller:
```
strncpy(dest->bowl,"y",LEN);
```
|
I am using a SocketCAN to access the CAN bus.
I have successfully created pass-filters like this:
```
struct can_filter m_Filter;
// ... setting up m_Filters
setsockopt(m_CanSockId, SOL_CAN_RAW, CAN_RAW_FILTER, m_Filter,
sizeof(struct can_filter));
```
This instructs to let CAN messages pass when meeting the filter settings.
Now I want to create a stop-filter but I do not know how to do it.
For example: I wish to let all CAN messages pass except the ones with ID 0x18DAF101.
Does anybody know how to do it?
|
You have to set the bitCAN_INV_FILTERin your filter to invert the filter logic.
From the documentation behind the link you have provided:
The filter can be inverted in this semantic, when the CAN_INV_FILTER
bit is set in can_id element of the can_filter structure.
|
If I have an anonymous enum, is there any way to pass a value of that type to a function? For example,
```
typedef struct {
enum { On, Off } status;
int max_amps;
} SWITCH;
void make_switches(){
SWITCH switch1 = createSwitch( On, 15 );
SWITCH switch2 = createSwitch( Off, 20 );
}
SWITCH* createSwitch( ??? status, int max_amps ){
SWITCH* new_switch = malloc( sizeof( SWITCH ) );
new_switch->status = status;
new_switch->max_amps = max_amps;
return new_switch;
}
```
I would like to pass the value of the anonymous enum into thecreateSwitch()function. Is there any way to do this?
|
As others have suggested, you can simply use anintin the place of???.
This is because as per6.7.2.2/3ofC11standard (Committee draft):
The identifiers in an enumerator list are declared as constants that have typeintand may appear wherever such are permitted.
|
This question already has answers here:How can I read an input string of unknown length?(11 answers)Closed4 years ago.
I have been trying to learn C, and was wondering: how would one get a string with an unknown length in C? I have found some results, but am not sure how to apply them.
|
If you're ok with extensions to the Standard, tryPOSIXgetline().
Example from documentation:
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(1);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
if (ferror(fp)) {
/* handle error */
}
free(line);
fclose(fp);
return 0;
}
```
|
I know the C11 standard definesrsize_tassize_tin the optional Annex K, but in what header file(s)? Where does the C standard say this type should be defined?
|
K.3.3 Common definitions<stddef.h>
The header<stddef.h>defines a type.The type isrsize_twhich is
the typesize_t.
Quoting thedraft.
Reading further, this is also defined in<string.h>,<stdlib.h>,<stdio.h>,<wchar.h>and<time.h>. There may be others.
|
while Copying the data from const string to an array-(-> which is a member of structure) using memcopy, compiler throwing error for buffer overflow in dest object
Thanks for the learnings.
```
#define LEN 9
typedef struct buff_ {
....
..
char bowl[LEN];
}buff;
buff *dest= NULL;
dest= malloc......();// This is allocated properly
'
'
'
memcpy(dest->bowl,"y",LEN); //compiler throwing error here:buffer overflow
```
There shouldn't be any error as I am copying the string in to buffer(dest) which LEN greater than the src.
|
Try using, this will limit to LEN or actual length of the string whichever is smaller:
```
strncpy(dest->bowl,"y",LEN);
```
|
I am using a SocketCAN to access the CAN bus.
I have successfully created pass-filters like this:
```
struct can_filter m_Filter;
// ... setting up m_Filters
setsockopt(m_CanSockId, SOL_CAN_RAW, CAN_RAW_FILTER, m_Filter,
sizeof(struct can_filter));
```
This instructs to let CAN messages pass when meeting the filter settings.
Now I want to create a stop-filter but I do not know how to do it.
For example: I wish to let all CAN messages pass except the ones with ID 0x18DAF101.
Does anybody know how to do it?
|
You have to set the bitCAN_INV_FILTERin your filter to invert the filter logic.
From the documentation behind the link you have provided:
The filter can be inverted in this semantic, when the CAN_INV_FILTER
bit is set in can_id element of the can_filter structure.
|
I'm looking atunsigned char(byte) arrays ingdb, i.e.
```
(gdb) p/x buf@4
$76 = {0xac, 0xa, 0xb0, 0xa}
```
Is there a way of forcing the preceding 0s? i.e output like:
```
$76 = {0xac, 0x0a, 0xb0, 0x0a}
```
|
From the gdbdocumentation:
'z'Like 'x' formatting, the value is treated as an integer and printed as hexadecimal, but leading zeros are printed to pad the value to the size of the integer type.
So...
```
(gdb) p/z buf@4
```
|
I want to make asynchronous read on stdin in Windows with I/O Completion Ports but this code doesn't works :
```
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "Kernel32.lib")
int main() {
HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD number;
HANDLE iocp = CreateIoCompletionPort(handle, NULL, 0, 0);
if(iocp == NULL) {
printf("error : %d\n", GetLastError());
}
}
```
I get the error 87 : ERROR_INVALID_PARAMETER
|
CreateIOCompletionPort cannot be used directly with stdin/stdout.
Checkthis. Either use a thread, or redirect stdin/stdout to named pipes.
|
im currently working on portscanner for my network scanner app with socket in c .
i found this code , and i want to understand what's the exact role of strncpy here ! and can someone please expalin this code for my cuz im beginner in network programming and thanks ..
|
strncpy((char*)&sa, "", sizeof sa);Here author is trying to set0to every byte ofsastructure.As perstrncpyIf the end of the source C string (which is signaled by a
null-character) is found before num characters have been copied,
destination is padded with zeros until a total of num characters have
been written to it.If I were you I would do it this way.memset(&sa, 0 , sizeof sa);
strncpy((char*)&sa.sin_addr, (char*) host->h_addr, sizeof sa.sin_addr);Here Author is trying to copychar *h_addrwhich holds first host address tos_addr.If I were you I would do it this way.sa.sin_addr.s_addr = inet_addr(host->h_addr);
|
I added GTK library to my C++ project, and this error comes up.
How do I solve this?
Error happens in this line:
line 84: GLIB_DEPRECATED_IN_2_54_FOR(g_object_new_with_properties and g_initable_init)
of/usr/include/glib-2.0/gio/ginitable.h.
Formally,
```
/usr/include/glib-2.0/gio/ginitable.h:84:58: error: identifier "and" is a special operator name in C++ [-Werror=c++-compat]
GLIB_DEPRECATED_IN_2_54_FOR(g_object_new_with_properties and g_initable_init)
```
How do I fix this?
|
Either don't use-Werror, or use-Wno-error=c++-compatin addition to your current compilation flags.
In general, unconditional-Werrorisa badidea. It's better to selectively promote warnings to errors, like e.g.-Werror=return-type. Otherwise your project is bound to fail to compile with a different compiler or even a newer version of current compiler.
|
This question already has answers here:Passing by reference in C(19 answers)Closed4 years ago.
Inpage 15of my lecture slide, there is an example.
```
int x = 10;
increment_int(x); // can’t change the value of x
increment2_int(&x); // can change the value of x
```
I don't understand why the first functionincrement_int(x)can't change the value of x. Though I don't know what those functions exactly do, I guess they are incrementing some amount to the argument.
|
increment_int is pass by value. If the function increment_int changes
the value of its parameter, it is only reflected in its local copy.
The caller doesn't see the change.increment2_int is pass by reference. You pass the address of x rather
the value of x to this function. This function changes the value of
at the specified address which is reflected on the caller side too.
|
im currently working on portscanner for my network scanner app with socket in c .
i found this code , and i want to understand what's the exact role of strncpy here ! and can someone please expalin this code for my cuz im beginner in network programming and thanks ..
|
strncpy((char*)&sa, "", sizeof sa);Here author is trying to set0to every byte ofsastructure.As perstrncpyIf the end of the source C string (which is signaled by a
null-character) is found before num characters have been copied,
destination is padded with zeros until a total of num characters have
been written to it.If I were you I would do it this way.memset(&sa, 0 , sizeof sa);
strncpy((char*)&sa.sin_addr, (char*) host->h_addr, sizeof sa.sin_addr);Here Author is trying to copychar *h_addrwhich holds first host address tos_addr.If I were you I would do it this way.sa.sin_addr.s_addr = inet_addr(host->h_addr);
|
I added GTK library to my C++ project, and this error comes up.
How do I solve this?
Error happens in this line:
line 84: GLIB_DEPRECATED_IN_2_54_FOR(g_object_new_with_properties and g_initable_init)
of/usr/include/glib-2.0/gio/ginitable.h.
Formally,
```
/usr/include/glib-2.0/gio/ginitable.h:84:58: error: identifier "and" is a special operator name in C++ [-Werror=c++-compat]
GLIB_DEPRECATED_IN_2_54_FOR(g_object_new_with_properties and g_initable_init)
```
How do I fix this?
|
Either don't use-Werror, or use-Wno-error=c++-compatin addition to your current compilation flags.
In general, unconditional-Werrorisa badidea. It's better to selectively promote warnings to errors, like e.g.-Werror=return-type. Otherwise your project is bound to fail to compile with a different compiler or even a newer version of current compiler.
|
This question already has answers here:Passing by reference in C(19 answers)Closed4 years ago.
Inpage 15of my lecture slide, there is an example.
```
int x = 10;
increment_int(x); // can’t change the value of x
increment2_int(&x); // can change the value of x
```
I don't understand why the first functionincrement_int(x)can't change the value of x. Though I don't know what those functions exactly do, I guess they are incrementing some amount to the argument.
|
increment_int is pass by value. If the function increment_int changes
the value of its parameter, it is only reflected in its local copy.
The caller doesn't see the change.increment2_int is pass by reference. You pass the address of x rather
the value of x to this function. This function changes the value of
at the specified address which is reflected on the caller side too.
|
I am supposed to write a logic to generate a combination of n-lettered words.
For example, if the number 2 is provided, I am required to generate all two-lettered words from a-z i.e:
```
aa-ba-ca.....za
ab-bb-cb.....zb
.
.
.
.
az-bz........zz
```
I understood that nested loops will not suffice for this problem since the number of nested loops changes with the number of letters in the word. This turns me to recursion, but I can't think of the logic.
|
Recursion is the key here. Here is an example written in Java:
```
public static void printCombos(int totalWords, String s) {
if(totalWords-- <= 0) {
System.out.print(s + " ");
return;
}
for(char i = 'a'; i <= 'z'; i++)
printCombos(totalWords, s + Character.toString(i));
System.out.println();
}
```
Invoke it:
```
printCombos(2, "");
```
|
A string is terminated by a s single null byte. Since a int is bigger then an char how can the int become 0 and terminate the loop consistenly?
source :http://www.cse.yorku.ca/~oz/hash.html
```
unsigned long
hash(unsigned char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
```
|
Loading an integer from a smaller type does not preserve the bits that the smaller type didn't have; they are cleared (or set by sign-extension, for signed types).
So:
```
int x = 0xfeefd00d;
x = (char) 1;
```
leaves the value1, as an integer, inx,not0xfeedf001.
|
Is
```
struct datainfo info = { 0 };
```
the same as
```
struct datainfo info;
memset(&info, 0, sizeof(info));
```
What's the difference and which is better ?
|
The first one is the best way by a country mile, as it guarantees that thestructmembers are initialised as they would be forstaticstorage.It's also clearer.
There's no guarantee from a standards perspective that the two ways are equivalent, although a specific compiler may well optimise the first to the second, even if it ends up clobbering parts of memory discarded aspadding.
(Note that in C++, the behaviour of the second way could well beundefined. Yes C is not C++ but a fair bit of C code does tend to end up being ported to C++.)
|
I have a certificate received from client. In my server application I need to check if the received certificate is a CA or User certificate. I am currently using mbedTLS library for implementing security. There is anexamplealready to check this case in JAVA. Similarly, I would like to know how to check using mbedTLS library or OpenSSL command.
|
Have a look at theint mbedtls_x509_crt::ca_istruefield. Which is:
Optional Basic Constraint extension value: 1 if this certificate
belongs to a CA, 0 otherwise.
https://tls.mbed.org/api/structmbedtls__x509__crt.html#a196b3a43dae5a1c0058f46075f832890
EDIT: According to yourexampleyou need to check the ifMBEDTLS_X509_KU_KEY_CERT_SIGN(link) of thekey_usage(link) is set in thembedtls_x509_crtstructure.
|
I plan to call the functiontest_func.
One way is to define a variable and send its address like:
```
int dummy;
test_func(&dummy);
```
This works fine. But what if I decide to avoid a dummy variable definition? Such an implementation fails with a compiler error:
```
test_func(&int());
```
main.c~~~(onlinegdb)
```
#include <stdio.h>
int action(int *x)
{
int error_code=0;
*x=123;
return error_code;
}
int test_func(int *x)
{
if(action(x))
{
printf("success!\n");
return 0;
}
else
{
printf("failue!\n");
return 1;
}
}
int main()
{
test_func(&int());
return 0;
}
```
How can I call this function in such a way?
|
While it's clearest to just use the variable, you can get what you're looking for with acompound literal:
```
test_func(&(int){1});
```
|
I'm playing with an Arduino board and the samples provided. Trying to get a message I received to be displayed on the LCD. I'm struggling to figure out how to work with some of the pre-built code.
I get the error: invalid conversion from 'const unsigned char*' to 'const char*
I tried modify thepayloadparameter type but it breaks other references to MessageCallback.
Screen.print() definition in the documentation for the arduino board:
int print(unsigned int line, const char s, bool wrap)
Code:
```
static int MessageCallback(const unsigned char *payload)
{
int result = 200;
const char screenMsg[100];
strcpy(screenMsg,"Set Temp: ");
strcat(screenMsg,payload);
Screen.print(1, screenMsg, true);
return result;
}
```
|
Strcat's arguments are(char *, const char *). You can cast "payload" to achar*by doing "strcat(screenMsg, (char*)payload);". ReadStrcat two unsigned char in C.
|
I want to print the ip address of the client connected to the server socket. I've seen many answers, but all gone wrong with me. Also please provide the right place to put the piece of code you're answering with
Expected result = IP of client is . . . .
|
You can use the functioninet_ntoa()for this:
```
printf("IP of client: %s\n", inet_ntoa(cli.sin_addr));
```
Put this somewhere after you haveaccept()ed the client connection.
To use the functioninet_ntoa()you have to include the appropriate header filearpa/inet.h. Otherwise, the returned (64-bit) pointer is crippled to a (32-bit) integer, resulting in a segfault.
You shouldalwaysenable all warnings; this would have shown you, that the function is undeclared.
Finally, this should result in your desired output.
|
I have this portion of code and I don't understand how the first typedef works and what happen when we use it in the struct.
```
#define MAX_BLOCKEDADDRESS_SIZE 256
typedef char BlockedAddress[MAX_BLOCKEDADDRESS_SIZE];
typedef struct Blocked {
int capacity;
int length;
BlockedAddress *mailAddress;
} Blocked;
```
|
BlockedAddressis a user defined type that is a 256chararray.
```
#define MAX_BLOCKEDADDRESS_SIZE 256
typedef char BlockedAddress[MAX_BLOCKEDADDRESS_SIZE];
```
Blockedis a user defined type, astructcontaining 2intand one pointer members.
```
typedef struct Blocked {
int capacity;
int length;
BlockedAddress *mailAddress;
} Blocked;
```
The membermailAddressis a pointer toBlockedAddress.mailAddress as pointer to array 256 of char
|
I'm a bit confused about size of element pointer points to. Including some basic code to visualize.
```
uint8_t var1;
uint8_t var2;
uint8_t *p[2]={&var1,&var2};
```
Result of sizeof(*p) is 4 instead of 1, why is that?
```
uint8_t var1;
uint8_t *p=&var1;
```
In this code result is correct sizeof(*p) is 1.
What i'm missing?
|
Note that the arraypdecays to a pointer, and as the array is itself an array of pointers, that's a pointer too.
```
#include <stdio.h>
int main(void)
{
char var1;
char var2;
char *p[2] = { &var1, &var2 };
printf("%zu\n", sizeof(*p)); // size of each element
printf("%zu\n", sizeof(**p)); // size of dereferenced element
return 0;
}
```
Program output
```
4
1
```
|
I'm homeworking now. Then one problem about increase/decrease operator err when I upload my explanation..
I tried while code to my problem then increase operator solved, but the decrease operator not solved..
the problem =
input variable x, and output x~x+5.After, output x~x-5. Use Increase / decrease operator to solve problem.
```
int x;
x = 10;
scanf("%d", &x);
int y = x + 6;
while (x < y)
{
printf("%d ", x);
++x;
}
```
outputx~x+5and after outputx~x-5
|
Use loops:
```
int x;
scanf("%d", &x);
int i;
for (i = 0; i < 5; i++) {
x++;
}
printf("%d\n", x);
for (i = 0; i < 5; i++) {
x--;
}
printf("%d", x);
```
|
I'm a bit confused about size of element pointer points to. Including some basic code to visualize.
```
uint8_t var1;
uint8_t var2;
uint8_t *p[2]={&var1,&var2};
```
Result of sizeof(*p) is 4 instead of 1, why is that?
```
uint8_t var1;
uint8_t *p=&var1;
```
In this code result is correct sizeof(*p) is 1.
What i'm missing?
|
Note that the arraypdecays to a pointer, and as the array is itself an array of pointers, that's a pointer too.
```
#include <stdio.h>
int main(void)
{
char var1;
char var2;
char *p[2] = { &var1, &var2 };
printf("%zu\n", sizeof(*p)); // size of each element
printf("%zu\n", sizeof(**p)); // size of dereferenced element
return 0;
}
```
Program output
```
4
1
```
|
I'm homeworking now. Then one problem about increase/decrease operator err when I upload my explanation..
I tried while code to my problem then increase operator solved, but the decrease operator not solved..
the problem =
input variable x, and output x~x+5.After, output x~x-5. Use Increase / decrease operator to solve problem.
```
int x;
x = 10;
scanf("%d", &x);
int y = x + 6;
while (x < y)
{
printf("%d ", x);
++x;
}
```
outputx~x+5and after outputx~x-5
|
Use loops:
```
int x;
scanf("%d", &x);
int i;
for (i = 0; i < 5; i++) {
x++;
}
printf("%d\n", x);
for (i = 0; i < 5; i++) {
x--;
}
printf("%d", x);
```
|
I'm homeworking now. Then one problem about increase/decrease operator err when I upload my explanation..
I tried while code to my problem then increase operator solved, but the decrease operator not solved..
the problem =
input variable x, and output x~x+5.After, output x~x-5. Use Increase / decrease operator to solve problem.
```
int x;
x = 10;
scanf("%d", &x);
int y = x + 6;
while (x < y)
{
printf("%d ", x);
++x;
}
```
outputx~x+5and after outputx~x-5
|
Use loops:
```
int x;
scanf("%d", &x);
int i;
for (i = 0; i < 5; i++) {
x++;
}
printf("%d\n", x);
for (i = 0; i < 5; i++) {
x--;
}
printf("%d", x);
```
|
I'm doing my homework about vectors and emerged me a question about the * behind de vector name. What does it mean? and what this do?
If i remove this, my code show a problem ("Format specifies type 'float *' but the argument has type 'double' "). thanks for the help, and sorry by the bad english.
´´´
```
float *numbers[] = {}, sum;
for (int i = 0; i <= quant; i++){
printf("%dº number\n", i);
scanf("%f", numbers[i]);
for(int y = 0; y <= i; y++){
sum = sum + numbers[y];
}
}
```
|
*in C/C++ means a pointer. A pointer is the address of some data, in this case the address of a float.numbersis an array of pointers to floats.http://www.cplusplus.com/doc/tutorial/pointers/
|
I'm wondering if the fopen command is smart enough to stop reading a file if it's to large and then wait for some proceeding read command to continue reading.
For that matter, how large is _iobuf?
|
fopen(...)doesn't do any size checks; it just returns a file pointer. Are you thinking offread(...), by any chance?
You can always find the size of the file that you are going to read by usingstat(...)system call.
|
I have seen something like this in some of my coworkers code today :
```
I2C1ADB1= (slave_read_address | 0x01);
```
What does this | 0x01 part do? Does it end 1 at the end of the bits?
Let's say I2C1ADB1=0b00000000. If I use above line, will the new I2C1ADB1 be 0b000000001? Will it also increase the bit count from 8 to 9?
|
'|' is bit-wise OR operator in C. It does bit-wise OR between two values and return the final value.
```
I2C1ADB1= (slave_read_address | 0x01);
```
Assume slave_read_address in binary is0bxxxxxxxxwhere eachxis bit value1or0. Similarly,0x01in binary is0x00000001.
As you know OR will returntrue (1)if at least one of the value istrue (1). Otherwise returnsfalse (0).
So After the above C line, I2C1ADB1 will have0bxxxxxxx1.
The operator will not ADD bits. Usually '|' (OR) operator is used to set a particular set of bits without altering other bits.
|
I am confused why this piece of code returns a segmentation fault.
Basically, I try to create a new text file usingfopen()andfprintf().
```
void my_function() {
FILE *g;
char s1[30];
printf("\nNew file (text): ");
scanf("%s",&s1); //gets(s1);
g = fopen(s1,"w");
fprintf(g,"something");
fclose(g);
}
```
I tried checking the validity of fopen with:
```
if (g == NULL) {
perror("fopen()");
exit(1);
}
```
which returnsfopen(): Bad address,so probably that's the problem.
Any idea what caused that and how to solve it?
|
The problem is onscanf("%s", &s1).
Rather writescanf("%s", s1);becauses1is already a pointer.
What you have done is passing a pointer to a pointer.
|
I have seen something like this in some of my coworkers code today :
```
I2C1ADB1= (slave_read_address | 0x01);
```
What does this | 0x01 part do? Does it end 1 at the end of the bits?
Let's say I2C1ADB1=0b00000000. If I use above line, will the new I2C1ADB1 be 0b000000001? Will it also increase the bit count from 8 to 9?
|
'|' is bit-wise OR operator in C. It does bit-wise OR between two values and return the final value.
```
I2C1ADB1= (slave_read_address | 0x01);
```
Assume slave_read_address in binary is0bxxxxxxxxwhere eachxis bit value1or0. Similarly,0x01in binary is0x00000001.
As you know OR will returntrue (1)if at least one of the value istrue (1). Otherwise returnsfalse (0).
So After the above C line, I2C1ADB1 will have0bxxxxxxx1.
The operator will not ADD bits. Usually '|' (OR) operator is used to set a particular set of bits without altering other bits.
|
I am confused why this piece of code returns a segmentation fault.
Basically, I try to create a new text file usingfopen()andfprintf().
```
void my_function() {
FILE *g;
char s1[30];
printf("\nNew file (text): ");
scanf("%s",&s1); //gets(s1);
g = fopen(s1,"w");
fprintf(g,"something");
fclose(g);
}
```
I tried checking the validity of fopen with:
```
if (g == NULL) {
perror("fopen()");
exit(1);
}
```
which returnsfopen(): Bad address,so probably that's the problem.
Any idea what caused that and how to solve it?
|
The problem is onscanf("%s", &s1).
Rather writescanf("%s", s1);becauses1is already a pointer.
What you have done is passing a pointer to a pointer.
|
I am trying to understand the following macro from the followingURL:
```
do { \
word _v(l) = vec_len (V); \
V = _vec_resize ((V), 1, (_v(l) + 1) * sizeof ((V)[0]), (H), (A)); \
(V)[_v(l)] = (E); \
} while (0)
```
what is the significance of _v(l)? Is it just a variable or something more?
|
The_vmacro is defined in vec.h atline 207:
```
#define _v(var) _vec_##var
```
This prepends_vec_beforevar. You can observe this by asking your favorite compiler to print the output of the preprocessor stage (-Eflag for clang/gcc and/Efor msvc).
```
#define _v(var) _vec_##var
word _v(l) = vec_len (V);
```
Is expanded into:
```
word _vec_l = vec_len (V);
```
|
I´m trying to run a website locally from a batch file on windows.
I am coding a project and want later to start this over xampp on a USB stick, to run that everywhere I want it to. Already tried to use some shell withPHPandstartcommands. But it´s not running in the expected ways....
C:\xampp\php\php D:\projects\project_x\index.php
AND
start D:\projects\project_x\index.php
I expected my website.... but the first command it is just putting it in my command line out...
the second shows just my code in the browser. Obviously without PHP.... so how to get that running over the xampp webserver and calling it then in my browser??
|
Thanks to that dude above, i got the right answer :D And it´s a mix of his code and that what i have already tried.
Instead try to call it over the webserver, I have just to call the url over an browser.
Means:
start http://localhost/project_x/index.php
|
Working to re-write the strchr method defined in string.h.
And i am getting "return discards ‘const’ qualifier from pointer target type"
```
char* strchr(const char* str, int character){
int idx = 0;
do{
if (str[idx] == character){
return &str[idx]; // This line has the error
}
idx++;
} while (str[idx] != '\0');
return NULL;
} // any help would be great, thanks.
```
|
A few notes:
Since you can't change the prototype you must cast away the const in thereturn:return (char *) &str[idx];.Your implementation has a bug, consider happens ifstrchr("", 'a')is called. You incrementidxinside the body of the loop, before NUL-checking so it will step beyond the end of the string.
|
I am reading input from different text files. These text files are integers that are either separated by a space, a new line, or a combination of spaces and new lines. I want to convert these strings to integers, and use these integers for a sorting algorithm.
```
char *line = malloc(BUF_SIZE);
char *token;
struct list* l = list_init();
while (fgets(buf, BUF_SIZE, stdin)) {
token = strtok(buf," \n");
printf("%s", token);
}
list_cleanup(l);
return 0;
```
What is wrong with this, it that it just prints the first element of each line. It doesn't handle multiple elements per line.
Thanks in advance.
|
You need to haveloopto process all the tokens.strtokwill returnNULLonce all the tokens are over.
Example:
```
while (fgets(buf, BUF_SIZE, stdin)) {
token = strtok(buf," \n");
while (token != NULL) {
printf("%s", token);
token = strtok(NULL," \n");
}
}
```
|
I'm learning about SO_REUSEPORT socket option, and when I read "https://lwn.net/Articles/542629/", I have a confusion about this sentence:"This eases the task of conducting stateful conversations between the client and server." in the article.
As far as I understand, the SO_REUSEPORT option works on the same machine, and the stateful task between the server and the client is for multiple servers. Why does SO_REUSERPORT have a simplified effect?
What dose "task of conducting stateful conversations between the client and server" mean?Please give some specific examples,thanks.
|
I got it, for examples, reverse proxy server.
|
I am reading input from different text files. These text files are integers that are either separated by a space, a new line, or a combination of spaces and new lines. I want to convert these strings to integers, and use these integers for a sorting algorithm.
```
char *line = malloc(BUF_SIZE);
char *token;
struct list* l = list_init();
while (fgets(buf, BUF_SIZE, stdin)) {
token = strtok(buf," \n");
printf("%s", token);
}
list_cleanup(l);
return 0;
```
What is wrong with this, it that it just prints the first element of each line. It doesn't handle multiple elements per line.
Thanks in advance.
|
You need to haveloopto process all the tokens.strtokwill returnNULLonce all the tokens are over.
Example:
```
while (fgets(buf, BUF_SIZE, stdin)) {
token = strtok(buf," \n");
while (token != NULL) {
printf("%s", token);
token = strtok(NULL," \n");
}
}
```
|
I'm learning about SO_REUSEPORT socket option, and when I read "https://lwn.net/Articles/542629/", I have a confusion about this sentence:"This eases the task of conducting stateful conversations between the client and server." in the article.
As far as I understand, the SO_REUSEPORT option works on the same machine, and the stateful task between the server and the client is for multiple servers. Why does SO_REUSERPORT have a simplified effect?
What dose "task of conducting stateful conversations between the client and server" mean?Please give some specific examples,thanks.
|
I got it, for examples, reverse proxy server.
|
I'm trying to get the most significant bit of an unsigned 8-bit type in C.
This is what I'm trying to do right now:
```
uint8_t *var = ...;
...
(*var >> 6) & 1
```
Is this right? If it's not, what would be?
|
To get the most significant bit from a memory pointed to byuint8_tpointer, you need to shift by 7 bits.
```
(*var >> 7) & 1
```
|
I want to use timer8 of stm32f746NG_Discovery board, but I don't know how can config it.Does anyone have a simple code in keil,please?
|
Tim 8 configure update interrupt
```
__HAL_RCC_TIM8_CLK_ENABLE();
TIM8 -> PSC = 999;
TIM8 -> ARR = SystemCoreClock / ((TIM8 -> PSC + 1) * freq) - 1;
TIM8 -> EGR |= TIM_EGR_UG;
if(TIM8 -> SR & TIM_SR_UIF) TIM8 -> SR = ~(TIM_SR_UIF);
TIM8 -> DIER |= TIM_DIER_UIE;
TIM8 -> CR1 = TIM_CR1_CEN;
NVIC_EnableIRQ(TIM8_TRG_COM_TIM14_IRQn);
```
|
How to implement this example in kernel driver?
I looked in 'cdev'. but, the result is not convincing for this function using this example struct.
For example:
```
dev/test/on // this function is change status in test module
dev/test/changed "hello" // this function is change char value
```
I Looked "cdev" and some github. But, it is "/dev/test" one file.
|
I found "sysfs"! Using this lib i can implement this example.
https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.