Cannot Figure Out Why "sizeof(msg) = 0"
I need to find the length of a Message which was entered. I have put all the characters in the msg into an array msg[]
, but when I check for the size of this array, it comes out to zero.
Thank you for your help.
#include <stdio.h>
#define SIZE ((int) (sizeof(msg)/sizeof(msg[0])))
int main(void){
int i = 0,j = 0;
char msg[i];
char ch = ' ';
printf("Please enter a msg you want traslated: ");
while(ch != '\n'){
scanf("%c",&ch);
if(ch == '\n'){
break;
}
i++;
msg[j] = ch;
j++;
}
printf("%d\n",SIZE);
return 0;
}
Answer
So here's the issue.
You are defining an array with zero elements:
int i = 0,j = 0;
char msg[i];
If you examine sizeof(msg)
, you will get zero.
If you examine sizeof(msg[0])
you will get 1 (At element 0 of your array, char
is 1 byte).
So your math at the end of the program is correct: 0 / 1 == 0
What you need to do is allocate some space for an array which will give msg
a size. If you do this:
char msg[50]
then sizeof(msg)
will be 50. Since a char
is 1 byte, and you want 50 of them: 50 * 1 == 50
I see what you are going for here. You want to count how many elements a user entered. Unfortunately, you can't use this method. The msg
array will always be 50 bytes no matter how many iterations your loop takes.
But, you already are on the right path. You are incrementing i
and j
every time someone adds something. So at the end of the program you could do:
printf("User entered %d records\n", i);
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page