c++ fixed This is a topic that many people are looking for. cfcambodge.org is a channel providing useful information about learning, life, digital marketing and online courses …. it will help you have an overview and solid multi-faceted knowledge . Today, cfcambodge.org would like to introduce to you Fixed and Variable Length Arrays in C and C++. Following along are instructions in the video below:
Fixed and Variable Length Arrays in C and C++ // Beginners to C and C++ are often confused with arrays and the different ways we create them. This video shows you how to create both static and dynamic arrays. I show you how to use malloc and free, as well as the new and delete operators to create different-lengthed arrays, and how to use realloc to resize an array if it needs to get bigger or smaller. I also show you how to pass arrays as arguments to functions and how to write functions that can handle arrays of variable lengths. Have fun. I hope this helps.
Welcome to my channel. I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.
About me: I’m a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.
More about me and what I do:
To Support the Channel:
+ like, subscribe, spread the word
+ contribute via Patreon — [https://www.patreon.com/jacobsorber]
Source code is also available to Patreon supporters. — [https://jsorber-youtube-source.heroku…]
Note: I haven’t posted ALL of the code from ALL of my videos yet. The site contains code from my recent tutorials (I wasn’t quite as organized in the pre-2019 past). I will add examples from older videos as I dig them up.
Everybody today we’re talking about arrays. A few different ways to create them and and how those different ways affect the programs that we write. And the options that have as a programmer hey welcome back everybody i haven’t really done.
A beginner video in a while. And it seems like in my classes with my students. I’ve been dealing a lot with array issues and so i thought it might be a good day to discuss.
Arrays static arrays. Dynamic. Arrays fixed.
Sizes. Variable sizes pointers to arrays. Basically.
All that good stuff. Both in c n. And c plus.
Plus. Now this is a beginner video. But you intermediate programmers may find something that you don’t know or you may find something that you have forgotten or not thought about for a while and it’s always good to get a refresher now of course.
There will be code in this video. As always source code is available through patreon a big thanks to all of you that support this channel. So if you’re watching this video.
You’ve probably at least heard about a raise maybe. It’s something that came up in class maybe you’re actually coming to this video with a specific question about arrays if by some chance. I don’t answer it please drop me a question down in the comments below and i will try to get to it in a future video and of course.
If i do answer your question or you find this video useful. Please consider dropping the video a like now onto arrays now basically arrays are what we use anytime. We want to store a series a bunch of elements.
These elements can be ints or characters or floats or structs. But we want a bunch of them laid out sequentially in memory basically just a list you know. 5 10.
15. Whatever and in c and c.
Plus. The elements of our arrays. Need to be the same type.
Now you can of course use pointer tricks. And polymorphism. If we’re talking about c.
Plus. Plus to store different kinds of elements in a single array. That’s not what i’m talking about today.
But make sure and mention in the comments. If you’d like to see a video about that in the future. But either way from your compiler’s point of view.
An array is homogeneous meaning that all of the different things in the array are of the same type and if we jump into the code. I have a very simple program here we can define our simplest of arrays like this so. This array is called a it’s gonna have five elements and we can initialize.
It with the numbers between one and five okay super simple array with an initializer. I don’t need the initializer this part i could just leave off if i wanted to so this declares a static array of ins and its length is five hey future jacob here. I just wanted to jump in and clarify one little thing i realized after i filmed it that i was using the word static and that may get confused with the static keyword in c.
Now. I have a video that talks about the static keyword in c. I’ll link to that in the description please check it out if you’re confused.
But when i say static here. What i mean simply is that these arrays don’t grow they’re a fixed size array. The compiler allocates memory for them statically and that memory doesn’t grow or shrink.
It just stays the same that’s what i mean by static okay. That’s it let’s get back to the video. So this declares a static array of ins and its length is five when the compiler sees this it’s going to set aside space in memory for five integers.
Five ins. And then we can simply interact with those ins something like this like i can say the first element is the zeroth element. So i can do something like this if i want to set that first element to 76.
It’s important to note for beginners that we do start with zero. If you’re wondering about why that is i do have a video that talks about that i’ll put a link in the description.
But so here we can set our first element to be 76. And we can also get the value of the second element. So something like we could say x equals.
A square bracket. 1. So this is basically going to grab the second element of the array.
A and assign its value to x. And of course. What happens when we want to pass our array to a function okay so let’s say i’ve got this array and i want to pass it to a function let’s start out with a really simple function.
Let’s just say we want to make one that prints out arrays so let’s it’s not going to return anything for now. But we’ll call it print. Array and we’re going to pass in an array call it my array and we’re going to make its length five okay so just like my array down below.
So when you pass this in now. All i’m going to do is have a quick little for loop. We’re going to go to five and then each time through the loop.
We’re going to print out the value of the ith element in the array forgot a comma add our semicolon and then down here at the end just to make things look. Nice. Let’s just add a new line at the end.
Okay. So what this is going to do is it’s just going to go through and it’s going to print out each element in the array on a line and then it’s going to end the line. Once we finish okay nothing too complicated here.
Now if we come down here. And we call it on one of our arrays. Just like this unless just for interest sake.
Let’s go down and make a second array. That’s going to be the same. But with some different values and we’ll do the reverse of the numbers now we can come in here and we can call it on a and we can call it on b okay so now i’m going to compile my code and come down and i can compile it and we do have one warning.
Which is this x is never used so for now. I’m just going to remove these two lines okay now i’m going to compile my code using a little make file that i created nothing fancy here if you are new to make files. And you haven’t seen these before be sure to check out my other videos on make i’ll put links in the description.
But so using this make file. I can come down here and i can compile my program no problem and i can run it and you can see it prints out the elements of each array.
I’m kind of not liking having a new line at the end of each. I meant it to be all on the same line. Sorry about that so we can recompile and we can run and they are still a little bunched together.
So let’s add a comma and a space make things make our output a little bit cleaner. Okay here we go so now you can see it prints out the elements in the array all in a line and then it jumps to the next one for the next array. So this worked and it’s a good first step.
But it has some limitations i want to talk about them before we move on the first one is that all of this code. So far is very very static. What i mean by that is that it’s fairly inflexible this the length of this array is five this array is five my print array up here can only accept things that are of length five and in reality.
Sometimes we want to deal with different lengths and sometimes we don’t necessarily know what the length needs to be until we get into our program. And so this limits us a little bit. It’s not super flexible now one other thing that i would always do in any real program.
Even for static arrays is i would get rid of these magic. Number fives. I would come up here and either pound to find a constant or use a const and let’s use constant for now and we’ll call this array length set it equal to five and then what we can do here is come down.
And we’ll just replace everything in our program with array length. And this basically just gives me the flexibility of saying. Let’s say at some point.
I want to actually change what the length of all of these different arrays are i can just change it in one place rather than having to remember everywhere in my code that needs to be changed. But again let’s come back to this question of what if i don’t know what length my array needs to be or what if i need arrays to be of different sizes. And maybe i want to use a function that can work on all of them so well let’s focus on one thing at a time.
How would i make an array. Where i can pick the size at runtime now for this i want to show you just a few different options now the classic way to do this is with a pointer. So the way i would do this is say so i would specify an integer pointer and then i would call malloc and tell it the size so malik allocates a block of memory and i’m going to tell it the size of the thing.
I need. Which is i need the size of an int. So that’s going to tell me the size and memory of an integer times.
The size of the thing that i want so in this case. I could use array length. But i can use really anything in here so i could use seven.
I can use 567 whatever i want i can basically specify the size. I want and this is something that happens at runtime so it’s super easy for me to specify the size if i want to make it bigger or smaller say for example.
I’m going to read in some data. And i need to make an array that’s the size of the data well that’s hard to know beforehand. What that’s going to look like but with this approach super.
Easy. If i have some variable that has that value in it i can just pass it directly there okay so this gives us the ability to create an array of variable size now we can come down here and we can try to print out that array at this point. I just want to mention that yes.
This is a pointer. But from now on we can basically just use p like we did any other array and that’s because pointers and arrays are almost exactly the same thing. Look if you’re a little fuzzy about the relationship between arrays and pointers.
I do have another video that looks at that issue another beginner video. I actually mentioned it before already. But there is a link down in the description so please check it out if this is a little fuzzy now before i go into printing this out the other thing that we need to do differently about this array is once we’re done with it we also need to free that pointer.
So once we’re done with that array once we don’t need it anymore. Then we’re basically going to release. It and say hey i don’t need this pointer.
Anymore so i’m giving it back to the system to the allocator to the heap okay so now let’s revisit our print array function. So i i can call it just like this and that’s cool except when i go around to run it you’re gonna notice that well something happens first of all i said i wanted it to be 567 entries. But i only got five right i’m able to pass it in but my program up here basically just says i only work on arrays of length 5.
So we want to make this function a little more flexible. I would like to be able to actually print out arrays of any length. And so what you’re going to see instead is you’re going to see a pattern with a lot of functions that take arrays as arguments is instead they’re going to pass in a pointer.
And they’re not going to specify this length right here they’re going to pass in two arguments. Instead you’re going to get an array and you’re going to get a length argument okay and then right here we basically would come down here change this length in our loop. So now we’re going to go basically to the length that gets passed in and the rest of this just stays the same right.
We just now are saying instead of me knowing beforehand that everything that’s going to come in is going to be length. 5. Now i’m going to ask you to give me the length.
You the programmer. The person calling this function tells me how long this thing is and then i will just respect that okay so then down here when we call it we would need to pass in the lengths. Let’s use our integer array length and then down here okay.
So i don’t have i’m still using a magic number here. But for now that’s fine let’s make it a little bit shorter.
So it’ll still fit on one line. But so we have 15 15. Okay great now if i come down here.
I can run it and you can see okay it works fine on my first two and then it works fine also on my p array and one thing to keep in mind here is that yes all of these entries right now are zeros. But that’s not guaranteed to be the case when you get memory from malik. You’re not guaranteed to have zeros you can use calc.
Which actually is guaranteed to zero them out or you can also go through and make sure you initialize this data to something else so you could have another for loop in here that actually goes through and initializes your variables so like for example. We could do this go up to 15. I really need to pound to find that somewhere.
But i’m not going to just for the moment. So let’s have this one count up too so we’re just initializing this to a certain value and mostly. I’m doing this so you can see that the values change.
So now you can see that yes we went from 0 to 14 instead of just all zeros but like i said before if you don’t initialize. It you’re not guaranteed that they’re all going to start out as zeros. So if you want them to all be zero you could either start out with a for loop that sets them all to zero or you could use something like memset to set them all to zero any of those approaches will work just fine.
Now one thing that i want to point out here with this printarray function is that we’re basically trusting the caller to give us the right length. If the caller sends us the wrong length for whatever reason. Then i could handle either too.
Few entries or worse. I can read or write. Too.
Many entries which can corrupt memory or just access memory. That we aren’t supposed to access. Which could give us garbage results or it could seg fault like for example.
Let’s just say i come down here array length. And i say i give it a length that is twice as long so it’s going to be 10. And if we run this i don’t really know what we’re going to get.
But you can see that we ended up with a bunch of just garbage numbers right we basically just were reading whatever memory happens to be right next to a and it doesn’t happen to be anything helpful and so we got the length wrong this just messed us up and so when you’re using this approach. You do have to be very careful to get the lengths right now. If you’re coming from a higher level language.
Like java python ruby or even c. Plus.
Plus. If you’ve been mostly using vectors you might be wondering why can’t i just programmatically get the length of this thing. Why isn’t there some get length method or i mean we’re talking about c.
Here. So why isn’t there a get length function that you just pass in an array. And it just grabs the length.
And the thing is is that c and c. Plus. Plus arrays.
Don’t store a length with the array in memory. They set aside memory. The compiler is going to set aside memory for the array.
But there is no length stored in there so you really just have to keep track of that length yourself okay. Now speaking of c. Plus.
Plus. Let’s just make a quick copy of this program. Let’s make a c plus version of this okay.
And this just allows us to talk about one other option and of course. You will note that in my makefile. I already set this up so that it will actually compile c.
And cpp files. Using the c. Plus plus.
Compiler for the one and the c compiler for the other no problem. But i just need to add array to two in here. So now it will compile both versions.
Oops i forgot to name it right so let’s. Arraytestcpp we’re going to move it to arraytest2cpp. Let’s clear this okay now we should be able to compile it and of course.
Okay. So one thing you are noticing here is that c.
Plus plus has a few different requirements. They’re a little picky about what’s coming back from malik. And so they would want me to cast.
It in c plus to basically say this is an in pointer. No problem okay. But so we have our programs.
They’re both working our c plus plus version and our c version. The reason. I wanted to show you this is simply that most c plus plus programmers would not allocate it like this using malloc.
Although you absolutely can it’s no problem. But instead we can also replace this with the new operator like this so this might be a little prettier. This is basically just saying give me a new integer array that has 15 elements no problem.
So that’s going to function. Exactly the same except that down here instead of free now we need to say delete p. Okay.
So we’re basically just taking advantage of these operators. And because we’re deleting an array we need our square brackets here and now if we compile it okay so we can compile this no problem and we can run it and everything’s working the same okay now i’ve had people ask in the past. Whether or not you can use free instead of delete to release a block of memory that was allocated with new and in practice.
This is really going to depend on how new and delete are implemented if delete was just translated by the compiler into a free call. Then sure this could work. Why not.
But that’s not guaranteed to be the case c. Plus. Plus.
Could actually be doing something differently with new than with malik. And so you really shouldn’t do that so. When your programs use free with pointers that came from malik use delete with pointers that came from new.
Okay now what do we do if we want to resize an array. This is a question that comes up a lot and for this let’s jump back into our c example let’s look at this array that we got from malik. If we are in c.
We can really simply change the size of this so i can just say p equals re alec i pass in the same pointer that i got from malik so that’s going to basically say. This is i want to reallocate this block.
And i give it the new size that i want so in this case. I still want integers. But maybe i want 20 of them so i’m basically saying give me five more than.
I had originally and so this is going to reallocate the block. So now if i come in here. We’re going to have a length of 20 now keep in mind that again those were not initialized and so when i run this so in this case.
It’s printing. Them all out in this case. We’re seeing that they’re all zeros.
But let’s say that i had if we go back and we see and we initialize them to an actual value the initial ones and we recompile. Then you notice that basically the only ones that are initialized are these first 15. The last five that i just added on here they’re just zeros and again you’re not guaranteed that they’re going to be zeros.
They could be anything they just happen to be zeros in this case. And so of course you can see that this works in your programs. You might want to see about initializing those new entries anytime you realize something just before you get too far into things.
But now if we jump back into our c plus. Version. What about resizing our array over here.
Well this is one situation where new and delete are kind of a pain. I can’t exactly just say resize this array. I could allocate a bigger array and copy my data over from my smaller array and then delete the old array and that’s just a pain.
And i know that this is essentially what realic may be doing under the hood. But the point is is i didn’t have to do it. And so that’s always a plus.
So in this case. What’s a c programmer to do will they stoop down to the old c style interface maybe. But most often what they’re going to do is just use vectors or some other container class from the standard template library.
That handles resizing for them and of course. That’s fine too small amount of overhead. But probably nothing to worry about of course let me know in the comments.
If you’d like to see a video on vectors containers or other c. Plus topics.
But let’s not get derailed. Because there’s more to say about arrays so back in the old days. Statically defined arrays like this had to have a constant size so basically 5 works 7 works 15 works but some dynamic variable x doesn’t work at least that’s how it used to be later versions of the c standard library.
Allowed array sizes to be any integer expression. So for example say i wanted to make an array that would store the lengths of the different arguments passed into my program. So basically i want one integer for every element of my arg v.
Array. Then i can do something like this here. I can just make an integer array.
We’ll call it arg lengths and we’re going to make it the length arc c. Right because that’s what argc tells us rxe is this integer coming in and so we’re saying. I want an array and i want it to be the size of arc c whatever rxc happens to be and then i can go through let’s just copy this and go to argc and then what i can do is something like let’s just get the length since that’s what i said.
I was going to be getting and we’ll say arg lengths. I is string length arg vi. Okay.
So what this is going to do is it’s going to go through and get the string length of each of my arguments. And it’s going to store them in my array. So now down here we can use print array on my arg lengths.
Array pass in rxc and so this way back in the old days would not have worked oh and it still doesn’t work today because i forgot to include string dot h. But now if we run this like this well you can see okay right off the bat uh. There’s only one argument and it is length.
Eleven okay it turns out that that’s array test if i pass in a bunch of other arguments and i run it you can see that sure enough we have one of length 11. We’ve got a bunch that are length three and so this array is not it’s still not very dynamic in the sense that it’s not changing size. While my program is running it’s never resized.
But my code is more flexible. Now and this can make a lot of your programs. A little simpler in the old days for something like this you would have to call malek.
So we would have to specify the size. So we would have to specify the size of the int and the number of elements and all of that and that’s not really a big deal either way. But you have options and in some cases that might be the better option.
And so i hope this video helps you keep things straight. So i hope that helps be sure to check out my other videos on c. And other low level programming concepts subscribe to the channel.
If you don’t want to miss out on the next one and i’ll see you then .
Thank you for watching all the articles on the topic Fixed and Variable Length Arrays in C and C++. All shares of cfcambodge.org are very good. We hope you are satisfied with the article. For any questions, please leave a comment below. Hopefully you guys support our website even more.