Suppose I have something like this
int strLen;
printf("Please enter a number: ");
scanf("%d", &strLen);
char *myString;
myString = (char*) malloc(strLen*sizeof(char));
then you fill string with something like “Hello World!” but now I want to just print out “World!” Since my string is just a pointer reference, I can’t call it out by indexes ie.
for(int i=6;i<strLen;i++)
{
printf("%s", myString[i]);
}
// THIS IS AN INCORRECT WAY TO DO THIS
How could I refer to a specific character or even pass the array onto another function of the program if all I have is the array base pointer? Can I ever get the full functionality as if I declared it as a static array before compile time?
A couple of things:
1) Allow for the null terminator in your “malloc()”:
2) The “sizeof(char)” is kind of duplicate redundant. No harm – but no purpose, either. So I omitted it.
3) This is wrong:
4) This is better: