Scope in Ex 29 (Ex Credit)

In the extra credit we are told to fix the function so it always takes a length, I did this setting the line length (see below) … My question is about scope - is this the best way to approach this … i.e setting up size_t in the 2 or more functions / or should I set up a global ? Or is there really a negligible difference in overhead and I shouldn’t care too much. Obviously in this program but say in a very large program?

int lowercase(const char *msg){

	int i = 0; 
	// BUG: \0 termination problems

	**_size_t line_length = strnlen(msg, MAX_LENGTH); ------>_** 

	for(i = 0; i == line_length; i++){
		printf("%c", tolower(msg[i]));
	}

	printf("\n");

	return 0; 
}

Are you sure that’s the real code? You have this line:

**_size_t line_length = strnlen(msg, MAX_LENGTH); ------>_** 

That’s not valid C, unless there’s been a huge change in the language to allow ------->_** to do something now. And the **_size_t isn’t anywhere in this code, so I can’t see how you’re setting it or what it is, and in theory that’s probably wrong just because it’s so strange a way to store the storage.

Also, slap these around your code to make it nicer:

[code]
// c code here
[/code]

You can actually just edit your post to put in a more complete example. One last thing, usually what i do is put the length of a line in a struct along with the char * for the line. I’m not quite sure if you’re doing that but update your code so I know where _size_t is defined and I’ll have more to say.

I was just using the ----> to draw attention to the line … the *** was added when I was making to bold. … not sure whats up with the editor

// that is the real line size_t is just the size of line length

[code]
size_t line_length = strnlen(msg, MAX_LENGTH);

[code]

Ahhh, ok. Yes, that’s the proper type for a size like this, however you always want to check the return codes on functions just in case they use an int (so they can use -1 to mean an error). In this case you’re right:

http://man7.org/linux/man-pages/man3/strnlen.3.html

Now that you have the line_length, it is going to disappear when this function exits. So that means you have to store it somewhere outside this function. Your choices generally are:

  1. Use a struct to keep the string and length together, and return that.
  2. Use an “out parameter”, which is a size_t *out_len. You then would assign to that with *out_len = strnlen(msg, MAX_LENGTH). You can actually look at the above document for strnlen to see how they do it and how you replicate it in your function.

I’d go with #2 in this.