I'm having a really hard time trying something super simple in other languages. But in C I was given an exercise that says:
Write a function that receives an array of strings and modify it based on user input.
My code so far:
#include <stdio.h>
#define GEN 3
void fillGenes(char **);
int main() {
char *genes[GEN] = {"Gen0", "Gen1", "Gen2"};
for (int i = 0; i < 3; i++) {
printf("%s\n", genes[i]);
}
fillGenes(genes);
for (int i = 0; i < 3; i++) {
printf("%s\n", genes[i]);
}
return 0;
}
void fillGenes(char **genes) {
printf("Introduce the name of %d genes.\n", GEN);
for(int i = 0; i < GEN; i++) {
printf ("Name of gene %d\n", i);
char newVal[10];
scanf("%s", newVal);
genes[i] = newVal;
}
}
This is wrong, as stated by @Eugene Sh:
newVal is array local to the function, after the function is returned, genes will be an array of dangling pointer:
genes[i] = newVal;
The thing is that I cannot strcpy as it is invalid. How can I make this thing to work?
newValis an array local to the function (actually, even worse - to the block that is inside theforloop). Once the function is returned, yourgeneswill contain an array of dangling pointers.strcpy. Let me rephrase the question, I would like to solve this.strcpybecause the arraygenesis initially containing pointers to string literals which cannot be written to. So you either define it as something likechar genes[GEN][MAX_LEN];to be able to overwrite the strings, or use dynamic allocation to overwrite the pointers.char *genes[GEN] = {"Gen0", "Gen1", "Gen2"};is not a modifiable array of strings.genes[i] = newVal;This is not how string assignment works. Also you cannot point at local arrays and return a pointer to one from a function. All of these issues are best studied by reading a good C programming book.