当我以下面给出的格式提交代码时,在线法官(Codechef)不接受它:
#include<stdio.h>
int main()
{
int length,test;
char check[26]="zyxwvutsrqponmlkjihgfedcba";
scanf("%d",&test);
while(test--){
scanf("%d",&length);
if(length%25 != 0)
printf("%s",check+25-(length%25));
length/=25;
while(length--)
{
printf("%s",check);
}
printf("\n");
}
return 0;
}
&#13;
然而,当我提交下面给出的代码时,它很容易被接受。在这里,我所做的只是将char数组从局部变为全局。任何人都可以理解它的原因。
#include<stdio.h>
char check[26]="zyxwvutsrqponmlkjihgfedcba";
int main()
{
int length,test;
scanf("%d",&test);
while(test--){
scanf("%d",&length);
if(length%25 != 0)
printf("%s",check+25-(length%25));
length/=25;
while(length--)
{
printf("%s",check);
}
printf("\n");
}
return 0;
}
&#13;
链接到使用它的问题:
答案 0 :(得分:5)
check
需要27 char
来存储你分配给它的字符串文字(包括终止null),而不是26。读到最后是UB,但可能发生的是在全局范围版本中,下一个字节恰好是0,但是本地范围版本,下一个字节非零,导致访问冲突。
答案 1 :(得分:2)
您不能将public class Database extends SQLiteOpenHelper {
// Version number to upgrade database version
// each time if you Add, Edit table, you need to change
// the version number
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "users.db";
private static final String TABLE_USERS = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public Database(Context context, String DATABASE_NAME, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// There must be a ',' in between every column definition
String query = "CREATE TABLE " + TABLE_USERS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USERNAME + " TEXT " +
");";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_USERS);
onCreate(db);
}
//Add a new row to the db
public void addUser(Users user){
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, user.get_username());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_USERS, null, values);
db.close();
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_USERS + " WHERE 1";
// Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
// Move to the first row in your results
c.moveToFirst();
while(!c.isAfterLast()) {
if(c.getString(c.getColumnIndex("username")) != null) {
dbString += c.getString(c.getColumnIndex("username"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
(在任一版本中)与“字符串”功能一起使用
check
没有终止NUL字节(check
),因此您调用未定义的行为。
提示:在使用字符串文字进行初始化时,不要使用数组的大小。
'\0'