• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

what am i doing wrong here (C related)

Status
Not open for further replies.

7imz

Member
i'm trying to read strings (no more than 100 characters long) from stdin and store them in an array of strings... so what am i doing wrong here?

#include <stdio.h>
#include <string.h>

int main(){

int i, counter;

scanf("%d", &counter);
char *strArr[counter][100];

for(i=0; i<counter; i++){
char str[100];
scanf("%s", str);
strcpy(strArr[100], str);
}

for(i=0; i<counter; i++)
printf("%s\n", strArr[100]);

return 0;
}
 

Mazre

Member
You can't use a variable to declare the size of an array. The compiler needs to let the final executable know how much memory to allocate for your array before execution. Variables aren't useable with static allocation. To allocate dynamically in C you'll need to use malloc() which can be rather messy if you haven't done it before. You may want to set some limit on how many strings you can take in during an execution and then hard setting it in your array declaration. You can still use counter for your loop controls though.
 

Diffense

Member
int main(){

int i, counter;

scanf("%d", &counter);
char strArr[counter][100];

for(i=0; i<counter; i++){
char str[100];
scanf("%s", str);
strcpy(strArr, str);
}

for(i=0; i<counter; i++)
printf("%s\n", strArr);

return 0;

}

There is a new feature that allows the variable sized array (vla) to work. Not all compilers implement it though (gcc apprently does since it compiled my code above). Typically you have to estimate the maximum size or dynamically allocate memory. I also changed the array declaration (took out the pointer declarator).
 
Status
Not open for further replies.
Top Bottom