0

I feel silly for asking, but I had trouble finding my answer. How do I re-assign "Rose" to "Douglas"? It seems like I have to use a loop.

#include <stdio.h>

int main() {

  char arr[3][12]= { "Rose", "India", "technologies" };
  printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]);
  arr[0][0] = {"Douglas"};
  printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]);

    return(0);
}
6
  • 1
    Note that you have an overflow in arr[2], since "technologies" requires 13 characters. Your compiler should be warning you about this. Commented May 8, 2012 at 20:16
  • You're right. You know what's funny? I copied that example (roseindia.net/c-tutorials/c-array-string.shtml) and I added the arr[0][0] = {"Douglas"}; part. Commented May 8, 2012 at 20:18
  • 2
    Use of void main and <conio.h> in that example should ring very loud alarm bells, i.e. poor quality Indian college C code. Commented May 8, 2012 at 20:21
  • @PaulR: Actually, the compiler allows that specific case for character arrays, and omits the trailing NUL character. Of course, using such a string as if it were properly NUL-terminated is then undefined behaviour. Commented May 8, 2012 at 20:42
  • @Greg: interesting - I didn't know that - I wonder if you get a warning though... Commented May 8, 2012 at 20:44

1 Answer 1

4

You can do this with strcpy():

strcpy(arr[0], "Douglas");

When using strcpy(), you will have to ensure that there is enough space in the destination to hold the string you're putting there (plus the terminating NUL character). In this case there is, because you have allocated 12 bytes for each string and "Douglas" will take 8.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.