[C] char[][] problem

Recommended Posts

Hello. I'm working on the function, which gives me some errors:

void splitStr(char str[])
{
char temp[CHARS] = {0};

int spaces = countCharStr(str, ' '); /* count the spaces in the phrase */

error here -> char tempPhrase[spaces + 1][CHARS]; /* an array in the size of the number in words in the phrase */

int occDot = occurence(str, '.', 1) - str; /* get the postion of the last character in the phrase
- it is always a full-stop. */

int i = 0, j;
char *p;
for(; *str; ++str, ++i)
{
int occSpace = occurence(str, ' ', i + 1) - str; /* get the position of space # i */
//printf("i = %d, occSpace = %d\n", i, occSpace);

if(!i) /* i = 0, first loop iteration */
for(j = 0; j <= occSpace; ++j) /* <= and not < to include  the space in the word */
temp[j] = str[j];

}

printf("temp = %s\n", temp);
}


The errors are: error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0 How can I fix that? (I'm not sure but that's one of the issus C++0x is going to solve). I don't want to wait for it to be released :p Thanks in advance.

Share on other sites
Quote:
 Original post by sheep19char tempPhrase[spaces + 1][CHARS]

Well, you can't declare arrays of variable length in C89 or C++. Only C99 allows that.

Oh and what is CHARS? Can you post the line of code where you define that name?

Quote:
 Original post by sheep19I'm not sure but that's one of the issus C++0x is going to solve

If you're writing C++, you shouldn't be using char arrays anyways. Use std::string and/or std::vector.

Share on other sites
try

    char *tempPhrase = new char[spaces + 1][CHARS];

and dont forget to delete it after.

Share on other sites
Quote:
Original post by DevFred
Quote:
 Original post by sheep19char tempPhrase[spaces + 1][CHARS]

Well, you can't declare arrays of variable length in C89 or C++. Only C99 allows that.

Oh and what is CHARS? Can you post the line of code where you define that name?

CHARS is
#define CHARS 100
I know it's not a good name. :p

I'm using Visual C++ 2008EE but I'm doing the program in C to become familiar with C-strings.

Share on other sites
Quote:
 Original post by mcmuzzletry char *tempPhrase = new char[spaces + 1][CHARS]; and dont forget to delete it after.

Well I'm programming in C so I can't do that.

Share on other sites
Quote:
Original post by sheep19
Quote:
 Original post by mcmuzzletry char *tempPhrase = new char[spaces + 1][CHARS]; and dont forget to delete it after.

Well I'm programming in C so I can't do that.

  char* tempPhrase = (char*)malloc(sizeof(char)*(spaces + 1)*(CHARS));

  free tempPhrase;

Share on other sites
Strange, I still get errors:

void splitStr(char str[]){	char temp[CHARS] = {0};	int spaces = countCharStr(str, ' '); /* count the spaces in the phrase */	char *tempPhrase = (char*)malloc(sizeof(char)*(spaces + 1)*(CHARS)); /* an array in the size of the number in words in the phrase */	int occDot = occurence(str, '.', 1) - str; /* get the postion of the last character in the phrase										    - it is always a full-stop. */	int i = 0, j;	char *p;	for(; *str; ++str, ++i)	{		int occSpace = occurence(str, ' ', i + 1) - str; /* get the position of space # i */		//printf("i = %d, occSpace = %d\n", i, occSpace);				if(!i) /* i = 0, first loop iteration */			for(j = 0; j <= occSpace; ++j) /* <= and not < to include  the space in the word */				temp[j] = str[j];	}	printf("temp = %s\n", temp);	free tempPhrase;}

warning C4013: 'system' undefined; assuming extern returning intwarning C4013: warning 'malloc' undefined; assuming extern returning int
error C2065: 'free' : undeclared identifier
error C2146: syntax error : missing ';' before identifier 'tempPhrase'

Why is that? Maybe I should use C++ and not C, but keep the C-strings. Will it make a difference?

Share on other sites
You need to include <stdlib.h> to use malloc and free. Also, free is a function so you need free(whatever); not free whatever;

Share on other sites
Quote:
 Original post by EasilyConfusedYou need to include to use malloc and free. Also, free is a function so you need free(whatever); not free whatever;

I just figured it out. But malloc and free work without including stdlib. (At least for me) :/

Share on other sites
Quote:
 Original post by c0uchm0nsterchar* tempPhrase = (char*)malloc(sizeof(char)*(spaces + 1)*(CHARS));

There is no need to cast the result of malloc in C, as void* can be implicitly converted to any other pointer type. It is required however if you want to write "upwards" (C++) compatible code.

Share on other sites
Quote:
 Original post by sheep19I'm using Visual C++ 2008EE but I'm doing the program in C to become familiar with C-strings.
Unfortunately Visual C++ 2008 doesn't support the C99 standard, so Variable Length Arrays are unsupported, otherwise you wouldn't be having this problem. I am wondering though, how familiar do you really have to be with C-strings? If you understand the principles, and you can use C++, then why not just go for std::string?

Quote:
 I just figured it out. But malloc and free work without including stdlib. (At least for me) :/
Chances are you include something which, at some point, in turn includes <stdlib.h>. Don't rely on this behaviour, there is no reason not to include it explicitly.

Share on other sites
0) It's generally a bad idea to mention C++0x if you're interested in a strict C solution ;)
1) a parameter declaration like '(char str[])' is exactly the same as one like '(char* str)'. For parameters, this is true even if you put a number between the square brackets. C (or C++) arrays aren't first-class types. You can't pass them around properly (except as members of a struct/class); you can only pass pointers. Sorry.
2) Printing the output is not very useful. Anyone who calls your function is probably going to want to do something with the split strings. So return them, and let the caller decide what to do with them. (In the documentation, you then have to explain that the caller is responsible for free()ing the returned strings, because they'll be dynamically allocated here, and you can't free them before the caller gets to use them.)
3) There's no reason to limit yourself to a specific number of characters here.
4) There's no reason to require a full-stop at the end of the phrase. There's a standard C library function that finds the length of strings. You ever heard of a "null terminator"? That's what they're there for: so the function strlen() can look for it.
5) Just because the standard library abbreviates functions names is no reason for you to do so, though. There are old legacy reasons why the C library names are all so short.
6) Your existing code makes no effort to actually accumulate the found words. I'm guessing that you intended to add this later but were stumped by the array declaration? :)
7) Speaking of strlen(), there is also strchr in the standard library for searching for a given character, and strncpy to copy substrings.

Off the top of my head:

char** splitString(char* str) {	int spaces = countCharStr(str, ' ');	// There is one more word than the count of spaces, but we also have	// to allow room for a null terminator on the result array, so that the	// calling code can see how many strings there were. It could just call	// countCharStr() itself, true; but why repeat that effort :)	char** result = malloc(sizeof(char*) * (spaces + 2));	if (!result) { return NULL; }	char** result_pos = result;	char* begin = str;	char* end = str + strlen(str);	// If the string ends with a space, we should end up creating one	// empty string ("") at the end.	while (begin <= end) {		char* end_of_word = strchr(str, ' ') || end;		int len = end_of_word - begin;		char* copy = malloc(len + 1);		if (!copy) {			while (result_pos != result) {				free(--*result_pos);			}			free(result);			return NULL;		}		strncpy(copy, begin, len);		copy[len] = '\0';		*result_pos++ = copy;		begin = end_of_word + 1;	}	assert(result_pos == result + spaces + 1);	*result_pos = NULL;	return result;}

You know, it's not too late to switch to C++ ;)

Create an account

Register a new account

• Forum Statistics

• Total Topics
628379
• Total Posts
2982349

• 10
• 9
• 15
• 24
• 11