Find The Length Of An Array Using sizeof() | C Programming Tutorial

Поділитися
Вставка
  • Опубліковано 19 жов 2024
  • How to find the length of an array in C using the sizeof() operator, including alternatives to using sizeof(), and potential pitfalls when using sizeof(). Source code: github.com/por.... Check out www.portfolioc... to build a portfolio that will impress employers!

КОМЕНТАРІ • 52

  • @fifaham
    @fifaham Рік тому +2

    Thank you Kevin for explaining the method to find size of array. Those C programming tips are very useful for embedded engineers like myself. I use them a lot in wireless and wired communications and user interface. Examples are communicating over the Bluetooth Low Energy (BLE), USART VCP port COMM, Electronic Control Panels, Robotics, Electronic displays and the like.

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +2

      You're welcome! :-) I was checking out your channel the other day, you do some cool work!

    • @fifaham
      @fifaham Рік тому

      @@PortfolioCourses Thank you Kevin for visiting my channel. I am originally hardware engineer and I want to do all software and firmware by myself. Your channel makes it possible for professionals to learn software and dive deep into it. Many thanks for your time and great efforts to bring your channel into UA-cam. Your time and efforts are greatly appreciated, Kevin.

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      You're welcome as always Firas! :-)

  • @siya.abc123
    @siya.abc123 Рік тому +1

    If you ever find yourself in South Africa, please let me know. I'd like to buy you your favourite beverages. You're the best programming channel on UA-cam

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      Thank you so much for the kind feedback Siya, if I ever do go to South Africa I will remember this! :-)

  • @pregenderneutral
    @pregenderneutral Рік тому +1

    This is one of the best coding videos I have ever watched

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      Wow thanks so much for the positive feedback Genevieve, I'm glad you enjoyed the video! :-)

  • @fifaham
    @fifaham Рік тому +1

    Those various methods of passing length of arrays may all be used but with caution. A code having thousends of lines with error resulting from passing global as local value may give the developer nightmare trying to find the problem. One should pay attention to which method to use before deploying the code and implement new customer requirements in the code at later time. To be in the safe side I would define the size of the array along with the array before sending them for execution - every time, yes every time. For example: to command the wireless controller go into "COMMAND" mode I send the array (pointed to by a pointer *) making up the command bytes as bytes and send along with it the number of bytes and ask the responsible subroutine to process them, this gives me peace of mind. Now even if the customer request new changes later then the code can still work without any problem.

  • @nameless5724
    @nameless5724 2 роки тому +1

    Thanks! Very Helpful

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому

      You're welcome, I'm glad to hear it was helpful for you! :-D

  • @mauricioyepez4361
    @mauricioyepez4361 2 роки тому

    the videos you make are so great and well explained sir , can you tell me which IDE are you using ?

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому +1

      Thank you Mauricio, I'm glad you enjoy the videos! :-) I'm using Xcode on OS X (Mac) in this video.

  • @IamRishavDas
    @IamRishavDas Рік тому

    Thanks for this much of good content ❤

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      You're very welcome, I'm glad you enjoy the content! :-)

  • @aliyuibrahim7076
    @aliyuibrahim7076 Рік тому

    I can understand the concepts of programming in a class but I find it difficult to solve programming problems in a test or exam. Can you tell me why pls?and how can i solve the problems

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +3

      This is a a great question. :-) It's unfortunately a very common problem Aliyu. The issue is that during a test or exam we need to create "new solutions" which is cognitively much more difficult than understand concepts. Understanding concepts is about understanding the building blocks. But building new solutions involves putting those building blocks together in new ways. It can be improved with lots and lots of practice though. The more we practice, the more we begin to recognize patterns in solution, and we build up a "toolbox" of potential ways of solving problems in our memory. We can then pull from this toolbox and experience when trying to solve new problems. It can takes months and years to get more comfortable with creating new solutions to problems, and even then we very often still do new research into similar problems to learn how to solve new problems. So it's very normal to experience what you are experiencing, and it gets better with time. :-) I have started making this playlist aimed at helping new programmers out in particular, you may find it interesting: ua-cam.com/play/PLA1FTfKBAEX6e_cFeqZCuUcexEJZS4OOQ.html.

  • @aliyuibrahim7076
    @aliyuibrahim7076 Рік тому

    Each integer is 4bytes so 4x9 =36
    ​and 36 /4=9 right?

  • @nub8312
    @nub8312 Рік тому

    That's an amazing video! Can you also make a video about a tictactoe game so I can finally understand how to build it :D

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      I've thought about covering tic tac toe one day, hopefully I can get to that topic sometime! :-)

    • @nub8312
      @nub8312 Рік тому

      Nice

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      @@nub8312 🙂

    • @nub8312
      @nub8312 Рік тому

      I dont know if you made a video about this topic yet since I didnt find it but my teacher went crazy and just give us this exercise, when we started programming for only 2 months. Write a function that takes as input parameters a *n × m* matrix of characters and a string, and calculates how many times the string is contained in the rows and columns of the matrix.
      Example: consider the following matrix *A* with *n = 4* rows and m = 5 columns and the string *B* with k = 3. Characters:
      A=
      x c e c a
      w a e c q
      d t p a z
      p c a t f
      B = c a t
      The string *B* is contained three times in matrix A: in the second column, in the fourth column, and in the fourth row.

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      @@nub8312 I don't have a video on that question. It sounds like a question that other people have solved though, there seems to be some results on Google that may give you some ideas for how to solve it. If it was me, I would have a loop nested inside a loop to go over the 2D array... you could go over each row in the outer loop, and then in the inner loop search for the word within that row (going along the columns with a counter variable). You might need *another* loop nested inside *this* loop checking for the matching word within that row along the columns. Every time you encounter the word you could count it. Then below all of this, you could make another loop nested inside a loop that goes over each column, and for each column you could search for the word within that column (like the above, but this time searching for the word along the "rows" of that column, and again, you may need a 3rd nested loop to do this). Unfortunately I agree that it's not an easy problem to solve for new programmers.

  • @ol554
    @ol554 Рік тому

    What is difference between size of an array and length of an array?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      Great question Rick! In practice, people will use the terms "length" and "size" interchangeably to refer to the number of elements the array can store... i.e. the capacity. So a lot of the time when you hear the term "size" it really just means "length". That said because we use the sizeof operator in C, sometimes somebody might say "the size of the array is 40 bytes" and they might be referring to the size of the array in bytes, so it sort of depends on the context. :-)

  • @Mnogojazyk
    @Mnogojazyk 2 роки тому +1

    Drat. Just when I thought there was a generic length(array) function to be had.
    I am beginning to understand the limits of C, and I suppose this is one. That's okey. Nothing is perfect and everything has limits, and that includes computer programming languages.

  • @historyimperfect4240
    @historyimperfect4240 Рік тому

    I have a question.
    Is it possible we allow user to enter the number of elements in a array
    And program tells how many numbers user has entered ?
    If possible then how? Please let me know.
    I don't want to initialise the array , just want to take user input and print how many elements user entered .

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      Sorry, I'm not sure I understand the question. :-( Do you just want to ask the user to enter a number and output the number? Or do you want the program to ask the user for the size of the array, and then create an array using that size, and print out the size they have entered too?

    • @historyimperfect4240
      @historyimperfect4240 Рік тому

      @@PortfolioCourses a program that prints "enter elements in array " and then which user initialises an array by entering 1 2 3 4 5 57 8 and then hits enter to complete the entry.
      Then program prints you have entered 8 elements.

    • @historyimperfect4240
      @historyimperfect4240 Рік тому

      I don't want program to ask size of array from user. In that case I can store size entered by user in a variable 'n ' upto which I can run for loop to store elements.
      I am asking is user enters elements in array and then program tells how many elements are there in an array.
      So is it possible? Because we are not initialising the array size and without initialising size we are asking user to enter number of elements and then we are printung the size

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      @@historyimperfect4240 So no, you couldn't do it without declaring the array first at some point. Unless you used something like dynamic memory allocation and the function realloc() which allows you to modify the size of dynamically allocated memory. Based on what you're describing I think you might be mixing the concepts of "declaring" and "initializing" too, so it's a bit hard to answer this question. Declaring is when we do this:
      int array[10];
      it creates the array. Initialization is when we set the initial values for the elements of the array like this:
      int array[10] = {1,2,3,4,5,6,7,8,9,10};
      In newer versions of C such as C99, we could do something like this mind you:
      int main(void)
      {
      int length = 0;
      printf("Enter Length: ");
      scanf("%d", &length);
      int array[length];
      for (int i = 0; i < length; i++)
      {
      printf("array[%d] = ", i);
      scanf("%d", &array[i]);
      }
      printf("Length: %d
      ", length);
      for (int i = 0; i < length; i++)
      {
      printf("array[%d] = %d
      ", i, array[i]);
      }
      return 0;
      }
      That would ask the user for the array length and then declare the array using the length they have entered. And then it would ask them for each element and output the length and elements. That is similar to what I think you may be asking for. That will not work in older versions of the C language though, they do not allow us to declare an array length using a variable. In that case we could do something like this:
      #define MAX 1000
      int main(void)
      {
      int array[MAX];
      int length = 0;
      printf("Enter Length: ");
      scanf("%d", &length);
      if (length > MAX)
      {
      printf("Length entered > MAX");
      return 0;
      }
      for (int i = 0; i < length; i++)
      {
      printf("array[%d] = ", i);
      scanf("%d", &array[i]);
      }
      printf("Length: %d
      ", length);
      for (int i = 0; i < length; i++)
      {
      printf("array[%d] = %d
      ", i, array[i]);
      }
      return 0;
      }
      Where we declare an array that's beyond the maximum size we think we think may be necessary, and then we only use "length" number of elements in the array. 🙂

    • @historyimperfect4240
      @historyimperfect4240 Рік тому

      @@PortfolioCourses I surely will try this program. I really appreciate your reply , people never reply . Thank you so much for your kind reply. i am a new programmer. Do you have any other social media platforms where I can clear my doubts? Whenever I encounter problems I will ask you.

  • @MarcoAurelio-sv2tk
    @MarcoAurelio-sv2tk 3 місяці тому

    You can use this in char arrays
    int i = 0;
    while(array[i] != '\0')
    i++;

  • @DavidWu-e3g
    @DavidWu-e3g Рік тому

    hello is it possible to do it inside of a function isntead of main ?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

      Great question! We could do it with an array that is declared locally inside the function, yes. But we could not do it with an array parameter of a function. This is because when we pass an array to a function, what is really passed is a pointer to the first element in the array. This video explains this idea: ua-cam.com/video/oe2bZKjiWrg/v-deo.html. :-)

  • @chandanverma5263
    @chandanverma5263 6 місяців тому

    Great

  • @gurramjayanthreddy9123
    @gurramjayanthreddy9123 2 роки тому

    Jefferson Sales done a few but not there yet

  • @milton_tom
    @milton_tom Рік тому

    what about 2d arrays?

  • @MarcoAurelio-sv2tk
    @MarcoAurelio-sv2tk 3 місяці тому

    Macros are basically text pasting

  • @lemmenmin7676
    @lemmenmin7676 2 роки тому

    компилятор ругается на:
    - void print_size(int* array) // warning: ‘sizeof’ on array function parameter ‘array’ will return size of ‘int *’ [-Wsizeof-array-argument]
    - printf("sizeof(array): %ld
    ", sizeof(array)); // warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому +1

      That's OK.... technically sizeof() returns an unsigned int so it's warning about using %d. This might matter if we were using very large numbers, but we are not. These videos explain more about sizeof and size_T:
      ua-cam.com/video/2wNc15926X4/v-deo.html
      ua-cam.com/video/nBJuP_un20M/v-deo.html

    • @lemmenmin7676
      @lemmenmin7676 2 роки тому

      @@PortfolioCourses good!