We created this program in university that creates an array of characters by address in language c. but the first element (char* str) output a weird space. I saw some tutorials about arrays of characters where the first element is the first character we typed.
so why is this happening ? is their some situations where this happens ? if so how can i know if my string starts from the first or second element without using printf everytime ?
This is my program
#include<stdio.h>
#include<stdlib.h>
char* newStr(int n);
int length(char* str);
int main() {
int n,i;
printf("Number of characters \n");
scanf("%d",&n);
char* str = newStr(n);
char* c = malloc(n*sizeof(char)+1);
c=str;
// check that c[0]=' ' and c[n+1]=\0
for(i=0;i<=n+1;i++) printf("*(str+%d) = %c \n",i,*(c+i));
return 0;
}
char* newStr(int n) {
int i;
char* c;
c=malloc(n*sizeof(char)+1);
printf("Enter a word of %d characters \n",n);
for(i=0;i<=n;i++) {scanf("%c",(c+i));}
*(c+n+1)='\0';
return c;
}
int length(char* str) {
int i=0;
while(*(str+i)!='\0'){i++;}
return i-1;
}
and this is the output
Number of characters
5
Enter a word of 5 characters
hello
*(str+0) =
*(str+1) = h
*(str+2) = e
*(str+3) = l
*(str+4) = l
*(str+5) = o
*(str+6) =
The length of your string is 5
can someone explain it to me in simple termes as i'm quite new to c. thanks in advance