question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I am trying to read in a .csv file (output from Excel) in C. I assumed the file would only be text values, but I have found 3 characters at the beginning of the file. They are (unsigned char): 239, 187, 191.
Since I am not expecting these values, my reader gets confused and causes problems. But I have not been able to find documentation. I saved the file as a UTF-8 .csv file from Excel.
|
The UTF-8 representation of the BOM (byte order mark) is the (hexadecimal) byte sequence 0xEF,0xBB,0xBF. These may be displayed as the characters .
In decimal, these values are 239, 187, and 191 as shown above.
|
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.Closed5 years ago.Improve this question
I would like to know if there is a difference in performance between :
```
while(true)
{
.....
}
```
And :
```
bool x;
x = true;
while(x)
{
.....
}
```
I need the best performance and a small difference between the two is important to my application.
Info from comment by OP:Thewhile(true)will at some point also be left, that is however rare.
|
If you need a truly endless loop, then why use a condition?If you need a loop which can be left, then yourwhile(true){...}will contain anif(!x)which yourwhile(x)does not contain.Any potential optimisation benefit ofwhile(true)overwhile(x)will be lost at that point.
|
I am trying to read in a .csv file (output from Excel) in C. I assumed the file would only be text values, but I have found 3 characters at the beginning of the file. They are (unsigned char): 239, 187, 191.
Since I am not expecting these values, my reader gets confused and causes problems. But I have not been able to find documentation. I saved the file as a UTF-8 .csv file from Excel.
|
The UTF-8 representation of the BOM (byte order mark) is the (hexadecimal) byte sequence 0xEF,0xBB,0xBF. These may be displayed as the characters .
In decimal, these values are 239, 187, and 191 as shown above.
|
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.Closed5 years ago.Improve this question
I would like to know if there is a difference in performance between :
```
while(true)
{
.....
}
```
And :
```
bool x;
x = true;
while(x)
{
.....
}
```
I need the best performance and a small difference between the two is important to my application.
Info from comment by OP:Thewhile(true)will at some point also be left, that is however rare.
|
If you need a truly endless loop, then why use a condition?If you need a loop which can be left, then yourwhile(true){...}will contain anif(!x)which yourwhile(x)does not contain.Any potential optimisation benefit ofwhile(true)overwhile(x)will be lost at that point.
|
I'm wrapping a C struct in a Ruby C extension but I can't find the differente between Data_Wrap_Struct and TypedData_Wrap_Struct in the docs, what's the difference between the two functions?
|
It's described pretty well in theofficial documentation.
The tl;dr is thatData_Wrap_Structis deprecated and just lets you set the class and the mark/free functions for the wrapped data.TypedData_Wrap_Structinstead lets you set the class and then takes a pointer to arb_data_type_structstructure that allows for more advanced options to be set for the wrapping:
the mark/free functions as before, but alsoan internal label to identify the wrapped typea function for calculating memory consumptionarbitrary data (basically letting you wrap data at a class level)additional flags for garbage collection optimization
Check myunofficial documentationfor a couple examples of how this is used.
|
I need to add same values on array and then to see it as one string.
```
char txt[33] = "";
for (int i=0; i<4; i++)
{
txt[i]="A";
}
LCDPutStr(txt,25);
```
I get4characters but they are strange symbols. I need to take"AAAA".
|
1) use'A', single quote, in stead of the double quote;
2) terminate the string with a'\0':text[i]= '\0';
Summary:
```
char txt[33] = "";
int i;
for (i=0; i<4; i++)
{
txt[i]='A';
}
txt[i]='\0';
LCDPutStr(txt,25);
```
(I movedint ito before the loop so it is available afer the loop to put the terminator there.)
|
I declare a constructor inconstructor.hand define it inconstructor.c.I will show both files:
constructor.h
```
void begin(void) __attribute__((constructor));
```
constructor.c
```
void begin(void) {
printf("INIT");
}
```
My main.c, which has code which uses the function, is including constructor.h.
Previously I defined and declaredbeginin the same .h file and that worked fine.Now I try to separate code, declare in .h and define in .c, and it is not working anymore.
Why could that be?
|
To make the compiler be aware of the content of the header while compiling the .c file, you need to include the header in the code file.
```
#include "constructor.h"
/* ... */
```
Also you should implement the function as declared:
```
/* ... */
void begin(void) __attribute__((constructor)) {
printf("INIT");
}
```
|
I'm wrapping a C struct in a Ruby C extension but I can't find the differente between Data_Wrap_Struct and TypedData_Wrap_Struct in the docs, what's the difference between the two functions?
|
It's described pretty well in theofficial documentation.
The tl;dr is thatData_Wrap_Structis deprecated and just lets you set the class and the mark/free functions for the wrapped data.TypedData_Wrap_Structinstead lets you set the class and then takes a pointer to arb_data_type_structstructure that allows for more advanced options to be set for the wrapping:
the mark/free functions as before, but alsoan internal label to identify the wrapped typea function for calculating memory consumptionarbitrary data (basically letting you wrap data at a class level)additional flags for garbage collection optimization
Check myunofficial documentationfor a couple examples of how this is used.
|
I need to add same values on array and then to see it as one string.
```
char txt[33] = "";
for (int i=0; i<4; i++)
{
txt[i]="A";
}
LCDPutStr(txt,25);
```
I get4characters but they are strange symbols. I need to take"AAAA".
|
1) use'A', single quote, in stead of the double quote;
2) terminate the string with a'\0':text[i]= '\0';
Summary:
```
char txt[33] = "";
int i;
for (i=0; i<4; i++)
{
txt[i]='A';
}
txt[i]='\0';
LCDPutStr(txt,25);
```
(I movedint ito before the loop so it is available afer the loop to put the terminator there.)
|
With the .NET Framework we can retrieve the received and sent bytes with the following functions.
```
NetworkInterface.GetIPv4Statistics().BytesReceived
NetworkInterface.GetIPv4Statistics().BytesSent
```
But i cannot find the alternative in native C. The closest i found was theGetIpStatistics. However this seems to be global instead of per interface.
Can anyone point me into the right direction?
|
Allthough we can all furiously debate what the correct terminology is, I think you can find what you seek by calling theGetIfTablefunction.
This will return aMIB_IFTABLEstruct, which in turn hasMIB_IFROWelements that contain the data you're looking for for the various network interfaces on your machine.
|
Error while trying to assign a value to a string from another matrix of strings.
```
last_command = buttonValues[i][j];
```
Solved by using :
```
strcpy (last_command, buttonValues[i][j]);
```
since you can't do that in C apparently.
|
The problem was in the line above
```
last_command = buttonValues[i][j];
```
and I thought it's in this line
```
g_signal_connect(G_OBJECT(buttons[i][j]), "clicked", G_CALLBACK(solve_button_callback), 0);
```
I had this bad c# habit of assigning strings directly :D
solved it by using this: (duh)
```
strcpy (last_command, buttonValues[i][j]);
```
Sorry for the tedious question and thanks everyone for the help.
|
I am assigned to implement a new programming language in lex and yacc. Below are some of my yacc code, it should print error and the line error occurs
```
//rest of the code
%%
#include "lex.yy.c"
extern int line_num;
main() {
return yyparse();
}
void yyerror( char *s )
{
fprintf(stderr,"Syntax Error in line: %d\n%s\n",line_num, s);
}
```
The compiler gives the following error message:
```
/tmp/cclW8fn4.o: In function `yyerror':
y.tab.c:(.text+0x200f): undefined reference to `line_num'
collect2: error: ld returned 1 exit status
make: *** [all] Error 1
```
How to fix it?
|
As it was discussed in the commentsextern int line_num;just declaresline_num, which has to exist in another file.
Therefore the problem was solved whenint line_numwas declared in the lex file:
```
%{
int line_num = 1;
%}
```
|
Very simply, is the following code safe/portable?
```
#include <stdio.h>
#include <stdlib.h>
int add(int *a, int *b)
{
return *a + *b;
}
int main()
{
int x = 2;
int y = 3;
void *ptr1 = &x;
void *ptr2 = &y;
fprintf(stdout, "%d + %d = %d\n", x, y, add(ptr1, ptr2));
return EXIT_SUCCESS;
}
```
I've compiled this with-Wall -Werrorand-Wextraand received no warnings; it seems to run fine.
|
There's two things to consider:
C allows the implicit conversion from a void pointer to any other object pointer type. So it's syntactically okay to pass those arguments.The type of the actual object being pointed to, and the type of the pointer the function expects, must satisfystrict aliasingconstraints, otherwise your program is in undefined behavior land.
You are okay on both points. So your program is perfectly fine.
|
Context:
I currently want to flush my L1 DATA cache (target: NXP P2020 Qoriq e500).
I have an issue while using "dcbf" instruction:
```
dcbf r3, r4 // with r3 and r4 defining the address of the DATA cache
```
Issue:My problem is that I don't know what parameter to give to this instruction to reach the DATA cache and flush the line ?
I tried with a "just created" variable :
```
int i = 0;
// let assume r3 = &i
dcbf 0, r3
isync
msync
```
I thougth that the dcbf instruction will reach the data cache via &i parameter, but when I futher look into the memory via a probe, I see the cache as not flushed and not invalidated.
|
My fundamental issue was that the address given to dcbf was not in cache.The reference manual says:Perform reads to any 48 Kbyte region, THEN execute dcbf instruction.
I now am searching how to read the L1 data cache
|
I'm trying to print a number in binary with these two approaches:
Approach 1:
```
int input;
scanf("%d", &input);
for(int i = sizeof(int)*CHAR_BIT - 1; i >= 0; i--)
printf("%u",(input & (1<<i)) >> i);
```
Approach 2:
```
int input;
scanf("%d", &input);
for(int i = sizeof(int)*CHAR_BIT - 1; i >= 0; i--)
(input & (1<<i)) ? putchar('1') : putchar('0');
```
Approach 2 works fine but in Approach 1 the first "digit" that is printed is 4294967295 and I can't find the error.
|
It doesn't make sense to use signed numbers for bit shifts. When you shift data into the sign bit of theint, you invoke undefined behavior. Also be aware that the1literal is of typeint.
Solve this by using unsigned types and get rid of the na(t)ive C types at the same time, in favour for stdint.h.
```
uint32_t input = 0x88776655;
for(uint32_t i=0; i<32; i++)
{
printf("%u", (input & (1u<<31-i)) >> 31-i);
}
```
|
I am trying to demonstrate a buffer overflow, and I wish to overwrite a local varible withgets. I have compiled my program using gcc with-fno-stack-protector, so I know that the buffer thatgetsuses is right next to another local variable I am trying to overwrite. My goal is to overflow the buffer and overwrite the adjacent variable so that both of them have the same string. However, I noticed that I need to be able to input the'\0'character so that strcmp will actually show that both are equal. How can I input'\0'?
|
On many keyboards, you can enter a NUL character withctrl@(might bectrlshift2orctrlalt2).
Barring that, you can create a file with a NUL byte and redirect that as stdin.
|
So I have this program that takes in PID input and a character.
```
$ ./transmit 1111 a
```
My question is. If it were
```
$ ./transmit 111a x
```
since PID are all numbers I'd need to catch that.
given:
```
char *a[] = {"./transmit", "111a", "x"};
```
how would I check if "111a" is numeric only? isdigit only works if it's a character. Do I have to loop through the entire input?
|
```
char *err;
unsigned long pid = strtoul(argv[1], &err, 10);
if (*err || err == argv[1])
error();
if ((pid_t)pid != pid || (pid_t)pid <= 0)
error();
```
When you are really pedantic, you can check forULONG_MAXanderrno == ERANGEtoo, but becausepid_tis smaller thanunsigned long, this will be catched by the second check already.
|
Mac OSX 10.13.3.
System leaks utility shows 4(two 2048 and two 16) leaks in next code:
```
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int st;
if (fork())
wait(&st);
else
while (1);
}
```
Why?
|
many of the C library functions will cause a 'leak' checker to flag a memory leak.
So a 'leak' checker needs to be told to NOT check the C library functions.
Other than the above, there is no memory leak in the posted code.
|
This question already has answers here:C function syntax, parameter types declared after parameter list(7 answers)Closed5 years ago.
Reading a document which is dated 1988, I found amain()function starting in this way:
```
main(argc, argv)
char *argv[];
{
//some statements...
}
```
Surprisingly, I noticed there is no return type and even no data type for the arguments of the function - except forargv[]that is declared once more on the second line of the code.Taking these considerations into account, my questions are: is that a valid syntax? If yes, why C language syntax is a bit different, nowadays?
|
That's the original, pre-1989 "K&R" function syntax. The return type (and even the parameter types) defaulted to int, and the parentheses contained only the names of the parameters, with their fully-typed declarations (if necessary) appearing before the first{.
|
quick question, porting my 15k line framework to UTF16 :)
do i manipulate single wchar_t's like this?
```
wchar_t Help[128];
Help[0] = '?'
Help[1] = '/0'
```
or
```
wchar_t Help[128];
Help[0] = L'?'
Help[1] = L'/0'
```
|
You should not assign achardirectly to awchar_twithout a type-cast, otherwise the compile is likely to issue a warning about data loss.
If you don't prefix a character literal, it will have typechar, soHelp[0] = '?'will not compile.
If you prefix a character literal withL, it will have typewchar_tinstead, soHelp[0] = L'?'will compile.
Note thatwchar_tis not 16bit on all platforms. It is on Windows, but on many other platforms, it is 32bit instead, so would be used for UTF-32 and not UTF-16. If you want to use UTF-16 on all platforms, you should usechar16_tand theuliteral prefix, which were introduced in C11:
```
char16_t Help[128];
Help[0] = u'?';
Help[1] = u'\0';
```
|
Why is the space complexity of this functionn*mand notm*log(n)?
as in each function recursive, it takes(m*2^i)/2^i = mandigo from0tolog(n)so it has to bem*logn, what am I missing here?
```
void f3(int n, int m) {
double *p;
int i;
if (n <= 1)
return;
p = (double *)malloc(m * sizeof(double));
if (p == NULL)
return;
for (i = 0; i < n; i++)
if (i < m)
p[i] = i;
printf("%f ", p[0]);
free(p);
f3(n / 2, m * 2);
f3(n / 2, m * 2);
}
```
|
There is an (approximate) invariance in your recursion:
```
n * m = (n/2) * (m*2)
```
Thus when your recursion goes deeper,mgets larger and larger untiln = 1, wheremism*nat the beginning.
You memory allocation is only
```
p = (double*)malloc(m * sizeof(double));
```
And it'sfreeed before going to the next recursion. So the biggestmis the maximal space complexity, which isO(mn).
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question
I just started learning C. I am writing my code as follows:
```
#include <stdio.h>
#include <conio.h>
void main()
{
int i, s = 0;
clrscr();
for(i = 1 ; i <= 5 ; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
{
printf("%d\n", &i);
s = s + i;
}
}
printf("sum is: %d\n", &s);
getch();
}
```
But I am getting trouble in output, which is this:
|
The address operator&is unnecessary:
```
printf("%d\n", i);
printf("sum is: %d\n", s);
```
|
quick question, porting my 15k line framework to UTF16 :)
do i manipulate single wchar_t's like this?
```
wchar_t Help[128];
Help[0] = '?'
Help[1] = '/0'
```
or
```
wchar_t Help[128];
Help[0] = L'?'
Help[1] = L'/0'
```
|
You should not assign achardirectly to awchar_twithout a type-cast, otherwise the compile is likely to issue a warning about data loss.
If you don't prefix a character literal, it will have typechar, soHelp[0] = '?'will not compile.
If you prefix a character literal withL, it will have typewchar_tinstead, soHelp[0] = L'?'will compile.
Note thatwchar_tis not 16bit on all platforms. It is on Windows, but on many other platforms, it is 32bit instead, so would be used for UTF-32 and not UTF-16. If you want to use UTF-16 on all platforms, you should usechar16_tand theuliteral prefix, which were introduced in C11:
```
char16_t Help[128];
Help[0] = u'?';
Help[1] = u'\0';
```
|
Why is the space complexity of this functionn*mand notm*log(n)?
as in each function recursive, it takes(m*2^i)/2^i = mandigo from0tolog(n)so it has to bem*logn, what am I missing here?
```
void f3(int n, int m) {
double *p;
int i;
if (n <= 1)
return;
p = (double *)malloc(m * sizeof(double));
if (p == NULL)
return;
for (i = 0; i < n; i++)
if (i < m)
p[i] = i;
printf("%f ", p[0]);
free(p);
f3(n / 2, m * 2);
f3(n / 2, m * 2);
}
```
|
There is an (approximate) invariance in your recursion:
```
n * m = (n/2) * (m*2)
```
Thus when your recursion goes deeper,mgets larger and larger untiln = 1, wheremism*nat the beginning.
You memory allocation is only
```
p = (double*)malloc(m * sizeof(double));
```
And it'sfreeed before going to the next recursion. So the biggestmis the maximal space complexity, which isO(mn).
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question
I just started learning C. I am writing my code as follows:
```
#include <stdio.h>
#include <conio.h>
void main()
{
int i, s = 0;
clrscr();
for(i = 1 ; i <= 5 ; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
{
printf("%d\n", &i);
s = s + i;
}
}
printf("sum is: %d\n", &s);
getch();
}
```
But I am getting trouble in output, which is this:
|
The address operator&is unnecessary:
```
printf("%d\n", i);
printf("sum is: %d\n", s);
```
|
Code to receive message like "hi i am man" and convert it to upper case "HI I AM MAN".
```
n = read(newsockfd, buffer, 255);
printf("Here is the message: %s\n", buffer);
```
|
```
#include <stdio.h>
#include <ctype.h>
n = read(newsockfd, buffer, 255);
for(int i = 0; i < n; i++)
buffer[i] = toupper(buffer[i]);
printf("Here is the message: %s\n", buffer);
```
|
In the code below, I would like to have the value of myvar be provided by a program argument.
```
#include <stdio.h>
int main(int argc, const char **argv)
{
const unsigned char myvar[] = "myvalue";
return 0;
}
```
How would I get myvar to contain the value of the string from argv[1]?
|
If you are only reading, then you can simply copy the address ofargv[1]like this:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char **argv) {
const unsigned char *myvar = NULL;
// Be sure to check argc first
if (argc < 2) {
fprintf(stderr, "Not enough arguments.\n");
return EXIT_FAILURE;
}
myvar = (const unsigned char *)argv[1];
printf("myvar = %s\n", myvar);
}
```
If you want to changemyvarthen you should copy the string withstrncpyor alike.
|
Everytime i use this function to print in a file text. Even if i put \n after, it will place a space. I want to remove the space after it. How?
I want to print this: "List i :", not "List i : " but without blank space after ":".
```
for(i = 0; i < 5; i++)
{
fprintf(f, "%s %d\n %s\n", "List", i, ":");
}
```
|
On my computer, the output of the code you have shown is
```
List 0$
:$
List 1$
:$
List 2$
:$
List 3$
:$
List 4$
:$
```
I added dollar signs at the end of each line, so you can see that there are no trailing spaces. On the other hand. the colons are being printed on their own lines, not after the numbers. Is that maybe your actual problem and you didn't explain it quite right?
To get the output you said you wanted, either of these is supposed to work:
```
fprintf (f, "List %d:\n", i);
```
or
```
fprintf (f, "%s%d%s\n", "List", i, ":");
```
|
I need, for a course, to program a simple server that answer "Goodbye" when we tell him "Hello".
I tried to do that using netcat, but how can I make a script that listen to the client, test his answer, then print the "Goodbye" ?
I tried to do :
```
netcat -l -p 8080 -e bye
```
with bye.c :
```
int main(int argc, char ** argl){
char res[100] ;
while(1){
fgets(res, 100, stdin) ;
if(!strcasecmp(res, "Hello"))
{printf("Goodbye\n") ; return 0 ; } }
}
```
but it doesn't seem to work.
Can you help me ?
|
Just replace strcasecmp with strncmp(res, "Hello", 5) and it should work.
However, you have to avoid blocking of fgets "It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first."
|
I ran a matrix multiplication code serially and parallelized.There was no significant improvement with the parallel version.
```
dimension =4000;
//#pragma omp parallel for shared(A,B,C) private(i,j,k)
{
for(int i=0; i<dimension; i++){
for(int j=0; j<dimension; j++){
for(int k=0; k<dimension; k++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
```
Output:
time ./a.out
```
real 4m58,760s
user 4m58,706s
sys 0m0,036s
```
for serial code (I put the #pragma... in a comment,rest of code is same)
I got following output
```
real 4m51,240s
user 4m51,210s
sys 0m0,024s
```
|
You need to compile code with-fopenmpfor the pragma to work. Also, you don't need to comment the pragma to run without OpenMP, just don't compile with OpenMP.
With OpenMP:gcc -fopenmp -o a.out code.cWithout OpenMP:gcc -o a.out code.c
|
In the code below, I would like to have the value of myvar be provided by a program argument.
```
#include <stdio.h>
int main(int argc, const char **argv)
{
const unsigned char myvar[] = "myvalue";
return 0;
}
```
How would I get myvar to contain the value of the string from argv[1]?
|
If you are only reading, then you can simply copy the address ofargv[1]like this:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char **argv) {
const unsigned char *myvar = NULL;
// Be sure to check argc first
if (argc < 2) {
fprintf(stderr, "Not enough arguments.\n");
return EXIT_FAILURE;
}
myvar = (const unsigned char *)argv[1];
printf("myvar = %s\n", myvar);
}
```
If you want to changemyvarthen you should copy the string withstrncpyor alike.
|
Everytime i use this function to print in a file text. Even if i put \n after, it will place a space. I want to remove the space after it. How?
I want to print this: "List i :", not "List i : " but without blank space after ":".
```
for(i = 0; i < 5; i++)
{
fprintf(f, "%s %d\n %s\n", "List", i, ":");
}
```
|
On my computer, the output of the code you have shown is
```
List 0$
:$
List 1$
:$
List 2$
:$
List 3$
:$
List 4$
:$
```
I added dollar signs at the end of each line, so you can see that there are no trailing spaces. On the other hand. the colons are being printed on their own lines, not after the numbers. Is that maybe your actual problem and you didn't explain it quite right?
To get the output you said you wanted, either of these is supposed to work:
```
fprintf (f, "List %d:\n", i);
```
or
```
fprintf (f, "%s%d%s\n", "List", i, ":");
```
|
I need, for a course, to program a simple server that answer "Goodbye" when we tell him "Hello".
I tried to do that using netcat, but how can I make a script that listen to the client, test his answer, then print the "Goodbye" ?
I tried to do :
```
netcat -l -p 8080 -e bye
```
with bye.c :
```
int main(int argc, char ** argl){
char res[100] ;
while(1){
fgets(res, 100, stdin) ;
if(!strcasecmp(res, "Hello"))
{printf("Goodbye\n") ; return 0 ; } }
}
```
but it doesn't seem to work.
Can you help me ?
|
Just replace strcasecmp with strncmp(res, "Hello", 5) and it should work.
However, you have to avoid blocking of fgets "It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first."
|
I ran a matrix multiplication code serially and parallelized.There was no significant improvement with the parallel version.
```
dimension =4000;
//#pragma omp parallel for shared(A,B,C) private(i,j,k)
{
for(int i=0; i<dimension; i++){
for(int j=0; j<dimension; j++){
for(int k=0; k<dimension; k++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
```
Output:
time ./a.out
```
real 4m58,760s
user 4m58,706s
sys 0m0,036s
```
for serial code (I put the #pragma... in a comment,rest of code is same)
I got following output
```
real 4m51,240s
user 4m51,210s
sys 0m0,024s
```
|
You need to compile code with-fopenmpfor the pragma to work. Also, you don't need to comment the pragma to run without OpenMP, just don't compile with OpenMP.
With OpenMP:gcc -fopenmp -o a.out code.cWithout OpenMP:gcc -o a.out code.c
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question
I am using fgets to get a sentence from the user and i am trying to get words and count on c code then print it.
Exapmle: i want to count "Hello". When the program starts user write "Hello World Hello" and then the program prints "Hello used 2 times".
|
You could use thescanf-function to get text input from the user; the function will put it into achararray. (You would ask the user for the sentence as well as the word you are looking for)
Then you could use theKMP-algorithmto search for the given word in the sentence and just count the times the algorithm finds your word.
|
Using TCMalloc - given heap allocated object, is there any way to get the allocated size of the object (meaning only the size passed in malloc call)?
I'm asking for a "reliable" method (i.e, not going a word size back assuming the allocation size is stored before the pointer)
|
Since version 1.6, TCMallocincludes:
```
size_t tc_malloc_size(void*);
```
which returns the usable size of the allocation starting at the argument.
It is identical to the glibcmalloc_usable_size(or BSD'smalloc_size), andlibtcmallocincludes aliases for both of those functions.
However, it isnotnecessarily the originally requested size. It may be larger (and usually is). I don't believe that TCMalloc (or most other malloc implementations) retain that metadata, so there is (afaik) neither a reliable nor an unreliable mechanism to time travel back to the original malloc call and inspect the request size.
|
I was going through the kernel source code and I found this statement:
```
char *tagp = NULL;
/* ...CODE... */
tagp = &descriptor->b_data[sizeof(journal_header_t)];
```
I wonderwhythis address is stored in a char pointer rather than any other type more related to what it represents, such as maybevoidif this is an opaque.
|
The individual cases may have their explicit use-cases, but in general, this is useful for two reasons.
acharpointer has the same alignment requirement as avoidpointer.charpointer can be used to access (via dereference) any other type of data, starting from lowest addressed byte of the object (Successive increments of the
result, up to the size of the object, yield pointers to the remaining bytes of the object.). Also, pointer arithmatic (if needed, is allowed oncharpointer, not onvoidpointers).
Thus, using achar *is more robust.
|
I saw once a usage of the macro__unusedwhich is explainedhere, but for some reason I can't find now where it is defined. Will appreciate help. I need it for an ansi C project. Thanks.
|
```
unused
```
is GCC specific6.32.1 Common Variable Attributes
This attribute, attached to a variable, means that the variable is meant to be possibly unused.GCCdoes not produce a warning for this variable.
NTERNATIONAL STANDARD ©ISO/IEC ISO/IEC 9899:201xdoes not even mentionunused.
|
```
#include <stdio.h>
#include <string.h>
int lsearch(char a[],int l,int h,char p)
{
int i=l;
for(i=l;i<=h;i++)
if(a[i]==p)
return i;
else
return 0;
}
int main()
{
int i,z;
char s[100];
scanf("%s",s);
char str[100];
scanf("%s",str);
z=lsearch(s,0,strlen(s)-1,str[1]);
printf("%d",z);
}
```
I want to search an element of the string str in the string s but when I'm trying to search anything(e.g. str[1]) in the string s, it returns 0
|
You need tocontinuethe loop when the element is not found. The function currently returns on first mismatch.
Something like:
```
...
for(i=l;i<=h;i++) {
if(a[i]==p) return i;
}
return -1;
}
```
Note that I changed to return-1on failure because0could also be the index where the char is found.
|
I try to access the bytes of a BIO with BUF_MEM.
But it is not working if it is a file-BIO.
```
BUF_MEM *bmmem = NULL, bmfil = NULL;
int ret = -1;
// OK for memory
BIO *biomem = BIO_new (BIO_s_mem ());
ret = BIO_get_mem_ptr (biomem, &bmmem); // ret = 1
printf ("\nbiomem - %d %d", ret, bmmem); // OK
// NOK for file
BIO *biofil = BIO_new (BIO_s_file ());
BIO_read_filename (biofil, "myfile.pem"); // ok
ret = BIO_get_mem_ptr (biofil, &bmfil); // ret = 0
printf ("\nbiofil - %d %d, ret, bmfil); // NOK
```
Do I miss something?
Thanks!
|
BIO_get_mem_ptrgives you a pointer into the underlying memory buffer of a mem bio. It only works with a mem BIO. In a file BIO there is no underlying memory buffer!
UseBIO_readto read data out of a BIO. That works on both a mem BIO and a file BIO.
https://www.openssl.org/docs/man1.1.0/crypto/BIO_read.html
|
If a "runtime error" happens in a script that is executed by perl_run() in an embedded perl instance on C (actually C++11), is there a more reasonable way other than to look for "Runtime error in..." at the stderr stream?
I'm using perl 5.26.1.
Thanks!
|
You can catch exceptions thrown by code executed bycall_*, so use the approach described inCalling a Perl subroutine from your C program, and refer toG_EVALinperlcall. Usedofrom within the called code to get Perl to execute a file.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question
I am using fgets to get a sentence from the user and i am trying to get words and count on c code then print it.
Exapmle: i want to count "Hello". When the program starts user write "Hello World Hello" and then the program prints "Hello used 2 times".
|
You could use thescanf-function to get text input from the user; the function will put it into achararray. (You would ask the user for the sentence as well as the word you are looking for)
Then you could use theKMP-algorithmto search for the given word in the sentence and just count the times the algorithm finds your word.
|
Using TCMalloc - given heap allocated object, is there any way to get the allocated size of the object (meaning only the size passed in malloc call)?
I'm asking for a "reliable" method (i.e, not going a word size back assuming the allocation size is stored before the pointer)
|
Since version 1.6, TCMallocincludes:
```
size_t tc_malloc_size(void*);
```
which returns the usable size of the allocation starting at the argument.
It is identical to the glibcmalloc_usable_size(or BSD'smalloc_size), andlibtcmallocincludes aliases for both of those functions.
However, it isnotnecessarily the originally requested size. It may be larger (and usually is). I don't believe that TCMalloc (or most other malloc implementations) retain that metadata, so there is (afaik) neither a reliable nor an unreliable mechanism to time travel back to the original malloc call and inspect the request size.
|
I was going through the kernel source code and I found this statement:
```
char *tagp = NULL;
/* ...CODE... */
tagp = &descriptor->b_data[sizeof(journal_header_t)];
```
I wonderwhythis address is stored in a char pointer rather than any other type more related to what it represents, such as maybevoidif this is an opaque.
|
The individual cases may have their explicit use-cases, but in general, this is useful for two reasons.
acharpointer has the same alignment requirement as avoidpointer.charpointer can be used to access (via dereference) any other type of data, starting from lowest addressed byte of the object (Successive increments of the
result, up to the size of the object, yield pointers to the remaining bytes of the object.). Also, pointer arithmatic (if needed, is allowed oncharpointer, not onvoidpointers).
Thus, using achar *is more robust.
|
I saw once a usage of the macro__unusedwhich is explainedhere, but for some reason I can't find now where it is defined. Will appreciate help. I need it for an ansi C project. Thanks.
|
```
unused
```
is GCC specific6.32.1 Common Variable Attributes
This attribute, attached to a variable, means that the variable is meant to be possibly unused.GCCdoes not produce a warning for this variable.
NTERNATIONAL STANDARD ©ISO/IEC ISO/IEC 9899:201xdoes not even mentionunused.
|
```
#include <stdio.h>
#include <string.h>
int lsearch(char a[],int l,int h,char p)
{
int i=l;
for(i=l;i<=h;i++)
if(a[i]==p)
return i;
else
return 0;
}
int main()
{
int i,z;
char s[100];
scanf("%s",s);
char str[100];
scanf("%s",str);
z=lsearch(s,0,strlen(s)-1,str[1]);
printf("%d",z);
}
```
I want to search an element of the string str in the string s but when I'm trying to search anything(e.g. str[1]) in the string s, it returns 0
|
You need tocontinuethe loop when the element is not found. The function currently returns on first mismatch.
Something like:
```
...
for(i=l;i<=h;i++) {
if(a[i]==p) return i;
}
return -1;
}
```
Note that I changed to return-1on failure because0could also be the index where the char is found.
|
I try to access the bytes of a BIO with BUF_MEM.
But it is not working if it is a file-BIO.
```
BUF_MEM *bmmem = NULL, bmfil = NULL;
int ret = -1;
// OK for memory
BIO *biomem = BIO_new (BIO_s_mem ());
ret = BIO_get_mem_ptr (biomem, &bmmem); // ret = 1
printf ("\nbiomem - %d %d", ret, bmmem); // OK
// NOK for file
BIO *biofil = BIO_new (BIO_s_file ());
BIO_read_filename (biofil, "myfile.pem"); // ok
ret = BIO_get_mem_ptr (biofil, &bmfil); // ret = 0
printf ("\nbiofil - %d %d, ret, bmfil); // NOK
```
Do I miss something?
Thanks!
|
BIO_get_mem_ptrgives you a pointer into the underlying memory buffer of a mem bio. It only works with a mem BIO. In a file BIO there is no underlying memory buffer!
UseBIO_readto read data out of a BIO. That works on both a mem BIO and a file BIO.
https://www.openssl.org/docs/man1.1.0/crypto/BIO_read.html
|
If a "runtime error" happens in a script that is executed by perl_run() in an embedded perl instance on C (actually C++11), is there a more reasonable way other than to look for "Runtime error in..." at the stderr stream?
I'm using perl 5.26.1.
Thanks!
|
You can catch exceptions thrown by code executed bycall_*, so use the approach described inCalling a Perl subroutine from your C program, and refer toG_EVALinperlcall. Usedofrom within the called code to get Perl to execute a file.
|
I try to access the bytes of a BIO with BUF_MEM.
But it is not working if it is a file-BIO.
```
BUF_MEM *bmmem = NULL, bmfil = NULL;
int ret = -1;
// OK for memory
BIO *biomem = BIO_new (BIO_s_mem ());
ret = BIO_get_mem_ptr (biomem, &bmmem); // ret = 1
printf ("\nbiomem - %d %d", ret, bmmem); // OK
// NOK for file
BIO *biofil = BIO_new (BIO_s_file ());
BIO_read_filename (biofil, "myfile.pem"); // ok
ret = BIO_get_mem_ptr (biofil, &bmfil); // ret = 0
printf ("\nbiofil - %d %d, ret, bmfil); // NOK
```
Do I miss something?
Thanks!
|
BIO_get_mem_ptrgives you a pointer into the underlying memory buffer of a mem bio. It only works with a mem BIO. In a file BIO there is no underlying memory buffer!
UseBIO_readto read data out of a BIO. That works on both a mem BIO and a file BIO.
https://www.openssl.org/docs/man1.1.0/crypto/BIO_read.html
|
If a "runtime error" happens in a script that is executed by perl_run() in an embedded perl instance on C (actually C++11), is there a more reasonable way other than to look for "Runtime error in..." at the stderr stream?
I'm using perl 5.26.1.
Thanks!
|
You can catch exceptions thrown by code executed bycall_*, so use the approach described inCalling a Perl subroutine from your C program, and refer toG_EVALinperlcall. Usedofrom within the called code to get Perl to execute a file.
|
When the server receives a termination signal it exits from the loop where the select() is monitoring the fds in the set (fd_set).
It is necessary look through fds and call shutdown(fd, SHUT_RDWR) if there are any of them still in the set? Or should I call close(fd)?
|
It's not necessary to callshutdown()beforeclose(). When you close a socket, it's automatically shut down in both directions.
You generally only need to useshutdown()if you need to keep the socket open for some reason. This might be done in a protocol where the end of the request is indicated by EOF; you callshutdown(fd, SHUT_WR)to send EOF, then read the response.
|
trying to wrap struct the reference it's definition as below
foo.c
```
typedef struct Foo {
struct Foo *foo;
} Foo;
```
how to model that, for example
foo.py
```
class Foo(Structure):
_fields_ = [('foo', pointer(Foo))]
```
of course python doesn't interpret that, I could use c_void_p instead of pointer(Foo), and cast it's value as follow
```
F = clib.get_foo()
cast(F.foo, pointer(Foo)) #although i'm not sure if it would work
```
but, is there a way to model that struct in a python class?
|
From[Python.Docs]: ctypes - Incomplete Types:
... . Inctypes, we can define thecellclass and and set the_fields_attribute later, after the class statement.
Applying that to the current problem, the code would looksmthlike:
```
import ctypes as ct
class Foo(ct.Structure):
pass
Foo._fields_ = (
("foo_ptr", ct.POINTER(Foo)),
)
```
|
```
char ch = 1107;
printf("ch = %c", ch);
```
Above code prints S.
I do not get how this happens. I am giving an out of range value for char type. How compiler gets this value "S" (ASCII 83)?
|
If 1107 is too big to fit into achar(it usually is but acharmight be larger than 8 bits), andcharisunsigned, then 1107 is converted to acharwith the normal wrap-around behaviour. Ifcharissignedthen the conversion is implementation-defined and an implementation-defined signal might be raised.
After thischis widened to anintas it's passed on the variable argument list.
Internally, insideprintf, thatintis converted to anunsigned char, with normalwrap-aroundrules applying.
|
I have a struct containing a bunch of char pointers whose values are used throughout the program's lifetime. Most are overwritten every iteration.
Should these values be freed at any point besides program exit? Should the value in the char pointer be freed before overwriting it withstrdup("new value")?
|
@some-programmer-dude is right, there will be memory leak without free if your program works like a server.
BTW, all memory will be released after the program exited no matter whether you call free() or not.
|
I have a struct containing a bunch of char pointers whose values are used throughout the program's lifetime. Most are overwritten every iteration.
Should these values be freed at any point besides program exit? Should the value in the char pointer be freed before overwriting it withstrdup("new value")?
|
@some-programmer-dude is right, there will be memory leak without free if your program works like a server.
BTW, all memory will be released after the program exited no matter whether you call free() or not.
|
```
void mystery2 (int n)
{
int i;
for (i = 1; i <= n; i++) {
double x = i;
double delta = 1 / (double)i;
while ( x > 0 )
x -= delta;
}
return 0;
}
```
Why is the BIG O, The time complexity of this function is O(n^3) and not O(n^2)?
What I done is when i=1 ==> 1 iterations, i=2 ==> 2iterations(in while) i=3 ==> 3 iteration ........ i=n ==> n iteration, if we sum all the iterations we get 1+2+3+4....+n = n*(n+1)/2. so what I missing here?
|
This is because inner loop runs like this.
```
For i=1, inner loop runs 1 time,
For i=2, inner loop runs 4 time,
//because x=2 and delta=0.5 so for x to become 0 it has to iterate 4 time
For i=3, inner loop runs 9 time
//because x=3 and delta=0.33 so for x to become 0 it has to iterate 9(atleast) time
and so on..
```
So inner loop runi^2time and the equation becomes1^2+2^2+3^2+...+n^2=n(n+1)(2n+1)/6which is equal to O(n^3) complexity.
|
The problem is as follows. I have a void pointer and I want to allocate string array with that. Is it possible to cast void* to char** like this:
```
void* ptr = (char**)calloc(size, sizeof(char*))
```
and then allocate each row of that table? I'm currently running out of ideas.
|
Psuedo Code that should get you what you need.
```
char **ptr = NULL;
// Allocates an array of pointers
ptr = malloc(sizeof(char *) * (NUM_OF_STRINGS_IN_ARRAY));
If (ptr == NULL)
return; // Do error handling here
for (int i =0; i < NUM_OF_STRINGS_IN_ARRAY; i++)
{
// Allocates each string in the array.
ptr[i] = malloc(strlen(STRING));
if (ptr[i] == NULL)
{
return; // Do error handling here
}
}
```
|
I'm trying to 'scanf' two dimensional array from arr[1][1]
first,
```
for(int i=1;i<=n;i++){
scanf("%s",arr[i]);
}
```
If I write a code like above,
contents start from[1][0]~[n][0].
But I want to start from[1][1].
I think
```
for(i=1;i<=n;i++) for(j=1;j<=n;j++)
scanf(" %c", &arr[i][j]);
```
is possible, but, is there any efficient way?
I tried...
```
for(i=1;i<=n;i++)
scanf("%s",(&arr[i][0]+1))
// or scanf("%s",&(*arr[i]+1)) //compile error..
```
but it failed.
|
Firstly @WhozCraig comment is correct, you should try to use zero base indices because otherwise you're wasting memory and making it harder to code in general.
Other than that your example with the two loops is the only way to do it and there is no more efficient way, if you want to read into the whole array you'll need to traverse it all.
|
Islong == signed long(int,char, etc)?
Is this guaranteed by the specification or is there some obscure version or compiler that will blow up if I take this for granted.
|
Yes for all the types you list, other thanchar.
charis signed or unsigned in an implementation defined manner. Furthermore,charis an entirely distinct type fromsinged charandunsigned char, even though it will have the exact same properties as one of them.
You may think I'm talking crazy here, but here it is straight from the C standard:
6.2.5 Types - p15
The three types char, signed char, and unsigned char are collectively
called the character types. The implementation shall define char to
have the same range, representation, and behavior as either signed
char or unsigned char.
|
The problem is as follows. I have a void pointer and I want to allocate string array with that. Is it possible to cast void* to char** like this:
```
void* ptr = (char**)calloc(size, sizeof(char*))
```
and then allocate each row of that table? I'm currently running out of ideas.
|
Psuedo Code that should get you what you need.
```
char **ptr = NULL;
// Allocates an array of pointers
ptr = malloc(sizeof(char *) * (NUM_OF_STRINGS_IN_ARRAY));
If (ptr == NULL)
return; // Do error handling here
for (int i =0; i < NUM_OF_STRINGS_IN_ARRAY; i++)
{
// Allocates each string in the array.
ptr[i] = malloc(strlen(STRING));
if (ptr[i] == NULL)
{
return; // Do error handling here
}
}
```
|
I'm trying to 'scanf' two dimensional array from arr[1][1]
first,
```
for(int i=1;i<=n;i++){
scanf("%s",arr[i]);
}
```
If I write a code like above,
contents start from[1][0]~[n][0].
But I want to start from[1][1].
I think
```
for(i=1;i<=n;i++) for(j=1;j<=n;j++)
scanf(" %c", &arr[i][j]);
```
is possible, but, is there any efficient way?
I tried...
```
for(i=1;i<=n;i++)
scanf("%s",(&arr[i][0]+1))
// or scanf("%s",&(*arr[i]+1)) //compile error..
```
but it failed.
|
Firstly @WhozCraig comment is correct, you should try to use zero base indices because otherwise you're wasting memory and making it harder to code in general.
Other than that your example with the two loops is the only way to do it and there is no more efficient way, if you want to read into the whole array you'll need to traverse it all.
|
Islong == signed long(int,char, etc)?
Is this guaranteed by the specification or is there some obscure version or compiler that will blow up if I take this for granted.
|
Yes for all the types you list, other thanchar.
charis signed or unsigned in an implementation defined manner. Furthermore,charis an entirely distinct type fromsinged charandunsigned char, even though it will have the exact same properties as one of them.
You may think I'm talking crazy here, but here it is straight from the C standard:
6.2.5 Types - p15
The three types char, signed char, and unsigned char are collectively
called the character types. The implementation shall define char to
have the same range, representation, and behavior as either signed
char or unsigned char.
|
I am a little bit newbie, and pointers still do troubles to me. I would like to change value ofint, which I get from parameter (as a pointer) in function.
```
#include <stdio.h>
bool function(int* a){
a++;
printf("%d",*a); //getting some big number, maybe address. If i did not use a++; I get just normal a, unchanged.
return false;
}
```
|
The problem is that you're incrementing the pointer (not the value pointed with it) in the statementa++. If you want to increment the value of the parameter, you should dereference it first:
```
(*a)++; //instead of a++;
```
Printf is not printing exactly an address, is just printing the value of the integer (may be an integer, can be something else) stored next to your parametera.
|
Lets say for example I want to print result 3 numbers after the dot.
I can just use the following code:
```
printf("%.3f",result);
```
I want to use it using the variable "precision" instead of writing 3
```
printf("%.precisionf");
```
how do i do that correctly
|
Use the somewhat forgotten".*"format:
```
printf("%.*f", precision, result);
```
whereprecisionis anint. Full program:
```
#include <stdio.h>
int main(void) {
double result = 1.234567;
int precision = 3;
printf("%.*f", precision, result);
}
```
Seehttps://ideone.com/WFimaU
|
According to Python documentation, implementing a class in C for Python can be roughly divided into three steps:
defining the Object (the data impl)defining the Type (the behavior wrapper)defining concrete behaviors, and set them into correspondingtp_xxslots
Fornewfunction,initfunction, instance members, attributes, and evendealloc, all of them can be found aslotinPyTypeObjectdeclaration, liketp_new,tp_init,tp_members,tp_methodsandtp_dealloc. But there is not a slot liketp_statics.
Where should I declare the static variables and where should I set them up? I searched for the internet but got nothing. Could anyone give me a clue about this?
|
Maybe you should check outthis question.
There is nostatickeyword in Python, class attributes are stored inclass.__dict__.
|
What doesstruct{...} x, y, z;mean in C programming language?
Related article:
Article
Could you please give examples about it.
```
struct {int a;} x, y;
int main()
{
x.a=0;
y.a=1;
return 0;
}
```
There is no error.
```
struct {...} x, y;
int main()
{
return 0;
}
```
but there is an error: expected specifier-qualifier-list before '...' token.
|
Well these are anonymous structures. And you are declaring those variablesx,yandzwhich are of that structure type. You can't pass it to other function though. So either you will keep these as global or static variables and use it accordingly. That's all you can do.
|
I'm trying to write code which is supposed to print all lines which have more then 5 characters, and I don't know where the problem is in my code. Can you help?
```
#include <stdio.h>
int main()
{
int i, s, n ;
char c, t[100];
n=0;
puts("start taping lines");
while(c=getchar()!=EOF)
{
s=0;
while(c!='/n')
{
++s;
}
if (s>=5){
t[n]=c ;
++n;
}
}
puts("lines >80 char =/n");
for(i=0;i<=n;++i)
{
printf("%s /n",t[i]);
}
return 0;
}
```
|
```
char *line;
if (strlen(line) >= 5)
printf(line);
```
Look for strlen() function in C library.
|
I am reading K&R. In an example it defines an array of structures as:
```
struct key {
char * word;
int count;
} keytab[] = {
"auto", 0,
"break", 0,
/*more members*/
"while", 0
};
```
Then to calculate the size of the array, it uses two approaches:
```
1) #define NKEYS (sizeof keytab/ sizeof(struct key))
2) #define NKEYS (sizeof keytab/ sizeof keytab[0])
```
Then it says that the second approach has the advantage that it does not need to be changed if the type changes. Can someone tell me the meaning of this last line? What advantage is being talked about here?
|
If in future you change thekeytabarray to be of a different type thanstruct key, then the first sizeof line has to be changed because the type was written there explicitly. The second sizeof line will remain working because it does not name the type, but takes whatever type of the array element is.
|
Graph500 has two implementations for generating graph using the kronecker graph generator:
Octave - This implementation generates a graph file which is in the form an edge list and is easily changed to a different format as a preprocessing step for performance evaluation or data analysis.c - This implementation generates two graph files, one for weights and one for edges but both in a bitmap format.
My question is regarding the c implementation. I am trying to reuse the graph in a different piece of code. I know how to reuse the graph in graph500's SSSP implementation by setting the environment variables of TMPFILE= and REUSEFILE=1, however, I am struggling to figure out a way to read it in some other program.
Please help..
|
You can usethisscript to convert the graph500 output binary to an edge list.
Usage:python graph500-binary-to-text.py "inputgraph500binary" "myoutput.txt"
|
What is the output of the following program?
```
#include<stdio.h>
void main()
{
printf("hello",printf("world"));
}
```
|
From the documentation forprintf:
If there are fewer arguments than required by format, the behavior is
undefined. If there are more arguments than required by format, the
extraneous arguments areevaluatedand ignored.
The output of the program is:
```
worldhello
```
The argument of the firstprintfis:printf("world")
Since the argument is a function, the function will be called producing word:
```
word
```
Then firstprintfwill printhello. Those prints together will give you:
```
worldhello
```
Try this:
```
#include<stdio.h>
int main(void)
{
printf(" hello! %d",printf("world"));
return 0;
}
```
Output:
```
world hello! 5
```
Ifprintfis successful the total number of characters written is returned. On failure, a negative number is returned.
|
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.Closed5 years ago.Improve this question
I wanna introduce info on a txt, and i have this:
```
int main(){
FILE * file;
file=fopen("viajes.txt", "w");
char select;
char dni[tm_dni];
printf("Introduce DNI:\n");
scanf("%s", dni);
fputs("DNI cliente:", file);
}
```
|
This:
```
fputs("DNI cliente:", file);
```
prints a static string to the file, which you then need to follow with the dynamic data:
```
fputs(dni, file);
```
You can also do:
```
fprintf(file, "DNI cliente: %s\n", dni);
```
You should of course also check that the various I/O calls (includingscanf()) succeed.
|
I am confused as to how to set the "editable" property to a specific child of a GtkTreeView, instead of the entire cell renderer.
```
| Column |
[+] Parent
|__ Child
|__ Child2 <-- Press to edit
```
I didn't seem to find a way to do that.
|
You add another boolean column to your ListStore. Then set your Renderer editable property to that extra column.
Sorry, I don't know the C code for a short example.
|
What is the output of the following program?
```
#include<stdio.h>
void main()
{
printf("hello",printf("world"));
}
```
|
From the documentation forprintf:
If there are fewer arguments than required by format, the behavior is
undefined. If there are more arguments than required by format, the
extraneous arguments areevaluatedand ignored.
The output of the program is:
```
worldhello
```
The argument of the firstprintfis:printf("world")
Since the argument is a function, the function will be called producing word:
```
word
```
Then firstprintfwill printhello. Those prints together will give you:
```
worldhello
```
Try this:
```
#include<stdio.h>
int main(void)
{
printf(" hello! %d",printf("world"));
return 0;
}
```
Output:
```
world hello! 5
```
Ifprintfis successful the total number of characters written is returned. On failure, a negative number is returned.
|
So I have the following structure:
```
typedef struct listElement
{
element value;
struct listElement;
} listElement, *List;
```
element is not a known type, meaning I don't know exactly what data type I'm dealing with, wether they're integers or or floats or strings.
The goal is to make a function that eletes the listElements that are redundant more than twice (meaning a value can only appear 0 times, once or twice, not more)
I've already made a function that uses bruteforce, with a nested loop, but that's a cluster**** as I'm dealing with a large number of elements in my list. (Going through every element and comparing it to the rest of the elements in the list)
I was wondering if there was a better solution that uses less isntructions and has a lower complexity.
|
You can use a hash table and map elements to their count.
if hashTable[element] (count for this particular element) returns 2, then delete the current element.
|
I am using printf but for some reason the cursor starts below the end of the previous line.
```
system("/bin/stty raw");
while(true){
char c = getchar();
printf("%c\n", c);
}
system ("/bin/stty cooked");
```
My output ends up looking like this.
```
Enter a value:
kk
kk
kk
kk
kk
kk
kk
kk
kk
kk
kk
kk
**
```
|
There is at least one environment which needs\r\ninstead of\nin some situations.
(In case this should survive for a long time, when the comments disappear, let me mention the recommendation from comments (credits to zwol), to use ncurses.)
|
I'm trying to create a window using GLFW on Ubuntu. I downloaded GLFW through anapt-getcommand and added it inBuild Options -> Linker Settings. However, when I try compiling the program it gives me an error saying
ld cannot find -lGLFW
I've searched the internet and I couldn't find what to do when this happens in Code::Blocks. What can I do to fix this problem?
I've read something like I need to add some options, but I don't know which ones and where exactly.
Note: I'm using GCC
|
Use-lglfw.
Library names are case-sensitive.-lGLFW!=-lgflw.
For instance:
On my Debian 9 systempkg-config --libs glfw3gives me:-lglfwAt:/usr/lib/x86_64-linux-gnu/libglfw.soAndpkg-config --libs glgives:-lGLCorresponding to:/usr/lib/x86_64-linux-gnu/libGL.so
|
im very new to programming, trying to learn C and cant figure out how to create/use a simple function.
Im trying to create a function called stringtest and then call it into the main and simply make the string strA print ABC.
```
void stringtest(char strA[20])
{
strA = "ABC";
}
int main()
{
char strA;
stringtest(strA[20]);
printf("This is strA", strA);
return 0;
}
```
|
You need to read up on pointers and the C syntax in general.
This is one way you could do it.
```
#include <stdio.h>
#include <string.h>
void stringtest(char *strA) {
strcpy(strA, "ABC");
}
int main(int argc, const char * argv[]) {
char strA[20];
stringtest(&strA[0]);
printf("This is strA -> %s \n", strA);
return 0;
}
```
Take care,
/Anders.
|
This question already has answers here:Got stuck with Segmentation Fault Error(2 answers)Closed5 years ago.
I am trying to read from a text file usingfscanf()and I am getting the output:
```
Process finished with exit code -1073741819 (0xC0000005)
```
The crash happens the first timefscanf()is called. here is my code:
```
int i=0;
FILE * trafficFile;
trafficFile = fopen("../trafficCount.txt","r");
if (trafficFile == NULL){
printf("Could not open traffic file\n");
}
int n = 30;
fscanf(trafficFile,"%d",n);
printf("%d",n);
for (i = 0; i < n; i++){
int temp = 0;
int temp2 = 0;
fscanf(trafficFile, "%d %d", temp, temp2);
printf("%d %d\n", temp, temp2);
}
fclose(trafficFile);
```
Any help is appreciated.
|
You need to pass in the address of the integer variables tofscanf()
```
fscanf(trafficFile, "%d", &n);
fscanf(trafficFile, "%d %d", &temp, &temp2);
```
|
for example.
mbtowc vs. mbstowcs (stdlib.h)
mbrtowc vs. mbsrtowc (wchar.h)
What is the difference between "sequence" and "string"?
In addition,
I'd like to know how to use mbstate_t of mbrtowc/mbsrtowc in an example.
|
In C, a "string" is defined as an array (possibly a subarray of a larger array) ofcharending with the null character. The multibytestringfunctions operate on strings, processing multibyte characters until they reach the end of the string (or run out of space in the destination buffer).
The multibyte character functions that operate on "sequences" of bytes (chars) convert only a single multibyte character at a time (or, in the case ofmbrtowc, possibly even less). There is no requirement that the inputchararray be a string.
|
In the following code segment, how many unique processes are created?
```
pid t pid;
pid = fork();
if (pid == 0) {
fork();
}
fork();
```
It seems that the answer is 6, based upon the process tree that I drew. Is my reasoning right?
|
Your reasoning is correct. There are 5 processes created from this code for a total of 6 processes including the original.
To verify, adding the following two lines after the above code:
```
printf("pid: %d, parent: %d\n", getpid(), getppid());
sleep(1);
```
Printed this on my machine (with comments added to match the pids with your tree:
```
pid: 2638, parent: 2498 // 1
pid: 2639, parent: 2638 // 2
pid: 2640, parent: 2638 // 4
pid: 2641, parent: 2639 // 3
pid: 2642, parent: 2639 // 5
pid: 2643, parent: 2641 // 6
```
|
This question already has answers here:Got stuck with Segmentation Fault Error(2 answers)Closed5 years ago.
I am trying to read from a text file usingfscanf()and I am getting the output:
```
Process finished with exit code -1073741819 (0xC0000005)
```
The crash happens the first timefscanf()is called. here is my code:
```
int i=0;
FILE * trafficFile;
trafficFile = fopen("../trafficCount.txt","r");
if (trafficFile == NULL){
printf("Could not open traffic file\n");
}
int n = 30;
fscanf(trafficFile,"%d",n);
printf("%d",n);
for (i = 0; i < n; i++){
int temp = 0;
int temp2 = 0;
fscanf(trafficFile, "%d %d", temp, temp2);
printf("%d %d\n", temp, temp2);
}
fclose(trafficFile);
```
Any help is appreciated.
|
You need to pass in the address of the integer variables tofscanf()
```
fscanf(trafficFile, "%d", &n);
fscanf(trafficFile, "%d %d", &temp, &temp2);
```
|
for example.
mbtowc vs. mbstowcs (stdlib.h)
mbrtowc vs. mbsrtowc (wchar.h)
What is the difference between "sequence" and "string"?
In addition,
I'd like to know how to use mbstate_t of mbrtowc/mbsrtowc in an example.
|
In C, a "string" is defined as an array (possibly a subarray of a larger array) ofcharending with the null character. The multibytestringfunctions operate on strings, processing multibyte characters until they reach the end of the string (or run out of space in the destination buffer).
The multibyte character functions that operate on "sequences" of bytes (chars) convert only a single multibyte character at a time (or, in the case ofmbrtowc, possibly even less). There is no requirement that the inputchararray be a string.
|
In the following code segment, how many unique processes are created?
```
pid t pid;
pid = fork();
if (pid == 0) {
fork();
}
fork();
```
It seems that the answer is 6, based upon the process tree that I drew. Is my reasoning right?
|
Your reasoning is correct. There are 5 processes created from this code for a total of 6 processes including the original.
To verify, adding the following two lines after the above code:
```
printf("pid: %d, parent: %d\n", getpid(), getppid());
sleep(1);
```
Printed this on my machine (with comments added to match the pids with your tree:
```
pid: 2638, parent: 2498 // 1
pid: 2639, parent: 2638 // 2
pid: 2640, parent: 2638 // 4
pid: 2641, parent: 2639 // 3
pid: 2642, parent: 2639 // 5
pid: 2643, parent: 2641 // 6
```
|
I have a 4 text-represented bytes that i need to divide into 2 bytes (HI and LO byte) and convert it to two integers.
How can i do that in plain C?
```
0x4b 0xab 0x14 0x9d
```
By text i mean that they look like "0x4b" not 0x4b.
I already have those string splited into char array, which represents like this:
```
item[0] = "0x4b";
item[1] = "0xab";
item[2] = "0x14";
item[3] = "0x9d";
```
Now the finish should look like this:
```
0x4b 0xab - one integer
0x14 0x9d - second integer
```
How to do this in Plain C?
|
You probbaly want this:
```
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *item[4];
item[0] = "0x4b";
item[1] = "0xab";
item[2] = "0x14";
item[3] = "0x9d";
int value1 = (strtol(item[0], NULL, 0) << 8) | strtol(item[1], NULL, 0);
int value2 = (strtol(item[2], NULL, 0) << 8) | strtol(item[3], NULL, 0);
printf("%x %x", value1, value2);
}
```
|
```
#include<stdio.h>
static int a=5;
main()
{
static int a=15;
printf("%d\n",a);
}
```
So, how are both variablesastored in internal memory?
How are global and local variables with the same variable names stored internally in memory?
|
```
#include<stdio.h>
static int a=5;
int main()
{
printf("%p\n",(void *)&a);
static int a=15;
printf("%p\n",(void *)&a);
return 0;
}
```
Output for the upper program is
```
0x564e6b67a030
0x564e6b67a034
```
So you can see that both are stored in different addresses. As one is a global variable and other is local.
|
The elements of an uninitialized char array in C all have the value 'Ì' (or -52 as an integer; 0xCC or 204 as char). Is this another type of null character? Or is it just a value that fills in the values of an uninitialized char array?
(In case it makes any difference, I am using visual studio)
|
Uninitialized variables have indeterminate values. They can make the behavior of your program undefined if the value is used to be a trap representation.
|
Can I integrate WireShark (as a command, or as system() command) into my C program in order to sniff all the received packets in my PC? I tried to use the NETCAT. but it doesn't work because the packets that I want to sniff are sent in an UDP multicast address: 224.1.1.113.
|
This tool seems to have what you want
http://www.netresec.com/?page=RawCap
Also, here is a reference to wireshark CLI
https://www.wireshark.org/docs/wsug_html_chunked/ChCustCommandLine.html
which has many options to do filtering so you can set it to the exact packet type you want. You could invoke this command.
Here is a wiki reference to a multicast filter
https://en.wikiversity.org/wiki/Wireshark/IPv4_multicastthat you could use.
|
```
#include<stdio.h>
static int a=5;
main()
{
static int a=15;
printf("%d\n",a);
}
```
So, how are both variablesastored in internal memory?
How are global and local variables with the same variable names stored internally in memory?
|
```
#include<stdio.h>
static int a=5;
int main()
{
printf("%p\n",(void *)&a);
static int a=15;
printf("%p\n",(void *)&a);
return 0;
}
```
Output for the upper program is
```
0x564e6b67a030
0x564e6b67a034
```
So you can see that both are stored in different addresses. As one is a global variable and other is local.
|
This question already has answers here:How do I return multiple values from a function in C?(8 answers)Closed5 years ago.
```
struct r() {
return 1, "hello";
}
int main() {
int x;
char y[100];
x, y = r(); // set x to int 1, and set y to "hello"
}
```
Is there anyway I can do this ? I believe this is possible in C
|
Yes, you can do this with structures, which may contain arbitrary data fields, as with the following complete program:
```
#include <stdio.h>
struct tPair {int one; int two;};
struct tPair returnPair(void) {
struct tPair plugh;
plugh.one = 7;
plugh.two = 42;
return plugh;
}
int main(void) {
struct tPair xyzzy = returnPair();
printf("Pair is %d, %d\n", xyzzy.one, xyzzy.two);
return 0;
}
```
If you compile and run that, you'll see:
```
Pair is 7, 42
```
|
When you call fsync on a file, you flush its buffer and make sure it gets written to disk.
But if your program newly creates a file, then that needs to get recorded in the metadata of the parent directory. Thus, even if youfsynca file, it's not guaranteed to be persistent in the file system yet. You need to flush the parent directory's buffer as well.
Is there a simple call, such asfsync_parent(fd)that'll accomplish this? If?
(Looking atthisquestion, it seems there's no C standard way to get the parent directory of a file)
|
There is no canonical "the parent directory" of a file. A file can have any number of links, or no links at all. If you needa particulardirectory containing (a link to) the file to be synchronized, you have to track that yourself.
|
This question already has answers here:How do I return multiple values from a function in C?(8 answers)Closed5 years ago.
```
struct r() {
return 1, "hello";
}
int main() {
int x;
char y[100];
x, y = r(); // set x to int 1, and set y to "hello"
}
```
Is there anyway I can do this ? I believe this is possible in C
|
Yes, you can do this with structures, which may contain arbitrary data fields, as with the following complete program:
```
#include <stdio.h>
struct tPair {int one; int two;};
struct tPair returnPair(void) {
struct tPair plugh;
plugh.one = 7;
plugh.two = 42;
return plugh;
}
int main(void) {
struct tPair xyzzy = returnPair();
printf("Pair is %d, %d\n", xyzzy.one, xyzzy.two);
return 0;
}
```
If you compile and run that, you'll see:
```
Pair is 7, 42
```
|
When you call fsync on a file, you flush its buffer and make sure it gets written to disk.
But if your program newly creates a file, then that needs to get recorded in the metadata of the parent directory. Thus, even if youfsynca file, it's not guaranteed to be persistent in the file system yet. You need to flush the parent directory's buffer as well.
Is there a simple call, such asfsync_parent(fd)that'll accomplish this? If?
(Looking atthisquestion, it seems there's no C standard way to get the parent directory of a file)
|
There is no canonical "the parent directory" of a file. A file can have any number of links, or no links at all. If you needa particulardirectory containing (a link to) the file to be synchronized, you have to track that yourself.
|
I use Visual Studio 2017 with ReSharper 2017.2 as the code editor for an embedded project. I managed to configure all but one thing:
How do I make VS/R# ignore that specific keyword,_Interrupt1? (this error causes other side effects).
I tried to add it as a preprocessor definition (Project's properties -> C/C++ -> Preprocessor -> Preprocessor Definitions), but it doesn't help.
|
I am not sure about R#, but in VS you could try to define globally:
```
#ifdef __INTELLISENSE__
#define _Interrupt1
#endif
```
to hide_Interrupt1from Intellisense parsing.
For completeness, thanks to @Hans Passant, use__RESHARPER__for RS
|
Is there a function like ctime that will get just the hours, minutes, and seconds as a char*?
I've tried
```
time_t time
struct tm* currtime = localtime(time);
printf("%d:%d:%d", currtime->tm_hour, currtime->tm_min, currtime->tm_sec);
```
but in the case of single digit values it'll print 8:2:5 instead of 08:02:05.
|
try the following:
```
`
struct timeval cur_time;
gettimeofday(&cur_time, NULL);
char dateTime[10 + 1] = {0};
strftime(dateTime, 10, "%H%M%S", localtime(&cur_time.tv_sec));
`
```
|
I use Visual Studio 2017 with ReSharper 2017.2 as the code editor for an embedded project. I managed to configure all but one thing:
How do I make VS/R# ignore that specific keyword,_Interrupt1? (this error causes other side effects).
I tried to add it as a preprocessor definition (Project's properties -> C/C++ -> Preprocessor -> Preprocessor Definitions), but it doesn't help.
|
I am not sure about R#, but in VS you could try to define globally:
```
#ifdef __INTELLISENSE__
#define _Interrupt1
#endif
```
to hide_Interrupt1from Intellisense parsing.
For completeness, thanks to @Hans Passant, use__RESHARPER__for RS
|
Is there a function like ctime that will get just the hours, minutes, and seconds as a char*?
I've tried
```
time_t time
struct tm* currtime = localtime(time);
printf("%d:%d:%d", currtime->tm_hour, currtime->tm_min, currtime->tm_sec);
```
but in the case of single digit values it'll print 8:2:5 instead of 08:02:05.
|
try the following:
```
`
struct timeval cur_time;
gettimeofday(&cur_time, NULL);
char dateTime[10 + 1] = {0};
strftime(dateTime, 10, "%H%M%S", localtime(&cur_time.tv_sec));
`
```
|
I am looking for theprintf(C) equivalent of thisC++output statement (cout):
```
cout << "Indices and values: " << i << " " << j << ":" <<A_ii <<" "<< A_jj << endl;
```
Herei,jare integers andA_ii,Ajjare decimals. Presently, I am trying this, but it doesn't seem to give the desired output inC.
printf("\nIndices and values: %d and %d : %d %d", i, j, A_ii, A_jj);
What am I doing wrong here?
|
You almost have it right, you are just using the int%dformat token for your decimals. Try%finstead.
```
printf("\nIndices and values: %d and %d : %f %f", i, j, A_ii, A_jj);
```
|
I'm looking in theebpfverifier code, and I can't get my head around the following macros:
```
#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE *)0)->MEMBER)
#define offsetofend(TYPE, MEMBER) \
(offsetof(TYPE, MEMBER) + sizeof(((TYPE *)0)->MEMBER))
<...>
#define bpf_ctx_range(TYPE, MEMBER) \
offsetof(TYPE, MEMBER) ... offsetofend(TYPE, MEMBER) - 1
#define bpf_ctx_range_till(TYPE, MEMBER1, MEMBER2) \
offsetof(TYPE, MEMBER1) ... offsetofend(TYPE, MEMBER2) - 1
```
I understandoffsetofandoffsetofendmacros, but what is...meaning?
Thanks.
|
Check out how it's used infilter.c:
```
case bpf_ctx_range(struct __sk_buff, data):
```
This is GCC'scase rangeextension (it's also supported by clang). With it, a single case statement can match on a range of values, likecase 0 ... 5:. There's more information here:
https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html
|
I'm looking in theebpfverifier code, and I can't get my head around the following macros:
```
#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE *)0)->MEMBER)
#define offsetofend(TYPE, MEMBER) \
(offsetof(TYPE, MEMBER) + sizeof(((TYPE *)0)->MEMBER))
<...>
#define bpf_ctx_range(TYPE, MEMBER) \
offsetof(TYPE, MEMBER) ... offsetofend(TYPE, MEMBER) - 1
#define bpf_ctx_range_till(TYPE, MEMBER1, MEMBER2) \
offsetof(TYPE, MEMBER1) ... offsetofend(TYPE, MEMBER2) - 1
```
I understandoffsetofandoffsetofendmacros, but what is...meaning?
Thanks.
|
Check out how it's used infilter.c:
```
case bpf_ctx_range(struct __sk_buff, data):
```
This is GCC'scase rangeextension (it's also supported by clang). With it, a single case statement can match on a range of values, likecase 0 ... 5:. There's more information here:
https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html
|
This question already has answers here:Trying to access array element in loop causes segmentation fault, why?(2 answers)No out of bounds error(7 answers)How dangerous is it to access an array out of bounds?(12 answers)Closed5 years ago.
i am getting segmentation fault while writing data into file. here is code
```
int arr[N]; // where N = 1508065
f = fopen( "datafile.txt", "w" );
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
for( i=1;i<=N;i++)
{
arr[i]=rand()%100;
fprintf(f, "%d %d %d\n",i,1,arr[i] );
}
fclose(f);
```
I have tried with double arr[N] even then is a segmentation fault. It works fine when N is small.
|
for( i=1;i<=N;i++)will give undefined behavior.
C arrays start at 0 and go to N-1. Accessing element N is a no-no.
Should befor( i=0;i<N;i++)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.