Hello I am wondering why this works since on tutorials and such it always lists that arrays must be of fixed size except when dynamically making one with malloc.
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
if(argc < 2)
return 0;
int tmp[ atoi(argv[1]) ];
printf("sizeof tmp equals to %d\n", sizeof tmp);
return 0;
}
What happens in the background at ASM-level when doing this? And how does it work?
Does it allocate the size given at starting the program on the stack and what's the max for the stack?
Also is this more memory expensive than using malloc?
Thanks in advance.
C99 introduces variable length array whose length is not a constant expression. The declaration
int tmp[ atoi(argv[1]) ];
declares tmp as VLA.
Related
So I've got to do an exercise in C where I have to create an twodimensional array as a "field". We have been given the term typedef char name[300][300]. Now I want to use malloc on this typedef char name, but I can't figure out how (I'm a total beginner in C). I've searched all the way through the internet but couldn't find an example with a typedef char thing and I have no plan how I can do that. Do I have to create a pointer or some special magic to use malloc on this or what am I missing out?
type *p = malloc(sizeof *p); pretty much works generically.
#include <stdio.h>
#include <stdlib.h>
typedef char name[300][300]; //makes `name` a typedef for `char[300][300]`;
int main()
{
name *p = malloc(sizeof *p);
printf("%zu\n", sizeof *p); //verify that this is 300*300==90000 bytes large
}
How to use the typedef char name[300][300] Dynamic memory allocation?
#include<stdio.h>
#include<stdlib.h>
typedef char name[300][300];
int main(){
name *namelist= malloc(sizeof *namelist); // we are pointing to char [300][300]
/* check the return value of malloc */
if( namelist == NULL ){
fprintf(stderr,"%s\n","Error in malloc");
exit(1);
}
for(int i=0;i<5;i++)
scanf("%299s",(*namelist)[i]); // dereferencing it to acccess the 2d array
for(int i=0;i<5;i++)
printf("%s\n",(*namelist)[i]);
free(namelist);
return 0;
}
Here the use of the typdef is shown with a small code.
Explanation:
typedef char name[300][300]
We associate name with the type char [300][300].
Defines name as 300 elements array of 300 element array of type
char.
Now pointer to this is basically pointer to a 2d array char[300][300] or simply char (*)[300][300].
That's why we need to dereference the variable first (*namelist) and then we access the 2d array.
Extra points:
Why sizeof *namelist = 90000 Byte?
Because *namelist denote the 2d array. From standard ยง6.5.3.4
When sizeof is applied to an operand that has type char, unsigned
char, or signed char, (or a qualified version thereof) the result is
1. When applied to an operand that has array type, the result is the total number of bytes in the array.
So the array has 300 x 300 = 90000 char variables each of which is of 1 Byte. So 90000 byte.
Emphasis added
This is not what you got to work with but you could also wrap char name[300][300] table in your own type:
#include <stdio.h>
#include <stdlib.h>
typedef struct my_array_type { char name[300][300]; } my_array_type;
int main(int argc, char* argv[]){
my_array_type * my_table = malloc(sizeof *my_table);
printf("%zu\n", sizeof *my_table);
return 0;
}
I am quite new with C.
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char* c=argv[1];
for (int i=0;i<sizeof(c);i++)
{
printf("%c\n",c[i]);
}
return 0;
}
I am trying to write a program to print every character of a word.
When I try with test: It displays
t
e
s
t
When I try with testtesttest: It displays:
t
e
s
t
I don't understand why, can you tell me why please?
Two problems: Using the sizeof operator on a pointer returns the size of the pointer and not what it points to. If you want the length of a string you should use strlen.
The second problem is what will happen if there are no arguments to your program. Then argv[1] will be NULL.
sizeof(c) is the memory size used by c, which is a char*, that is, a pointer on a char. This type takes 4 bytes of memory, hence the t e s t (4 chars). What you want is strlen, which gives you the length of a string.
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char* c=argv[1];
int length = strlen(c);
for (int i=0;i<length;i++)
{
printf("%c\n",c[i]);
}
return 0;
}
You should also test that your program gets at least one argument. argc is the length of argv, so you need to ensure that argc > 1.
sizeof operator returns the size of the type of operand. c is of type char *, therefore sizeof(c) will return the size of char * instead of the string. You should use strlen(c).
I want to find size or length of an unsigned char pointer in a function where that pointer is an argument to that function.Near the pointers declaration size is coming correctly.
But when i am trying to find size in function it is giving 4.
How can i do this ?
#include <stdio.h>
//void writeFile(unsigned char *da);
void writeFile(char *da);
int main(int arc,char **argv)
{
unsigned char block_bmp[]=
{
0x0,0xff,0xff,0xff,0x0,0x0,0x0,0xff,0xff,0xff,0x0,0x0,0x0,0xff,0xff,0xff,//*16bytes*
};
printf("size::%d\n",sizeof(block_bmp));
writeFile(block_bmp);
}
//void writeFile(unsigned char *da)
void writeFile(char *da)
{
printf("%d\n",__LINE__);
printf("size::%d\n",sizeof(da));
printf("length::%d\n",strlen(da));
FILE *fp;
int i;
fp=fopen("/tmp/hexfile","wb");
for(i=0;i<3780;i++)
fprintf(fp,"%c",da[i]);
// fwrite(da,sizeof(unsigned char),sizeof(da),fp);
fclose(fp);
}
If it points to a NULL-terminated string, use strlen. If not, the pointer is just some memory address for the called function, without any additional information about the size of the array (I assume, you try to pass an array). I suggest passing the number of array elements as additional parameter to the function.
You can not use sizeof in this condition. You should be using the strlen if the char array is NULL terminated.
When you pass array to a function, it decays to pointer, you can't use sizeof on this pointer to get the size of the array. The sizeof will give you 4 bytes (assuming 32 bit machine).
Example:
#include <stdio.h>
void fun(int myArray[10])
{
int i = sizeof(myArray);
printf("Size of myArray = %d\n", i);
}
int main(void)
{
// Initialize all elements of myArray to 0
int myArray[10] = {0};
fun(myArray);
getch();
return 0;
}
/**************OUTPUT**************
Size of myArray = 4
***********************************/
unsigned char array[100];
// sizeof(array) == 100
unsigned char* ptr = array;
// sizeof(ptr) == 4 for 32 bit platform.
When you call a function such as
foo(unsigned char* ptr)
{
}
with 'array' as argument, you only see a 'unsigned char *', not an array with 100 elements. That's why 'sizeof' returns 4.
pointers size sizeof(any_pointer_variable) will not depend on the datatype to which it is going to point. The size of the pointer is mostly 4 that is what you are getting in function. and it doesnt depend on what it points to. all pointers will have same size independent of what type they point to.
#include <stdio.h>
#include <stdlib.h>
int constChars(const char* str) {
int size = sizeof(str)/sizeof(char);
printf("Size is %d.\n", size);
int i = 0;
for (i=0;i<size;i++)
printf("%c ", str[i]);
return 0;
}
int main(void) {
char a[10]={'b','c','d','e','f','f','f','f','f','f'};
constChars(a);
return 0;
}
I wrote piece of code like above, but the output result is:
Size is 8.
b c d e f f f f
I'm quite confused, why the sizeof() function gives a size of 8?
I use gcc and freebsd.
When you pass an array to a function, it gets rewritten as a pointer, where sizeof information is lost. If you did this in main instead, i.e:
char a[10]={'b','c','d','e','f','f','f','f','f','f'};
int size = sizeof(a)/sizeof(a[0]);
printf("Size is %d.\n", size);
It prints 10 as expected. But once you pass it to constChars, it prints the size of a pointer.
Str is a pointer to a char. That is typically 4 to 8 bytes. You are not getting the size of the array, but the size of the variable. The only way to know the length of the array is to pass the size in with it, or you could deliminate the array with some sort of signal value (like \0) and do some iteration.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
size of a datatype without using sizeof
This is question asked in a C interview I wanted to know what is the correct logic for this
If you are not having a sizeof operator in C, how will you get to know
the size of an int ?
Use an array[*]:
int a[2];
int sizeof_int = (char*)(a+1) - (char*)(a);
Actually, due to a note in the section on pointer arithmetic, you don't even need an array, because for the purposes of pointer arithmetic an object behaves like an array of size 1, and an off-the-end pointer is legal for an array:
int a;
int sizeof_int = (char*)((&a)+1) - (char*)(&a);
[*] By which I mean, "a solution to the puzzle posed is to use an array". Don't actually use an array, use sizeof!
One way would be to calculate the address difference between two consecutive int variables.
I think of two ways. One is to print '-1' as a unsigned value and deduce the size basing on the number that is printed. Second is this:
#include <stdio.h>
int size()
{
int a = 1;
int size = 1;
while(a<<=1)
size++;
return size;
}
int main(int argc, char** argv)
{
printf("Size of int: %d\n", size());
return 0;
}
Declare int, init it to -1. Repeatedly '<<1' it until it's 0. Number of shifts requried = size in bits. '<<3' for size in bytes.
Rgds,
Martin