question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
keep in mind i'm a complete beginner and i'm still getting acclimated to the programming vocabulary.
When I run the debug from visual studio, the command prompt comes up with "Enter any string: " but when I enter something, i get "Exception thrown blah blah blah". What is going wrong? Any help and criticism is greatly appreciated. I've been losing my mind over this for 4 hours now.
Heres my code:
```
int main(){
char str[100];
int i=0;
printf("Enter any string: ");
scanf_s("%s",str);
printf("ASCII values of each characters of given string: ");
while(str[i])
printf("%d ",str[i++]);
return 0;
}
```
|
Thescanf_s()function must be used with a third argument to indicate the max length of the string i.e.scanf_s("%s", str, 100);
BTWscanf_s()is specific to Microsoft Visual Studio so it's less portable so I don't recommend it andstrisn't a really good variable name
|
I am working with ANSI C for the first time and I need to sum a series out to an N number of terms.
My background is in physics, not CS, so I instinctively thought to use the old (-1)^N trick, but quickly realized that 1) it didn't work, and 2) ANSI C doesn't have a built in exponentiation operator.
Since I now realize that exponentiation is slow, what is the best way to create an alternating series in for this? My second thought was checking the parity of N and then using an if statement that gives me either a 1 or -1 to multiply the term by, but I don't know any good methods to check parity on a computer, and I think it would be even slower than exponentiating -1.
Are there better ways to accomplish this that won't heavily tax the CPU?
|
Just keep the sign as a separate variable, and negate it as you process each term:
```
int sign = 1;
for ( int i = 0; i < N; i++ )
{
printf( "%2d\n", sign );
sign = -sign;
}
```
|
keep in mind i'm a complete beginner and i'm still getting acclimated to the programming vocabulary.
When I run the debug from visual studio, the command prompt comes up with "Enter any string: " but when I enter something, i get "Exception thrown blah blah blah". What is going wrong? Any help and criticism is greatly appreciated. I've been losing my mind over this for 4 hours now.
Heres my code:
```
int main(){
char str[100];
int i=0;
printf("Enter any string: ");
scanf_s("%s",str);
printf("ASCII values of each characters of given string: ");
while(str[i])
printf("%d ",str[i++]);
return 0;
}
```
|
Thescanf_s()function must be used with a third argument to indicate the max length of the string i.e.scanf_s("%s", str, 100);
BTWscanf_s()is specific to Microsoft Visual Studio so it's less portable so I don't recommend it andstrisn't a really good variable name
|
Do these two pieces of C code achieve the same goal:
```
char ** p;
p = malloc(sizeof(char*) * 10);
--------------------------------
char * z[10];
```
It seems like they can be used identically:
```
p[1] = "Foo";
*(p+2) = "Bar";
---------------------
z[1] = "Foo";
*(z+2) = "Bar";
```
Is there a difference?
|
If you just store and retrieve values from the array, or malloc-allocated area, they work the same.
There are differences, though.sizeofand&work differently, you need to explicitlyfreethe malloc-allocated area to release the memory, and you can change its size withrealloc.
|
```
int *a[4] = {
(int[]){ 1},
(int[]){ -4, -5},
(int[]){ -4, -5, 0},
(int[]){ 1, 3, 4, 6}
};
for (i = 0; i < 4; i++)
len = sizeof(a[i])/sizeof(int);
```
I know it is not a correct approach, but len is always 2. Could someone explain why len is two? Is it a undefined behavior, if not, how is it being calculated?
|
a[i]is pointer toint.sizeof(a[i])will return sizeofint *, not the array it points to. On 64-bit machines, size of a pointer is8bytes and size ofintis4bytes.8/4 = 2.
|
```
int *a[4] = {
(int[]){ 1},
(int[]){ -4, -5},
(int[]){ -4, -5, 0},
(int[]){ 1, 3, 4, 6}
};
for (i = 0; i < 4; i++)
len = sizeof(a[i])/sizeof(int);
```
I know it is not a correct approach, but len is always 2. Could someone explain why len is two? Is it a undefined behavior, if not, how is it being calculated?
|
a[i]is pointer toint.sizeof(a[i])will return sizeofint *, not the array it points to. On 64-bit machines, size of a pointer is8bytes and size ofintis4bytes.8/4 = 2.
|
```
#include <stdio.h>
int main()
{
int i;
i=0;
printf("%d\n%d\n%d\n", i, &i, &(&i));
return 0;
}
```
i think that &i is just a value of address, and assume that it's 0xFF so &(&i)should be the address of 0xFF but why it's not valid?
|
Unary&operator need an lvalue as its operand and returns an rvalue.&iis an rvalue, therefore&ican't be an operand of&.
|
I'm trying to build and run this code
```
#include<stdio.h>
#include<conio.h>
main()
{
textcolor(RED);
cprintf("Hello, World!");
getch();
return 0;
}
```
I use code blocks - gcc compiler.As GCC doesn't support conio.h , i'm getting a lot of errors.I want to add a library which is needed for running this kind of programs.
Being instructed by a blog I downloaded conio21 from this link:https://sourceforge.net/projects/conio/but I can't find the libconio.a there.Can you please explain how to add the library?
|
Download and extractconiolibrary that you link in your question. Inside of it takeconio.candconio2.hto your project folder. Then include conio2.h to your source code:
```
#include<stdio.h>
#include"conio2.h"
main()
{
textcolor(RED);
cprintf("Hello, World!");
getch();
return 0;
}
```
I tested, it works.
|
I'm new to C and I want to trythisjson de/serializer. As it doesn't need any dependence I've just put the code in a subdir of my project.
```
/
json_test.c
json/
json.c
json.h
```
Source ofjson_test.c:
```
#include "json/json.h"
int main() {
JsonNode *json = json_mkobject();
}
```
And a part of thejson/json.h:
```
JsonNode *json_mkobject(void);
```
The problem is that I can't use any function from the lib because the compilation fail (I think it's the linker):
```
$ gcc json_test.c -o json_test
/tmp/cco4ZDh0.o: in function « main »:
json_test.c:(.text+0x9): undefined reference to « json_mkobject »
collect2: error: ld returned 1 exit status
```
I'm on it since yesterday, have you got any suggestion to make it work ?
|
You should compilejson/json.cas well:
```
gcc json/json.c json_test.c -I json -o json_test
```
|
if I have a pointer to an integer such as:
```
int num = 12;
int *p = #
```
and then print the address so
```
printf("%p\n", (void*)p);
```
What is the difference between the previous and this:
```
printf("%p\n", (void*)&p);
```
|
Here,pcontains the address ofnum, so the firstprintfoutputs the address ofnum.
On the other hand,&pis the address ofp, so the secondprintfprints the address ofp.
|
I want to be able to do this:
```
typedef int a[2], b[2], c[2];
```
without having to type the[2]. One solution is to do:
```
typedef struct { int a[2] } a, b, c;
```
but then you have to always do stuff likea.a[0]and that's no good.
|
For C or C++98, a simple typedef will do:
```
typedef int int2[2];
int2 a, b, c;
```
|
In talking about "clean code", we typically hear that a cleanly written function doesonly one thing.
When it comes to handling user input, does it count as part of thatone thingto validate the input? For example,
```
/* Arg1 is passed directly from user input */
int foo(int arg1) {
if (!arg1 || arg1 < 500) {
return -1;
}
/* Do foo */
}
```
Is it best to write these validation tests inside the function, or should they be separated somehow, as in:
```
if (argIsValid(arg1)) {
foo(arg1);
}
```
Whatever the case, I would like to hear supporting reasoning with your answer. Thanks!
|
It isbest to write the validation logic in a functionwith a namevalidate_args()for example.
You see, when you want to enhance the validation logic, it will obvious were you have to look too, even if you are not the author of the code, so +1 for maintenance!
Moreover, it makes the code more elegant too!
|
I am currently working on a C networking application for linux. It is based on DPDK. I've executed the app using valgrind which does not show any memory leaks. I've also tried Intel Inspector 2016, with the same results. But when I let my app run on a system (AWS EC2 instance) for a couple of days while monitoring the RAM usage(Cloudwatch), it shows the RAM increasing constantly, linearly and slowly(about 1 MB/day). How can I find this leak?
|
One way to debug this is to write some code that monitors all memory allocations and all de-allocation. With such monitor code, you'll be able to find "where" the allocated memory is.
Since you are using Linux, this may be a place to start:
http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/Hooks-for-Malloc.html
A first test could be to check whether all allocated memory is free'd when the program is closed. This will tell whether you have a leak or a build up of used memory.
|
I came across system call "write" then, I tried to compare "putchar" with "write". Now, I am confused with above lines of code.
|
The putchar is a library function. It calls the write system call to write the character in stdout.
If we access the system call so many time, the system performance will get slow.
So only, the library functions are implemented.
The library functions for writing, it allocates a buffer, once if the buffer is fulled or flushed then only it calls the write system call to write the contents in stdout.
So, if you want good system performance, you have to use the library functions (putchar).
Is there any need you have the write the output immediately, you can use the write system call.
|
I have a problem about Netbeans. This is my code :
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int i;
clock_t start, finish;
start = clock();
for(i = 0; i < 10000000000; i++);
finish = clock();
printf("%f", (float)(finish-start)/CLOCKS_PER_SEC);
return 0;
}
```
When I run the program on Netbeans 8.1, the output is 0.000000, but it is 0.2100000 when I tried on Dev C.
|
It is likely that yourforloop is optimized away by the compiler, as the loop has no side effects (i.e. does not affect the rest of the program in any way).
It's not clear what you want to achieve. Do you want to learn how to measure execution time? Then use calls tousleep()orsleep()orwhile (clock() < XXX);between the measurements to delay the system for some time. Or do you want to learn the execution time of specific algorithm? Then put that algorithm in the code instead of the dummyforloop.
|
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.Closed7 years ago.Improve this question
In short: When do I break ABIs while working at larger C/C++ libraries, that have consumers and are expecting stability throughout non-major releases?
|
No, there's a difference between API and ABI incompatibility. API incompatibility refers to deprecating/removing a function as you said that users can no longer use in a new library. This will make old code not compile.
ABI incompatibility on the other hand includes instability/linking errors, such if a library was compiled on a System V versus ARM system, or compiled with libstdc++ or libc++. This requires that the entire library be recompiled for the target system.
|
I have a file consist of 6 columns of data. I would like to retrieve the second and the last last three data. The last three data need to be stored in a 3 dimension array,
Here is example of the data in files:
```
gly 1 A 12.11 13.14 14.14
asp 2 A 13.23 24.64 35.25
glu 3 B 32.45 11.45 54.86
```
|
Read each line with your preferred function (fgets,fscanf, ...) and parse the line withsscanf.
```
char buffer[50];
char token1[15];
int token2;
char token3;
float token4, token5, token6;
while(fgets(buffer, 49, file)) {
sscanf(buffer, "%s %d %c %f %f %f", token1, &token2, &token3, &token4, &token5, &token6);
...
}
```
Also, be careful with the return value of sscanf.
|
I'm learning how to useo-llvmbased on llvm 3.4.
I have a really simple c file, named "Example.c" that I'm obfuscating and compiling.
```
clang -mllvm -sub Example.c
```
Is there a way to emit the obfuscated code as a .c file??
|
LLVM Obfuscation happens after the C code has been transformed to LLVM IR. There is not really a good way to convert IR directly back into C code either. You can have o-llvm output the obfuscated code as IR though by using the command line arguments
```
-S -emit-llvm
```
|
How can I reliably detect msvc standard library via preprocessor?
Not msvc compiler with checking _MSC_VER but another compiler utilizing this library?
I'm looking for specific preprocessor macro like__MINGW32__in mingw ,__MINGW64_VERSION_MAJORin mingw-w64
This just academic question.
|
First off, don't compile the msvc libraries with another compiler, they depend upon msvc compiler behaviors and defines.
Secondly, there isn't anything in every msvc standard library header that you could use to test against. Even if there was it would be implementation defined and may also be defined by another standard library implementation.
That said#include <iostream>is about as close to universal as it gets. You could look through this file for a unique enough define that you could key off of. For example_IOSTREAM_.
|
My iOS app uses a C function for some computing. I want to call it from
-(void)viewDidLoad but I don't want it to freeze the main thread. I tried calling it with dispatch_async(dispatch_get_main_queue... block but it still was being called on the main thread. Also including function call into objective-c method and calling [self performSelector: InBackground] didn't work either. Please help. Is there any way I can perform C function in background in objective-c app ?
|
You have to use a different queue, e.g.:
```
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(backgroundQueue, ^{
// do something
});
```
SeeDispatch Queuesfor more details.
|
I have array defined like this
```
float array [1000][3]
```
I want to extract third column
```
float third[1000]
for (i = 0; i < 999,i++)
```
and then what?
|
```
for (i=0; i<1000; i++)
{
third[i]=array[i][2];
}
```
This should do it if I understood your question correctly.
|
I want to copy the content o directory(tmp1) to another directory(tmp2). tmp1 may contain files and others directories. I want to copy the content of tmp1 (including the mode) using C/C++. If tmp1 contains a tree of directories I want to copy them recursively.
What is the simplest solution?
I found a solution to open the directory and read every entry and copy it withcpcommand. Any simpler solutions?
|
I recommend usingstd::filesystem(merged to ISO C++ as of C++17!)
Shamelessly copied fromhttp://en.cppreference.com/w/cpp/filesystem/copy:
std::filesystem::copy("/dir1", "/dir3", std::filesystem::copy_options::recursive);
Read more about it:
https://gcc.gnu.org/onlinedocs/gcc-6.1.0/libstdc++/api/a01832.html
experimental::filesystem linker error
|
ceilfunction inCis declared asdouble ceil(double). Is it safe to cast return value of the function toint? I mean is there any guarantee that the following will never occur (the sample is just to illustrate of what I mean)?
```
double r = ceil(234235.53453);
// imagine r = 234235.9999999 due to round errors or
// due to the peculiarities of the machine arithmetics, etc.
int i = (int)r;
// i = 234235, but must be 234236
```
Of course, I know that the range ofdoubleis large than the range ofint, so the cast may fail. My question is not about it, but about rounding errors or machine arithmetics side effects.
|
A 64-bitdoublerepresents integers of up to 2 in power 53 exactly. Integers larger than that do not have any fractional part when represented asdouble.
In other words, you can safely cast the result ofceilorfloorto an integer, as long as that integer can hold the value.
|
I'm reading the source of aCproject and am trying to discern why a particular use ofexternis being used. (Note:This questionis related but for C++, not C.) Say I have four header files that each declare anextern conststruct:
```
extern const struct puppy fido;
```
This struct is defined in a source file like so:
```
extern const struct puppy fido;
static const struct puppy *puppies[] = { &fido };
const struct puppy fido = { "fido", 10, 10 };
```
Is there some kind of benefit to marking the variable declaration asexternin the source file, when those variables are defined in that very same source file?
|
The only advantage would be that any code between the declaration and the definition will be able to access the variable. Apart from that, the extern declaration in the same file is pointless.
|
I have an if statement:
```
printf("name");
if((fp = fopen(path, "r")) == NULL) {
perror("fopen");
exit(1);
}
printf("name2");//Debug propose
while(fgets(mensagem,250,fp)!=NULL){
printf("%s",mensagem);
}
fclose(fp);
```
For some reason ,name2is never printed butnameis printed ,pathis a Fifo:
```
mknod(path, S_IFIFO|0666, 0);
```
|
From the FIFO man page (http://man7.org/linux/man-pages/man7/fifo.7.html):
Normally, opening the FIFO blocks until the other end is opened also.
That is, unless you open it explicitly in nonblocking mode.
So, I would expect your process to be hanging in thefopen()call until someone opens the fifo for writing as well.
|
I have a function in C that takes a function callback as an argument in dll. It is OK for MFC and below is C code
```
void OnReceive(unsigned char* pReportBuf, int nReportLen, int nReportCount, SYSDELTA_TIME timeStamp) {
for (int iCount = 0; iCount < nReportCount; iCount++) {
BYTE *Buf = new BYTE[nReportLen + 1];
memcpy(Buf, &pReportBuf[iCount*nReportLen], sizeof(BYTE)*nReportLen);
SYSDELTA_TIME *sTime = new SYSDELTA_TIME;
memcpy(sTime, &timeStamp, sizeof(SYSDELTA_TIME));
}
}
res = InputRawRegHIDCallback(OnReceive);
```
Now I need to move above code to Python, but I don't know how to code
callback function to Python code. Could anyone help me to code???
Thank you for your great help.
BR,
Alan
|
Using ctypes, you canwrap/annotate the callback functionwith type information using CFUNCTYPE so they can be called from the C library.
|
This question already has answers here:What is "..." in switch-case in C code(4 answers)Closed7 years ago.
Is '...' symbol is a c language keyword?
The code:
```
#include <stdio.h>
typedef enum {
A=0,B,C,D,E,F,G,H,I,J,K,M
} alpha;
int main(int argc, char const *argv[])
{
alpha table = C;
switch (table)
{
case A ... D:
/* I have never seen "..." grammar in textbook */
printf("Oh my god\n");
break;
default:
printf("default\n");
break;
}
return 0;
}
```
Is...allowed in C for range?
|
It's not standard C, but a GCC extension:
You can specify a range of consecutive values in a single case label, like this:case low ... high:This has the same effect as the proper number of individual case labels, one for each integer value from low to high, inclusive.
More inGCC extension: Case ranges
|
I have to parse MPLS packets. I gathered some packet captures(pcap) of MPLS protocol. Some had 2 headers of MPLS protocol whereas some have just one header. How do I know when will a packet single MPLS header and when will it have 2 headers?
|
It is bottom-of-stack bit, to indicate one more label. Else the data is popped out of MPLS headers and given to next level engine to Handle (it will typically contain a L2 or L3/IP header), it is done while the programming that correct engine is associated.
|
I am using the fwrite to write integers stored in a structure into a .txt file. However, when I open the file, the numbers are not readable (become box):
Here is my code:
```
fp=fopen("pre-survey.txt", "a");
printf("name\n");
scanf("%s", &temp.name);
printf("q1:\n");
scanf("%d", &temp.q1);
printf("q2:\n");
scanf("%d", &temp.q2);
printf("q3:\n");
scanf("%d", &temp. q3);
fwrite(&temp, sizeof(temp), 1, fp);
fclose(fp);
}
```
temp is a structure i declared:
```
struct pre_survey{
char name[20]; int q1; int q2; int q3; };
struct pre_survey temp;
struct pre_survey get;
```
Any advice?
|
You can use fprintf function.
Something like:
```
fprintf(fp, "%s, %d, %d, %d", temp.name, temp.q1, temp.q2, temp.q3);
```
|
When I attempt to convert one byte of hex into a char string I find that it takes 3 bytes. I am using Visual Studio 2013.
If I have less than 3 bytes I get an error: "Stack around the variable 'str' was corrupted."
What am I doing wrong? Surely the hex value 0xF1 should fit intochar str[1]? Why should I have to declare a 3 byte array to assign a 1 byte value?
```
char str[3];
sprintf(str, "%02X", 0xF1);
```
The content ofstris 0x0026fd18 "F1"
|
The issue is that's trying to print "F1" into the string followed by a null terminator - this would be three bytes. That's the whole point of the sprintf function - it formats the input into a readable string. If you're trying to simply assign the hex value of 0xF1 to a char, you would do it like this:
char str = (char)0xF1
|
```
long long n, prod, i;
n = 13;
prod = 1;
for (i = 1 ; i <= n ; i++) {
prod *= i;
}
printf("%d\n", prod);
printf("%d\n", sizeof(long long));
```
returns
```
$ 1932053504
$ 8
```
Result is clearly overflowing. But I don't get why this is happening withlong long.sizeof(int)returns 4 [bytes] but the product is the same. What am I doing wrong?
|
You have to use the correct specifier. The"%d"specifier expects anintand you passed along long int. According to thecstandard this will invoke undefined behavior. The observed behavior might be explicable but that doesn't mean it isn't rigorouslyundefined behavior.
Fix the code like this
```
printf("%lld\n", prod);
printf("%zu\n", sizeof(long long));
```
and it should work as intended.
NOTE: enable compilation warnings and you should find out this kind of mistake very quickly.
|
I have array defined like this
```
float array [1000][3]
```
I want to extract third column
```
float third[1000]
for (i = 0; i < 999,i++)
```
and then what?
|
```
for (i=0; i<1000; i++)
{
third[i]=array[i][2];
}
```
This should do it if I understood your question correctly.
|
I want to copy the content o directory(tmp1) to another directory(tmp2). tmp1 may contain files and others directories. I want to copy the content of tmp1 (including the mode) using C/C++. If tmp1 contains a tree of directories I want to copy them recursively.
What is the simplest solution?
I found a solution to open the directory and read every entry and copy it withcpcommand. Any simpler solutions?
|
I recommend usingstd::filesystem(merged to ISO C++ as of C++17!)
Shamelessly copied fromhttp://en.cppreference.com/w/cpp/filesystem/copy:
std::filesystem::copy("/dir1", "/dir3", std::filesystem::copy_options::recursive);
Read more about it:
https://gcc.gnu.org/onlinedocs/gcc-6.1.0/libstdc++/api/a01832.html
experimental::filesystem linker error
|
ceilfunction inCis declared asdouble ceil(double). Is it safe to cast return value of the function toint? I mean is there any guarantee that the following will never occur (the sample is just to illustrate of what I mean)?
```
double r = ceil(234235.53453);
// imagine r = 234235.9999999 due to round errors or
// due to the peculiarities of the machine arithmetics, etc.
int i = (int)r;
// i = 234235, but must be 234236
```
Of course, I know that the range ofdoubleis large than the range ofint, so the cast may fail. My question is not about it, but about rounding errors or machine arithmetics side effects.
|
A 64-bitdoublerepresents integers of up to 2 in power 53 exactly. Integers larger than that do not have any fractional part when represented asdouble.
In other words, you can safely cast the result ofceilorfloorto an integer, as long as that integer can hold the value.
|
I'm reading the source of aCproject and am trying to discern why a particular use ofexternis being used. (Note:This questionis related but for C++, not C.) Say I have four header files that each declare anextern conststruct:
```
extern const struct puppy fido;
```
This struct is defined in a source file like so:
```
extern const struct puppy fido;
static const struct puppy *puppies[] = { &fido };
const struct puppy fido = { "fido", 10, 10 };
```
Is there some kind of benefit to marking the variable declaration asexternin the source file, when those variables are defined in that very same source file?
|
The only advantage would be that any code between the declaration and the definition will be able to access the variable. Apart from that, the extern declaration in the same file is pointless.
|
I have an if statement:
```
printf("name");
if((fp = fopen(path, "r")) == NULL) {
perror("fopen");
exit(1);
}
printf("name2");//Debug propose
while(fgets(mensagem,250,fp)!=NULL){
printf("%s",mensagem);
}
fclose(fp);
```
For some reason ,name2is never printed butnameis printed ,pathis a Fifo:
```
mknod(path, S_IFIFO|0666, 0);
```
|
From the FIFO man page (http://man7.org/linux/man-pages/man7/fifo.7.html):
Normally, opening the FIFO blocks until the other end is opened also.
That is, unless you open it explicitly in nonblocking mode.
So, I would expect your process to be hanging in thefopen()call until someone opens the fifo for writing as well.
|
I have a function in C that takes a function callback as an argument in dll. It is OK for MFC and below is C code
```
void OnReceive(unsigned char* pReportBuf, int nReportLen, int nReportCount, SYSDELTA_TIME timeStamp) {
for (int iCount = 0; iCount < nReportCount; iCount++) {
BYTE *Buf = new BYTE[nReportLen + 1];
memcpy(Buf, &pReportBuf[iCount*nReportLen], sizeof(BYTE)*nReportLen);
SYSDELTA_TIME *sTime = new SYSDELTA_TIME;
memcpy(sTime, &timeStamp, sizeof(SYSDELTA_TIME));
}
}
res = InputRawRegHIDCallback(OnReceive);
```
Now I need to move above code to Python, but I don't know how to code
callback function to Python code. Could anyone help me to code???
Thank you for your great help.
BR,
Alan
|
Using ctypes, you canwrap/annotate the callback functionwith type information using CFUNCTYPE so they can be called from the C library.
|
This question already has answers here:What is "..." in switch-case in C code(4 answers)Closed7 years ago.
Is '...' symbol is a c language keyword?
The code:
```
#include <stdio.h>
typedef enum {
A=0,B,C,D,E,F,G,H,I,J,K,M
} alpha;
int main(int argc, char const *argv[])
{
alpha table = C;
switch (table)
{
case A ... D:
/* I have never seen "..." grammar in textbook */
printf("Oh my god\n");
break;
default:
printf("default\n");
break;
}
return 0;
}
```
Is...allowed in C for range?
|
It's not standard C, but a GCC extension:
You can specify a range of consecutive values in a single case label, like this:case low ... high:This has the same effect as the proper number of individual case labels, one for each integer value from low to high, inclusive.
More inGCC extension: Case ranges
|
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.Closed7 years ago.Improve this question
If I have :
```
char *name; //this is in a struct
*row->name //row is able to get in the struct
```
How do I read *row->name and what is it returning?
I'll link the code I am reading:http://pastebin.com/MvLXkDCz
|
First the->operator is evaluated and then the resulting pointer which is pointing to whatnamepoints to is dereferenced with*. So it's the same as
```
row->name[0]
```
and IMHO this is a better way of expressing the same (althought sometimes using the indirection operator*is clearer).
|
Let's say I have a variableithat comes from external sources:
```
int i = get_i();
```
AssumingiisINT_MINand two's complement representation, is-iundefined?
|
It depends on the platform. C supports three representations for negative numbers (seesection 6.2.6.2of the C99 standard):
Two's complement.One's complement.Sign and magnitude.
With one's complement and sign and magnitude,-INT_MINis defined (and equal toINT_MAX). With two's complement, it depends on whether the value with sign bit 1 and all value bits zero is a trap representation or a normal value. If it's a normal value,-INT_MINoverflows, resulting in undefined behavior (seesection 6.5of the C99 standard). If it's a trap representation,-INT_MINequalsINT_MAX.
That said, most modern platforms use two's complement without trap representations, so-INT_MINtypically results in undefined behavior.
|
I wrote a C program using opengl, I tried to profile it, and kept getting no profile data found.
I disabled all flags except -pg and -g (from the options) and -std=c99 & -Iinclude (from "Other Options").
I tried putting pg and g in my build options for all targets, I tried putting -pg in the linker, I changed my programing to simply return 0; incase exiting was an issue.
What makes me suspect OpenGl is that I opened a previous project (that used graphics.h - the flags of which are still in the linker, idk if thats an issue) and ran it with the same flags and everything, and it worked fine.
I read just about every page on google, but nothing turns up if I include opengl in the search :/
|
The working directory was in a random place (outside the project) so gmon.out could not be found.
"Project -> Properties -> Build targets -> Execution working dir"
Correcting the directory fixed the problem.
|
I use Clion 2016.1
Clion creates project with CMakeLists.txt and main.c:
The content of CMakeLists.txt is:
```
cmake_minimum_required(VERSION 3.4)
project(Fir)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror")
set(SOURCE_FILES main.c)
add_executable(Fir ${SOURCE_FILES})
```
The content of main.c is:
```
#include <stdio.h>
int main(void) {
printf("Hello, world");
getchar();
return 0;
}
```
But it gives:
```
Configuration is still incorrect. Do you want to edit it again?
```
How to properly declare configuration to run the project
|
It works for me, I make a new project, build it and choose the project name as executable with this cmake contents:
```
cmake_minimum_required(VERSION 3.5)
project(new)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.c)
add_executable(new ${SOURCE_FILES})
```
|
I was working with an example regarding seg fault:
```
char m[10]="dog";
strcpy(m+1,m);
```
In my centOs machine the result was as expected: segmentation fault. but on Ubuntu nothing happen. then I add a printf("%s",m); to the code on ubuntu and surprisingly I got the "ddog" as result.
I am using GCC and the ubuntu version was the latest.
can anyone tell me why the results are different. I also check it on raspbian and I also received segmentation fault.
Thanks,
|
This causesundefined behaviour.strcpymay only be used between areas that do not overlap.
To fix this code you could write:
```
memmove(m+1, m, strlen(m) + 1);
```
|
I installed simgrid according to instruction in INSTALL file:
```
cmake -DCMAKE_INSTALL_PREFIX=~/SimGrid -Denable_maintainer_mode=off -Denable_java=on -Denable_scala=off -Denable_lua=off -Denable_smpi=on -Denable_model-checking=off
make
sudo make install
```
But I can't find msg.h file in include directory:
What did I make incorrectly?
|
you are definitely not using a 3.13 version of SimGrid but at most a 3.11. I'm certain because the file you are using (msg/msg.h) does not work anymore since then. Plus, 3.13 introduces many files that should appear on that screenshot.
Could you please fix your question, or close it ?
|
I'm writing a simple udp server application and i ran into an error when i try to get the address of the remote connecting user.
```
while(run == 1) {
struct sockaddr_in client_addr;
char message[1024];
int len = recvfrom(sockfd, message, 1024, 0, (struct sockaddr*)&client_addr, sizeof client_addr);
printf("Received request from: %s#%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
}
```
It always return the remote address: 0.0.0.0#0
|
If you read the documentation forrecvfrom, you'll see the last parameter is apointer toa socklen_t holding the size of the address.
So it should be:
```
socklen_t client_addr_len = sizeof client_addr;
int len = recvfrom(....., (struct sockaddr*)&client_addr, &client_addr_len);
```
After callingrecvfrom,client_addr_lenwill hold the actual address length (which could be smaller than the buffer, in theory, if it not an AF_INET address).
|
I wrote a C program using opengl, I tried to profile it, and kept getting no profile data found.
I disabled all flags except -pg and -g (from the options) and -std=c99 & -Iinclude (from "Other Options").
I tried putting pg and g in my build options for all targets, I tried putting -pg in the linker, I changed my programing to simply return 0; incase exiting was an issue.
What makes me suspect OpenGl is that I opened a previous project (that used graphics.h - the flags of which are still in the linker, idk if thats an issue) and ran it with the same flags and everything, and it worked fine.
I read just about every page on google, but nothing turns up if I include opengl in the search :/
|
The working directory was in a random place (outside the project) so gmon.out could not be found.
"Project -> Properties -> Build targets -> Execution working dir"
Correcting the directory fixed the problem.
|
```
struct packet_event *packet_event_p[8];
```
What does this mean ? Is it a pointer to an array of structure data type (struct packet_event) that has 8 elements ? And how could I make use of this pointer ?Is it different from :
```
struct packet_event **packet_event_p;
```
If yes, how could I use this pointer ?
|
The first one:
```
struct packet_event *packet_event_p[8];
```
stands for 'declare packet_event_p as an array of 8 pointers to struct packet_event'. Thus, you create an arraypacket_event_pof 8 elements, which are pointers to the struct packet_event. Please seethis link.
whereas the second one:
```
struct packet_event **packet_event_p;
```
stands for 'declare packet_event_p as pointer to pointer to struct packet_event'. Please seethis link.
Hope this is helpful.
|
In my linux experiment(linux kernel version 4.5), I need to create a file in directory /proc/pid in a module. I have got a certain pid and a pointer to its task_struct, but I don't know how to get the pointer to the struct proc_dir_entry of the directory /proc/pid. Can anyone help me?
|
There is noproc_dir_entryfor process entries under /proc. if you still need to add a directory you need to add an entry to the following data structure in 'fs/proc/base.c'...
```
static const struct pid_entry tgid_base_stuff[];
```
This is where all the virtualdirectoriesyou see under/proc/pidare defined. You'd also need to add patch the existing kernel to make sure you handle the new entry.
|
I've got a question to C structs and datatypes. I have a struct calledtest:
```
struct test
{
char* c;
char* c2;
};
```
And I am returning this struct from a function:
```
struct test a()
{
struct test t = { "yeah!", "string" };
return t;
}
```
My question is whether the memory for the struct is freed automatically or if I have to do this manually viafree().
[updatefrom comment:]
The function a is in a DLL and I want to use the struct in the main program.
|
You should onlyfreesomething which youmalloced (or used another similar function) first. Since nothing wasmalloced, nothing should befreed.
|
inotify file in C
I have seen the following codes used to call
```
(void) inotify_rm_watch(fd, wd);
(void) close(fd);
```
Why not?
```
inotify_rm_watch(fd, wd);
close(fd);
```
What is the difference between the two usages?
|
There are some cases when ignoring return value of the function causes compiler to warn you about it.
Casting return type tovoideffectively suppresses the warning. However, the wisdom of ignoring return type is questionable. If function return something, you probably want to know what it returned? Just in case there was a problem, you know.
In particular,inotify_rm_watchreturns-1when the function fails - and you are usually interested to know it. On the other hand, checking for return value ofcloseis usually not neccessary and borders with paranoia :)
|
Is it possible to read superscript from string in C?
string is for examplef(x)=x²+2x.
I want to read that power as2and use it in calculations.
|
In UTF-8, the ² is U+00B2 (0xC2 0xB2) bytes; in ISO 8859-1 or 8859-15, it is a single byte, 0xB2 (the similarity is not coincidental). There's nothing to stop you reading the character and interpreting it as 'power of 2'. U+00B3 is superscript 3; U+00B9 is superscript 1; the characters U+2070..U+2079 are superscript digits 0-9. Isn't in fun having so many numbers to choose from? If you have a different code set, you have to know what you're dealing with. – Jonathan Leffler
|
I checked the man pages, but they don't explain the RND meaning. I want to know the words the RND stand for. Like SHM_RDONLY stand for read-only.thank you!
|
the following is an excerpt from the man page forshmat()
If shmaddr isn't NULL and SHM_RND is specified in shmflg, the attach
occurs at the address equal to shmaddr rounded down to the nearest mul‐
tiple of SHMLBA. Otherwise shmaddr must be a page-aligned address at
which the attach occurs.
|
How might I end a function after it has been called once within ado...whileloop? For example, in the below code, I would wantmyfunc()to be called only once, then not be called again within the loop. Is that possible?
```
do{
myfunc();
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, fb_width, fb_height, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
drawSomething();
glfwSwapBuffers(w);
glfwPollEvents();
}
while (something);
```
|
Either yo can put it before the do while loop
or you can hold a flag variable that store whether the function has already been executed or not.
```
int flag = 0;
do {
if(flag==0){
myfunc();
flag=1;
}
... // Rest of the loop
}
```
|
I checked the man pages, but they don't explain the RND meaning. I want to know the words the RND stand for. Like SHM_RDONLY stand for read-only.thank you!
|
the following is an excerpt from the man page forshmat()
If shmaddr isn't NULL and SHM_RND is specified in shmflg, the attach
occurs at the address equal to shmaddr rounded down to the nearest mul‐
tiple of SHMLBA. Otherwise shmaddr must be a page-aligned address at
which the attach occurs.
|
How might I end a function after it has been called once within ado...whileloop? For example, in the below code, I would wantmyfunc()to be called only once, then not be called again within the loop. Is that possible?
```
do{
myfunc();
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, fb_width, fb_height, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
drawSomething();
glfwSwapBuffers(w);
glfwPollEvents();
}
while (something);
```
|
Either yo can put it before the do while loop
or you can hold a flag variable that store whether the function has already been executed or not.
```
int flag = 0;
do {
if(flag==0){
myfunc();
flag=1;
}
... // Rest of the loop
}
```
|
I'm trying to implement my ownstrcmpfunction, mystrcmpbahaves differently when I use special characters.
```
#include <string.h>
int my_strcmp(const char *s1, const char *s2)
{
const char *str1;
const char *str2;
str1 = s1;
str2 = s2;
while ((*str1 == *str2) && *str1)
{
str1++;
str2++;
}
return (*str1 - *str2);
}
int main()
{
char *src = "a§bcDef";
char *des = "acbcDef";
printf("%d %d\n", my_strcmp(des, src), strcmp(des, src));
return(0);
}
```
OUTPUT
161 -95
|
charis signed in many implementations, and yourstrcmpimplementation considerscharvalues < 0 to be smaller than those greater than 0. Perhaps you want to compare the unsigned values instead.
```
const unsigned char *str1 = (unsigned char*) s1;
const unsigned char *str2 = (unsigned char*) s2;
```
|
I am completely new to C.I want to read two integers with thescanffunction, that are seperated by whitespaces OR by one comma. If the formatstring says"%d%d"the whitespaces are automatically handled for me. But if I change it to
```
scanf("%d,%d", &firstNum, &secondNum);
```
I have to seperate both values with one comma. It should by possible for the user to enter1,2or1 2(no matter how many whitespaces are inbetween).Is it possible to achieve this function with one call ofscanf?
|
usescanset
```
scanf("%d%*[, ]%d", &a, &b);
```
http://www.cplusplus.com/reference/cstdio/scanf/
|
Hi I have a piece of code as below, I want to avoid multiple if else, is there a better approach for this:
```
if(strcmp(somename, "some") == 0)
{
fun();
}
else if(strcmp(somename,"some1") == 0)
{
fun();
}
else if(strcmp(somename,"some2") == 0)
{
fun();
}
else if(strcmp(somename,"some3") == 0)
{
fun();
}
```
|
You can use a pointer to pointer and a loop:
```
const char *ap[] = {"some", "some1", "some2", "some3", NULL};
const char **p = ap;
while (*p) {
if (strcmp(somename, *p) == 0) {
fun();
break;
}
p++;
}
```
|
This question already has answers here:How do I understand complicated function declarations?(12 answers)Tool to explain C code [closed](3 answers)Closed7 years ago.
I'm a little confused... Would it be possible for somebody to identify the order of evaluation and what is actually being declared here, perhaps in terms of pointers and the types we expect to find using these?
A written explanation would also be adequate, all would be awesome. Really any means you feel you can explain fully what this does would be great!
What does this do in C / C++?
```
int (*f) (float *);
```
|
It declares a function pointerfto a function that accepts a pointer to float and returns an int.
Without the parens around*fyou would be declaring a functionfthat takes a pointer to float and returns a pointer to int.
|
I know that macros in C such as:
```
#define VARNULL (u8)0
```
doesn't store thisVARNULLin RAM, but this of course will increase the code size in the FLASH.
But what if I have a multi-line macro such as:
```
#define CALL_FUNCS(x) \
do { \
func1(x); \
func2(x); \
func3(x); \
} while (0)
```
By knowing thatfunc1,func2, andfunc3are functions from different.cfiles. Does this means that these functions will be stored in RAM? And of course in the FLASH (the code).
Kindly correct me if I'm wrong?
|
You keep saying that "of course" the macros will be "stored" in flash memory on your target device, but that is not true.
The macros exist in the source codeonly; they are replaced with their defined values during compilation. The program in flash memory will not "contain" them in any meaningful way.
|
I'm not sure how to unlock characters past 255 automatically.
```
char f;
f = 'k';
printf("%d\n", f);
```
Results in107. No surprise.
```
f += 500;
printf("%d\n", f);
```
Results in95. It seems this has been modulo divided by 255.
```
printf("%c\n", 607);
```
Results in_. There are many more characters that extend into the thousands as well. How come adding a value and making a char go past 255 forces a modulo operation? I need to go past 255 for the sake of a hash function.
|
Acharis a byte in memory. So you can not store values > 255 because it has only 8 bits (assuming that on your platform a char is defined as a byte of 8 bits). When the value is more than 255, it overflows.
Furthermore, you don't know if acharis unsigned (values can be between 0 and 255) or signed (values can be between -128 and 127).
You can use another type thancharif you want to store values > 255.
|
I have astructdefined:
```
struct Query {
int *pages;
int currentpage;
};
struct Query *new = malloc(sizeof(struct Query));
new->pages = malloc(sizeof(int) * 4);
```
I then checked the size ofnew->pagesto ensure that the size was 4 by doing:
```
int size = sizeof(new->pages)/sizeof(new->pages[0]);
```
However,sizekeeps returning2as opposed to4.
Would anyone know what I might be doing wrong?
Thanks for your help.
|
Your expectation is wrong.
sizeof(new->pages)in
```
int size = sizeof(new->pages)/sizeof(new->pages[0]);
```
doesn't return the total number ofintelements. Just the size of the int pointer (int*). Sincesizeof(int*)is 8 andsizeof(int)is 4 on your platform, it returns 2.
By the way, you should usesize_tforsizeassizeofoperator returns asize_tand%zuis the format specifier (inprintf()) to printsize_t.
|
Suppose I have a C source file which does not contain any reference to any other file. You may assume it only contains -
```
int main(void) {
int a=5, b=10;
}
```
Will this source file go to the linker? What will be the task of the linker in this case?
|
It will because linker will be invoked to form the runnable executable. No matter it's one source file or many, each translation unit will be first compile to object file, and then linked against the C's runtime to form the executable program. So even you see only one source file, it is still linked to the runtime by the linker.
|
I am trying to cross compile libcollections library for ARM architecture. After running the command./configure --host=arm-none-linux-gnueabi, it fails with the errorconfigure: error: C compiler cannot create executables.
Inside the config.log file, I found that this is due toas: unrecognized option '-meabi=5'.
What does this line mean and how do I resolve this issue?
The library is found here:https://bitbucket.org/manvscode/libcollections
|
-meabi=5is anARM specific GNU assembler command line optionto specify the EABI version to be used, where valid values are 4, 5 and gnu.
You should ensure that you have installed an appropriate build of binutils for ARM, as per the solutionhere.
|
```
#include<stdio.h>
int main()
{
double a,b;
scanf("%lf",&a);
printf("%lf\n",a);
return 0;
}
```
I'm getting output0.000000— why? — but the same code gets input and output asdoublein a C program. Withfloattype, the code works in C++. I have used GNUgcccompiler.
|
Inprintf%lfis not existing per say.
Inscanfit does.
(seespecifiers x lengthtable)
Lots of OS accept%lfin printf to be consistent, but Windows is not one of them.
So you have to scanf%lf, but printf%f, and it should work everywhere.
|
I'm not sure how to unlock characters past 255 automatically.
```
char f;
f = 'k';
printf("%d\n", f);
```
Results in107. No surprise.
```
f += 500;
printf("%d\n", f);
```
Results in95. It seems this has been modulo divided by 255.
```
printf("%c\n", 607);
```
Results in_. There are many more characters that extend into the thousands as well. How come adding a value and making a char go past 255 forces a modulo operation? I need to go past 255 for the sake of a hash function.
|
Acharis a byte in memory. So you can not store values > 255 because it has only 8 bits (assuming that on your platform a char is defined as a byte of 8 bits). When the value is more than 255, it overflows.
Furthermore, you don't know if acharis unsigned (values can be between 0 and 255) or signed (values can be between -128 and 127).
You can use another type thancharif you want to store values > 255.
|
I have astructdefined:
```
struct Query {
int *pages;
int currentpage;
};
struct Query *new = malloc(sizeof(struct Query));
new->pages = malloc(sizeof(int) * 4);
```
I then checked the size ofnew->pagesto ensure that the size was 4 by doing:
```
int size = sizeof(new->pages)/sizeof(new->pages[0]);
```
However,sizekeeps returning2as opposed to4.
Would anyone know what I might be doing wrong?
Thanks for your help.
|
Your expectation is wrong.
sizeof(new->pages)in
```
int size = sizeof(new->pages)/sizeof(new->pages[0]);
```
doesn't return the total number ofintelements. Just the size of the int pointer (int*). Sincesizeof(int*)is 8 andsizeof(int)is 4 on your platform, it returns 2.
By the way, you should usesize_tforsizeassizeofoperator returns asize_tand%zuis the format specifier (inprintf()) to printsize_t.
|
Suppose I have a C source file which does not contain any reference to any other file. You may assume it only contains -
```
int main(void) {
int a=5, b=10;
}
```
Will this source file go to the linker? What will be the task of the linker in this case?
|
It will because linker will be invoked to form the runnable executable. No matter it's one source file or many, each translation unit will be first compile to object file, and then linked against the C's runtime to form the executable program. So even you see only one source file, it is still linked to the runtime by the linker.
|
I am trying to cross compile libcollections library for ARM architecture. After running the command./configure --host=arm-none-linux-gnueabi, it fails with the errorconfigure: error: C compiler cannot create executables.
Inside the config.log file, I found that this is due toas: unrecognized option '-meabi=5'.
What does this line mean and how do I resolve this issue?
The library is found here:https://bitbucket.org/manvscode/libcollections
|
-meabi=5is anARM specific GNU assembler command line optionto specify the EABI version to be used, where valid values are 4, 5 and gnu.
You should ensure that you have installed an appropriate build of binutils for ARM, as per the solutionhere.
|
```
#include<stdio.h>
int main()
{
double a,b;
scanf("%lf",&a);
printf("%lf\n",a);
return 0;
}
```
I'm getting output0.000000— why? — but the same code gets input and output asdoublein a C program. Withfloattype, the code works in C++. I have used GNUgcccompiler.
|
Inprintf%lfis not existing per say.
Inscanfit does.
(seespecifiers x lengthtable)
Lots of OS accept%lfin printf to be consistent, but Windows is not one of them.
So you have to scanf%lf, but printf%f, and it should work everywhere.
|
I have files with a single column full of numbers and I want to sum all the files. The problem is to be able to exit as soon as invalid data is found (as soon asfprintffails).
A first attempt usinggoto(and inspired bythis answer) is the following
```
while(1) {
sum_a = 0;
for(i=0 ; i<N ;i++){
if(fscanf(infiles[i], "%d\n", &a) != 1){
goto end; // yeah, I know...
}
sum_a += a;
}
printf("%d\n", sum_a); // Should NOT be read if anything failed before
}
end:
for(i=0 ; i<N ;i++)
fclose(infiles[i]);
```
I would glad to see a nicer solution (ie not usinggotoandwhile(1)!). I don't want to mess up with many flags set and unset in a dirty way.
|
Why?
It's a perfectly valid use case ofgoto. It's the most readable solution, and does the job. Why bother changing it?
|
First of all: my application does not run on a "normal" operating system with virtual memory or MMU or something like that, but on an embedded system with fixed and limited amount of physical memory.
So this question focuses on plain ANSI-C: when I do calls to malloc() the amount of available memory reduces by the allocated size. Is there an ANSI-C function which can be used to retrieve the amount of remaining, free memory?
|
No. ..............................
|
I have a structure as below:
```
struct Query {
int pages[];
int currentpage;
};
```
I was wondering if it was possible to set the size of this array after creating the structure.
```
Query new = malloc(sizeof(struct Query));
```
After this, I will perform some calculations which will then tell me the size thatpages[]needs to be. Ifpages[]needed to be of size 4, how can I set it as such?
|
In C99 you can useFlexible array members:
```
struct Query {
int currentpage;
int pages[]; /* Must be the last member */
};
struct Query *new = malloc(sizeof(struct Query) + sizeof(int) * 4);
```
|
Having forgotten my C knowledge now, having a really hard time figuring out how to do the following:
```
int a = 5; //getting value from a function
int b = 1; //from a function
```
what I want to have is:
```
char * returnstring = "5:1"; //want to return this
```
I have tried the following but it doesn't work.
```
char astr[5], bstr[5];
sprintf( astr, "%d", a);
sprintf( bstr, "%d", b);
char finstr[100]; //final string
strcpy(finstr, astr);
strcpy(finstr, ":");
strcpy(finstr, bstr);
printf ("%s", finstr);
```
|
You can just do it with onesprintf:
```
char str[100];
sprintf(str, "%d:%d", a, b);
```
|
What I want the code to do is:
printing "Hello",
waiting 2 seconds, and
printing "world".
What happens:
Once I run the program, it waits two seconds, then prints "helloWorld"
```
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t current_time = 0; //A variable to save the time
printf("Hello");
current_time = clock();
//wating 2 seconds
for ( ; (clock() - current_time) < (2 * CLOCKS_PER_SEC); );
printf("Wolrd");
return 0;
}
```
As if the wait command is before the two printing commands?!
|
Print a new line to flush stdout :
```
printf("Hello\n");
```
Currently no characters in the standard output will be displayed because it is line buffered. You can also call thefflushfunction for the same outcome.
|
After running Valgrind on my code I got an error:
```
uninitialized value was created by a heap allocation.
```
My code:
```
void adicionaHashtag(char* x){
char*y=malloc(sizeof(x));/***ERROR IS HERE***/
int i;
for(i=0; i<strlen(x); i++){
y[i]=tolower(x[i]);
}
Lista_Hashtags*aux = (Lista_Hashtags*)malloc(sizeof(Lista_Hashtags));
strcpy(aux->nome, y);
aux->contador=1;
if(contador_unitario == 0){
ultimo = aux;
}
contador_unitario++;
aux->proximo = primeiro;
primeiro = aux;
}
```
any tips?
also, what does "Conditional jump or move depends on uninitialised value(s)" mean?
~
|
"uninitialized value ..."
You may usechar*y=calloc(strlen(x),0);instead ofchar*y=malloc(sizeof(x));.Initialize the memory with "0".
|
I have an array which is stored in my program memory
```
const char* const paragraph[] PROGMEM = {
"First Line",
"Second Line"
};
```
How do I read one string at a time so that it output
```
First Line
Second Line
```
|
```
int i;
for (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {
printf("%s\n", paragraph[i]);
}
```
|
I managed to narrow my problem to this code snippet:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
void **arr;
int max = 10; //tr = 0;
int size = sizeof(int);
arr = malloc(max*sizeof(void*));
for (int i=0; i<=6; i++)
{
arr[i] = malloc(size);
memcpy(arr+i, &i, size);
}
for (int i=0; i<=6; i++)
{
printf("%d ", *(int*)(arr + i));
}
free(arr[0]);
free(arr[1]);
free(arr);
return 0;
}
```
It's ok when I freearr, and it's ok when I freearr[0]. But anything other than that I get a segfault.
Am I doing the allocations wrong? Or is it something else?
|
should be
```
for (int i=0; i<=6; i++)
{
arr[i] = malloc(size);
memcpy(arr[i], &i, size);
}
for (int i=0; i<=6; i++)
{
printf("%d ", *(int*)(arr[i]));
}
```
|
I wrote this brief example in order to understand thread programming in C.It was supposed to write "thread 0". But there is no output.
Here is the code.
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int i=0;
pthread_mutex_t mutex;
void * fonction(){
pthread_mutex_lock(&mutex);
printf("thread %d \n",i++);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(){
pthread_t a;
pthread_mutex_init(&mutex,NULL);
pthread_create(&a,NULL,fonction,NULL);
return EXIT_SUCCESS;
}
```
Can someone help me ?
Ps : I used this to compile it
```
gcc -pthread test.c -o test
```
|
Insertpthread_join(a, NULL)afterpthread_create()and beforereturn EXIT_SUCCESS;to ensure the child thread is finished beforemain()returns.
|
```
if ((vnd = (struct diam_vnd_t *)g_hash_table_lookup(vendors,vend))) {...}
```
Can you tell me why it is an assignment but not a boolean expression in the brackets ? And in what situation this assignment can be considered "true" or "false" ?
|
QuotingC11, chapter §6.5.16,Assignment operators(emphasis mine)
An assignment operator stores a value in the object designated by the left operand.An
assignment expression has the value of the left operand after the assignment,111)but is not
an lvalue.
So, first the assignment will happen, and then, the value that has been assigned will be used as the conditional statement inif.
So, in case of
```
if (p = 0 )
```
will evaluate to FALSE and
```
if (p = 5)
```
will be TRUE.
|
I tried to follow this:http://www.troubleshooters.com/codecorn/lua/lua_lua_calls_c.htm
I tried to compile the c code like it says in the guide:
gcc -Wall -shared -fPIC -o power.so -I/usr/include/lua5.1 -llua5.1 hellofunc.c
but I gothttp://pastebin.com/KQvA0qFHwhich I recognized as the error you get when you forget to include a lib or framework but I did -I/usr/include/lua5.1
If it matters I am running os x and I installed lua with brew
|
You haven't told it where to find lua5.1
use-Lto tell the compiler where the library is located
From your own example page it says to look athttp://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm#_Anatomy_of_a_Lua_Call
|
I know that this strcpy function below is incorrect, but I cannot seem to figure out the one or two things I need to change to fix it. Any help would be greatly appreciated as I am completely stuck on this:
```
void strcpy(char *destString, char *sourceString)
{
char *marker, *t;
for(marker = sourceString, t = destString; *marker; marker++, t++)
*t = *marker;
}
```
|
Well it depends on your environment..
For example I see a few things I don't like:
You do not check for input parameters to be!= NULL. This will cause a*0accessI see you are not terminating your string with the'\0'character (or0).. So, after the loop (please intent.) add*t = 0;
|
After running Valgrind on my code I got an error:
```
uninitialized value was created by a heap allocation.
```
My code:
```
void adicionaHashtag(char* x){
char*y=malloc(sizeof(x));/***ERROR IS HERE***/
int i;
for(i=0; i<strlen(x); i++){
y[i]=tolower(x[i]);
}
Lista_Hashtags*aux = (Lista_Hashtags*)malloc(sizeof(Lista_Hashtags));
strcpy(aux->nome, y);
aux->contador=1;
if(contador_unitario == 0){
ultimo = aux;
}
contador_unitario++;
aux->proximo = primeiro;
primeiro = aux;
}
```
any tips?
also, what does "Conditional jump or move depends on uninitialised value(s)" mean?
~
|
"uninitialized value ..."
You may usechar*y=calloc(strlen(x),0);instead ofchar*y=malloc(sizeof(x));.Initialize the memory with "0".
|
I have an array which is stored in my program memory
```
const char* const paragraph[] PROGMEM = {
"First Line",
"Second Line"
};
```
How do I read one string at a time so that it output
```
First Line
Second Line
```
|
```
int i;
for (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {
printf("%s\n", paragraph[i]);
}
```
|
I managed to narrow my problem to this code snippet:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
void **arr;
int max = 10; //tr = 0;
int size = sizeof(int);
arr = malloc(max*sizeof(void*));
for (int i=0; i<=6; i++)
{
arr[i] = malloc(size);
memcpy(arr+i, &i, size);
}
for (int i=0; i<=6; i++)
{
printf("%d ", *(int*)(arr + i));
}
free(arr[0]);
free(arr[1]);
free(arr);
return 0;
}
```
It's ok when I freearr, and it's ok when I freearr[0]. But anything other than that I get a segfault.
Am I doing the allocations wrong? Or is it something else?
|
should be
```
for (int i=0; i<=6; i++)
{
arr[i] = malloc(size);
memcpy(arr[i], &i, size);
}
for (int i=0; i<=6; i++)
{
printf("%d ", *(int*)(arr[i]));
}
```
|
I wrote this brief example in order to understand thread programming in C.It was supposed to write "thread 0". But there is no output.
Here is the code.
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int i=0;
pthread_mutex_t mutex;
void * fonction(){
pthread_mutex_lock(&mutex);
printf("thread %d \n",i++);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(){
pthread_t a;
pthread_mutex_init(&mutex,NULL);
pthread_create(&a,NULL,fonction,NULL);
return EXIT_SUCCESS;
}
```
Can someone help me ?
Ps : I used this to compile it
```
gcc -pthread test.c -o test
```
|
Insertpthread_join(a, NULL)afterpthread_create()and beforereturn EXIT_SUCCESS;to ensure the child thread is finished beforemain()returns.
|
```
if ((vnd = (struct diam_vnd_t *)g_hash_table_lookup(vendors,vend))) {...}
```
Can you tell me why it is an assignment but not a boolean expression in the brackets ? And in what situation this assignment can be considered "true" or "false" ?
|
QuotingC11, chapter §6.5.16,Assignment operators(emphasis mine)
An assignment operator stores a value in the object designated by the left operand.An
assignment expression has the value of the left operand after the assignment,111)but is not
an lvalue.
So, first the assignment will happen, and then, the value that has been assigned will be used as the conditional statement inif.
So, in case of
```
if (p = 0 )
```
will evaluate to FALSE and
```
if (p = 5)
```
will be TRUE.
|
I tried to follow this:http://www.troubleshooters.com/codecorn/lua/lua_lua_calls_c.htm
I tried to compile the c code like it says in the guide:
gcc -Wall -shared -fPIC -o power.so -I/usr/include/lua5.1 -llua5.1 hellofunc.c
but I gothttp://pastebin.com/KQvA0qFHwhich I recognized as the error you get when you forget to include a lib or framework but I did -I/usr/include/lua5.1
If it matters I am running os x and I installed lua with brew
|
You haven't told it where to find lua5.1
use-Lto tell the compiler where the library is located
From your own example page it says to look athttp://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm#_Anatomy_of_a_Lua_Call
|
I know that this strcpy function below is incorrect, but I cannot seem to figure out the one or two things I need to change to fix it. Any help would be greatly appreciated as I am completely stuck on this:
```
void strcpy(char *destString, char *sourceString)
{
char *marker, *t;
for(marker = sourceString, t = destString; *marker; marker++, t++)
*t = *marker;
}
```
|
Well it depends on your environment..
For example I see a few things I don't like:
You do not check for input parameters to be!= NULL. This will cause a*0accessI see you are not terminating your string with the'\0'character (or0).. So, after the loop (please intent.) add*t = 0;
|
2d array declared by me.
```
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
```
I want address location of the element [1][5].
When I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p = &(*(*daytab+1)+5);then it shows error?
|
That's becausea[i]is equivalent to*(a+i), not*a+i.
|
I am trying to use width array for printing variables in specific widths. I want to do something like
```
int widthArr[] = {5, 4};
uint32_t var1 = 123;
uint32_t var2 = 4567;
printf("%widthArr[0]u, %widthArr[1]u ", var1, var2);
```
but using the actual values fromwidthArrfor the widths. Can that be done?
|
Instead of hard-coding the width, you can use a*modifier to read the field width from the arguments, like this:
```
printf("%*u, %*u ", widthArr[0], var1, widthArr[1], var2);
// prints " 123, 4567 "
```
Fromthe C++ reference page:
In the case when*is used, the width is specified by an additional
argument of typeint.
Note that asterisks may also be used to dynamically set the precision.
|
The code is as follows:
```
printf("u");
write(STDOUT_FILENO, "m", 1);
printf("d\n");
```
output: mud
Can someone explain why the output is printed in this order?
|
The standard output is line buffered by default, that meansprintf("u"), will only put the"u"in its buffer, until afflushor a new line character is seen. To see the output in order, try this:
```
printf("u");
fflush(stdout);
write(STDOUT_FILENO, "m", 1);
printf("d\n");
```
|
Can you use a pipe to share threads between two processes in C? I am writing my own shell and want to know if this implementation would be more optimal, if it is even possible?
|
Each thread is specific to a process and share memory of the calling thread.
If you want efficient inter process communication, you can use shared memory.
Seehttp://man7.org/linux/man-pages/man7/shm_overview.7.html
|
2d array declared by me.
```
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
```
I want address location of the element [1][5].
When I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p = &(*(*daytab+1)+5);then it shows error?
|
That's becausea[i]is equivalent to*(a+i), not*a+i.
|
I am trying to use width array for printing variables in specific widths. I want to do something like
```
int widthArr[] = {5, 4};
uint32_t var1 = 123;
uint32_t var2 = 4567;
printf("%widthArr[0]u, %widthArr[1]u ", var1, var2);
```
but using the actual values fromwidthArrfor the widths. Can that be done?
|
Instead of hard-coding the width, you can use a*modifier to read the field width from the arguments, like this:
```
printf("%*u, %*u ", widthArr[0], var1, widthArr[1], var2);
// prints " 123, 4567 "
```
Fromthe C++ reference page:
In the case when*is used, the width is specified by an additional
argument of typeint.
Note that asterisks may also be used to dynamically set the precision.
|
I have the following make file, which runs perfectly:
```
CFLAGS=-O2 -g -Wall
RANLIB=ranlib
all: test libeasyperf.a
libeasyperf.a: easyperf.o
$(AR) rc $@ $^
$(RANLIB) $@
test: easyperf.o test.o
$(CC) -o $@ $^ -lm
clean:
rm -f *.o test libeasyperf.a
```
Can we rewrite the make file withoutranliband archive (ar) things. Actually I want to run./testby manually compiling each file (easyperf.c,test.c) without Makefile doing all these.
Is it possible?
|
```
gcc -O2 -g -Wall -c test.c -o test.o
gcc -O2 -g -Wall -c easyperf.c -o easyperf.o
gcc -O2 -g -o test easyperf.o test.o -lm
./test
```
|
Is it possible to have dynamic memory allocation in a string that is read with scanf without first declaring it as an array?
|
It is not possible to dynamically allocate memory for astringafterhaving read it withscanf, asscanfneeds a pointer. This means that you must allocate memory first, in order to give it as an argument toscanf.
You can do this like the following example :
```
char *str;
str = malloc(X*sizeof(char)); //where x is the number of characters you want to allocate
if (str != NULL)
int result = scanf("%s", str);
```
In other words, pass the allocated pointer toscanf.
Note: You should be careful about the input you give, as you might cause abuffer-overflowif you give a string which is larger than the allocated space.
|
I'm new to C (and structures in C). And I've seen varying code examples across the internet, but what is the benefit of doing this:
void foo(LargeStruct* struct);
instead of this
void foo(LargeStruct struct);
Does it make memory management easier?
|
The former passes a pointer to the structure to the function. The latter makes a copy of the structure and passes it to the function. If the structure is large, making a copy of it for the function is expensive (uses lots of resources), so it should be avoided unless it's necessary.
|
I'm new to C (and structures in C). And I've seen varying code examples across the internet, but what is the benefit of doing this:
void foo(LargeStruct* struct);
instead of this
void foo(LargeStruct struct);
Does it make memory management easier?
|
The former passes a pointer to the structure to the function. The latter makes a copy of the structure and passes it to the function. If the structure is large, making a copy of it for the function is expensive (uses lots of resources), so it should be avoided unless it's necessary.
|
This question already has answers here:Correct format specifier for double in printf(5 answers)Closed7 years ago.
I can't scan a double to a variable.
This is my code, it is very simple. I built it with command:
gcc -Wall -Wextra -Wpedantic -ansi -c double.c
```
#include <stdio.h>
int main() {
double f;
scanf("%lf", &f);
printf("%lf\n", f);
return 0;
}
```
Input: 5.5 (or any other numbers)
Output: 0 (always)
I am using (GCC) 4.9.3.
|
Read the compiler warning and fix it.
```
~$ gcc -Wall -Wextra -Wpedantic -ansi -c mydouble.c
mydouble.c: In function ‘main’:
mydouble.c:5:12: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]
printf("%lf\n", f);
```
You can change the compiler flag or change the code.
```
#include <stdio.h>
int main() {
double f;
scanf("%lf", &f);
printf("%f\n", f);
return 0;
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.