Open Side Menu Go to the Top
Register
C char array question C char array question

12-04-2016 , 07:10 PM
Input:

#include <stdio.h>
int main ()
{
/* variable definition: */

char StudentName[4];
float ExamValue, Sum, Avg;
int students,exams;
// Loop through 5 Students
for (students=0; students <5 ; students++)

{
// reset Sum to 0
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);

// Nested Loop for Exams
for (exams=0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}

output:

Enter Student Name
Enter exam grade:
Enter exam grade:
Enter exam grade:
Average for casey is 99.333336
Enter Student Name
Enter exam grade:
Enter exam grade:
Enter exam grade:
Average for bob is 99.333336
Enter Student Name
Enter exam grade:
Enter exam grade:
Enter exam grade:
Average for zachary is 99.333336
Enter Student Name
Enter exam grade:
Enter exam grade:
Enter exam grade:
Average for roberto is 99.333336
Enter Student Name
Enter exam grade:
Enter exam grade:
Enter exam grade:
Average for timi is 99.333336


question:

how come despite only allocating 4 characters in the array, the program still prints names of +4 characters such as casey,zachary,roberto?

If I change it so it is char studentname [3] it only prints cas, zac, rob, ect ect

whats happening here?

note: though this is code from a class assignment, the assignment is already submitted and is not a question from the homework.
C char array question Quote
12-04-2016 , 07:51 PM
Quote:
Originally Posted by de4df1sh
how come despite only allocating 4 characters in the array, the program still prints names of +4 characters such as casey,zachary,roberto?
Welcome to C. Many functions in C will happily overflow the memory you've provided them, and that is what scanf is doing here. Sometimes it does what you've shown here, sometimes it does weirder things. For example, because you've written into memory space not owned by StudentName, it's possible that another variable owns that space and may write into it.

Quote:
If I change it so it is char studentname [3] it only prints cas, zac, rob, ect ect
If you change to to [3] it should have the same behavior as [4]. If it isn't doing that, then it's pure luck/happenstance. As I said above, the behavior is essentially undefined.

How do you fix it? Here's the really funny part - you really can't. There is no absolutely safe way to use %s with scanf.

If you must use %s with scanf, then the best way to do it is to read the data another way, say using getline() and then manually truncate the string before using sscanf() to be sure you won't overrun your variable. (sscanf is a variant of scanf that reads from a char array instead of a file handle)
C char array question Quote
12-04-2016 , 09:10 PM
thanks much appreciated!
C char array question Quote
12-04-2016 , 10:07 PM
C is really full of this kind of stuff. It is very difficult to write C programs that don't accidentally screw up the memory somewhere.

I was a TA for C and C++ classes while I was a grad student and I became very suspicious of printfs and couts that were not strictly called for or required. The reason it's suspicious is that if you have screwed up memory allocation or usage in a way that causes your program to crash, sometimes you can force it to work by inserting extra commands where not needed. It's a little hard to explain why the basic reason is that memory usage is predictable from the point of view of the compiler but not to the programmer, so sometimes you can "fix" a memory allocation error by re-ordering your commands to work around it, whether you know WHY it makes it work or not.
C char array question Quote
12-06-2016 , 02:55 PM
Lol pretty sure i passed a few exams by doing that
C char array question Quote
12-06-2016 , 07:54 PM
Quote:
Originally Posted by RustyBrooks
C is really full of this kind of stuff. It is very difficult to write C programs that don't accidentally screw up the memory somewhere.

I was a TA for C and C++ classes while I was a grad student and I became very suspicious of printfs and couts that were not strictly called for or required. The reason it's suspicious is that if you have screwed up memory allocation or usage in a way that causes your program to crash, sometimes you can force it to work by inserting extra commands where not needed. It's a little hard to explain why the basic reason is that memory usage is predictable from the point of view of the compiler but not to the programmer, so sometimes you can "fix" a memory allocation error by re-ordering your commands to work around it, whether you know WHY it makes it work or not.
Could you provide an example of something that you would avoid? I don't think cout or printf are exception safe FWIW. So yeah be careful in using. This article on doing a safe printf might be interesting to some:

Safe Printf
C char array question Quote
12-06-2016 , 08:18 PM
Anything that has a version that takes a length should be used vs one that doesn't. Depending on going until you get to a null character has all kinds of buffer overrun and other problems. For example
strcpy vs strncpy
strcat vs strncat
strlen vs strnlen
strtok vs strtok_r (the latter is thread safe, the former is not, although frankly they're both pretty awful)

I'm sure there are more. I don't do a lot of plain C programming any more.
C char array question Quote
12-06-2016 , 08:41 PM
C++11 and C++14 have some nice features, but man a lot of it should have just been present from the start. C++ was missing a lot of very obvious basic stuff.
C char array question Quote
12-06-2016 , 09:04 PM
Quote:
Originally Posted by RustyBrooks
Anything that has a version that takes a length should be used vs one that doesn't. Depending on going until you get to a null character has all kinds of buffer overrun and other problems. For example
strcpy vs strncpy
strcat vs strncat
strlen vs strnlen
strtok vs strtok_r (the latter is thread safe, the former is not, although frankly they're both pretty awful)

I'm sure there are more. I don't do a lot of plain C programming any more.
Quote:
Originally Posted by RustyBrooks
C++11 and C++14 have some nice features, but man a lot of it should have just been present from the start. C++ was missing a lot of very obvious basic stuff.
Yeah C was a big improvement over assembly language and C++ evolved due to the adoption of OO. The boost library development with it's use of templates and such paved the way for C++ 11 and later versions.
C char array question Quote
12-06-2016 , 09:32 PM
Boost is good stuff for the most part and I use it a fair amount. It adheres to the principle that your libraries should have clean interfaces and dirty interiors. I mean holy **** a lot of the header-only libraries are just hellscapes of templating.

I remember being curious once how they managed to make the tuples work, and as I recall what they did was just make templates for tuples with 2 args, with 3 args, with 4 args, with 5 args...... These days you can probably do it with variadic templates.

Honestly, variadic templates became a thing during the last year I had a professional job writing C++. I just use it for some personal projects now and I do not make heavy use of templating at all, much less variadic templates. I use the **** out of nice stuff like auto iterators and what not though.
C char array question Quote
12-08-2016 , 02:40 PM
Quote:
Originally Posted by RustyBrooks
Boost is good stuff for the most part and I use it a fair amount. It adheres to the principle that your libraries should have clean interfaces and dirty interiors. I mean holy **** a lot of the header-only libraries are just hellscapes of templating.

I remember being curious once how they managed to make the tuples work, and as I recall what they did was just make templates for tuples with 2 args, with 3 args, with 4 args, with 5 args...... These days you can probably do it with variadic templates.

Honestly, variadic templates became a thing during the last year I had a professional job writing C++. I just use it for some personal projects now and I do not make heavy use of templating at all, much less variadic templates. I use the **** out of nice stuff like auto iterators and what not though.
QFT
C char array question Quote

      
m