-2

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.

  • 5
    `stack = "im a string"` -> `strcpy(stack, "im a string")` The former is wrong as it overwrites the buffer pointer (causing a memory leak) whereas you want to replace the contents of the buffer. – kaylum Jun 01 '22 at 11:30
  • 3
    May I suggest programming is not a guessing game. Basic language features like strings and dynamic allocations are covered in any good C book or tutorial and you should go thru one first. – kaylum Jun 01 '22 at 11:31
  • 1
    "*it wont let me modify using indexing like I'm doing in the first code block*". Why do you think that? You have not made any such attempt in that second code block. What happens if you try? Please show that code. It should work just fine after you fix the problem in the first comment. – kaylum Jun 01 '22 at 11:34
  • @MrBrightside, "For my program, I need to be able to ... add another char to the end of the string. " --> First be sure the array or allocated memory is large enough for the longer _string_. – chux - Reinstate Monica Jun 01 '22 at 11:35
  • @MrBrightside `stack = malloc( 999* sizeof(char)); stack = "im a string" ;` assigns a pointer of allocated to `stack` and then assigns a new pointer to a _string literal_ to `stack`, losing the prior pointer to allocated memory. Certainly bad code. Proper coding best fully explained in a C tutorial and not here. – chux - Reinstate Monica Jun 01 '22 at 11:38
  • I wrote a newbie string handling FAQ here: [Common string handling pitfalls in C programming](https://software.codidact.com/posts/284849). Your FAQ is bug #4, but perhaps read the whole post. – Lundin Jun 01 '22 at 11:54

0 Answers0