The checking for NULL trick only works for NULL terminated strings. For a numeric array you'll have to pass in the size too.
void printArray(int *ptr, size_t length);
{
//for statement to print values using array
size_t i = 0;
for( ; i < length; ++i )
printf("%d", ptr[i]);
}
void printString(const char *ptr);
{
//for statement to print values using array
for( ; *ptr!='\0'; ++ptr)
printf("%c", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10};
const char* str = "Hello World!";
printArray(array, 6);
printString(str);
return 0;
}
Answer from Praetorian on Stack OverflowVideos
The checking for NULL trick only works for NULL terminated strings. For a numeric array you'll have to pass in the size too.
void printArray(int *ptr, size_t length);
{
//for statement to print values using array
size_t i = 0;
for( ; i < length; ++i )
printf("%d", ptr[i]);
}
void printString(const char *ptr);
{
//for statement to print values using array
for( ; *ptr!='\0'; ++ptr)
printf("%c", *ptr);
}
int main()
{
int array[6] = {2,4,6,8,10};
const char* str = "Hello World!";
printArray(array, 6);
printString(str);
return 0;
}
You have several options:
- You could pass the size of your array into the function.
- You could have a special "sentinel" value (e.g.
-1) as the last element of your array; if you do this, you must ensure that this value cannot appear as part of the array proper.
fixing your many errors and re-editing to use strlen:
#define LENGTH 8
#include <stdio.h>
#include <string.h>
int main()
{
typedef char Arr[LENGTH];
Arr test = {'1','0','1'};
Arr* a = &test;
size_t len = strlen(test);
for(int i=0;i<len;i++){
printf("%c ", (*a)[i]);
}
}
Three problems:
- You are using
%s, which is for strings. Use%cfor characters. - You need
(*a)[i], asais a pointer to an array, so*ais an array. - 1 and 0 encode non-printable characters. So you won't see anything.
Let's start from this line
int(*p)[10] = arr;
The array arr used as an initializer is implicitly converted to a pointer to its first element of the type int *.
However the initialized pointer p has the type int ( * )[10] and there is no implicit conversion between these two pointers.
So the compiler should issue at least a warning.
You have to write
int(*p)[10] = &arr;
On the other hand, values of the expressions arr and &arr are equal each other. It is the initial address of the extent of memory occupied by the array. (The address of the first element of an array is equal to the address of the array as a whole object).
So the function accepts a pointer of the type int ( * )[10] that points to an array.
Dereferencing the pointer in the expression (*p) you get an object of the type int[10] (the array pointed to by the pointer) that is an object of the array type.
So you can apply the subscript operator (*p)[i] to access elements of the array.
p is a pointer to the 10 elements int array.
(*p)[i] first, you dereference the pointer p and you get the array of 10 integers. Then you access the ith element of the array.