0

I am looking to modify a char array with different strings, like a temp char array which takes various strings. Let's say a char array A[10] = "alice", how to assign A[10] = "12". Without using string functions?

TIA

3 Answers 3

2

In C, a string is just an array of type char that contains printable characters followed by a terminating null character ('\0').

With this knowledge, you can eschew the standard functions strcpy and strcat and assign a string manually:

A[0] = '1';
A[1] = '2';
A[2] = '\0';

If there were characters in the string A beyond index 2, they don't matter since string processing functions will stop reading the string once they encounter the null terminator at A[2].

Sign up to request clarification or add additional context in comments.

Comments

2

it's like Govind Parmar's answer but with for loop.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char str[11] = "hello world";
    char new[5] = "2018";   
    int i = 0;

    for (i; new[i] != '\0'; i++)
         str[i] = new[i];

    str[i] = '\0';

    printf("str => '%s' ",str);

    return 0;
}

output :

str => '2018'                                                                                                              

Comments

0

Well since string array is noting but pointer to array you can simply assign like this

int main(void) {
    char *name[] = { "Illegal month",
                            "January", "February", "March", "April", "May", "June",
                            "July", "August", "September", "October", "November", "December"
    };
    name[10] = "newstring";
    printf("%s",name[10]);
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.