Home > database >  How to put a value into a char * with an index
How to put a value into a char * with an index

Time:12-29

I have a function that gets char * and I want to print the additional value in each interaction For example: hello

h

he

hel

hell

hello

The problem is that I have a memory impairment and writing Exception thrown at 0x7B18F791 (ucrtbased.dll) in workhome4.exe: 0xC0000005: Access violation reading location 0x00000069.

void addSpaceCheck(char* word)
{
    char* stringOne = malloc(sizeof(char) * 1024);
        for (int i = 0; i < strlen(word); i  ) {
                    
            strcat(stringOne, word[i]);
    
                    
                printf("%s , stringOne);
            }
    
        }
}

CodePudding user response:

strcat(stringOne, word[i]); causes the problem in this case. strcat expects a NUL terminated string. stringOne is allocated but does not contain any useful data. Optionally, you could use calloc() to zero out the allocated block of memory. In any case, strcat(stringOne, word[i]); will not do what you think because the second argument is a char.

You could do this:

void addSpaceCheck(char* word)
{
    char* stringOne = malloc(sizeof(char) * 1024);
        for (int i = 0; i < strlen(word) - 1; i  ) {
                stringOne[i] = word[i];
                stringOne[i   1] = '\0';
                printf("%s , stringOne);
            }
    
        }
}

CodePudding user response:

You can't use strcat() without adding a string terminator first.

Nor can you hope that strcat() can add a single character like that.

Instead I suggest

for (size_t i = 0; i < strlen(word); i  ) {
    stringOne[i] = word[i]; 
    stringOne[i 1] = '\0';
    printf("%s ", stringOne);
}

This will ouput

H He Hel Hell Hello 

CodePudding user response:

strcat requires char * as second parameter not char

if you want to use strcat you need to pass a valid C string as second parameter

void addSpaceCheck1(char* word)
{
    size_t length = strlen(word);
    char* stringOne = malloc(length   1);
    for (size_t i = 0; i < length; i  ) 
    {            
        strcat(stringOne, (char[]){word[i], 0});
        printf("%s ", stringOne);
    }
    free(stringOne);
}

But it makes a little sense to use this very heavy function. You can simply assign the char and terminate the string.

void addSpaceCheck(char* word)
{
    size_t length = strlen(word);
    char* stringOne = malloc(length   1);

    for(size_t index = 0; index < length; index  )
    {
        stringOne[index] = word[index];
        stringOne[index   1] = 0;
        printf("%s\n", stringOne);
    }
    free(stringOne);
}
  •  Tags:  
  • c
  • Related