Thread: Setting a char array after declaring error

  1. #1
    Registered User
    Join Date
    Jan 2019
    Posts
    5

    Post Setting a char array after declaring error

    Hello I've been having trouble with a really simple concept, and I'm new to C, and other resources are confusing me.

    I have declared an array, and want to set each element but get a: Warning: assignment makes integer from pointer without cast.

    This is what I to did:

    Code:
     int main() {
       char myArray[30];
       myArray[0]="h";
       myArray[1]=" ";
       myArray[2]="i";
       myArray[3]="\0";
    
       return 0;
    }
    I know its illegal to assign in this way:

    Code:
    char myArray[30];
    myArray="h i";
    but I thought my first method should have worked. (I am not allowed to declare and initialize in the same step, I'm trying to set an array after it was declared). If anyone can tell me what mistake I'm making here, I would really appreciate it!

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    I am not allowed to declare and initialize in the same step,
    Why not? It is good practice to define and initialize your variables at the same time.

    But your first snippet is incorrect because you're trying to use strings in your assignments. Double quotes denote a string, single quotes denote a character.

  3. #3
    Registered User
    Join Date
    Jan 2019
    Posts
    5
    Thank you very much! This was something I didn't know, and it now works as I expected.

    Also, the reason I didn't define and initialize in the same step is because I'm working through C practice problems, and this particular one had the array declared for me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Declaring dynamic vs fixed 2D char array
    By imuneer in forum C Programming
    Replies: 7
    Last Post: 01-27-2016, 09:29 AM
  2. Setting character in malloc'ed char array
    By bricardo in forum C Programming
    Replies: 2
    Last Post: 10-16-2013, 06:07 AM
  3. setting structure char array with string
    By Tom Bombadil in forum C Programming
    Replies: 6
    Last Post: 04-03-2009, 07:10 AM
  4. Setting String equal to char array?
    By Stunner in forum C++ Programming
    Replies: 16
    Last Post: 07-24-2007, 02:41 AM
  5. dynamically setting size of 2d char array
    By waxydock in forum C Programming
    Replies: 4
    Last Post: 05-13-2007, 10:58 PM

Tags for this Thread