question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
```
#include <stdio.h>
int main()
{
char*str="ββ¬π12345";
printf("%d",*str );
return 0;
}
```
please help me to find the output of the given code
|
Assuming the file is encoded using UTF-8, the string consists of these bytes in hex:
```
E2 86 94 E2 AC 86 F0 9F 99 82 31 32 33 34 35
```
On a system wherecharmeansunsigned char, the first char is 226.
On a two's-complement system wherecharmeanssigned char, the first char is -30.
On a one's-complement system wherecharmeanssigned char, the first char is -29.
This value will be promoted to an equivalentint, passed toprintf, and printed.
|
I want to have a macro which does something like:
#define TEST(_ptr) ({ if ((_ptr) == NULL) ERROR; (_ptr); })
which check_ptrand callsERRORmacro or return its value.
However, if I use something likevar = TEST(fun())this results infun()being called two times.
I can do something like:
#define TEST(_tmp, _ptr) ({ _tmp = _ptr; if ((_tmp) == NULL) ERROR; (_tmp); })
is there any clean way of doing this without passing temporary storage, e.g. usingtypeofoperator!?
|
Rather than using a macro definition, why not use a regular function as in:
```
void *funcCaller (void *f) {
if (f == NULL) {
ERROR; // not sure what the ERROR thing is supposed to do or look like.
}
return f;
}
```
Then call it as in:
```
p = funcCaller (func());
```
Since the argument list forfuncCaller()is using avoid *then the return type offunc()could be any pointer type.
|
I have an array declared in my main function:float A[n][n];
My goal is to pass it to a function with therestrictkeyword:void func(int n, float restrict A[][n])
I tried the syntax above, but I am not getting the optimization in running time that I am expecting. I have also seen this syntax for 1d arrays:void func(int n, float A[restrict])
|
The pointer can be restrict. All below forms are equivalent:
```
void func(int n, float A[restrict n][n]);
void func(int n, float A[restrict][n]);
void func(int n, float (* restrict A)[n]);
```
|
Let's say I have this string:
```
char *myTestString = "Hello AND test AND test2";
```
I want to break this down into the set {Hello,test,test2}, which I can finally iterate over.
Or I have
```
char *myTestString2 = "Hi AND there AND test AND test2";
```
I want to break this down into the set {Hi,there,test,test2}, which I can later iterate over.
How do I achieve this using C?
EDIT:
Another example is splitting"Hello there AND test"should give out set {Hello there,test}.
For clarification"AND"is delimiter here.
|
When code does not want to alter the source string, usestrcspn(s, delimet)to look for initial portion of asnotmake up ofdelimit. It returns the offset.
Usestrspn(s, delimet)to look for initial portion of asmade up ofdelimit. It returns the offset.
|
I am trying to write a C code with regex.h library that can find out a Chrome version from user agent. I am trying below
```
regex_t re;
regmatch_t pm;
if(regcomp(&re, "Chrom[^ \\/]+\\/(\\d+)[\\.\\d]* ", 0) != 0) {
cout << "C - Invalid Regex\n";
return;
} else {
cout << "C - valid Regex\n";
}
if ( regexec(&re, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.3987.66 Safari/537.36", 1, &pm, 0) == 0 ) {
cout << "Match Found !!" << "start location: " << pm.rm_so << "end location: " << pm.rm_eo << "\n";
} else {
cout << "Match Not Found\n";
}
regfree(&re);
```
but this does not work and it prints "Match Not Found". What am i missing ?
|
Try this:
```
regcomp(&re, "Chrome\\/[0-9]+[.[0-9]+]*", REG_EXTENDED)
```
You can get more info about regex.h here:https://pubs.opengroup.org/onlinepubs/7908799/xsh/regex.h.html
|
I am trying to create a message with a repeated field which has some default values.
I'm starting slow, with a simple int repeated (my final goal is a repeated message which all fields are have some value default)
so, to start my proto is:
```
syntax = "proto2"
import "google/protobuf/descriptor.proto";
import "nanopb.proto";
message MyDefault {
repeated int32 default = 1 [(nanopb).max_count = 3];
}
extend google.protobuf.FieldOptions {
optional MyDefault my_default = 1234;
}
message M {
repeated int32 x = 1 [(my_default) = {default: [1, 2, 3]}, (nanopb).max_count = 3];
}
```
protobuf is compiled, but no trace to my default values.
|
There are no default values for repeated fields in nanopb currently. As far as I know, they don't exist in other protobuf implementations either.
Some other protobuf libraries do provide access to custom field options, but nanopb currently does not.
|
I have an array declared in my main function:float A[n][n];
My goal is to pass it to a function with therestrictkeyword:void func(int n, float restrict A[][n])
I tried the syntax above, but I am not getting the optimization in running time that I am expecting. I have also seen this syntax for 1d arrays:void func(int n, float A[restrict])
|
The pointer can be restrict. All below forms are equivalent:
```
void func(int n, float A[restrict n][n]);
void func(int n, float A[restrict][n]);
void func(int n, float (* restrict A)[n]);
```
|
I have this struct in c
```
struct node{
int info;
struct node* link;
};
```
this procedure:
```
void example(struct node** head){
struct node* tmp;
tmp=*head;
tmp->info=0;
*head=tmp;
}
```
and call the procedure in the main with
```
example(&head);
```
so to modify head->info I need a support variable,there is another way without a support variable?
|
Use this:
```
void example(struct node** head){
(*head)->info=100;
}
```
It'll do the same as yourexamplefunction.
By dereferencingstruct node**we getstruct node*, then we can simply access it's member by using->arrow operator.
|
Here is the code I wrote:
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 50
int main(int argc, char *argv[])
{
char str[SIZE];
char str2[] = "exit";
//fgets(str, sizeof str, stdin);
while (strcmp(str, str2) != 0)
{
fgets(str, sizeof str, stdin);
printf("%s", str);
}
return 0;
}
```
But it doesn't seem to exit and is stuck in an infinite loop.
|
One solution would be to use:
```
char str2[]="exit\n";
```
But ado - whilecycle would be best:
```
int main () {
char str[SIZE];
char str2[]="exit\n";
do {
fgets(str, sizeof(str), stdin);
printf("%s",str);
} while(strcmp(str,str2));
return 0;
}
```
Since in the first iteration of you cyclestris empty.
|
My objective in this exercise is to create a function namesMultiTwo()that will multiply two inserted integers by the user and then print the quotient.MultiTwohas to be called insidemain().
Here's my try:
```
#include <stdio.h>
int MultiTwo(int x, int y, int result);
int main() {
int x, y, result;
printf("Insert an integer: \n");
x = scanf("%d", &x);
printf("Insert a second integer: \n");
y = scanf("%d", &y);
result = x * y;
printf("The quotient of the two inserted integers is: %d", result);
return 0;
}
```
I insert two integers and the result I always get, despite the integers inserted, is 1.
|
```
x = scanf("%d", &x);
```
This first reads the value from input and assigns it to the variable x. Then you clobber that value by setting x to the return value of scanf(), which is the number of variables successfully read, in this case it is 1.
|
Insertion sort is not working, it is only printing some of the values. Does anyone know what I can do to fix it?
```
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
int j = i;
while (j >= 0 && Array[j] < Array[j - 1]) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
j--;
}
}
}
```
|
The test in the inner loop is incorrect: whenj == 0you read and possibly modify the element at offset-1, which hasundefined behavior, possibly causing the incorrect output, but since you did not post the output code, there might be other problems there.
Here is a modified version:
```
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && Array[j] < Array[j - 1]; j--) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
}
}
}
```
|
New programmer here!
I am implementing selection sort, with a max variable instead of the usual min, but I still want to sort from lowest to highest.
The code below sorts the list perfectly except for the first value which it makes a very large negative number...
Any tips for what I can fix to get it sorting properly?
```
void selection(int Array[], int size) {
int i, j, max, temp;
for (i = 0; i < size-1; i++) {
max = i;
for (j = i+1; j <= size; j++) {
if ( Array[j] < Array[max] )
max = j;
}
temp = Array[max];
Array[max] = Array[i];
Array[i] = temp;
}
}
```
|
```
for(j = i+1; j<=size; j++)
```
This line is your problem. You are accessing one past the end of the array, which will be undefined behavior and can often give you weird values. Change the condition toj < size.
|
Taking in input a number and then put every digit into an array, I have, converted it into a string so that I can put it into an array, but then when I use the cast to remake it a int i get the ascii number..
```
#include <stdio.h>
#include <stdlib.h>
int main(){
char num_str[64] = {0};
int num, cifra;
printf("Write a number: \n");
scanf("%d", &num);
int len = snprintf(num_str, 64, "%d", num);
printf("The length is %d\n", len);
for(int i = 0; i < len; i++) {
cifra = (int)(num_str[i]);
printf("%d \n", cifra);
}
return 0;
}
```
|
convert it fromchartoint
Test the character for digit and subtract'0'.
```
for(int i = 0; i < len; i++) {
int cifra = num_str[i];
if (cifra >= '0' && cifra <= '9') printf("%d\n", cifra - '0');
else printf("%c\n", cifra); // such as '-'
}
```
|
The answer isO(n^6)but I am not quite sure how to get there, trying with small numbers shows that g ups the number n to the power of 3 sok=n^3and thusk^2=n^6(I think), but how do I show it mathematically, specifically, we were taught a method to use a new functionT(n)but I'm not sure how to apply it here, appreciate any help thanks.
```
int g(int n)
{
if (n <= 1) return 1;
return 8 * g(n / 2);
}
void f3(int n)
{
int k = g(n);
for (int i = 2; i < k * k; ++i)
{ printf("*"); }
}
```
|
Let's first analyze the functiong(n):
```
g(n) = 8 * g(n/2)
```
if you eliminate the recursion, this breaks down to
```
g(n) = 8^log_2(n)
```
and eliminating the logarithm yields:
```
g(n) = n^3
```
Nowk*kisn^3*n^3 = n^6, so the loop printsn^6asterisks. This results in the time complexity ofO(n^6).
|
Here is the code I wrote:
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 50
int main(int argc, char *argv[])
{
char str[SIZE];
char str2[] = "exit";
//fgets(str, sizeof str, stdin);
while (strcmp(str, str2) != 0)
{
fgets(str, sizeof str, stdin);
printf("%s", str);
}
return 0;
}
```
But it doesn't seem to exit and is stuck in an infinite loop.
|
One solution would be to use:
```
char str2[]="exit\n";
```
But ado - whilecycle would be best:
```
int main () {
char str[SIZE];
char str2[]="exit\n";
do {
fgets(str, sizeof(str), stdin);
printf("%s",str);
} while(strcmp(str,str2));
return 0;
}
```
Since in the first iteration of you cyclestris empty.
|
My objective in this exercise is to create a function namesMultiTwo()that will multiply two inserted integers by the user and then print the quotient.MultiTwohas to be called insidemain().
Here's my try:
```
#include <stdio.h>
int MultiTwo(int x, int y, int result);
int main() {
int x, y, result;
printf("Insert an integer: \n");
x = scanf("%d", &x);
printf("Insert a second integer: \n");
y = scanf("%d", &y);
result = x * y;
printf("The quotient of the two inserted integers is: %d", result);
return 0;
}
```
I insert two integers and the result I always get, despite the integers inserted, is 1.
|
```
x = scanf("%d", &x);
```
This first reads the value from input and assigns it to the variable x. Then you clobber that value by setting x to the return value of scanf(), which is the number of variables successfully read, in this case it is 1.
|
Insertion sort is not working, it is only printing some of the values. Does anyone know what I can do to fix it?
```
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
int j = i;
while (j >= 0 && Array[j] < Array[j - 1]) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
j--;
}
}
}
```
|
The test in the inner loop is incorrect: whenj == 0you read and possibly modify the element at offset-1, which hasundefined behavior, possibly causing the incorrect output, but since you did not post the output code, there might be other problems there.
Here is a modified version:
```
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && Array[j] < Array[j - 1]; j--) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
}
}
}
```
|
New programmer here!
I am implementing selection sort, with a max variable instead of the usual min, but I still want to sort from lowest to highest.
The code below sorts the list perfectly except for the first value which it makes a very large negative number...
Any tips for what I can fix to get it sorting properly?
```
void selection(int Array[], int size) {
int i, j, max, temp;
for (i = 0; i < size-1; i++) {
max = i;
for (j = i+1; j <= size; j++) {
if ( Array[j] < Array[max] )
max = j;
}
temp = Array[max];
Array[max] = Array[i];
Array[i] = temp;
}
}
```
|
```
for(j = i+1; j<=size; j++)
```
This line is your problem. You are accessing one past the end of the array, which will be undefined behavior and can often give you weird values. Change the condition toj < size.
|
Taking in input a number and then put every digit into an array, I have, converted it into a string so that I can put it into an array, but then when I use the cast to remake it a int i get the ascii number..
```
#include <stdio.h>
#include <stdlib.h>
int main(){
char num_str[64] = {0};
int num, cifra;
printf("Write a number: \n");
scanf("%d", &num);
int len = snprintf(num_str, 64, "%d", num);
printf("The length is %d\n", len);
for(int i = 0; i < len; i++) {
cifra = (int)(num_str[i]);
printf("%d \n", cifra);
}
return 0;
}
```
|
convert it fromchartoint
Test the character for digit and subtract'0'.
```
for(int i = 0; i < len; i++) {
int cifra = num_str[i];
if (cifra >= '0' && cifra <= '9') printf("%d\n", cifra - '0');
else printf("%c\n", cifra); // such as '-'
}
```
|
The answer isO(n^6)but I am not quite sure how to get there, trying with small numbers shows that g ups the number n to the power of 3 sok=n^3and thusk^2=n^6(I think), but how do I show it mathematically, specifically, we were taught a method to use a new functionT(n)but I'm not sure how to apply it here, appreciate any help thanks.
```
int g(int n)
{
if (n <= 1) return 1;
return 8 * g(n / 2);
}
void f3(int n)
{
int k = g(n);
for (int i = 2; i < k * k; ++i)
{ printf("*"); }
}
```
|
Let's first analyze the functiong(n):
```
g(n) = 8 * g(n/2)
```
if you eliminate the recursion, this breaks down to
```
g(n) = 8^log_2(n)
```
and eliminating the logarithm yields:
```
g(n) = n^3
```
Nowk*kisn^3*n^3 = n^6, so the loop printsn^6asterisks. This results in the time complexity ofO(n^6).
|
Insertion sort is not working, it is only printing some of the values. Does anyone know what I can do to fix it?
```
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
int j = i;
while (j >= 0 && Array[j] < Array[j - 1]) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
j--;
}
}
}
```
|
The test in the inner loop is incorrect: whenj == 0you read and possibly modify the element at offset-1, which hasundefined behavior, possibly causing the incorrect output, but since you did not post the output code, there might be other problems there.
Here is a modified version:
```
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && Array[j] < Array[j - 1]; j--) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
}
}
}
```
|
New programmer here!
I am implementing selection sort, with a max variable instead of the usual min, but I still want to sort from lowest to highest.
The code below sorts the list perfectly except for the first value which it makes a very large negative number...
Any tips for what I can fix to get it sorting properly?
```
void selection(int Array[], int size) {
int i, j, max, temp;
for (i = 0; i < size-1; i++) {
max = i;
for (j = i+1; j <= size; j++) {
if ( Array[j] < Array[max] )
max = j;
}
temp = Array[max];
Array[max] = Array[i];
Array[i] = temp;
}
}
```
|
```
for(j = i+1; j<=size; j++)
```
This line is your problem. You are accessing one past the end of the array, which will be undefined behavior and can often give you weird values. Change the condition toj < size.
|
Taking in input a number and then put every digit into an array, I have, converted it into a string so that I can put it into an array, but then when I use the cast to remake it a int i get the ascii number..
```
#include <stdio.h>
#include <stdlib.h>
int main(){
char num_str[64] = {0};
int num, cifra;
printf("Write a number: \n");
scanf("%d", &num);
int len = snprintf(num_str, 64, "%d", num);
printf("The length is %d\n", len);
for(int i = 0; i < len; i++) {
cifra = (int)(num_str[i]);
printf("%d \n", cifra);
}
return 0;
}
```
|
convert it fromchartoint
Test the character for digit and subtract'0'.
```
for(int i = 0; i < len; i++) {
int cifra = num_str[i];
if (cifra >= '0' && cifra <= '9') printf("%d\n", cifra - '0');
else printf("%c\n", cifra); // such as '-'
}
```
|
The answer isO(n^6)but I am not quite sure how to get there, trying with small numbers shows that g ups the number n to the power of 3 sok=n^3and thusk^2=n^6(I think), but how do I show it mathematically, specifically, we were taught a method to use a new functionT(n)but I'm not sure how to apply it here, appreciate any help thanks.
```
int g(int n)
{
if (n <= 1) return 1;
return 8 * g(n / 2);
}
void f3(int n)
{
int k = g(n);
for (int i = 2; i < k * k; ++i)
{ printf("*"); }
}
```
|
Let's first analyze the functiong(n):
```
g(n) = 8 * g(n/2)
```
if you eliminate the recursion, this breaks down to
```
g(n) = 8^log_2(n)
```
and eliminating the logarithm yields:
```
g(n) = n^3
```
Nowk*kisn^3*n^3 = n^6, so the loop printsn^6asterisks. This results in the time complexity ofO(n^6).
|
probably a dumb question but how do you access a specific character in a char pointer?
I've tried following...
```
char *pointer = "Hello";
printf("%s", pointer); // prints "Hello"
printf("%s", &pointer[0]); // also prints "Hello"
```
But what I want is printf(???) => "H". A single character. Or the "e". How is that possible?
|
pointeris a pointer tochar, also called achar *.
Afterchar *pointer = "Hello";,pointerpoints to the βHβ.
Whenprintfis given%s, it takes achar *and printsallthe characters it finds starting at that location, until a null character is seen.
To tellprintfto print a single character, pass it the actual character value (not a pointer) and use%c:
```
printf("%c", *pointer);
```
or:
```
printf("%c", pointer[0]);
```
or, for the βeβ instead of the βHβ:
```
printf("%c", pointer[1]);
```
|
Take a look at the following piece of code:
```
#include <stdio.h>
int main()
{
int i;
for (i = 48; i < 58; i++)
{
printf("%d", i);
}
return 0;
}
```
The output is:48495051525354555657But if you changeprintf("%d", i);toprintf("%c", i);the output becomes:0123456789
Shouldn't both output48495051525354555657Why are the outputs different when substitutingdwithc?
|
Because with%ctheiis interpreted as a character and if you look at theASCII tableyou can see that48represents the character'0',49is'1', etc.
|
I have a general case iterating over e.g. 30 loops in afor loop, however, in some case I only need the information of the first loop. Thus, I break the for loop in this case.
Is this a good practice or should I combine a conditional statement and 2for loopsto have two independent cases?
Typical pattern :
```
int i;
for(i=0; i<30; i++)
{
//do something generic
if(specificCase)
{
break;
}
}
```
Use case :
I use this to build a frame with 30 measurements. But sometimes I need a frame with only the first measurement.
|
Specific case could be returned by a third party that's failing , a database or a messaging system for instance. If this error condition is not transient then it makes perfect sense to break out of the loop and try to reconnect.
|
I am trying to use libcurl for uploading a file via POST using theCURLOPT_UPLOADoption:
```
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
```
By default, it uses PUT as explainedhere, where it is mentioned:If the protocol is HTTP, uploading means using the PUT request unless you tell libcurl otherwise.How do Itell libcurl otherwise, specifically, to use POST.
I have tried adding the following after the previous line of code above, but it did not work:
```
curl_easy_setopt(curl, CURLOPT_POST, 1L);
```
|
You can useCURLOPT_CUSTOMREQUESTfor that:
```
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
```
This method is suitable for setting any custom HTTP method for your request.
For more details, see the corresponding page in thecurl manual
|
Let's say my array looks like this. The number of rows will always match the number of columns in this program.
```
[0] [1] [2]
[3] [4] [5]
[6] [7] [8]
```
I would need to turn this into the reversed form:
```
[2] [1] [0]
[5] [4] [3]
[8] [7] [6]
```
I know that multidimensional arrays are just arrays of arrays, which hopefully shortens the scale of my question to just reversing a 1D array, but I don't know how to apply that same idea to a 2D array. The size will not always be a 3 by 3 array, but again the rows and columns will always be the same number.
|
Try following code, here n is the number of rows and m is the number of columns. Hopefully this will solve your problem. Happy coding!
```
for(i = 0; i < n; i++) {
for(j = 0; j < m/2; j++) {
int temp = arr[i][j];
arr[i][j] = arr[i][m-j-1];
arr[i][m-j-1] = temp;
}
}
```
|
I try to useva_argto retrieve next argument in function. It works well for all types (including char*) but char:
```
void test1(char t,...) {
va_list args;
va_start(args, t);
if(t=='c') Serial.println(va_arg(args, char));
else if(t=='n') Serial.println(va_arg(args, int));
va_end(args);
}
```
Test:
```
int n = 42;
char c = '?';
test1('n', n); // prints 42
test1('c', c); // prints nothing!
```
Can you verify/explain it? The code runs on Arduino Uno, 9600 bauds.
|
Arguments smaller thanintare promoted tointbefore being passed to variadic functions, and such functions should thus retrieve the arguments as typeint.
|
I have tried to dynamically allocate an object as member of a structure with this code:
```
#include <stdlib.h>
#define width 4
struct foo{
int* p1 = malloc(sizeof(*p1) * width);
};
```
but the compilers, both clang and gcc, throw the error:
```
error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
```
when I attempt to compile the code; here is the link:https://godbolt.org/z/-Sy6CK.
My question:
How can I create a structure that has dynamically allocated members in C?
|
Or this:
```
struct foo{
int* p1;
};
int main()
{
struct foo bar = {.p1 = malloc(sizeof(*bar.p1) * width)};
}
```
or
```
int main()
{
struct {
int* p1;
} bar = {.p1 = malloc(sizeof(*bar.p1) * width)};
}
```
|
I have a question, how the compiler operate on the following code:
```
#include<stdio.h>
int main(void)
{
int b=12, c=11;
int d = (b == c++) ? (c+1) : (c-1);
printf("d = %i\n", d);
}
```
I am not sure why the result is βββd = 11.
|
Inint d = (b == c++) ? (c+1) : (c-1);:
The value ofc++is the current value ofc, 11. Separately,cis incremented to 12.b == 11is false, sincebis 12.Since(b == c++)is false,(c-1)is used. Also, the increment ofcto 12 must be completed by this point.Sincecis 12,c-1is 11.dis initialized to that value, 11.
|
Sometimes when reading books, Like The C Programming Language, The author talk about that number and types of register variables vary from machine to machine.
|
There are hundreds of different CPU architecture with different instructions, register numbers and length etc.
With regards to C, it is machine dependent how for example anintis represented. Most architecture treat it as 32 bit integer, but others may as 64 bit, so there are machine dependent aspects.
|
I have tried to dynamically allocate an object as member of a structure with this code:
```
#include <stdlib.h>
#define width 4
struct foo{
int* p1 = malloc(sizeof(*p1) * width);
};
```
but the compilers, both clang and gcc, throw the error:
```
error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
```
when I attempt to compile the code; here is the link:https://godbolt.org/z/-Sy6CK.
My question:
How can I create a structure that has dynamically allocated members in C?
|
Or this:
```
struct foo{
int* p1;
};
int main()
{
struct foo bar = {.p1 = malloc(sizeof(*bar.p1) * width)};
}
```
or
```
int main()
{
struct {
int* p1;
} bar = {.p1 = malloc(sizeof(*bar.p1) * width)};
}
```
|
I have a question, how the compiler operate on the following code:
```
#include<stdio.h>
int main(void)
{
int b=12, c=11;
int d = (b == c++) ? (c+1) : (c-1);
printf("d = %i\n", d);
}
```
I am not sure why the result is βββd = 11.
|
Inint d = (b == c++) ? (c+1) : (c-1);:
The value ofc++is the current value ofc, 11. Separately,cis incremented to 12.b == 11is false, sincebis 12.Since(b == c++)is false,(c-1)is used. Also, the increment ofcto 12 must be completed by this point.Sincecis 12,c-1is 11.dis initialized to that value, 11.
|
Sometimes when reading books, Like The C Programming Language, The author talk about that number and types of register variables vary from machine to machine.
|
There are hundreds of different CPU architecture with different instructions, register numbers and length etc.
With regards to C, it is machine dependent how for example anintis represented. Most architecture treat it as 32 bit integer, but others may as 64 bit, so there are machine dependent aspects.
|
I've got the following faulty piece of code in C and I am wondering if there will be a memory leak or if there will be a pointer which is pointing to a free memory location.
```
int* p = (int*) malloc(sizeof(int));
p = NULL;
free(p);
```
|
Yes it will leak memory. You assign p to NULL before freeing the contents it's pointing to. One quick change will fix it:
```
int* p = malloc(sizeof(int));
free(p);
p = NULL;
```
The difference here is we give free the address allocated by malloc before setting p to NULL. In general setting a pointer to NULL will not free the contents, but will allow you to check if the pointer is valid or not which can have a lot of practical applications.
|
I've got the following faulty piece of code in C and I am wondering if there will be a memory leak or if there will be a pointer which is pointing to a free memory location.
```
int* p = (int*) malloc(sizeof(int));
p = NULL;
free(p);
```
|
Yes it will leak memory. You assign p to NULL before freeing the contents it's pointing to. One quick change will fix it:
```
int* p = malloc(sizeof(int));
free(p);
p = NULL;
```
The difference here is we give free the address allocated by malloc before setting p to NULL. In general setting a pointer to NULL will not free the contents, but will allow you to check if the pointer is valid or not which can have a lot of practical applications.
|
I would like to know ifpthreadsis doingbusy waiting internallywhen callingpthread_cond_timedwait()?
I'm analysing a multi-threaded program and need to know if a thread is potentially blocking ressources when calling the above function.
Platform: Intel x86_64, CentOS 7.5.1804 with GCC 5.3.0
|
As you will have read in their documentation, thepthread_cond_wait()andpthread_cond_timedwait()functions cause the calling thread toblockuntil the CV is signaled, or, in the latter case, the specified time arrives. (Or the thread is cancelled, or it is temporarily aroused to handle a signal, or ....) Blocking does not merely mean that the thread does not return from the function. It means that the thread is not scheduled on any execution unit as long as it remains blocked. Thus, no, threads blocked inpthread_cond_timedwait()do not busy-wait.
|
So I have two structs, which for simplicity we shall callAandB.Acontains a pointer toB, andBcontains anA. So here is the code:
a.h
```
#ifndef A_H
#define A_H
#include "b.h"
typedef struct _A {
B *b;
} A;
#endif
```
b.h
```
#ifndef B_H
#define B_H
#include "a.h"
typedef struct _B {
A a;
} B;
#endif
```
Now the issue is that when I import a.h from my main c file, I get errors about how A is an unknown type from b.h. I'm not sure how to resolve this.
|
The way to do this is to pre-define the structs using empty definition
```
typedef struct _A A;
typedef struct _B B;
typedef struct _A {
B *b;
} A;
typedef struct _B {
A a;
} B;
```
You can put the pre-definitions in a global include file to include from wherever you need.
`
|
I just wanted this while loop to go through each slot ofparty -> fragmentsand free each spot if it isn't NULL, but it seems to be getting stuck in an infinite loop instead when I go to run it. If I insert an else and put a break in it, it'll run, but I still have memory leaks.
```
while(i < party -> num_active_fragments)
{
if(party -> fragments[i] != NULL)
{
free(party -> fragments[i]);
i++;
}
}
```
|
The problem here is thati++should be out of the if statement.
The infite loop is caused because an element is NULL and in that iterationiis not incremented, and same happens repeatedly.
As people commented, there is no need for checking if the value is NULL.
And as @thebusybee commented, you should set the freed pointers as NULL.
Your code may look like this:
```
while(i < party->num_active_fragments)
{
free(party->fragments[i]);
party->fragments[i] = NULL;
i++;
}
```
|
I will admit I have not kept up with the latest C/C++ releases but I was wondering why having a function prototype in a function is valid code? Is it related to lambda usage?
Here is sample code - this will compile/run on Visual Studio 2019 and g++ 5.4.0
```
int main()
{
int func(bool test);
return 0;
}
```
|
A code block may contain any number of declarations. And because a function prototype is a declaration, it may appear in a block.
Granted, it doesn't make much sense to do so logistically as opposed to declaring a function at file scope, but it's syntactically correct.
|
Can I safelyusethesend_sig()function in kernel-mode to send a signal to a processfrom within atomic context?In other words, could this function block or sleep?
|
Taking a quick look at the source code (v4.20):
send_sig()only callssend_sig_info()...... which checks if the signal value is valid and then callsdo_send_sig_info()...... which callslock_task_sighand()...... which has the function of locking thespinlocktsk->sighand->siglock(throughspin_lock_irqsave()). This spinlock is only released at the end ofdo_send_sig_info(), which then returns immediately.
We know that kernel code must not sleep while holding a spinlock, as that would be a fatal error. Since the very first chain of calls done bysend_sig()has the effect of locking a spinlock which is then held for the entirety of the operation, we can deduce thatthesend_sig()function does not sleep.
|
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.Closed3 years ago.Improve this question
```
#include <stdio.h>
int main(void) {
int a[4][5] = { { 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9,10 },
{11,12,13,14,15 },
{16,17,18,19,20 } };
printf("%d\n", *(*(a + **a + 2) + 3));
return 0;
}
```
The above code gives 19 as answer. I want to know how does it calculates.
|
Lets do it one step at a time:
**aisa[0][0]which is1a + 1 + 2is&a[3]*(&a[3])isa[3]*(a[3] + 3)isa[3][3]which is19.
QED
|
I am trying to make a function to swap two rows from a 2D double array inside a struct using a pointer to that struct.
This is my function code so far.
```
void swap_rows(struct Double_Array* ptr , int r1 , int r2){
double temp = ptr->array[r1];
ptr->array[r1] = ptr->array[r2];
ptr->array[r2] = temp;
}
```
These are the errors I am getting:
```
cannot convert 'double*' to 'double' in initialization
invalid array assignment
incompatible types in assignment of 'double' to 'double [9]'
```
The array is part of a struct which is allocated in memory. However I get errors when compiling.
|
First thing is you have to access a 2D array using its two indices likearray[0][r1]and then swapr1andr2column by column in a loop like inhow do you swap two rows in a matrix (in C)?
|
I don't understand this line of code:
if (i && (i - 1))
printf("%d\n", p[i - 1]);
```
int main(void) {
int p[7] = {-5, 1, 4, -7, 2, 8, 0};
int i;
for (i = 0; i < 7; i++) {
if (i && (i - 1))
printf("%d\n", p[i - 1]);
}
return 0;
}
```
|
The condition of this if statement
```
if (i && (i - 1))
```
can be rewritten for clarity like
```
if (i != 0 && (i - 1) != 0)
```
In the condition there is checked whether the current value of the index i is equal to 0. And if it is not equal to 0 then whether the preceding value of the index i - 1 is equal to 0.
This evaluates to true when i is not equal to 0 and is not equal to 1.
So the condition evaluates to true starting from the index i equal to 2.
So the loop outputs all elements of the array except the first element and the last element.
|
Do the below codes do the exact same thing?
Code Snippet 1:
```
#include <stdio.h>
int main(void){
int size;
scanf("%d", &size);
int arr[size];
//code to manipulate array
return 0;
}
```
Code Snippet 2:
```
#include <stdio.h>
int main(void){
int size;
scanf("%d", &size);
int *arr = malloc(size*sizeof(int));
//code to manipulate array
free(arr);
return 0;
}
```
|
These are not the same.
The first snippet creates an array with automatic storage duration, i.e. on the stack in most implementations, while the second creates an array dynamically on the heap. The former has a lifetime of the scope than encloses it, while the latter is valid for the lifetime of the program or until it is freed, whichever comes first.
|
When I search for static initialization order problems, I see a lot of examples in C++ that explain this problem. I wonder: can the static initialization order fiasco problem occur in C programs?
|
Static initialization in C does not have the same problems that C++ has.
In C, objects with static storage duration may only be initialized via constant expressions, i.e. values that can be computed at compile time, so there are no issues that can arise regarding order of initialization.
In contrast, C++ allows calling functions to initialize static objects, and the order in which those functions are called are not well-defined.
|
Do the below codes do the exact same thing?
Code Snippet 1:
```
#include <stdio.h>
int main(void){
int size;
scanf("%d", &size);
int arr[size];
//code to manipulate array
return 0;
}
```
Code Snippet 2:
```
#include <stdio.h>
int main(void){
int size;
scanf("%d", &size);
int *arr = malloc(size*sizeof(int));
//code to manipulate array
free(arr);
return 0;
}
```
|
These are not the same.
The first snippet creates an array with automatic storage duration, i.e. on the stack in most implementations, while the second creates an array dynamically on the heap. The former has a lifetime of the scope than encloses it, while the latter is valid for the lifetime of the program or until it is freed, whichever comes first.
|
When I search for static initialization order problems, I see a lot of examples in C++ that explain this problem. I wonder: can the static initialization order fiasco problem occur in C programs?
|
Static initialization in C does not have the same problems that C++ has.
In C, objects with static storage duration may only be initialized via constant expressions, i.e. values that can be computed at compile time, so there are no issues that can arise regarding order of initialization.
In contrast, C++ allows calling functions to initialize static objects, and the order in which those functions are called are not well-defined.
|
I have read that dangling pointers are bad as they point to location that is supposed to be free.But I don't understand why is that bad?So can you give me any example of disadvantages of dangling pointer.
|
Once you have a dangling pointer, two things are forbidden:
You are not allowed todereferencethe pointer. The behaviour on doing so isundefined.You are not allowed toreadthe pointer. It's as if the pointer is an uninitialised variable, or one you've just declared.
Few folk tend to fully grasp (2), and are surprised the first time they find out about this!
As such, dangling pointers can compromise program stability. And that's quite a disadvantage.
|
I have a make file called hello.
```
hello:
cl hello.c
```
is the contents of it. I Don't have an existing .exe ready, and when I type nmake hello,
I get a message that 'hello' is up to date.
Output expecting:
What is the reason I'm not getting the expected output?
and how do I get it working?
many thanks.
|
I Don't have an existing.exeready
That's ok, but your target is not calledhello.exe, it's calledhello.
What is most probably happening is thatnmakeis telling you thathellois already up to date because you have an existinghellofile in your folder. Either rename the rule tohello.exe:
```
hello.exe:
cl hello.c
```
Or leave it as is and delete thehellofile.
|
I've seen the following in C code and it seems strange to me:
```
myType GetStuff(size_t *iSize) {
*iSize = (size_t)0;
size_t h = 0;
*iSize += h;
}
```
Everything works without the cast as well:*iSize = 0;.
Is there any need for the(size_t)cast or is it superfluous?
|
Is there any need in (size_t) cast or its superfluous?
Arithmetic types convert implicitly. You don't need a cast. That said, the cast improves the readability of the code and might avoid some warnings from some compilers.
|
I have read that dangling pointers are bad as they point to location that is supposed to be free.But I don't understand why is that bad?So can you give me any example of disadvantages of dangling pointer.
|
Once you have a dangling pointer, two things are forbidden:
You are not allowed todereferencethe pointer. The behaviour on doing so isundefined.You are not allowed toreadthe pointer. It's as if the pointer is an uninitialised variable, or one you've just declared.
Few folk tend to fully grasp (2), and are surprised the first time they find out about this!
As such, dangling pointers can compromise program stability. And that's quite a disadvantage.
|
I have a make file called hello.
```
hello:
cl hello.c
```
is the contents of it. I Don't have an existing .exe ready, and when I type nmake hello,
I get a message that 'hello' is up to date.
Output expecting:
What is the reason I'm not getting the expected output?
and how do I get it working?
many thanks.
|
I Don't have an existing.exeready
That's ok, but your target is not calledhello.exe, it's calledhello.
What is most probably happening is thatnmakeis telling you thathellois already up to date because you have an existinghellofile in your folder. Either rename the rule tohello.exe:
```
hello.exe:
cl hello.c
```
Or leave it as is and delete thehellofile.
|
I've seen the following in C code and it seems strange to me:
```
myType GetStuff(size_t *iSize) {
*iSize = (size_t)0;
size_t h = 0;
*iSize += h;
}
```
Everything works without the cast as well:*iSize = 0;.
Is there any need for the(size_t)cast or is it superfluous?
|
Is there any need in (size_t) cast or its superfluous?
Arithmetic types convert implicitly. You don't need a cast. That said, the cast improves the readability of the code and might avoid some warnings from some compilers.
|
I am writing a program in C and here is my code
```
#include<stdio.h>
#include<conio.h>
void main(){
int a,b;
float division;
clrscr();
printf("Enter value of a :"); scanf("%d",&a);
printf("Enter value of b :"); scanf("%d",&b);
division = a/b;
printf("\nDivision : %.2f",division);
getch();
}
```
When I execute this code and enter values it does not return accurate output.
For example ifa = 15 & b = 10then output is1.00and another example isa = 10 & b=15then output is0.00. Is there a way to prevent integers from truncating?I can't take a and b as floats.
|
No, integer division always truncates. However, you can do floating point division if you just cast (at least) one of your operands:
```
division = (float)a/b;
```
|
I am new in programming I have started learning with C. I wanted to learn about the precedence of the operators in the following
```
if ( p == 2 || p % 2 )
```
Please help me.
|
ReferPrecedence Of OperatorsandShort Circuiting.
Precedence: Operator precedence determines how the operators and operands are grouped within an expression when there's more than one operator and they have different precedences.Associativity: Operator associativity is used when two operators of the same precedence appear in an expression.
Since||exists, it is required that the left side of the||be evaluated first to decide if the right side of||needs to be processed.
Ifp == 2returns true,p % 2will not be evaluated.
Hencep == 2will be executed first, followed byp % 2(because%has higher precedence than||).
The result of these 2 will then be evaluated against||.
|
h_array[i] is less than 19 for the first few cases. However, it still prints k as 0. Could someone help me out as to why this happens?
```
for (int i = 0; i < 10; i++) {
int j = h_array[i];
int k = 0;
if (h_array[i]<19) {
int k = 20 - j;
}
int l = 20;
while (l>=k) {
printf ("%d - %d\n\n\n",l,k);
l--;
}
}
```
|
The issue is you've re-declared 'k' inside the body of the if statement. The compiler will usually generate a warning about this.
In this case the 'k' variable with the scope of the condition body is modified, whilst the 'k' in the parent scope retains its original value (0).
Removing the type specifier should fix the issue.
```
for (int i = 0; i < 10; i++) {
int j = h_array[i];
int k = 0;
if (h_array[i]<19) {
k = 20 - j;
}
int l = 20;
while (l>=k) {
printf ("%d - %d\n\n\n",l,k);
l--;
}
}
```
|
```
#include<stdio.h>
void sum();
int main(){
sum();
sum();
sum();
sum();
}
void sum(){
int x;
x++;
printf("%d\n",x);
}
```
the output of this code(in devc,codeblocks) is:- 1 2, but i don't understand why??
As the variable "x " should be destroyed when it goes out of scope.
|
What you're seeing is a manifestation ofundefined behavior.
The variablexis uninitialized so its value isindeterminate. You then attempt to increment the variable, which first reads the indeterminate value. Once you do that, you can't predict what your program will do.
In thisparticularcase, the stack forsumeach time it is called happens to be in the same location in memory, so whatever valuexhad before happens to still be there. If you added a call toprintfin between the calls tosumyou would probably see different results.
|
With C igraph we can create a graph from an adjacency list withigraph_adjlist.
It there a way to create a graph from an incidence list ?
|
Unfortunately no such functionality is implemented. Feel free to open an issue athttps://github.org/igraph/igraphto suggest such a feature. Alternatively, if you want to discuss it, theigraphproject recently opened a new forum to facilitate discussions, seehttps://igraph.discourse.group.
|
I asked other programmers, and they said that carat^means xor. But it seems there is an obscure use of carat that I don't fully understand. It seems that^suffixing a type modifies it in some way, like how suffixing a type with*declares it a pointer type. The code below works, but can someone explain why and what is going on, and how the carat symbol allows me to declare anonymous function literals inline? I didn't know that you could do that, but I want to fully understand this mysterious functionality.
```
void(^Function)(void);
int main(int argc, char *argv[]) {
Function = ^{
int x = 10;
printf("%d\n", x);
};
Function();
Function = ^{
putchar(65);
};
Function();
return 0;
}
```
Also, is this some compiler extension or is this pure C?
|
This is an Apple extension to C calledBlocks, forGrand Central Dispatch.
|
I see that alinux\pid.hin the kernel defines the following type:
```
enum pid_type
{
PIDTYPE_PID,
PIDTYPE_TGID,
PIDTYPE_PGID,
PIDTYPE_SID,
PIDTYPE_MAX,
};
```
and thestruct pidtype uses it when keeping track of the tasks associated to the PID:
```
struct pid
{
atomic_t count;
unsigned int level;
/* lists of tasks that use this pid */
struct hlist_head tasks[PIDTYPE_MAX];
struct rcu_head rcu;
struct upid numbers[1];
};
```
But what does each list refers to? It's my understanding thatPIDTYPE_PIDrefers to tasks which use this as PID (the "thread ID" from kernel perspective) andPIDTYPE_TGIDas tasks which use this as TGID, i.e. thread group ID which denotes a group of threads which share the same userspace PID, what arePIDTYPE_PGIDandPIDTYPE_SID?
|
SID = session ID,
PGID = process group ID as described here:https://www.win.tue.nl/~aeb/linux/lk/lk-10.html
|
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.Closed3 years ago.Improve this question
I'm trying to do a high speed memcpy in Python. I use the ctypes library which allows me to interact with C programms.
I follow this steps:
I get the memory addressI get the length of the dataI use the ctypes' functions memmove or string_at
The results are correct but I need higher speed. Is there any faster way to do this without using C?
Thank you.
|
I found one solution in this post:
How to read from pointer address in Python?
In the answer of Hannah Zhang.
|
I know if we want to map a const string in the flash data,
we can write:
```
static const char example[] = "map_in_flash";
```
We can find it in the flash memory at 0x08xxxxxx;
But I want to map a const string array in the flash and write:
```
static const char * example_array[10] = {"abc","def","ddd","fff"};
```
It is mapped in the ram.
```
0x20018ae4 0x28 Src/main.o
.data.example_array
0x20018b0c 0x28 Src/main.o
```
How to map the const string array in the flash data?
|
"When in doubt, add more const" - in other words, your array contains values of type "pointer to const char", which means the strings itself can't be changed, but the elements of the array can still be modified to point to different strings!
You'll want to useconst char * constto make it so the pointers can't be changed either, and they can reside in the flash.
|
```
#include<stdio.h>
void sum();
int main(){
sum();
sum();
sum();
sum();
}
void sum(){
int x;
x++;
printf("%d\n",x);
}
```
the output of this code(in devc,codeblocks) is:- 1 2, but i don't understand why??
As the variable "x " should be destroyed when it goes out of scope.
|
What you're seeing is a manifestation ofundefined behavior.
The variablexis uninitialized so its value isindeterminate. You then attempt to increment the variable, which first reads the indeterminate value. Once you do that, you can't predict what your program will do.
In thisparticularcase, the stack forsumeach time it is called happens to be in the same location in memory, so whatever valuexhad before happens to still be there. If you added a call toprintfin between the calls tosumyou would probably see different results.
|
With C igraph we can create a graph from an adjacency list withigraph_adjlist.
It there a way to create a graph from an incidence list ?
|
Unfortunately no such functionality is implemented. Feel free to open an issue athttps://github.org/igraph/igraphto suggest such a feature. Alternatively, if you want to discuss it, theigraphproject recently opened a new forum to facilitate discussions, seehttps://igraph.discourse.group.
|
I asked other programmers, and they said that carat^means xor. But it seems there is an obscure use of carat that I don't fully understand. It seems that^suffixing a type modifies it in some way, like how suffixing a type with*declares it a pointer type. The code below works, but can someone explain why and what is going on, and how the carat symbol allows me to declare anonymous function literals inline? I didn't know that you could do that, but I want to fully understand this mysterious functionality.
```
void(^Function)(void);
int main(int argc, char *argv[]) {
Function = ^{
int x = 10;
printf("%d\n", x);
};
Function();
Function = ^{
putchar(65);
};
Function();
return 0;
}
```
Also, is this some compiler extension or is this pure C?
|
This is an Apple extension to C calledBlocks, forGrand Central Dispatch.
|
I see that alinux\pid.hin the kernel defines the following type:
```
enum pid_type
{
PIDTYPE_PID,
PIDTYPE_TGID,
PIDTYPE_PGID,
PIDTYPE_SID,
PIDTYPE_MAX,
};
```
and thestruct pidtype uses it when keeping track of the tasks associated to the PID:
```
struct pid
{
atomic_t count;
unsigned int level;
/* lists of tasks that use this pid */
struct hlist_head tasks[PIDTYPE_MAX];
struct rcu_head rcu;
struct upid numbers[1];
};
```
But what does each list refers to? It's my understanding thatPIDTYPE_PIDrefers to tasks which use this as PID (the "thread ID" from kernel perspective) andPIDTYPE_TGIDas tasks which use this as TGID, i.e. thread group ID which denotes a group of threads which share the same userspace PID, what arePIDTYPE_PGIDandPIDTYPE_SID?
|
SID = session ID,
PGID = process group ID as described here:https://www.win.tue.nl/~aeb/linux/lk/lk-10.html
|
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.Closed3 years ago.Improve this question
I'm trying to do a high speed memcpy in Python. I use the ctypes library which allows me to interact with C programms.
I follow this steps:
I get the memory addressI get the length of the dataI use the ctypes' functions memmove or string_at
The results are correct but I need higher speed. Is there any faster way to do this without using C?
Thank you.
|
I found one solution in this post:
How to read from pointer address in Python?
In the answer of Hannah Zhang.
|
I'd like to display an inverted half pyramid using a pattern made of "*" characters.
After running my code, the output seems empty. I'd like to know what is the problem.
Here's the desired output:
```
*****
****
***
**
*
```
And here is my code:
```
for (int i=1;i<=5 ;i++)
{
for(int x=5;x<=1;x--)
{
printf("* ");
}
printf ("\n");
}
```
|
generic solution to change the size of pyramid only once
```
for (int nb = 5; nb > 0; nb--) {
for(int i = 0; i < nb; i++) {
printf("* ");
}
printf ("\n");
}
```
|
When I try to compile including the filestack.hmy GCC gives me the error "No such file or directory"
```
gcc -std=c99 -Wall -o Ou1 ou1.c -I C:\Users\NAME\Documents\C programmering\DOA\stack.h
```
The code looks like this:
```
#include <stdio.h>
#include <stdbool.h>
#include "stack.h"
```
I've tried to change its folder and changing the.hto.cand the.cto.h.
|
First,-Iexpects a path to a directory. Secondly, your path contains spaces, so you should enclose it in quotes to make sure it's not wrongly treated as two different arguments:
```
gcc -std=c99 -Wall -o Ou1 ou1.c -I "C:\Users\NAME\Documents\C programmering\DOA"
```
|
I'd like to display an inverted half pyramid using a pattern made of "*" characters.
After running my code, the output seems empty. I'd like to know what is the problem.
Here's the desired output:
```
*****
****
***
**
*
```
And here is my code:
```
for (int i=1;i<=5 ;i++)
{
for(int x=5;x<=1;x--)
{
printf("* ");
}
printf ("\n");
}
```
|
generic solution to change the size of pyramid only once
```
for (int nb = 5; nb > 0; nb--) {
for(int i = 0; i < nb; i++) {
printf("* ");
}
printf ("\n");
}
```
|
When I try to compile including the filestack.hmy GCC gives me the error "No such file or directory"
```
gcc -std=c99 -Wall -o Ou1 ou1.c -I C:\Users\NAME\Documents\C programmering\DOA\stack.h
```
The code looks like this:
```
#include <stdio.h>
#include <stdbool.h>
#include "stack.h"
```
I've tried to change its folder and changing the.hto.cand the.cto.h.
|
First,-Iexpects a path to a directory. Secondly, your path contains spaces, so you should enclose it in quotes to make sure it's not wrongly treated as two different arguments:
```
gcc -std=c99 -Wall -o Ou1 ou1.c -I "C:\Users\NAME\Documents\C programmering\DOA"
```
|
I came across typedef declaration or definition(?) while learning about linked listsin c:
```
typedef struct _node{
int a;
struct _node* next
} node;
```
I have no idea how it can work since the above typedef declaration's body it initiates a pointer variable with its own structure(it seems like _node is being used while defining _node). Or is there anything wrong in my understanding of what it actually does? From depiction maybe I got confused over different terms as well.
|
Also, the type definition will only work after the struct is defined and not while defining it(C does only allow forward definitions).
This is why you cannot usenodebutstruct node_.
In the code, you can usenodebecause the compiler will interpret it asstruct node_.
|
I'd like to debug a program that uses the dollars in identifiers extension.
Take
```
#include <stdio.h>
int main()
{
int $a = 42, b= 43;
printf("%d %d\n", $a, b);
}
```
for a simplified example. If I run it under gdb, I can inspectbusingp b, but forp $aI getvoid. I can only show the value withinfo locals.
Is there a way to refer to $-containing identifiers in gdb?
|
gdbinterprets the initial$inp $abefore parsing the expression to print.
Note however that it only does this for the initial$: if the$sign appears in the middle of a symbol, (eg:p a$1) the variable is printed correctly.
A work-around for local variables whose name start with a dollar-sign is to print all local variables with
```
info locals
```
|
I cannot see the difference betweenyandy2
```
uint16_t x = 0x0F1F2;
uint8_t y = (x & 0xFF00) >> 8;
uint8_t y2 = x >> 8;
printf("%x,", y);
printf("%x,", y2);
```
But I see the style with a mask often. Is there ever any reason to mask with&before doing this operation?
|
Typically you might mask before if some bits represent an integer stored in the value. This would probably be a hardware or network interface. So you might have the bit mask of 0xff00 defined, and a shift count, so you mask first then shift.
As for your example,yandy2are the same, and if you compile and optimize (possibly in separate compilations), the code generated should be the same. (And will almost certainly not contain a shift operation, as it just needs to read the right byte.)
|
This question already has answers here:How does the Comma Operator work(9 answers)Closed3 years ago.
Program code :
```
int main()
{
int i;
for (i = 0; i < 0, 5; i++)
printf("%d ", i);
return 0;
}
```
The loop above is executed infinite times.
What doesi<0,5mean, and how it is evaluated?
|
Based on operator precedence, this is interpreted as(i < 0), 5. The comma operator evaluates all statements, but discards their values except the last. So for practical purposes the loop reads as
for (int i = 0; 5; ++i) {...}
Because a non-zero value is interpreted astruein C/C++, this is equivalent to:
for (int i = 0; true; ++i) {...}
which is an infinite loop.
|
```
#define FUNCXY(x,y) void FUNC_##x_##y(int){}
#define FUNCXYGOOD(x,y) void FUNCGOOD_##x##_##y(int){}
FUNCXY(2, 1) //get expanded to void FUNC_x_1(int){}
FUNCXYGOOD(2, 1) //get expanded to void FUNCGOOD_2_1(int){}
```
Why doesn't FUNCXY work but FUNCXYGOOD work, that is the C rule behind this?
|
The answer is very simple. there is nox_macro parameter. Underscores are part of the macro token. Underscore is same as any other valid token character
Othersise it would be inposibe to have macro like this:
```
#define FOO(x, xa, xb)
```
|
Here is the Code of:
```
# include <stdio.h>
# define scanf "%s Geeks For Geeks "
main()
{
printf(scanf, scanf);
getchar();
return 0;
}
```
Output is:%s Geeks For Geeks Geeks For Geeks
How is this output generated?
|
your printf will become
```
printf(scanf, scanf);
|
|
\ /
printf("%s Geeks For Geeks ", "%s Geeks For Geeks" );
|
| //%s is replaced with "%s Geeks For Geeks" string
\ /
printf("%s Geeks For Geeks Geeks For Geeks ");
```
and on the console
```
%s Geeks For Geeks Geeks For Geeks
```
Aside: Please don't do this kind of coding. It sucks.
|
I have this command here:
```
gcc -MD -fno-builtin -nostdinc -fno-stack-protector -Os -g -m32 -I. -c -o boot1lib.o
boot1lib.c
```
It runs fine if I run this in the folder whereboot1lib.oandboot1lib.clocated. But when I tried to run it from the upper folder i.e../boot/boot1/boot1lib.c
It will shows:./boot/boot1/boot1lib.c:1:10: fatal error: boot1lib.h: No such file or directory #include <boot1lib.h>
How do I modify the parameters to fix this issue? I am trying to build a makefile in the root folder so I don't have to copy and paste the command every time I tried to compile.
|
With GCC,#include <file>looks for files only in configured system directories, including those added with switches.#include "file"looks in the directory of the source file it is in.
|
Follow upCan UTF-8 contain zero byte?
Can I safely store UTF8 string in zero terminatedchar *?
I understandstrlen()will not return correct information, put "storing", printing and "transferring" the char array, seems to be safe.
|
Yes.
Just like with ASCII and similiar 8-bit encodings before Unicode, you can't store theNULcharacter in such a string (the value\u+0000is the Unicode code pointNUL, very much like in ASCII).
As long as you know your strings don't need to contain that (and regular text doesn't), it's fine.
|
I am trying to pass variable arguments that I get to another function I call.
I had written a sample code to test this.
Why is my_printf working but not my2_printf in below code?
```
#include <stdio.h>
#include <stdarg.h>
my2_printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
printf(fmt, ap);
va_end(ap);
}
my_printf(const char *fmt, ...)
{
va_list ab;
va_start(ab, fmt);
vfprintf(stdout, fmt, ab);
va_end(ab);
}
main()
{
int i = 5;
my_printf("This is a test %d => %s\n", i, "done");
my2_printf("This is a test %d => %s\n", i, "done");
}
```
Output I get is as below:
```
This is a test 5 => done
This is a test -171084944 =>
```
|
Because there's variant ofprintfthat expects ava_listargument. If you have ava_listyoumustuse the functions with thevprefix, such asvprintf.
The call toprintfleads toundefined behavior.
|
I am trying to pass variable arguments that I get to another function I call.
I had written a sample code to test this.
Why is my_printf working but not my2_printf in below code?
```
#include <stdio.h>
#include <stdarg.h>
my2_printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
printf(fmt, ap);
va_end(ap);
}
my_printf(const char *fmt, ...)
{
va_list ab;
va_start(ab, fmt);
vfprintf(stdout, fmt, ab);
va_end(ab);
}
main()
{
int i = 5;
my_printf("This is a test %d => %s\n", i, "done");
my2_printf("This is a test %d => %s\n", i, "done");
}
```
Output I get is as below:
```
This is a test 5 => done
This is a test -171084944 =>
```
|
Because there's variant ofprintfthat expects ava_listargument. If you have ava_listyoumustuse the functions with thevprefix, such asvprintf.
The call toprintfleads toundefined behavior.
|
The basic ternary operator usage is
```
(condition) ? True part : False part
```
How can we add "multiple-else-if" functionality to that?
|
When chaining the ternary operator, formatting is key to making it readable:
Trying to do it all on one long line makes it unintelligible.
```
int result = (oper=='+')? a+b :
(oper=='-')? a-b :
(oper=='/')? a/b :
(oper=='*')? a*b :
(oper=='^')? a^b :
(oper=='&')? a&b :
0;
```
Or, to format Zafeer's example:
```
#include <stdio.h>
int main(){
for(int i = 1; i<=10; i++)
printf("%d%s\n",i, (i==1)? "st":
(i==2)? "nd":
(i==3)? "rd":
"th");
}
```
|
I have two questions regarding SDL2's hardware-accelerated texture rendering:
When usingSDL_Createtexture(...), are textures automatically pooled/transferred between system RAM and VRAM when VRAM is at a premium? In order to ensure I don't inundate VRAM, I was considering loading textures into surfaces and converting them to textures as and when required (it's unlikely that all textures will fit into VRAM at once).When minimizing a fullscreen application and/or changing screen resolutions, willSDL_Textureinstances need to be recreated?
|
No, you don't need to recreate yourSDL_Textureinstances after minimize a window or change its resolutions. Maybe you only need to redraw things in the screen after change its resolutions, but not after minimize it.
Also, I recommend you to look at these SDL2 tutorials:https://lazyfoo.net/tutorials/SDL/index.php
|
so i'm making a function that gets 10 names. I tried to use strcspn() to remove the \n from the end of the string. However I get this warning.
```
#define NUM_OF_NAMES 10
#define STR_LEN 50
void input (char arr[][STR_LEN]);
int main()
{
char str [NUM_OF_NAMES][STR_LEN] = {0};
input(str);
return 0;
}
void input (char arr[][STR_LEN])
{
int i = 0;
printf("Enter 10 names:\n");
for (i = 0; i < NUM_OF_NAMES; i++)
{
fgets(arr[i], STR_LEN, stdin);
arr[i][strcspn(arr, "\n")] = 0;
}
for (i = 0; i < NUM_OF_NAMES; i++)
{
puts(arr[i]);
}
}
```
|
You have entered a string
```
fgets(arr[i], STR_LEN, stdin);
```
and are going to remove the appended new line character of the string. Then use the string!
```
arr[i][strcspn(arr[i], "\n")] = 0;
```
|
This is actually a question from an exam and I don't quite understand what that typedef does if someone can explain i would be grateful.
```
typedef int (*funcptr_t)(int);
int myfoo(int i) {
printf("%d\n", i + 1);
return i;
}
funcptr_t foo(int i) {
printf("%d\n", i + 1);
return myfoo;
}
int main() {
funcptr_t fooptr = foo(0);
fooptr(10);
printf("%p %p\n", fooptr, myfoo);
return 0;
}
```
|
int (*funcptr)(int);would declarefunctptras apointer to a function taking anintand returningint.
typedef int (*funcptr_t)(int);declaresfunctptr_tas thetype"pointer to a function taking anintand returningint.
The typedef allows you to declare/definefoowithfuncptr_t foo(int i)rather than the classical but arguably more confusing:
```
int (*foo(int i))(int)
```
|
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.Closed3 years ago.Improve this question
Insert the element in last using single link list . please suggest what is the mistake i made . i shows run time error
|
In the condition check of while loop, it should be
```
while(temp->next!=NULL){
```
|
As part of an anti-aliasing routine I'm running on an STM32 (single precision FPU, if that matters), I'm looking to convert a float value 0 β€ x < 1 to a 4 bit nibble representing opacity. Basically each LSB of the nibble corresponds to a 16th of the float, so 0 β€ x < 0.0625 would be 0x0, 0.0625 β€ x < 0.125 would be 0x1, so on. Are there any bit manipulation tricks I could use to make this operation fast/efficient?
|
For any floating-point value,x, such that0 <= x < 1, the valuey = x * 16will givey <= 0 < 16. Casting thisfloatvalue to anunsigned charwill set the lower nibble of that byte to the number of 16ths. Thus:
```
float x = 0.51;
unsigned char b = (unsigned char)(x * 16);
```
Thenbwill have the value0x08- representing eight sixteenths; and likewise for any other (valid) value ofx.
|
The following code does not work:
```
char text[10];
scanf(" %s", &text);
if (strcmp(text, "some text") == 0)
puts("some text");
```
But when I change 'if part' thus, then everything is fine:
```
if (strcmp(text, "sometext") == 0)
```
why does it work this way and how to fix it?
|
The problem is not with yourstrcmpcall but, rather, in yourscanfcall! When you typesome textas the input,scanfwill stop reading at the first whitespace, so yourtextstring will be "some" - and, thus, thestrcmpcall will (correctly) return non-zero, as this isnotthe same as "some text".
For more information on this feature ofscanf, spaces and the%sformat, see this topic:How do you allow spaces to be entered using scanf?
|
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.Closed3 years ago.Improve this question
```
#include <stdio.h>
void f(char**);
int main()
{
char *argv[] = { "ab", "cd", "ef", "gh", "ij", "kl" };
f(argv);
return 0;
}
void f(char **p)
{
char *t;
t = (p += sizeof(int))[-1];
printf("%sn", t);
}
```
t = (p += sizeof(int))[-1];how does it reference to index three ofargvI am confuse due to[-1]
|
Though it's a weird line it does exactly that, since the size ofintis 4 normally, you should note that this may not work in all machines, since in some,intmay not be 4 bytes in size.
Havingargv[4]is the same as*(argv + 4)sincep=argv, having(p + sizeof(int)) - [1]is the same as having(argv + sizeof(int)) - [1]orargv + sizeof(int) - 1, so*(argv + 4 - 1), so*(argv + 3)orargv[3]. .
|
My IT teacher said that when space is allocated for a constant in C and C ++ only the STRICTLY necessary space is allocated: he said that if we store the value 12 in a constant, for example, only 4 bits of memory will be allocated. I believe this is not true, both because the memory is almost always divided into 8-bit "cells", and because when we declare a constant we also indicate its type, so we decide how much memory to dedicate to it. Any expert opinion?
PS: He was talking about constants declared with theconstqualifier.
|
Of course your IT teacher is wrong. The size depends on thetypeof the const value. But you must also remember that any objects can be removed by the optimizing compiler if the they are not needed.
|
I wanted to know how this function returns 4 which is the correct answer, when it resets theresvariable every time the function calls itself.num = 2367319
```
int func(int num)
{
int res = 0;
if (num > 0)
res = (num % 10 % 3 == 0 ? 1 : 0) + func(num / 10);
return res;
}
```
|
resisn't "reset". Rather a new local variable namedresis created for each recursive call.
I suggest you add someprintf()statements in order to see how this function works.
|
Will this code give a Buffer overflow crash?
```
#include <stdio.h>
void show(char text[2]) {
printf("%c%c\n", text[0], text[1]);
return;
}
int main() {
char *txt = "aabc";
show (txt);
return 0;
}
```
I meantxthas 4 characters (plus'\0'), while text has only 2.
|
Arrays are passed in C by reference, this means when a function accepts an array as an argument it does not get a copy of that array, but rather a pointer to it.
So in your casechar text[2]is not a new copy oftxtin main, but rather a pointer to it. Thus you will not get an overflow as you are not trying to copy the contents oftxtintochar text[2],textjust points to it.
For example the output of the following is13
```
void test(char a[2]){
printf("%d", strlen(a));
}
int main(){
char* text = "Hello World!\n";
test(text);
}
```
|
This question already has answers here:What is "..." in switch-case in C code(4 answers)Closed3 years ago.
I was going through the latest code in the Linux kernel, when I found aswitchwritten differently.
```
kernel/drivers/net/ethernet/intel/e1000/e1000_main.c Line number 3524
```
As per my C knowledge,switch/caseneeds to be written as
```
case e1000_undefined: // enum value as 0
case e1000_82542_rev2_0: // enum value as 1
case e1000_82542_rev2_1: // enum value as 2
// code
```
But in kernel code I found it like this:
```
case e1000_undefined ... e1000_82542_rev2_1:
// code
```
Is this C18 coding style for C?
Can someone point me a resource (book/GNU man pages) to understand more about C18?
|
Case ranges are aGCC extension for C.
|
I want to have a program with specific arguments of different types. For example I start my program like this:
```
./program picture.jpg image.jpg
./program picture.ppm image.jpg
```
Now I want my program to recognize the different extensions,jpgvsppm. How can I easily do it? I tried:
```
if (argv[1][-3] == j)
{
//do something
}
...
```
But this is not working and I can't find any reply on my question on internet (probably, because I am asking badly...).
btw. I am python programmer and I am learning c...
|
You should
Check the count of argument fromargc.Loop over each command line argument by usingargv[i], whereiis from1toargc-1.make use ofstrstr()to check if the.jpgor.ppmis present in any of the strings pointer to byargv[i].
|
This question already has answers here:Is floating point math broken?(33 answers)Closed3 years ago.
```
double a = 1E100
printf("%f", a);
```
It seems to be printing a different value other than 1 followed by a 100 zeros:
```
10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104
```
What might be the problem here?
|
Thedoubletype, assuming it uses IEEE 754 double precision floating point representation, only holds about 16 decimal digits of precision.
So any decimal digits after that will only be an approximate value, i.e. the closest value to1E100that itcanrepresent.
|
I've been trying to setup an kernel module to later fake a GPS within a program, in order to simulate communication with gpsd which uses a fixed path. But right now I'm stuck due to gpsd checking if there's more than one link to the file in /proc//fd before starting reading/writing.
Is there a way to exclude the link from this directory but still be able to read/write to file from my gpsfake? Or bypass this fd tracking altogether from the module?
|
/proc/<pid>/is afilesystem-likeview on the process<pid>, exposed by the kernel.
As such, theonlyway to remove/add/change anything within this directory is by changing the process itself (in your case: make the process close the offending file-descriptor to have the corresponding symlink go away).
Theotherway is to patch the kernel, but you probably don't want to do this.
|
Is there any way to get freetype man pages?
I can't find them and have to use the documentation on the web.
The problem is when I don't have internet access.
|
Freetype doesn't provide man pages. Only html documentation.
You can download it fromhere(see the archives that have "-doc" in their name).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.