question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
If I have the following lines of code, why is b-a = 2?
```
int a[] = {1,2,3,4,5};
int *b = &(a[2]);
```
|
To elaborate slightly on Eugene's answer,ais a pointer to the beginning of the array, anda[2]is the same as*(a+2).
So you could say that the&"cancels" the*as you dereference the pointer and then look at the address of the element that it points to. So*b = &(a[2]) = &(*(a+2)) = a+2.
Thereforeb-a=2
|
I'm trying to read the U-Boot environment that is stored on eMMC, but I can't figure out how I can list the disks. The driver I'm creating is separated of the mmc device driver (/dev/mmcblk0p1).
I already found out that the partitions ofmmcblk0arestruct mmc_partentries instruct mmc_card. Basically I'm searching for the mmc variant of__mtd_next_device.
EDIT 1:I found out that I can get ablock_devicestruct throughbdget, butgendiskpoints toNULL.
```
struct block_device *my_bdevice;
struct gendisk *my_gdisk;
my_bdevice = bdget(179);
my_gdisk = part_to_disk(my_bdevice->bd_part);
if (!my_gdisk) goto end; // Goes to end..
```
|
In my code above,my_bdevice = bdget(179);is wrong:
```
dev_t devt = blk_lookup_devt("mmcblk0", 0);
my_bdevice = bdget(devt);
```
|
For example, in the functionSYSCALL_DEFINE2of linux kernel (https://elixir.bootlin.com/linux/v4.15.3/source/arch/alpha/kernel/osf_sys.c#L657):
```
SYSCALL_DEFINE2(osf_proplist_syscall, enum pl_code, code,
union pl_args __user *, args)
{
long error;
...
get_user(error, &args->set.nbytes)
...
}
```
Why it isn't need to usecopy_from_useronargsbefore using arrow and dot on it?
|
&args->set.nbytesis anaddress. It's allowed to compute the address of some member even if you couldn't actually read it — the compiler just adds the offset of theset.nbytesmember ofunion pl_argsto the address passed inargs. Then it passes that address toget_user, which does the actual copying from userspace.
|
```
#include <stdio.h>
int reverse(int *prr, int i)
{
for (i = 6; i; i--)
{
printf("%d is reverse \n", *prr + i);
}
}
int main()
{
int arrr[] = {1, 2, 3, 4, 5, 6, 7};
int *ptr = arrr;
reverse(ptr, 6);
return 0;
}
```
The output I am getting is
```
7 is reverse
6 is reverse
5 is reverse
4 is reverse
3 is reverse
2 is reverse
```
but not 1!
|
The loop conditioniis equivalent toi != 0(and for your specific use-casei > 0).
That is, the loop will end when theireaches0, so that index will not be printed.
To be able to print the last element, you need to include it in the loop with a condition likei >= 0.
|
In Xlib there is a function calledXSetWindowBorder()which takes a color value (an unsigned long). In the documentation, it talks about "entries in the color map" and other stuff but I just tried it with a normally encoded RGB color and it seems to work. What are the potential pitfalls with this?
My encoding function is:
```
unsigned long _RGB(int r,int g, int b)
{
return b + (g<<8) + (r<<16);
}
```
|
Your display probably uses TrueColor (24-bit deep) visual. On that visual, the colormap essentially implements an identity mapping: a colormap entry equals its index. On PseudoColor or StaticColor visuals, that is not true anymore. Your program will not work or will work incorrectly on less than 24-bit visuals.
|
I'm not really experienced with pointers in C and I've been given the following code:
```
void backtrack(int *pback1, int *pback2)
{
if (condition)
*pback1++;
else if (another condition)
*pback2--;
else if (third condition)
*pback1++;
else if (last condition)
*pback2++;
}
int main()
{
int b1, b2;
b1=7, b2=9;
backtrack(&b1, &b2);
printf("%d %d", b1, b2);
return 0;
}
```
The code is printing the result without any changes (7 9).
What should be modified for it to run properly?
|
The postfix++and--operators have higherprecedencethan the*dereference operator, so*pback++increments the pointerpbackinstead of the thing it points to. You want(*pback)++.
|
I was wondering how i can use functions that im going to implement myself in FreeRTOS.Example: if i want to create any function likecalculateTotalof two values (just an example), how can i use it with the Task? should i prevent using functions outsideTasksand instead write plain code of all functions in theTask? can anybody help me out ?
```
void randomTask(void* param) {
//initialize something
for(;;){
//can i call functions here and define them outside?
}
}
```
|
Yes, you can define functions outside and call them from the tasks. These functions are executed in the context of the calling task, and they use the stack memory allocated for the task.
You can also call the same function from different tasks, as long as they are stateless. A function is stateless if it doesn't use global variables and static local variables. Of course, you can provide a state (context) as a function parameter.
|
In Xlib there is a function calledXSetWindowBorder()which takes a color value (an unsigned long). In the documentation, it talks about "entries in the color map" and other stuff but I just tried it with a normally encoded RGB color and it seems to work. What are the potential pitfalls with this?
My encoding function is:
```
unsigned long _RGB(int r,int g, int b)
{
return b + (g<<8) + (r<<16);
}
```
|
Your display probably uses TrueColor (24-bit deep) visual. On that visual, the colormap essentially implements an identity mapping: a colormap entry equals its index. On PseudoColor or StaticColor visuals, that is not true anymore. Your program will not work or will work incorrectly on less than 24-bit visuals.
|
I'm not really experienced with pointers in C and I've been given the following code:
```
void backtrack(int *pback1, int *pback2)
{
if (condition)
*pback1++;
else if (another condition)
*pback2--;
else if (third condition)
*pback1++;
else if (last condition)
*pback2++;
}
int main()
{
int b1, b2;
b1=7, b2=9;
backtrack(&b1, &b2);
printf("%d %d", b1, b2);
return 0;
}
```
The code is printing the result without any changes (7 9).
What should be modified for it to run properly?
|
The postfix++and--operators have higherprecedencethan the*dereference operator, so*pback++increments the pointerpbackinstead of the thing it points to. You want(*pback)++.
|
I was wondering how i can use functions that im going to implement myself in FreeRTOS.Example: if i want to create any function likecalculateTotalof two values (just an example), how can i use it with the Task? should i prevent using functions outsideTasksand instead write plain code of all functions in theTask? can anybody help me out ?
```
void randomTask(void* param) {
//initialize something
for(;;){
//can i call functions here and define them outside?
}
}
```
|
Yes, you can define functions outside and call them from the tasks. These functions are executed in the context of the calling task, and they use the stack memory allocated for the task.
You can also call the same function from different tasks, as long as they are stateless. A function is stateless if it doesn't use global variables and static local variables. Of course, you can provide a state (context) as a function parameter.
|
I am trying to return a string from str function but it prints (null)
```
#include<stdio.h>
char* str()
{
char hi[10] = "return this";
return hi;
}
void main()
{
printf("%s", str());
}
```
|
readstatic variablesorglobal variablesto access the variable outside the functions
there is an overflow in your code, readbuffer overflow in c
Also readWhat should main() return in C and C++?
```
#include<stdio.h>
char* str()
{
static char hi[] = "return this";
return hi;
}
int main()
{
printf("%s", str());
return 0;
}
```
|
I was wondering if anyone knows if it is possible to create a table in which each component contains a table of characters.
I know the code I'm going to put in is wrong, but I mean something like this
```
txt[1] = "ASD";
txt[2] = "FF";
txt[3] = "S43";
txt[4] = "ASF";
```
Thank you so much for all.
|
You need to have an array of arrays
```
array[size][size]
```
Next first positon
```
strcpy(array[0], "HELLO");
strcpy(array[1], "HY");
```
You can make a table, you just need to use the line and column that you want
```
array[line][column]
```
For example:
```
#include <stdio.h>
#include <string.h>
int main(){
char array[100][256];
strcpy(array[0], "HELLO");
strcpy(array[1], "HY");
printf("%s\n%s\n", array[0], array[1]);
return 0;
}
```
Imagine that you inser the words that you want on scanf, the array[0] will have the first entire word, and so.
|
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.Closed2 years ago.Improve this question
```
int i;
for(i=10;i<=20;i=i+2)
if(i%10 <= 5)
printf("hello\n");
```
Why is "hello" printed four times? I expected it to be three times. Is it because of precedence?
|
Pay attention to the loop exit condition, which is<=rather than the more common<. The printout is triggered forivalues of10,12,14, and also20.
|
I'm working on a program for Windows and Linux, coding it in C, and I want the program to get input from a user, show it until it finished (i.e. pressed 'enter'), then un-display what the user entered, finally re-displaying it with a time stamp.
It should look like this:
(Before user hits enter)
Enter a string: abcde
(Then after inputting the string "abcde")
|19:53| User: abcde
Currently what the program does is:
Enter a string: abcde
|19:53| User: abcde
Without the row of the input dissappearing.
|
Well, it's hard. You have to go up one line to clear it. On Linux, you can use ANSI escape codes like"\033[A"to go up one line. There is no C standard way to do it.
If you print something and you are on the same line, use"\b"to backspace one character. From then, you can use white space to clear the inputs.
|
This snippet of code I wrote is supposed to traverse through
a file and increment the size-counter each-time it goes+1character:
```
while (fgetc(input) != EOF)
size++;
if (feof(input)) {
buff = (char *)malloc(sizeof(char) * size + 1);
}
```
while the end of the file is not reached size is being incremented. IfEOF-> feof==trueand the the buffer-size
can be determined.
Just wanted to know if it is possible that way or if there are better ways to do it.
|
Using ftell() function size can be determined, as
```
fseek( input, 0, SEEK_END );
size = ftell( input);
```
Then set the pointer to the file beginning,
```
fseek( input, 0, SEEK_SET );
```
|
How can I write a C program which can read the numbers and strings in a .txt file? I am just able to read a portion of text file till now.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("data3.txt", "r")) == NULL)
{
printf("Error! opening file");
exit(1);
}
fscanf(fptr, "%[]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}
```
|
I have used another method to solve it.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * txt;
char ch;
txt = fopen("nameOfTheFile.txt", "r");
if(txt == NULL)
{
printf("Unable to open the file\n");
exit(EXIT_FAILURE);
}
do
{
ch = fgetc(txt);
putchar(ch);
} while(ch != EOF);
fclose(txt);
return 0;
}
```
|
```
typedef struct { int b, p; } A;
void f(A c);
int main()
{
int i;
A a = {1,2};
f(a);
printf("%d,%d\n",a.b,a.p);
return 0;
}
void f(A c)
{
int j;
c.b += 1;
c.p += 2;
}
```
In the following code, why is it that a.b and a.p are still 1 and 2 even after being passed through f(a), which should change them to 2 and 3?
|
What you are using is called call by value, in call by value the changes you are doing to function arguments will not be reflected in the caller, for that you need call by reference
```
typedef struct { int b, p; } A;
void f(A c);
void f2(A *c);
int main()
{
int i;
A a = {1,2};
// call by value
f(a);
printf("%d,%d\n",a.b,a.p);
//call by referecne
f2(&a);
printf("%d,%d\n",a.b,a.p);
return 0;
}
void f(A c)
{
int j;
c.b += 1;
c.p += 2;
}
void f2(A *c)
{
int j;
c->b += 1;
c->p += 2;
}
```
|
This snippet of code I wrote is supposed to traverse through
a file and increment the size-counter each-time it goes+1character:
```
while (fgetc(input) != EOF)
size++;
if (feof(input)) {
buff = (char *)malloc(sizeof(char) * size + 1);
}
```
while the end of the file is not reached size is being incremented. IfEOF-> feof==trueand the the buffer-size
can be determined.
Just wanted to know if it is possible that way or if there are better ways to do it.
|
Using ftell() function size can be determined, as
```
fseek( input, 0, SEEK_END );
size = ftell( input);
```
Then set the pointer to the file beginning,
```
fseek( input, 0, SEEK_SET );
```
|
How can I write a C program which can read the numbers and strings in a .txt file? I am just able to read a portion of text file till now.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("data3.txt", "r")) == NULL)
{
printf("Error! opening file");
exit(1);
}
fscanf(fptr, "%[]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}
```
|
I have used another method to solve it.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * txt;
char ch;
txt = fopen("nameOfTheFile.txt", "r");
if(txt == NULL)
{
printf("Unable to open the file\n");
exit(EXIT_FAILURE);
}
do
{
ch = fgetc(txt);
putchar(ch);
} while(ch != EOF);
fclose(txt);
return 0;
}
```
|
```
typedef struct { int b, p; } A;
void f(A c);
int main()
{
int i;
A a = {1,2};
f(a);
printf("%d,%d\n",a.b,a.p);
return 0;
}
void f(A c)
{
int j;
c.b += 1;
c.p += 2;
}
```
In the following code, why is it that a.b and a.p are still 1 and 2 even after being passed through f(a), which should change them to 2 and 3?
|
What you are using is called call by value, in call by value the changes you are doing to function arguments will not be reflected in the caller, for that you need call by reference
```
typedef struct { int b, p; } A;
void f(A c);
void f2(A *c);
int main()
{
int i;
A a = {1,2};
// call by value
f(a);
printf("%d,%d\n",a.b,a.p);
//call by referecne
f2(&a);
printf("%d,%d\n",a.b,a.p);
return 0;
}
void f(A c)
{
int j;
c.b += 1;
c.p += 2;
}
void f2(A *c)
{
int j;
c->b += 1;
c->p += 2;
}
```
|
I understand the basic concept of short-circuiting with operators, but why does
```
int i = 0, j = -1, k = 1, m;
m = !(i++ && ++j) || ++k;
printf("%d %d %d %d", i, j, k, m);
```
have 1 -1 1 1 as an output? Specifically, why is j == -1 instead of 0?
I know similar questions have been already asked, but I don't understand this specific example which I didn't find anywhere.
|
```
i = -1;
i++; // value of expression is -1
// side effect is changing i to 0
if (i++) ; // value of `i++` is zero; the if will not "trigger"
i = 0;
if (i++ && foo) ; // i++ has value of zero (false)
// so false && <anything> is false
// so foo is not evaluated
```
|
This program reads and writes on a binary file. The professor is asking to switch the value of the source port and destination port. But I know we can not change if it is const, I also get this error. Does anyone know what he means by that or have any idea how I can switch? Thanks a lot.
```
error: assignment of read-only location ‘*array’
/*array = the array the data is stored.*/
void header(const unsigned char array [], unsigned char filename [])
{
}
```
|
You can do this through pointers:
```
void header(const unsigned char array [], unsigned char filename [])
{
char *array2 = (char *)array;
// You can freely modify array2 elements here, resulting in the original array's modification
}
```
|
This question already has answers here:Is there an equivalent of Python's `pass` in c++ std11?(7 answers)Closed2 years ago.
Is there a C or C++ equivalent to 'pass' in python? Also the same with break. For example:
```
while True:
if x == 1:
break
else:
pass
```
But in C/C++ instead?
|
Is there a C or C++ equivalent to 'pass' in python?
Yes. There are actually two equivalents. One is the null statement:
```
;
```
Another is the empty block statement:
```
{}
```
These are in most cases inter-changeable except the null statement cannot be used in all cases where the empty block statement can. For example, the function body must be a block statement.
In the example case, you can omit the else-statement entirely just like you can in Python.
|
I compiled the following code on Code::Blocks - gcc :
```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void test_print(uint8_t test_var);
int main()
{
uint32_t var = 100000U;
test_print(var);
return 0;
}
void test_print(uint8_t test_var)
{
printf("test_var = %d\n", test_var);
}
```
Why does it not raise any warning ?
It seems weird to me since I am implicitly casting an U32 to a U8. (which should be avoided since information will be lost in the process)
|
You would need to use the-Wconversionflag to gcc, which will pick up on this:
```
[dbush@db-centos7 ~]$ gcc -Wconversion -g -Wall -Wextra -o x1 x1.c
x1.c: In function ‘main’:
x1.c:11:5: warning: conversion to ‘uint8_t’ from ‘uint32_t’ may alter its value [-Wconversion]
test_print(var);
```
This is one of those flags that isn't included in-Wallor-Wextra.
|
In a project that includes dozens of modules, we haveO1as the default debug optimization level.
Sometimes, I need a lesser optimization (i.e., no optimization at all). So I use the clang attributeoptnoneto exclude a single function from optimization.
But when the number of functions to exclude is large, this becomes cumbersome.
Is there a way to exclude a whole module from optimization? For example set a pragma at the top of the module.
|
Clang has a compiler-specificpragmayes, try:
```
#pragma clang optimize off
//region of code
#pragma clang optimize on
```
|
I don't know how to include my own header files in my source file.
I declare addition in my header file(myhead.h):
```
int addition(int a, int b);
```
In the source file I define it(myhead.c):
```
int addition(int a, int b){
return a+b;
}
```
In the third source file I include the header file and use addition(processSimulator.c):
```
#include "myhead.h"
#include <stdio.h>
int main(){
printf("Compiled %d\n", addition(3,5));
}
```
It gives me this error
|
You need to add myhead.c file to gcc argumentsgcc processSimulator.c my head.c
|
I have a method called printNums, where I would like to print integers from 1 - 10. For my assignment, I'm supposed to malloc an int pointer, set it, pass in to my function as a void* point and inside the function, cast it, deference it and print that integer out before each iteration of the counter.
However, I keep getting a segmentation fault after*((int*)ptr)and I'm not too sure why. Any help would be appreciated.
Here is my code:
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void* printNums(void *ptr);
int main(int argc, char **argv)
{
int *ptr = (int*)malloc(sizeof(int));
ptr = 0;
printNums(ptr);
return 0;
}
void* printNums(void *ptr){
int i = 0;
for (i = 0; i <= 10; i++){
*((int*)ptr) = i;
printf("%d\n", *((int*)ptr));
}
}
```
|
You're assigning ptr pointer to zero.
changeptr = 0;to*ptr = 0;.
|
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.Closed2 years ago.Improve this question
my question is fairly simple, namely: Can we write a program consisting only of library calls and no system calls? My question comes from the context of C library calls and system calls.
|
yes, whats the problem with this one.printfinternally callswritebut that is not known to us.
```
int main()
{
printf("hello world");
return 0;
}
```
|
I don't know how to include my own header files in my source file.
I declare addition in my header file(myhead.h):
```
int addition(int a, int b);
```
In the source file I define it(myhead.c):
```
int addition(int a, int b){
return a+b;
}
```
In the third source file I include the header file and use addition(processSimulator.c):
```
#include "myhead.h"
#include <stdio.h>
int main(){
printf("Compiled %d\n", addition(3,5));
}
```
It gives me this error
|
You need to add myhead.c file to gcc argumentsgcc processSimulator.c my head.c
|
I have a method called printNums, where I would like to print integers from 1 - 10. For my assignment, I'm supposed to malloc an int pointer, set it, pass in to my function as a void* point and inside the function, cast it, deference it and print that integer out before each iteration of the counter.
However, I keep getting a segmentation fault after*((int*)ptr)and I'm not too sure why. Any help would be appreciated.
Here is my code:
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void* printNums(void *ptr);
int main(int argc, char **argv)
{
int *ptr = (int*)malloc(sizeof(int));
ptr = 0;
printNums(ptr);
return 0;
}
void* printNums(void *ptr){
int i = 0;
for (i = 0; i <= 10; i++){
*((int*)ptr) = i;
printf("%d\n", *((int*)ptr));
}
}
```
|
You're assigning ptr pointer to zero.
changeptr = 0;to*ptr = 0;.
|
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.Closed2 years ago.Improve this question
my question is fairly simple, namely: Can we write a program consisting only of library calls and no system calls? My question comes from the context of C library calls and system calls.
|
yes, whats the problem with this one.printfinternally callswritebut that is not known to us.
```
int main()
{
printf("hello world");
return 0;
}
```
|
```
#include <stdio.h>
#define DIM 10
typedef struct{
int nelem; //amount of numbers in the array
int vector[DIM];
}t_vector_int;
int main(){
t_vector_int vect={5,{3, 23, 56, 109, 238}};
int n, i=0;
printf(" Vector inicial: 3, 23, 56, 109, 238\n\nIntroduzca un valor entero: ");
scanf("%d", &n);
while(vect[i] <= n){
}
return 0;
}
```
I get the error in line 15while(vect[i] <= n){, I know it's because vect is defined as{5,{3, 23, 56, 109, 238}}but don't really know how to chech if n belongs to vect.
|
You need to use the membervector, not the structure variable itself.
Change
```
while(vect[i] <= n)
```
to
```
while(vect.vector[i] <= n)
```
|
I passed an int pointer as an argument to execv(...), which is now in string form in the other program. How do I parse that string back to a pointer array. For example, argv[2] is "0x7ffeec636875". How do I parse it to a int pointer so I can use it?
```
int main(int argc, char **argv) {
int *matrix1Start = argv[2];
printf("pointer: %p", argv[2]);
}
```
Thank you!
|
You can't.
In a system with memory virtualization (e.g. any modern general purpose computer), each process has its own address space. What one process has at address0x7ffeec636875is completely unrelated to what another process has at that same address.
Since pointers refer to a location in a process's address space, it's useless to pass them to a different process (except in very exceptional circumstances you would have mentioned if applicable).
This is not a suitable way to achieve inter-process communication (IPC).
|
I am really confused about what is going on here. I tried changing the variable and inputting other things, but every single time it would always say,use of undeclared identifier 'height'. does anyone know what to do?
here's the code
```
#include <stdio.h>
#include <cs50.h>
int main(void)
{
printf("hello!\a");
do
{
int height = get_int("pick a number, any number!: ");
}
while ( height > 1 || height < 8);
```
p.s. I'm kinda new to this and it's a work in progress.
|
heightis only defined within the loop, due to C's block scoping. This means that it is undeclared in the while condition, causing the compile error. To fix it, move the declaration before the loop:
```
int height;
do
{
height = get_int("pick a number, any number!: ");
}
while ( height > 1 || height < 8);
```
|
I'm trying to retrieve some text from a char array, like this:
```
unsigned char some_variable[3][10] = {"text1","text2","text3"};
int i;
for(i=0;i<3;i++){
functionIcantChange(some_variable[i])
}
```
I'm getting this issue since this functionICantChange takes aguments like "hello" and "world" with"characters included. And by calling for example some_variable[0] I just gettext1for example.
I need to add the"character to the array before passing the array to the function. How could I do this?
|
I recommend you use sprintf to insert quotations in the front and back of your array. You would need some large buffer to hold the value of the variable.
```
char buffer[255];
sprintf(buffer, "\"%s\"", some_variable[i]);
functionIcantChange(buffer);
```
|
I'm learning C programming language and as you know there is a commandprintfand it uses the "" symbol. I'm using Visual Studio Code for writing C. And I want add a snippet for printf. But when I tried adding these letters in JSON file of snippets and using these snippets,
```
"printf": {
"prefix":"printf",
"body": ["printf("$1"$2);"]
}
```
it turns into this:
```
printf(
);
```
How can I fix it?
|
Use the backslash character\to escape the"quotes inside your snippet content string.
```
"printf": {
"prefix":"printf",
"body": ["printf(\"$1\"$2);"]
}
```
|
I'm looking for a solution to count rows and columns in a file.
I have while loop with that loads the file into a buffer.
```
while(fgets(buffer, row_length,stdin) !=NULL)
```
Note: I can't print file into 2D array and i can't use fopen or alloc memory.
|
If you have the row length, is that not already the column size? You said you can't use a 2D array, in fact you said nothing about whether you want to store this data so the buffer remains the same.
```
while(fgets(buffer, row_length + 2, myfile) != NULL) {
rows++;
}
columns = row_length;
printf("COLUMNS: %d, ROWS: %d\n", columns, rows);
```
|
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.Closed2 years ago.Improve this question
Write a program on C for creating and displaying an integer matrix a [4] [4]. The matrix is formed using the index. The matrix is displayed row by row.Can someone help me?
This is what it should look likeenter image description here
|
```
#include <stdio.h>
int main()
{
int n = 4;
int a[n][n];
//creating
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j)
a[i][j] = 1;
else
a[i][j] = 0;
}
}
//printing
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}
```
|
How can I call a C-function from SQL in Tarantool?
Documentationsays:
C functions are imported from .so files
But where shall I specify the reference to my .so file?
It would be great to see an example.
|
You should firstly register your function via:func.create:
```
box.schema.func.create("function1.divide", {language = 'C', returns = 'number',
is_deterministic = true,
exports = {'LUA', 'SQL'}})
```
You can read more info on the subj here:https://www.tarantool.io/en/doc/latest/tutorials/c_tutorial/
Then you can use it in SQL:
```
box.execute('SELECT "function1.divide"()')
```
Also you can examine more examples in source code (test/box/function1.test.lua).
|
I have these time duration values such as 1:23, 2:45(2 minutes 45 seconds). And i want to read these values from a file into the duration field of a song struct as 1.23 and 2.45. Is there an easy way to do it or i have to just change semicolon to dot and convert it to a double? (It will be in C)
|
1 minute and 23 seconds is not the same as 1.23 minutes.
One way to do this:
```
int min, sec;
double dur = -1.0; // initialize to an invalid duration
if ( scanf( "%d:%d", &min, &sec ) == 2 )
{
dur = min + sec/60.0;
}
else
{
fprintf( stderr, "Invalid duration, try again\n" );
while ( getchar() != '\n' ) // clear out the input stream
; // empty loop
}
```
|
Informations:OS: Windows 10Compiler: MinGW gccLanguage: CSDL & OpenGL are already installed
When i try to compile the test file , i receive this error:
```
gcc test.c -o test
teste.c:1:10: fatal error: SDL2: No such file or directory
1 | #include <SDL2>
| ^~~~~~
compilation terminated.
```
The test file content is:
```
#include <SDL2>
#include <stdio.h>
void main()
{
printf("Testing");
}
```
This is my problem, help me pls.
|
In order to use the SDL header you need to use#include <SDL2/SDL.h>instead of#include <SDL2>.
|
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.Closed2 years ago.Improve this question
Write a program on C for creating and displaying an integer matrix a [4] [4]. The matrix is formed using the index. The matrix is displayed row by row.Can someone help me?
This is what it should look likeenter image description here
|
```
#include <stdio.h>
int main()
{
int n = 4;
int a[n][n];
//creating
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j)
a[i][j] = 1;
else
a[i][j] = 0;
}
}
//printing
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}
```
|
How can I call a C-function from SQL in Tarantool?
Documentationsays:
C functions are imported from .so files
But where shall I specify the reference to my .so file?
It would be great to see an example.
|
You should firstly register your function via:func.create:
```
box.schema.func.create("function1.divide", {language = 'C', returns = 'number',
is_deterministic = true,
exports = {'LUA', 'SQL'}})
```
You can read more info on the subj here:https://www.tarantool.io/en/doc/latest/tutorials/c_tutorial/
Then you can use it in SQL:
```
box.execute('SELECT "function1.divide"()')
```
Also you can examine more examples in source code (test/box/function1.test.lua).
|
I have these time duration values such as 1:23, 2:45(2 minutes 45 seconds). And i want to read these values from a file into the duration field of a song struct as 1.23 and 2.45. Is there an easy way to do it or i have to just change semicolon to dot and convert it to a double? (It will be in C)
|
1 minute and 23 seconds is not the same as 1.23 minutes.
One way to do this:
```
int min, sec;
double dur = -1.0; // initialize to an invalid duration
if ( scanf( "%d:%d", &min, &sec ) == 2 )
{
dur = min + sec/60.0;
}
else
{
fprintf( stderr, "Invalid duration, try again\n" );
while ( getchar() != '\n' ) // clear out the input stream
; // empty loop
}
```
|
Informations:OS: Windows 10Compiler: MinGW gccLanguage: CSDL & OpenGL are already installed
When i try to compile the test file , i receive this error:
```
gcc test.c -o test
teste.c:1:10: fatal error: SDL2: No such file or directory
1 | #include <SDL2>
| ^~~~~~
compilation terminated.
```
The test file content is:
```
#include <SDL2>
#include <stdio.h>
void main()
{
printf("Testing");
}
```
This is my problem, help me pls.
|
In order to use the SDL header you need to use#include <SDL2/SDL.h>instead of#include <SDL2>.
|
I'm building a small C project from source (https://github.com/danos/vyatta-route-broker) which has multiple .c and .h files. I run its Makefile and this error occurred:
"fatal error: ini.h: No such file or directory"
It is due to this line in one of its files:
"#include <ini.h>"
There is also "LIBS += -linih -pthread" in the Makfile. I commented out ini.h library in both places, but it is a necessary one and building is impossible without having it.
What is "ini.h"? It is a C standard library?
How can I find it and install it on my system?
|
I think inih in your case refers to the library inih (INI Not Invented Here), it is a simple .ini file parser. They have a github pagehttps://github.com/benhoyt/inih. Also, if you are using linux, you can search on the package management tool of your distribution. For example, for debian you can get it from this linkhttps://packages.debian.org/bullseye/libinih-dev.
|
I was reading about pointers in K&R book here
https://hikage.freeshell.org/books/theCprogrammingLanguage.pdf
and then, explaining what strcpy do exactly its written :
```
/* strcpy: copy t to s; pointer version */
void strcpy(char *s, char *t) {
while ((*s = *t) != ’\0’) {
s++;
t++;
}
}
```
But I couldn't understand the linewhile ((*s = *t) != ’\0’)in which there are 2 of ().
What I learned is using it as :while( condition )!
|
```
while ((*s = *t) != ’\0’)
```
Actually, there is an assignment, followed by a comparison:
*s = *t; // copy the character *t in the string sCompare the value of this character with\0, if equals the loop is finished
In order to reduce the number of lines of code, they put all in 1 line.
|
```
int main(int argc, char const *argv[])
{
fork();
fork();
fork();
exit(0);
}
```
Can this about code create aZombieprocess? if yes how and how many? It would be great if you could elaborate. Also can see process becoming a zombie usingps aux | grep a.out
|
No, that won't create any zombie processes. When a process becomes orphaned (because its parent calledexit, for example),initadopts it, andinitquickly reaps any of its children that die.
|
I'm building a small C project from source (https://github.com/danos/vyatta-route-broker) which has multiple .c and .h files. I run its Makefile and this error occurred:
"fatal error: ini.h: No such file or directory"
It is due to this line in one of its files:
"#include <ini.h>"
There is also "LIBS += -linih -pthread" in the Makfile. I commented out ini.h library in both places, but it is a necessary one and building is impossible without having it.
What is "ini.h"? It is a C standard library?
How can I find it and install it on my system?
|
I think inih in your case refers to the library inih (INI Not Invented Here), it is a simple .ini file parser. They have a github pagehttps://github.com/benhoyt/inih. Also, if you are using linux, you can search on the package management tool of your distribution. For example, for debian you can get it from this linkhttps://packages.debian.org/bullseye/libinih-dev.
|
I was reading about pointers in K&R book here
https://hikage.freeshell.org/books/theCprogrammingLanguage.pdf
and then, explaining what strcpy do exactly its written :
```
/* strcpy: copy t to s; pointer version */
void strcpy(char *s, char *t) {
while ((*s = *t) != ’\0’) {
s++;
t++;
}
}
```
But I couldn't understand the linewhile ((*s = *t) != ’\0’)in which there are 2 of ().
What I learned is using it as :while( condition )!
|
```
while ((*s = *t) != ’\0’)
```
Actually, there is an assignment, followed by a comparison:
*s = *t; // copy the character *t in the string sCompare the value of this character with\0, if equals the loop is finished
In order to reduce the number of lines of code, they put all in 1 line.
|
```
int main(int argc, char const *argv[])
{
fork();
fork();
fork();
exit(0);
}
```
Can this about code create aZombieprocess? if yes how and how many? It would be great if you could elaborate. Also can see process becoming a zombie usingps aux | grep a.out
|
No, that won't create any zombie processes. When a process becomes orphaned (because its parent calledexit, for example),initadopts it, andinitquickly reaps any of its children that die.
|
I want to to show aGtk.Popoverat the position of the cursor of aGtk.Entry. I'm only only able to add the popover relative to the entry itself, but theGtk.Popoverappears at the center of theGtk.Entryeverytime.
Is there a way how I can get the position of myGtk.Entrycursor and create the popover at this position?
|
You should set the widget to which your popover is relative to, by usingGtk.Popover.relative_to; then you can useGtk.Popover.pointing_toand the rectangle with the location of the cursor. To get that, useGtk.Entry.cursor_positionto retrieve the index of the cursor in characters and transform it into a location within the Pango.Layout of theGtk.Entrywidget; if the entry is allowed to scroll, you should also get theGtk.Entry.scroll_offsetand subtract it from the coordinates returned by Pango.
|
I was wondering what happens when mutex unlocks, and two different threads waiting for that same mutex receive acknowledgement of that? Is there some queue like order to assign mutex to a thread that requested it first or is the choice random?
|
Quoting from thePOSIX specification:
If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.
So the choice can be random, it can be a queue, it can be whatever the scheduler wishes to do.
|
I'm new to C Programming and I am stuck on a simple problem. Here is the following code...
```
#include <stdio.h>
/* Write a C Program that accepts two integers from the
user and calculate the sum of the two intergers. Go to the editor!
*/
int main()
{
int firstInteger, secondInteger;
int sum;
printf("Input two Integers: \n");
scanf("%d%d", &firstInteger, &secondInteger);
sum = firstInteger + secondInteger;
printf("%d", sum);
return 0;
}
```
After I run my code on the GCC compiler I don't get what I expect!
```
C:\XXXX\XXXX\XXXX\XXXX\XXXX>gcc 2sumOfTwoIntegers.c
C:\XXXX\XXXX\XXXX\XXXX\XXXX>a
Input two Integers:
25, 38
25
```
Why don't I get the sum of my inputted Integers?
|
You are putting comma in input. Just put a single space
Like that
25 38
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question
AFAIK, Some part of C compilation phases can be multi-threaded.
For example, At least Preprocessing and Parsing (creating AST) is only related its source file itself so each file can be parallelized.
Is there any reason that GCC has no multi-threaded compile option?
|
You can build C/C++ in paralell if you use and setup a proper build system, which handles this for you.
Basically in C/C++ every .c/.cpp file is complied to an .o file. All these .o files are then linked to the resulting binary.
A build system (make for instance) can be used, to build all the .o files in paralell.
|
Say I have data:0 (or near 0), 0, 0, ..., 1, 10, 52, 80, 100, 100, 100, 100 (for a while), 90, 45, 5, 0, 0, 0...I want to find the index (not necessarily an int, I want more precision) of the 'center' of my plateau of data.
My first thought was to do a gaussian fit, but the data is rather flat for a while in the center. So maybe some kind of square (?) fit. I've been looking at minimization with gsl also, but I don't know what the simplest way to do this would be.
A simple way would be to find the index corresponding to the median value, but that gives me only a precision of 1. With a curve fitting I can do better.
Note: I'm in C and can use GSL, but a general math solution would work too!
|
Suggested algorithm:
Optionally filter data: median of 3, low pass, etc.Find average value:AvgFind average index of values aboveAvg:Center_index.Average a few of the "values above" nearCenter_index.
|
I have some C/C++ code where I have a 16-bit number (uint16_t), and I need to swap the first 5 bits with the last 5 bits, keeping their left-to-right order within each block of 5 bits. The middle 6 bits need to remain intact. I am not great at bitwise maths/operations so help would be appreciated!
Conceptually speaking, the switching of positions would look like:
ABCDEFGHIJKLMNOPbecomesLMNOPFGHIJKABCDE
or more literally...
10101000000001010becomes0101000000010101.
Any help would be much appreciated!
|
First, you should check if whatever library you use doesn't have a RGB-BGR swap for R5G6B5 pixels already.
Here is a literal translation of what you wrote in your question. It is probably too slow for real-time video:
```
uint16_t rgbswap(uint16_t in) {
uint16_t r = (in >> 11) & 0b011111;
uint16_t g = (in >> 5) & 0b111111;
uint16_t b = (in >> 0) & 0b011111;
return b << 11 | g << 5 | r << 0;
}
```
|
I have exploitableccode which takes user input. I am able to print out contents of the stack using%10$pwhich prints out the 10th value stored on the stack. However when I try to run the same program but with%10$nit segfaults. Which does not make sense. Segfaults means I am trying to access memory that does not belong to me. However, this memory does 'belong to me' since I can print it out. Why does this happen?
Unfortunately, I cannot postcode for it because it is for an assignment. So I have to keep this question abstract.
|
%10$nmeans write the number of characters printed to the addresspointedto by the 10th element on the stack, not the actual 10th element of the stack. This means that if the 10th element doesn't point to valid, writable memory, which it likely doesn't, then you will segfault upon trying to write to it.
|
I want to to show aGtk.Popoverat the position of the cursor of aGtk.Entry. I'm only only able to add the popover relative to the entry itself, but theGtk.Popoverappears at the center of theGtk.Entryeverytime.
Is there a way how I can get the position of myGtk.Entrycursor and create the popover at this position?
|
You should set the widget to which your popover is relative to, by usingGtk.Popover.relative_to; then you can useGtk.Popover.pointing_toand the rectangle with the location of the cursor. To get that, useGtk.Entry.cursor_positionto retrieve the index of the cursor in characters and transform it into a location within the Pango.Layout of theGtk.Entrywidget; if the entry is allowed to scroll, you should also get theGtk.Entry.scroll_offsetand subtract it from the coordinates returned by Pango.
|
I was wondering what happens when mutex unlocks, and two different threads waiting for that same mutex receive acknowledgement of that? Is there some queue like order to assign mutex to a thread that requested it first or is the choice random?
|
Quoting from thePOSIX specification:
If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.
So the choice can be random, it can be a queue, it can be whatever the scheduler wishes to do.
|
This question already has answers here:semicolon and comma in for loops(1 answer)Why does the for loop use a semicolon?(6 answers)Closed2 years ago.
```
#include <sdio.h>
int main(void)
for (int k = 1, k <19, k++); {
printf("%d*%d=%d \n", k, k, k * k);
return 0;
}
```
I have just started learn C and faced with that problem. If you can, recommend me good guide for beginner in addition. :)
|
The issue is in this line:
```
for (int k = 1, k <19, k++);
```
In a for statement, you should separate elements with a semicolon (;)
```
for (int k = 1; k <19; k++)
```
There's also no (;) at the end of it.
Also, you should include<stdio.h>instead of<sdio.h>.
|
Does rename() make a copy of the file into another file and then delete the original one? Or is there some other way it works?
I couldn't find anything on the internet which explains this.
|
The exact mechanisms depend entirely on the OS and file system in use, but in general a file's name is stored in a directory. So typically changing the name of a file involves modifying the name in the directory listing (or if moving the file, removing the directory entry and adding it elsewhere in the tree).
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed2 years ago.Improve this question
```
#include <stdio.h>
int main (void)
{
int a;
a = 4;
printf("a = %d \n");
return 0;
}
```
and that is what i get when debug:
a = 1220497792 or other big numbers.
|
You are not passing anything to you'reprintfcall so it is printing garbage.
To fix you need to passaas a second argument toprintf.
```
#include <stdio.h>
int main (void)
{
int a;
a = 4;
printf("a = %d \n", a);
return 0;
}
```
|
Reference:Suffix in Integer Constants
```
unsigned long long y = 1 << 33;
```
Results in warning:
```
left shift count >= width of type [-Wshift-count-overflow]
```
Two Questions need to be cleared from the above context:
unsigned long long type has 64-bit, why cant we do left shift in it?how shifting works in int constants('1')?
|
In C language, 1 is anintwhich is 32 bits on most platforms. When you try to shift it 33 bitsbeforestoring its value in anunsigned long long, that's not going to end well. You can fix this in 2 ways:
Use1ULLinstead, which is anunsigned long longconstant:
```
unsigned long long y = 1ULL << 33;
```
Assign the value, then shift it:
```
unsigned long long y = 1;
y <<= 33;
```
Both are valid, but I'd suggest the first one since it's shorter and you can makeyconst.
|
I have encountered problem with linking static lib - when there no windows.h and calls to WinAPI, it links and works fine, but when they used, I get this error when building:
```
error: linking with `link.exe` failed: exit code: 1120
note: external-test.lib(library_win32.cpp.obj) : error LNK2019: unresolved external symbol __imp_MessageBoxW referenced in function init_window
```
In list of all used libs, there no user32.lib. Maybe it is the problem? How can I tell linker to use it
```
note: "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX64\\x64\\link.exe" ... "kernel32.lib" "advapi32.lib" "ws2_32.lib" "userenv.lib" "msvcrt.lib"
```
Here build script:
```
fn main() {
println!("cargo:rustc-link-search={}/src/external",env::var("CARGO_MANIFEST_DIR").unwrap());
}
```
|
Solution was simple - link user32 in build script
|
This question already has answers here:semicolon and comma in for loops(1 answer)Why does the for loop use a semicolon?(6 answers)Closed2 years ago.
```
#include <sdio.h>
int main(void)
for (int k = 1, k <19, k++); {
printf("%d*%d=%d \n", k, k, k * k);
return 0;
}
```
I have just started learn C and faced with that problem. If you can, recommend me good guide for beginner in addition. :)
|
The issue is in this line:
```
for (int k = 1, k <19, k++);
```
In a for statement, you should separate elements with a semicolon (;)
```
for (int k = 1; k <19; k++)
```
There's also no (;) at the end of it.
Also, you should include<stdio.h>instead of<sdio.h>.
|
Does rename() make a copy of the file into another file and then delete the original one? Or is there some other way it works?
I couldn't find anything on the internet which explains this.
|
The exact mechanisms depend entirely on the OS and file system in use, but in general a file's name is stored in a directory. So typically changing the name of a file involves modifying the name in the directory listing (or if moving the file, removing the directory entry and adding it elsewhere in the tree).
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed2 years ago.Improve this question
```
#include <stdio.h>
int main (void)
{
int a;
a = 4;
printf("a = %d \n");
return 0;
}
```
and that is what i get when debug:
a = 1220497792 or other big numbers.
|
You are not passing anything to you'reprintfcall so it is printing garbage.
To fix you need to passaas a second argument toprintf.
```
#include <stdio.h>
int main (void)
{
int a;
a = 4;
printf("a = %d \n", a);
return 0;
}
```
|
I would like to ask if there is a way how to read (stdin) input where is letter(space)number and save the letter to char and number to int. So, basically, I need to say to the "scanf" of "get" that they should stop reading after first spacer is entered. I am looking for easier way than getting string and than reading it character by character.
Thank you so much
Ref. input:
H 1234
Ref. work:
char a='H'
int b=1234
|
You could usescanflike:
```
char input[] = "H 1234";
char c;
int i;
sscanf(input, "%c %d", &c, &i);
// Prints out the character and the number
printf("Charcter: %c, integer: %d", c, i);
return 0;
```
|
Take for example time: if we have the starting hour and ending hour, what's the best way to find the number of hours between them?
If we take a 12-hour clock, we'd get the following results
from 1 to 5 = 4from 11 to 1 = 2
What is the most efficient way to do that?
|
Assuming a 12 hour clock, the number of hours fromatobcan be calculated as:
```
difference = ((b + 12) - a) % 12;
```
This also assumes thataandbare both in the range[1, 12]. In case they are not, you can do:
```
a %= 12;
b %= 12;
```
before doing the difference calculation.
|
is possible to use %d to concat a value but in a linear condition?
```
printf("You paid € %.2f, %s",
price,
(price > 100 ?
("Discount %d", discount)
:
"No Discount"));
```
Thanks in advance :)
|
You can put the thing to print in another buffer and print that conditionally.
```
char discount_str[128];
snprintf(discount_str, sizeof(discount_str), "Discount %d", discount);
printf("You paid € %.2f, %s",
price,
(price > 100 ?
discount_str
:
"No Discount"));
```
|
how can I assign an integer value like 111 to an other integer value but considering 111 as a binary?
For example I want to do that:
```
int x = 0b111; // x has the value 7
```
but I have the "111" saved as an integer;
what I tried to do is something like that:
```
int value = 111;
int x = 0bvalue;
```
obviously that doesn't work. So how should I do it?
|
One way is converting the value to string and converting back to integer specifying radix.
```
int value = 111;
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%d", value);
int x = strtol(buffer, NULL, 2);
```
Another way is converting integer without converting to string.
```
int value = 111;
int x = 0;
for (int delta = 1, value2 = value; value2 > 0; value2 /= 10, delta *= 2) {
x += (value2 % 10) * delta;
}
```
|
This question already has answers here:What's an object file in C?(5 answers)Closed2 years ago.
I got these console output while compilation via GCC.
```
Building CXX object xxxxxxx.cpp.obj
```
What are the.cpp.objfiles? Are they theobjectfile? Do the same as the.ofile?
|
What is .c.obj / .cpp.obj file?
Object files created from compiling.cand.cppfiles respectively.
What are the .cpp.obj files?
See above.
Are they the object file?
Yes.
Do the same as the .o file?
Yes.
Note that "extension" is just part of a filename and is customizable. You can name your file anything you want you want, it will not affect the content. In cmake seeCMAKE_C_OUTPUT_EXTENSION.
|
```
#include<stdio.h>
int main()
{
int a =0, b=1, c=2;
*( ( a+1==1) ? &b : &a) = a ? b : c;
printf("%d, %d, %d \n", a , b, c );
return 0;
}
```
Can anyone explain me the solution and output?
|
You can split this code into something longer but probably more readable like this:
```
#include<stdio.h>
int main()
{
int a=0, b=1, c=2;
int *ptr;
if (a + 1 == 1) { // this will be true
ptr = &b;
}
else {
ptr = &a;
}
if (a != 0) { // this will be false
*ptr = b;
}
else {
*ptr = c;
}
printf(“%d, %d, %d \n” a , b, c );
return 0;
}
```
Based on the initial values,a + 1 == 1will be true, soptr = &b;.
Sincea=0;thena != 0will be false and thus*ptr = c;
==> same asb = c;
So the expected output is
0, 2, 2
|
I can use GCC to convert assembly code files into reallocatable files.
```
gcc -c source.S -o object.o -O2
```
Is the optimization option effective? Can I expect GCC to optimize my assembly code?
|
No.
GCC passes your assembly source through the preprocessor and then to the assembler. At no time are any optimisations performed.
|
My input is: 1 + 2
I found that the value stored inargv[2][1]andoparen't the same, I just want to see if they are both the "+" operand.opstores the ascii value of "+" whileargv[2][1]stores some random value. How would I compare them?
*I don't want to use "strcmp"
|
Array indexes start at0, so you need to use[0]to compare the first character of the argument.
```
if (argv[2][0] != c) {
```
|
I am adding threads as user wants. It means I stdin and if he wants new thread I create it. User give specific name to thread so I can not create it sooner than he wants.
Part of my code:
```
while(read != EOF) {
if(user_wants_new_thread) {
worker_t *data = malloc(sizeof(worker_t));
data->name = malloc((strlen(arg1) + 1) * sizeof(char));
strcpy(data->name, arg1);
pthread_create(&thread, NULL, worker, (void *) data);
pthread_join(thread, NULL);
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
```
Thread should start to work without waiting. Now it waits for finishing of worker function.
Thank you for help :)
|
Yes, when I usepthread_join(thread, NULL);it will wait till end of created thread. So it's necessary to delete this line.
|
you can generate bytecode in form of c with luaJIT :luajit -b main.lua main.cit generate a c code with no main so my guess is to link it. How to do that with mingw64?
|
You seem to misunderstand what exactly that does.
LuaJIT doesnotcompile your Lua source code into equivalent C code. It compiles it to Lua bye code, and encodes this binary data as a static C array, so you can include the byte code directly in a program that uses LuaJIT and have it as a single executable.
|
For example, I know the address of the function (lets say its0x0183ad0), and I would like to get an object from that function which returns an unknown type:
```
unknownType(*fname)() = (unknownType(*)())0x0183ad0
```
Is there any global type I can replaceunknownTypewith or any method to get that object as a byte array (I know thesizeof(unknownType))
NOTE:
The function return an object NOT A POINTER
EDIT:
It worked thanks to Botje's answer:
|
"byte array" would beuint8_t*orunsigned char*.
If you know the size ofunknownTypeI would create a
```
struct unknownType {
uint8_t stuff[123];
};
```
so you can adapt the struct definition as you gain better understanding of its fields.
|
I am trying to make a loop of:
```
hi
:)
```
for number of times that the user inputshorizontally.
So for example, my goal is:
```
num =3
hi hi hi
:) :) :)
```
For now, my codes are
```
for (int i = 0; i<n; i++)
{
printf("\n hi \n:) \n" );
}
return 0;
```
Since I wanted a line difference betweenhiand:), I used\n.
However, due to this my output is shown vertically, not horizontally:
```
num=3
hi
:)
hi
:)
hi
:)
```
How can I make my output horizontally when I have line spacing in the output?
|
Try this. As already mentioned in the comments, two loops would suffice.
```
for(int i=0; i<n; i++)
{
printf("hi ");
}
printf("\n")
for(int i=0; i<n; i++)
{
printf(":) ");
}
```
|
I have to make the code of a coffee dispenser in C.
I already have everything done and I just need to know how I can keep on running my "main" function until a certain condition is met (for example: util the machine can give no more change).
How can I achieve this?
|
I don't think you need a recursive main or for that matter any recursive function call at all for this. All you need is an infinite loop.
```
int main()
{
while (1) /* Infinite Loop */
{
... do stuff
if (condition is met)
break;
}
}
```
|
```
unsigned int file = open(argv[1], O_RDONLY);
printf("%u\n", file);
printf("%u\n", elf.offset);
lseek(file, elf.offset, SEEK_SET);
printf("%u", file);
```
OutPut:
```
3
52
3
```
Shouldn'tfilebe set to52?
|
Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned.
try thisprintf("lseek_offset: %d\n", lseek(file, elf.offset, SEEK_SET));
|
```
struct node
{
int data1;
int data2;
struct node* link; //line 5
};
```
How much memory will be allocated for line 5 ,and will it be 1 memory block or 2 memory block since what it is pointing to is having two seperate integers.
Please help i am confused with self referencing pointers memory allocation.
```
```
|
The size of an object pointer is always same in standard C++ regardless of what the pointed object contains. The size can vary between systems, but as a rule of thumb, a pointer is 64 bits on 64 bit programs, 32 bits on 32 bit programs and ... you hopefully get the pattern.
An analogy for this is addresses of buildings. The size of the building has no effect on the size of the address of the building.
|
I am trying to write a basic script in C that I can use to download files off of a webserver. It would use wget, but I want to find a way where I can specify the directory and file that I want to download using a arguments. I'm just very new to C and I don't know how that would work. If anyone can show me how to write that or just point me in the write direction that would be amazing, thank you!
|
The simple solution to this is, as I already commented, to usesnprintfto format the command-string, and then pass it tosystemfor execution.
Something like
```
void download(const char *path, const char *file)
{
char command[1024];
// Create the command
snprintf(command, sizeof command, "wget https://1.1.1.1/%s/%s", path, file);
// Execute the command
system(command);
}
```
|
I discovered we can use one (or multiple) quote in the conversion specification of a format string. For instance:
```
void f(int i)
{
printf("%'d\n", i);
}
```
This code compiles well and behaves exactly as without the quote.
I would like to know what is the meaning of this quote. Does it can have an effect on the behavior of theprintffunction? If not, why is this allowed?
I found no information about it incppreference.
|
Cppreference documents the C standard. The apostrophe is an extension to the C standard documented by POSIX. FromPOSIX fprintf:
The flag characters and their meanings are:'(The <apostrophe>.) The integer portion of the result of a decimal conversion ( %i, %d, %u, %f, %F, %g, or %G ) shall be formatted with thousands' grouping characters. For other conversions the behavior is undefined. The non-monetary grouping character is used.
|
you can generate bytecode in form of c with luaJIT :luajit -b main.lua main.cit generate a c code with no main so my guess is to link it. How to do that with mingw64?
|
You seem to misunderstand what exactly that does.
LuaJIT doesnotcompile your Lua source code into equivalent C code. It compiles it to Lua bye code, and encodes this binary data as a static C array, so you can include the byte code directly in a program that uses LuaJIT and have it as a single executable.
|
For example, I know the address of the function (lets say its0x0183ad0), and I would like to get an object from that function which returns an unknown type:
```
unknownType(*fname)() = (unknownType(*)())0x0183ad0
```
Is there any global type I can replaceunknownTypewith or any method to get that object as a byte array (I know thesizeof(unknownType))
NOTE:
The function return an object NOT A POINTER
EDIT:
It worked thanks to Botje's answer:
|
"byte array" would beuint8_t*orunsigned char*.
If you know the size ofunknownTypeI would create a
```
struct unknownType {
uint8_t stuff[123];
};
```
so you can adapt the struct definition as you gain better understanding of its fields.
|
I am trying to make a loop of:
```
hi
:)
```
for number of times that the user inputshorizontally.
So for example, my goal is:
```
num =3
hi hi hi
:) :) :)
```
For now, my codes are
```
for (int i = 0; i<n; i++)
{
printf("\n hi \n:) \n" );
}
return 0;
```
Since I wanted a line difference betweenhiand:), I used\n.
However, due to this my output is shown vertically, not horizontally:
```
num=3
hi
:)
hi
:)
hi
:)
```
How can I make my output horizontally when I have line spacing in the output?
|
Try this. As already mentioned in the comments, two loops would suffice.
```
for(int i=0; i<n; i++)
{
printf("hi ");
}
printf("\n")
for(int i=0; i<n; i++)
{
printf(":) ");
}
```
|
I have to make the code of a coffee dispenser in C.
I already have everything done and I just need to know how I can keep on running my "main" function until a certain condition is met (for example: util the machine can give no more change).
How can I achieve this?
|
I don't think you need a recursive main or for that matter any recursive function call at all for this. All you need is an infinite loop.
```
int main()
{
while (1) /* Infinite Loop */
{
... do stuff
if (condition is met)
break;
}
}
```
|
```
unsigned int file = open(argv[1], O_RDONLY);
printf("%u\n", file);
printf("%u\n", elf.offset);
lseek(file, elf.offset, SEEK_SET);
printf("%u", file);
```
OutPut:
```
3
52
3
```
Shouldn'tfilebe set to52?
|
Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned.
try thisprintf("lseek_offset: %d\n", lseek(file, elf.offset, SEEK_SET));
|
```
#include <stdio.h>
#include <ncurses.h>
int main() {
initscr();
int height, width;
getmaxyx(stdscr, height, width);
endwin();
printf("width : %i\n", width);
printf("height : %i\n", height);
return 0;
}
```
result iswidth : 148height : 38
How the width and height were changed without passing a pointer
|
If you readhttps://linux.die.net/man/3/getmaxyxyou'll see:
Notes All of these interfaces are macros. A "&" is not necessary
before the variables y and x.
|
How can I make it stop when I'm end of the file?
txt file is look like this;
2 4
5 6
7 8
but it prints
2 x , 4 y
5 x , 6 y
7 x , 8 y
1429697293 x , 4199392 y
```
int x[20];
int y[20];
FILE *fp;
fp = fopen("coord.txt", "r");
for(int i = 0; i<4; i++){
if((x[i]=='\0')||(y[i]=='\0')) break;
fscanf(fp, "%d %d", &x[i],&y[i]);
}
for(int i=0; i<4;i++)
{
if((x[i]=='\0')||(y[i]=='\0')) break;
printf("%d x , %d y \n",x[i],y[i]);
}
```
|
Alright I just wrote
```
while (fscanf(fp, "%d %d", &x[i],&y[i]) != EOF)
printf("%d x , %d y \n",x[i],y[i]);
```
instead of everything and it works.
|
This question already has answers here:How to find the size of an array (from a pointer pointing to the first element array)?(17 answers)Closed2 years ago.
For ex.
I have a function
```
void len(int *A){ // or we have its reference
// can I find the length of array here or
// we just need to pass the length along as the parameter
}
```
|
can I find the length of array here or we just need to pass the length along as the parameter
You can't find the length once the array has decayed into a pointer so one option is to supply the length as a parameter as you said yourself.
Another option is to not let it decay into a pointer:
```
template<size_t N>
void len(int(&A)[N]) {
// N is the length
}
```
Or you could use astd::vector<int>:
```
void len(std::vector<int>& A) {
// A.size() returns the length
}
```
|
I want to calculate the i-th sentence of theFibonaccisequence:
```
#include <stdio.h>
int fibo(int i);
int main()
{
return 0;
}
int fibo(int i)
{
switch (i)
{
case 1:
return 0;
break;
case 2:
return 1;
break;
default:
int a = 0, b = 1;
for (int p = 3; p <= i; p++)
{
b += a;
a = b - a;
}
return b;
break;
}
}
```
But it has an error for 18 line forint a = 0, b = 1;as this:
```
10.c: In function 'fibo':
10.c:18:9: error: a label can only be part of a statement and a declaration is not a statement
18 | int a = 0, b = 1;
| ^~~
```
I use VS Code for IDE.
|
in C, in aswitchstatement, in acase, to have a local variable, the body of thecasemust be enclosed in braces '{' and '}'
|
I'm having a disagreement with my professor about the following function prototype:
Prompt: "function that takes pointer to a float, a pointer to a pointer to a char and returns a pointer to a pointer to a integer."
I say it is
int ** function(float * myFloat, char ** myChar)
but the options given are:
```
A. int **fun(float **, char**)
B. int *fun(float*, char*)
C. int ***fun(float*, char**)
D. int ***fun(*float, **char)
```
none of which I think are correct. To be clear, I'm not asking for a solution - I'm posting my function prototype to show that I THINK I know the solution and have worked through it.
Is it possible that any of the options given are correct? I'd love to be proven wrong and told that one of the solutions is possible (again, don't tell me which is correct if any are possible)
|
You're right, and none of the 4 suggested answers matches what is stated in the prose.
|
This question already has answers here:What is the meaning of a dot (.) after an integer in c?(2 answers)Closed2 years ago.
I read a code online and the next line caught my attention since I don't know why does it have a "." after the 0:
```
variable=0.;
```
I couldn't find the answer after looking for it. Could you please tell me what is the dot for?
Thanks!!
|
The dot makes it adouble. A clearer way to write it is0.0.
|
I am writing some software that corrupts files. It stores the file in a buffer, corrupts that buffer by xoring it with random masks, then writes the modified buffer to stdout so that the (linux) user can pipe it to somewhere.
I have opened stdout in binary mode:
```
FILE *const out = fdopen(dup(fileno(stdout)), "wb");
```
But how do I actually write the whole buffer tooutin one go?
It seems I have 2 options:
Iterate all bytes and dofputcHope that there are no nullbytes in the data and dofputs
I'm looking for afputbwhich takes:
A pointer to the data to be writtenA file descriptor to write it toThe amount of bytes to write
(with better performance than afputc-loop)
|
You're looking forfwrite ( const void * ptr, size_t size, size_t count, FILE * stream ):
Writes an array ofcountelements, each one with a size ofsizebytes, from the block of memory pointed byptrto the current position in thestream.
|
How do I write in a loop instead of a ternary operator ?
```
temp->status = (inStore ? waiting : called);
```
would it be like:
```
if (inStore){
return waiting;
}
else (
return called;
}
```
I'm unsure becauseI get an error doing this, I'm using it in a void function
|
The problem is here:else (. Change the(to{and your compile should be clean.
Theternary operatoris simply anif-then-elsestatement in a shortcut syntax, with the assignment statement presented as its singlelvalue. So:
```
temp->status = (inStore ? waiting : called);
```
is translated to:
```
if(inStore == true)
{
temp->status = waiting;
}
else
{
temp->status = called;
}
```
Note that there is nothing wrong with your syntax (except maybe the"("here:else (). In a function, it might be preferable to usereturnstatements if the function required no clean up before leaving.
|
This question already has answers here:How can I declare and define multiple variables in one line using C++?(10 answers)Closed2 years ago.
I'm new to C, this is My code. Maybe this is too easy for someone else.
```
#include <stdio.h>
int main()
//Assign value to identifiers
{
int a,b,c,d=6;
printf("a:%d\n",a);
printf("b:%d\n",b);
printf("c:%d\n",c);
printf("d:%d",d);
return 0;
}
```
Why is a=16, b=0, and c=12522400?
```
a:16
b:0
c:12522400
d:6
```
|
Because those variables are not initialized. You always have to initialize a local, automatic variable to avoid undefined behaviour.
For more details look here:https://en.wikipedia.org/wiki/Uninitialized_variable
|
I am using Qt 5 to send data via serial port. The problem comes from a conversion bewteen float and unsigned char [4] with union structure.
```
typedef union {
float df;
unsigned char uc4[4];
}fuc4;
fuc4 t1, t2;
t1 = (a+b)/c, t2 = -(a-b)/c;
```
Both is 0 as we can have a look at t1.df and t2.df with qDebug().
However, the last byte of them is quite different where t2.dc[3] is 0x80=128d.
On the other side, I have to use the bytes without any conversion. For example, I need t2.dc[2]*256+t2.dc[3] to get an integer number but it is clearly a mistake if I do so. How can I correct this or do it in a safe way.
|
I've always done this one:
```
float f = something;
unsigned char *uc4 = (unsigned char*)&f;
```
You don't need to go through an union for char or unsigned char, though you do for any other types.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.