PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to append to array in C

 May 13, 2022     append, arrays, c, c-strings     No comments   

Issue

Let's say I have an empty array that will be filled with strings, how do I then append a string to it when I want to?

Here is what I kind of have so far

string people[20] = {};

string name = "james";

strcpy(people[0], name);


Solution

Taking into account your code snippet

string people[20] = {};

string name = "james";

strcpy(people[0], name);

it seems that the type string is defined like

typedef char * string;

So this declaration

string people[20] = {};

declares an array of elements of the type char *.

You may not use as an initializer empty braces. You need to write at least like

string people[20] = { NULL };

So to add an element to the array you should write

people[0] = name;

Or without using an intermediate variable

people[0] = "james"; 

Another approach is to allocate a memory dynamically for an element of the array and copy in the memory a string. For example

people[0] = malloc( strlen( name ) + 1 );
strcpy( people[0], name );


Answered By - Vlad from Moscow
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing