5
Contributors
10
Replies
11
Views
9 Years
Discussion Span
Last Post by freelancelote
Featured Replies
  • 1
    Salem 5,138   9 Years Ago

    Unless it's an array of chars, which if you regard it as a string, is conventionally marked at the end with a \0, then you're stuck. Given [ICODE]void foo ( char *p );[/ICODE] Then [code] char a[10]; char *p = malloc( 20 ); foo( a ); foo( p ); [/code] … Read More

0

Not without resorting to non-portable solutions. Just do what everyone else does and don't lose the size that was passed to the allocation function.

0

Thanks Narue,
any chance to know why that is?

Also, the function I have to do takes an array as a parameter and needs to know the size of the array and then loop through all members of it. Have you got a suggestion on how to do it?

0

Salem,
I don't know the size and it's exactly what I'm trying to find out (I'm trying to build a function that takes an array as a parameter, finds out the size of the array and loops through all members of it)

0

>I don't know the size
Change your code so that you do. Put simply, if you don't know the size of an array parameter in a function you wrote, you've written bad code.

1

Unless it's an array of chars, which if you regard it as a string, is conventionally marked at the end with a \0, then you're stuck.

Given void foo ( char *p ); Then

char a[10];
char *p = malloc( 20 );
foo( a );
foo( p );

As far as foo() is concerned, there's nothing standard to tell what kind of memory it is, or how big that memory is.

Further, this is also valid foo ( &p[5] ); which would almost certainly break any non-standard API which only worked on the result of malloc calls.

Votes + Comments
Thanks. The kind of answer I needed.
0

You can loop through a string and find the '/0' though, correct?

Almost. You can loop through a c-style-string (an array of char) and find the '\0' (backslash) to find it's length. But you could also use strlen() which is a function specially made for this :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.