#include<stdio.h>
int main()
{
//int *a={5641,5,98};
char *s="this is a character array";
printf("%s",s);
}
This method of INITIALIZING array works for character array but fails for interger array please tell me why..?
#include<stdio.h>
int main()
{
//int *a={5641,5,98};
char *s="this is a character array";
printf("%s",s);
}
This method of INITIALIZING array works for character array but fails for interger array please tell me why..?
For starters in your program s
is not an array. It is a pointer.
char *s="this is a character array";
So the pointer s
is initialized by the address of the first character of the string literal "this is a character array"
that is indeed has type of a character array.
In C you can use a compound literal to initialize a pointer that will point to first element of an array.
For example
#include <stdio.h>
int main(void)
{
enum { N = 5 };
int *p = ( int[N] ) { 1, 2, 3, 4, 5 };
for ( size_t i = 0; i < N; i++ ) printf( "%d ", p[i] );
putchar( '\n' );
return 0;
}
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
If you want to statically initialize array, the use the form int a[] = { ... }
as mentioned in the comment. Following is the way to do that:
#include<stdio.h>
int main()
{
int a[] = { 5641, 5, 98};
char const *s = "this is a character array";
printf("%s\n",s);
int arrayLength = sizeof(a) / sizeof(a[0]);
int i = 0;
printf("Array length is %d\n", arrayLength);
for(; i < arrayLength ; ++i){
printf("%d ", a[i]);
}
printf("\n");
}
If you want to dynamically allocate array, which is reside in the heap memory, then you could do the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//int a[] = { 5641, 5, 98};
int arrayLength = 3;
int *a = (int*) malloc( (arrayLength + 1) * sizeof(a));
a[0] = 5641;
a[1] = 5;
a[2] = 98;
char const *s = "this is a character array";
printf("%s\n",s);
int i = 0;
printf("Array length is %d\n", arrayLength);
for(; i < arrayLength ; ++i){
printf("%d ", a[i]);
}
printf("\n");
free(a);
}
You have to call malloc()
to allocate memory in the heap. Call free()
when you're done with array, otherwise it will lead to memory leak.