How can I change a pointer's value from another function? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I been struggling with this piece of code and I can't really figure out what is wrong with it. The code simply takes an input integer k from the user, passes it to the powerOfTen function along with a pointer of type double, and calculates the result. But, when I store the result inside the *my_dbl and try printing that value through *my_double, I get nothing as a result.
#include <stdio.h>
void powerOfTen(int k, double *my_dbl);
int main()
{
int k;
double *my_double;
scanf("%d", &k);
power_of_ten(k, my_double);
printf("%.15lf\n", *my_double);
}
void power_of_ten(int k, double *my_dbl)
{
double result = 1.0;
if(k >= 0){
for(int i = 0; i < k; i++) result = result*10.0;
} else{
for(int i = 0; i < (0-k); i++) result = result/10.0;
}
// printf("%f\n", result);
*my_dbl = result;
}

The pointer was never initialized. Easiest fix is:
int main(int argc, char **argv)
{
int k;
double my_double;
k = argc > 1 ? strtol(argv[1], NULL, 10) : 5;
power_of_ten(k, &my_double);
printf("%.15lf\n", my_double);
}
In the original code, the uninitialized pointer my_double does not yet point to a valid memory location, so the attempt to write to *my_dbl in the function fails. It basically writes data to some random place in memory. A different fix would be something like: double value; double *my_double = &value. Another might be double my_double[1]. Whatever you do, the address you referenced needs to be a place to which writes are valid.

Related

How to calculate long long / int [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to learn how to code by myself and is experiencing some difficulty in calculations. Can someone please explain why the pf always return 0 in the below?
int main(void)
{
//solicit input from users
long long int num = get_long_long("Credit card no: ");
eprintf("%lld\n",num);
//initialize
int i =0;
int j =0;
int counter =0;
string status;
//find length of input
while (num>0)
{
num/= 10;
counter++;
}
printf("counter is %i\n",counter);
//Identify card type by prefix
int power=(counter-2);
eprintf("power is %i\n", power);
int dp = pow(10,power);
eprintf("divofp is %i\n", dp);
//prefix=num
long long int pf=(num/dp);
eprintf("pf is %lld\n",pf);
}
pf will always be zero, because num is set to zero at the end of your while loop.
Therefore num/anything will always equal zero.
A good method of debugging, is to step through the code line by line, and look at the values of your variables at each point in time.
This can help you narrow down problems like this.
The problem is where you get the length of your number:
while (num>0)
num/=10;
num will always be 0 after this and thus your final expression will result in 0 because 0/x = 0 (x != 0).

Primes in C: RunTime Error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#include <stdio.h>
int isPrime(int n){
int ndiv = 0;
int i;
for(i=1;i<=n;i=i+1){
if(n%i == 0){
ndiv = ndiv+1;
}
}
if(ndiv == 2){
return 1;
}
else{
return 0;
}
}
int nextPrime(int n){}
int main(){
int a = isPrime(7);
printf(a);
//printf(isPrime(4));
}
This code gives me a run time error, I think there's a problem here with the way I deal with data types while using a functions and the printf command, but I can't really figure it out. Help!
f in printf stands for "format". You need to supply a format string for printing: printf("%d\n", a)
Your isPrime is inefficient: you do not need to attempt dividing all the way up to the number itself. You could stop once you reach the square root of the number
Moreover, you could exit the loop early once you see that the number is not prime.
Once you fix these errors, your program would start running and producing the output that you expect.
Here is a small example of how to use printf. You can find more format specifiers here.
#include <stdio.h>
int main()
{
int a = 97;
int b = 98;
char hello[6] = "world";
printf("%d\n", a);
printf("%d\n", b);
printf("%s\n", hello);
return 0;
}
It is because your method of printing a variable is wrong. Here's the right one.
int main(){
int a = isPrime(7);
printf("%d",a);
}
I'm no C/C++ expert, but try
printf("%d", a);
%d is a format placeholder expecting an integer number, essentially.
That looks like an interesting isPrime function. Not very efficient at all, but different from what I have seen in the past. You can also loop over all the numbers between 1 and n, and just return false (or 0) if you find any that divise n. Or look up more efficient algorithms.

Fill a array with numbers from 0-100 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to fill an array with integers 0-100.
Here's my code:
int main()
{
int a[100];
for(int i = 0; i < a; i++)
{
a[i] = i;
printf("\n%d\n", a[i]);
}
}
I get this error:
comparison between pointer and integer (int and int) over the for line.
I can't figure it out. Any thoughts?
The cancel condition in your for loop is wrong. i<a You are comparing an int i variable with the pointer a that points to the memory location of the array. You would need to calculate the length of the array:
for(int i=0; i<sizeof(a)/sizeof(int); i++) {
But you could have found this solution in this 9 year old answer
Yes you are comparing pointer with an integer. This is why the error.
for(size_t i=0; i<sizeof(a)/sizeof(a[0]); i++) {
is what you wanted it to be and can be done in C language. Remember that sizeof operator results in value in size_t.
If you are not aware what that sizeof is doing - it is basically total number of bytes that the array object has - divided by each element's size - resulting in number of elements.
In case you are thinking from where did that pointer come?
Note one thing here a is converted into pointer (array decaying)to the first element - so it is nothing other than a pointer to the first element.
This should work for you,
int main()
{
int a[100];
int n = sizeof(a) / sizeof(a[0]); //Get the size of the array
for(int i=0; i<n; i++) { // loop through each elements of the array
a[i] = i;
printf("\n%d\n", a[i]);
}
}

function returns not expected value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
i have a function that counts arithmetic mean of even numbers in an array.
int func(int *x, int length)
{
float even_sum = 0;
int even_num;
int i;
float result;
for (i = 0; i<length; i++)
{
if (x[i] % 2 == 0)
{
even_sum = even_sum + x[i];
even_num++;
}
}
result = even_sum/even_num;
return result;
}
giving an array 1 2 2 1 i expect to receive 2 as mean, but i keep getting 0 as result. Where is a mistake in my code?
int func(int *x, int length)
{
float even_sum = 0;
int even_num; // <-- uninitialized, could be anything!
int i;
float result;
for (i = 0; i<length; i++)
{
if (x[i] % 2 == 0)
{
even_sum = even_sum + x[i];
even_num++; // <-- adding 1 to anything yields undefined behavior
}
}
result = even_sum/even_num; // <-- even more undefined behavior
return result;
}
You initialized some, but not all of your variables. It's best to get in the habit of setting your variables to sensible starting values, just as you do here with float even_sum = 0;
Initialize even_num=0
If you don't initialize variables, they can have garbage values.
In your case, even_num has a huge values, greater that even_sum causing your result to be 0.
#Pbd is correct. If you have the latest version of gcc installed and use the command line flags -Wall -Wextra -Wshadow when compiling, it will give you a warning for uninitialized values. 🤓
I think The only problem in your code is when you are passing int array into this function. Apart from that everything looks fine. I ran the code by initialling the 'x' array and it is working fine.

C telling me to initialize variable even though it's already initialized [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am working on CS50 PSET1. I have the following code so far:
#include <stdio.h>
#include <cs50.h>
int main(void) {
float change;
do {
printf("Change: ");
change = get_float();
} while(change < 0);
int coins;
for(int q = change; q < 25; q++) {
q = 25 / q;
coins += 1;
}
printf("%i", coins);
}
I am having an issue. When I try to compile my code with the make command I get an error saying this
greedy.c:17:9: error: variable 'coins' is uninitialized when used here [-> Werror,-Wuninitialized]
coins += 1;
The compiler is correct. You never assign anything to coins in the first place. All you do is increment its (uninitialized) value.
To assign an initial value, write
int coins = 0; /* or whatever the correct initial value is */
As an aside, I'm not quite sure what the intent is, but the following is highly unlikely to be what you want:
for(int q = change; q < 25; q++) {
q = 25 / q;
Note how the assignment modifies the loop variable. While this is permissible, in this context it looks unlikely to be intentional.

Resources