If you have some string (as a variable type from ), let`s assume it is string S that is "AAA". You can change individual chars freely. Like:
for(int i=0; i<3; i++)
{
S[i]++
}
which as i guess will make it "BBB".
So, in cs50 course lection we got that string function is just like char *
and here is this code:
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
// Get a string
char *s = get_string("s: ");
// Allocate memory for another string
char *t = malloc(strlen(s) + 1);
// Copy string into memory
for (int i = 0, n = strlen(s); i <= n; i++)
{
t[i] = s[i];
}
// Capitalize copy
t[0] = toupper(t[0]);
// Print strings
printf("s: %s\n", s);
printf("t: %s\n", t);
}
which effectively is copying one string to another, not just making another copy of link to starting character of string, but making another string with same filling just with the difference we are capitilizing first letter. SO, I've got a thought, why should I even use this new malloc(strlen(s) + 1)
. If I need another string to appear in means of just creating some memory jar, why can't I just make new string with any filling. Like this:
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
// Get a string
string s = get_string("s: ");
// Let`s consider we know exact size of s we are getting, so we are creating the string of same size, just for question purposes
string t = "qooq";
// Copy string into memory
for (int i = 0, n = strlen(s); i <= n; i++)
{
t[i] = s[i];
}
// Capitalize copy
t[0] = toupper(t[0]);
// Print strings
printf("s: %s\n", s);
printf("t: %s\n", t);
}
And at this point it does not work, it compiles, but shows some cryptic errors when it goes into for loop. So where am I basically wrong? Am I missing something? I can do whatever I want with characters in a string, so why can`t I just give to characters the valuse of another character in this t[i] = s[i]
???