I'm new to C. I have been trying to modify my string so that:
- I can change the value of a singular char within the string using indexing
- I can change the entire string and replace it with a new one.
With the static arrays i am able to change the char within the string simply by indexing.
#include <stdlib.h>
#include <string.h>
char string[10] = "pan";
int main()
{
string[0] = 'm';
printf("im the %s \n", string);
}
But this does not allow me to reassign a string to the array like i can with int variables. For this purpose i switched to the dynamically allocated arrays (which i know very little about) and so far ive been able to reassign the strings:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* stack;
int main()
{
stack = malloc( 999* sizeof(char));
stack = "im a string" ;
int stacklen = strlen(stack);
printf("the string says: %s, with length %d \n", stack, stacklen);
stack = "i can change";
printf(" now the string says %s" , stack);
}
Now my problem with dynamically allocated arrays is that it wont let me modify using indexing like I'm doing in the first code block. For my program, I need to be able to replace certain chars on the string or add another char to the end of the string. Ive been stuck at this for quite some time now.