mugetsu
mugetsu

Reputation: 4398

trouble understanding C pointer in the following

I have the following function:

int do_something(...,const float writeArray[],...){
printf("%d",*writeArray);
return 0;
}

how I use this function is:

do_something(...,&data[0],...);

where data[0]=1

obviously my code isn't as simple as this, but this is an illustration of the problem. When I run do_something, I get a printf value of a very large number like 23259894325. What am I doing wrong? How should I make it printf 1 like its supposed to?

Upvotes: 0

Views: 75

Answers (3)

Dennis
Dennis

Reputation: 14477

%d specifies an signed integer. Use %f instead.

Upvotes: 1

Keith Nicholas
Keith Nicholas

Reputation: 44298

you are passing a float in, your printf is trying to print an int

Upvotes: 0

Brendan Long
Brendan Long

Reputation: 54242

printf("%d",*writeArray);

First off, you're printing the first element of the array in a really weird way. If you want to do that, do writeArray[0] so other people can read your code.

Second, %d is for print integers, but writeArray is full of floats. Try using %f. You need to use the right format string for each type.

do_something(...,&data[0],...);

This is really confusing. You want a pointer to the first element of the array? Or you're just trying to pass the entire array? If you want to pass the array (like your later function signature suggests), just do this:

do_something(...,data,...);

Arrays turn into pointers when you pass them to functions anyway.

If you really do want a pointer, change your second function signature to show that:

int do_something(...,const float *writeArray,...){

Upvotes: 3

Related Questions